diff --git a/.bazelignore b/.bazelignore deleted file mode 100644 index 284b0692ec13..000000000000 --- a/.bazelignore +++ /dev/null @@ -1,3 +0,0 @@ -.git -dist -node_modules diff --git a/.bazelrc b/.bazelrc index 0704eeca0a66..a02316a9aa50 100644 --- a/.bazelrc +++ b/.bazelrc @@ -1,3 +1,10 @@ +# Disable NG CLI TTY mode +build --action_env=NG_FORCE_TTY=false + +# Required by `rules_ts`. +common --@aspect_rules_ts//ts:skipLibCheck=always +common --@aspect_rules_ts//ts:default_to_tsc_transpiler + # Make TypeScript compilation fast, by keeping a few copies of the compiler # running as daemons, and cache SourceFile AST's to reduce parse time. build --strategy=TypeScriptCompile=worker @@ -5,6 +12,13 @@ build --strategy=TypeScriptCompile=worker # Enable debugging tests with --config=debug test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test_strategy=exclusive --test_timeout=9999 --nocache_test_results +# Enable debugging tests with --config=no-sharding +# The below is useful to while using `fit` and `fdescribe` to avoid sharing and re-runs of failed flaky tests. +test:no-sharding --flaky_test_attempts=1 --test_sharding_strategy=disabled + +# Frozen lockfile +common --lockfile_mode=error + ############################### # Filesystem interactions # ############################### @@ -22,24 +36,28 @@ test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test # See https://github.com/bazelbuild/bazel/issues/4603 build --symlink_prefix=dist/ -# Disable watchfs as it causes tests to be flaky on Windows -# https://github.com/angular/angular/issues/29541 -build --nowatchfs - # Turn off legacy external runfiles -run --nolegacy_external_runfiles -test --nolegacy_external_runfiles +build --nolegacy_external_runfiles # Turn on --incompatible_strict_action_env which was on by default # in Bazel 0.21.0 but turned off again in 0.22.0. Follow # https://github.com/bazelbuild/bazel/issues/7026 for more details. # This flag is needed to so that the bazel cache is not invalidated -# when running bazel via `yarn bazel`. +# when running bazel via `pnpm bazel`. # See https://github.com/angular/angular/issues/27514. build --incompatible_strict_action_env run --incompatible_strict_action_env test --incompatible_strict_action_env +# Enable remote caching of build/action tree +build --experimental_remote_merkle_tree_cache + +# Ensure that tags applied in BUILDs propagate to actions +common --incompatible_allow_tags_propagation + +# Ensure sandboxing is enabled even for exclusive tests +test --incompatible_exclusive_test_sandboxed + ############################### # Saucelabs support # # Turn on these settings with # @@ -65,7 +83,21 @@ test:saucelabs --define=KARMA_WEB_TEST_MODE=SL_REQUIRED # Releases should always be stamped with version control info # This command assumes node on the path and is a workaround for # https://github.com/bazelbuild/bazel/issues/4802 -build:release --workspace_status_command="node ./tools/bazel_stamp_vars.js" +build:release --workspace_status_command="pnpm --silent ng-dev release build-env-stamp --mode=release" +build:release --stamp + +build:snapshot --workspace_status_command="pnpm --silent ng-dev release build-env-stamp --mode=snapshot" +build:snapshot --stamp +build:snapshot --//:enable_snapshot_repo_deps + +build:e2e --workspace_status_command="pnpm --silent ng-dev release build-env-stamp --mode=release" +build:e2e --stamp +test:e2e --test_timeout=3600 --experimental_ui_max_stdouterr_bytes=2097152 + +# Retry in the event of flakes +test:e2e --flaky_test_attempts=2 + +build:local --//:enable_package_json_tar_deps ############################### # Output # @@ -77,20 +109,13 @@ query --output=label_kind # By default, failing tests don't print any output, it goes to the log file test --test_output=errors - -################################ -# Settings for CircleCI # -################################ - -# Bazel flags for CircleCI are in /.circleci/bazel.rc - ################################ # Remote Execution Setup # ################################ # Use the Angular team internal GCP instance for remote execution. -build:remote --remote_instance_name=projects/internal-200822/instances/default_instance -build:remote --project_id=internal-200822 +build:remote --remote_instance_name=projects/internal-200822/instances/primary_instance +build:remote --bes_instance_name=internal-200822 # Starting with Bazel 0.27.0 strategies do not need to be explicitly # defined. See https://github.com/bazelbuild/bazel/issues/7480 @@ -99,40 +124,52 @@ build:remote --define=EXECUTOR=remote # Setup the remote build execution servers. build:remote --remote_cache=remotebuildexecution.googleapis.com build:remote --remote_executor=remotebuildexecution.googleapis.com -build:remote --tls_enabled=true -build:remote --auth_enabled=true -build:remote --remote_timeout=3600 -build:remote --jobs=50 - - # Setup the toolchain and platform for the remote build execution. The platform -# is automatically configured by the "rbe_autoconfig" rule in the project workpsace. -build:remote --host_javabase=@rbe_ubuntu1604_angular//java:jdk -build:remote --javabase=@rbe_ubuntu1604_angular//java:jdk -build:remote --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8 -build:remote --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8 -build:remote --crosstool_top=@rbe_ubuntu1604_angular//cc:toolchain -build:remote --action_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1 -build:remote --extra_toolchains=@rbe_ubuntu1604_angular//config:cc-toolchain -build:remote --extra_execution_platforms=//tools:rbe_ubuntu1604-angular -build:remote --host_platform=//tools:rbe_ubuntu1604-angular -build:remote --platforms=//tools:rbe_ubuntu1604-angular - - # Setup Build Event Service -build:remote --bes_backend=buildeventservice.googleapis.com -build:remote --bes_timeout=30s -build:remote --bes_results_url="https://source.cloud.google.com/results/invocations/" - - # Set remote caching settings +build:remote --remote_timeout=600 +build:remote --jobs=150 + +# Setup the toolchain and platform for the remote build execution. The platform +# is provided by the shared dev-infra package and targets k8 remote containers. +build:remote --extra_execution_platforms=@devinfra//bazel/remote-execution:platform_with_network +build:remote --host_platform=@devinfra//bazel/remote-execution:platform_with_network +build:remote --platforms=@devinfra//bazel/remote-execution:platform_with_network + +# Set remote caching settings build:remote --remote_accept_cached=true +build:remote --remote_upload_local_results=false -############################### -# NodeJS rules settings -# These settings are required for rules_nodejs -############################### +# Force remote executions to consider the entire run as linux. +# This is required for OSX cross-platform RBE. +build:remote --cpu=k8 +build:remote --host_cpu=k8 + +# Set up authentication mechanism for RBE +build:remote --google_default_credentials + +# Use HTTP remote cache +build:remote-cache --remote_cache=https://storage.googleapis.com/angular-team-cache +build:remote-cache --remote_accept_cached=true +build:remote-cache --remote_upload_local_results=false +build:remote-cache --google_default_credentials + +# Additional flags added when running a "trusted build" with additional access +build:trusted-build --remote_upload_local_results=true + +# Fixes issues with browser archives and files with spaces. Could be +# removed in Bazel 8 when Bazel runfiles supports spaces. +build --experimental_inprocess_symlink_creation + +#################################################### +# rules_js specific flags +#################################################### + +# TODO(josephperrott): investigate if this can be removed eventually. +# Prevents the npm package extract from occuring or caching on RBE which overwhelms our quota +build --modify_execution_info=NpmPackageExtract=+no-remote -# Turn on managed directories feature in Bazel -# This allows us to avoid installing a second copy of node_modules -common --experimental_allow_incremental_repository_updates +# Allow the Bazel server to check directory sources for changes. `rules_js` previously +# heavily relied on this, but still uses directory "inputs" in some cases. +# See: https://github.com/aspect-build/rules_js/issues/1408. +startup --host_jvm_args=-DBAZEL_TRACK_SOURCE_DIRECTORIES=1 #################################################### # User bazel configuration @@ -141,4 +178,4 @@ common --experimental_allow_incremental_repository_updates # Load any settings which are specific to the current user. Needs to be *last* statement # in this config, as the user configuration should be able to overwrite flags from this file. -try-import .bazelrc.user \ No newline at end of file +try-import .bazelrc.user diff --git a/.bazelversion b/.bazelversion new file mode 100644 index 000000000000..11f1d47dac93 --- /dev/null +++ b/.bazelversion @@ -0,0 +1 @@ +8.8.2 diff --git a/.circleci/bazel.rc b/.circleci/bazel.rc deleted file mode 100644 index 18fd21f023b3..000000000000 --- a/.circleci/bazel.rc +++ /dev/null @@ -1,23 +0,0 @@ -# These options are enabled when running on CI -# We do this by copying this file to /etc/bazel.bazelrc at the start of the build. - -# Echo all the configuration settings and their source -build --announce_rc - -# Don't be spammy in the logs -build --noshow_progress - -# Don't run manual tests -test --test_tag_filters=-manual - -# Workaround https://github.com/bazelbuild/bazel/issues/3645 -# Bazel doesn't calculate the memory ceiling correctly when running under Docker. -# Limit Bazel to consuming resources that fit in CircleCI "medium" class which is the default: -# https://circleci.com/docs/2.0/configuration-reference/#resource_class -build --local_resources=3072,2.0,1.0 - -# More details on failures -build --verbose_failures=true - -# Retry in the event of flakes -test --flaky_test_attempts=2 diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 2a066447ca89..000000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,457 +0,0 @@ -# Configuration file for https://circleci.com/gh/angular/angular-cli - -# Note: YAML anchors allow an object to be re-used, reducing duplication. -# The ampersand declares an alias for an object, then later the `<<: *name` -# syntax dereferences it. -# See http://blog.daemonl.com/2016/02/yaml.html -# To validate changes, use an online parser, eg. -# http://yaml-online-parser.appspot.com/ - -version: 2.1 - -# Variables - -## IMPORTANT -# If you change the cache key prefix, also sync the fallback_cache_key fallback to match. -# Keep the static part of the cache key as prefix to enable correct fallbacks. -# Windows needs its own cache key because binaries in node_modules are different. -# See https://circleci.com/docs/2.0/caching/#restoring-cache for how prefixes work in CircleCI. -var_1: &cache_key angular_devkit-0.12.0-{{ checksum "yarn.lock" }} -var_2: &cache_key_fallback angular_devkit-0.12.0 -var_1_win: &cache_key_win angular_devkit-win-0.12.0-{{ checksum "yarn.lock" }} -var_2_win: &cache_key_fallback_win angular_devkit-win-0.12.0 -var_3: &default_nodeversion "12.9" -# Workspace initially persisted by the `setup` job, and then enhanced by `setup-and-build-win`. -# https://circleci.com/docs/2.0/workflows/#using-workspaces-to-share-data-among-jobs -# https://circleci.com/blog/deep-diving-into-circleci-workspaces/ -var_4: &workspace_location . -# Filter to ignore pull requests on a given job. -var_5: &ignore_pull_requests - filters: - branches: - ignore: - - /pull\/.*/ - -# Executor Definitions -# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-executors -executors: - action-executor: - parameters: - nodeversion: - type: string - default: *default_nodeversion - docker: - - image: circleci/node:<< parameters.nodeversion >> - working_directory: ~/ng - - test-executor: - parameters: - nodeversion: - type: string - default: *default_nodeversion - docker: - - image: circleci/node:<< parameters.nodeversion >>-browsers - working_directory: ~/ng - environment: - NPM_CONFIG_PREFIX: ~/.npm-global - resource_class: xlarge - - windows-executor: - working_directory: ~/ng - resource_class: windows.medium - shell: powershell.exe -ExecutionPolicy Bypass - machine: - image: windows-server-2019 - -# Command Definitions -# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-commands -commands: - custom_attach_workspace: - description: Attach workspace at a predefined location - steps: - - attach_workspace: - at: *workspace_location - setup_windows: - steps: - - run: - # Need to install node and yarn before to ensure correct versions. - name: Setup windows node environment - command: ./.circleci/windows-env.ps1 - - run: node --version - - run: yarn --version - - setup_bazel_rbe: - parameters: - key: - type: env_var_name - default: CIRCLE_PROJECT_REPONAME - steps: - - run: - name: "Setup bazel RBE remote execution" - command: | - touch .bazelrc.user; - # We need ensure that the same default digest is used for encoding and decoding - # with openssl. Openssl versions might have different default digests which can - # cause decryption failures based on the openssl version. https://stackoverflow.com/a/39641378/4317734 - openssl aes-256-cbc -d -in .circleci/gcp_token -md md5 -k "${<< parameters.key >>}" -out /home/circleci/.gcp_credentials; - sudo bash -c "echo -e 'build --google_credentials=/home/circleci/.gcp_credentials' >> .bazelrc.user"; - # Upload/don't upload local results to cache based on environment - if [[ -n "{$CIRCLE_PR_NUMBER}" ]]; then - sudo bash -c "echo -e 'build:remote --remote_upload_local_results=false\n' >> .bazelrc.user"; - echo "Not uploading local build results to remote cache."; - else - sudo bash -c "echo -e 'build:remote --remote_upload_local_results=true\n' >> .bazelrc.user"; - echo "Uploading local build results to remote cache."; - fi - # Enable remote builds - sudo bash -c "echo -e 'build --config=remote' >> .bazelrc.user"; - echo "Reading from remote cache for bazel remote jobs."; - -# Job definitions -jobs: - setup: - executor: action-executor - steps: - - checkout - - run: - name: Rebase PR on target branch - command: > - if [[ -n "${CIRCLE_PR_NUMBER}" ]]; then - # User is required for rebase. - git config user.name "angular-ci" - git config user.email "angular-ci" - # Rebase PR on top of target branch. - node tools/rebase-pr.js angular/angular-cli ${CIRCLE_PR_NUMBER} - else - echo "This build is not over a PR, nothing to do." - fi - - restore_cache: - keys: - - *cache_key - - *cache_key_fallback - - run: yarn install --frozen-lockfile - - persist_to_workspace: - root: *workspace_location - paths: - - ./* - - save_cache: - key: *cache_key - paths: - - ~/.cache/yarn - - lint: - executor: action-executor - steps: - - custom_attach_workspace - - run: yarn lint - - run: 'yarn bazel:format -mode=check || - (echo "BUILD files not formatted. Please run ''yarn bazel:format''" ; exit 1)' - # Run the skylark linter to check our Bazel rules - - run: 'yarn bazel:lint || - (echo -e "\n.bzl files have lint errors. Please run ''yarn bazel:lint-fix''"; exit 1)' - - validate: - executor: action-executor - steps: - - custom_attach_workspace - - run: yarn validate --ci - - test: - executor: action-executor - steps: - - custom_attach_workspace - - run: yarn test --full - - test-large: - parameters: - ve: - type: boolean - default: false - glob: - type: string - default: "" - executor: test-executor - resource_class: large - parallelism: 4 - steps: - - custom_attach_workspace - - run: yarn webdriver-update - - run: yarn test-large --full <<# parameters.ve >>--ve<> <<# parameters.glob >>--glob="<< parameters.glob >>"<> --nb-shards=${CIRCLE_NODE_TOTAL} --shard=${CIRCLE_NODE_INDEX} - - e2e-cli: - parameters: - ve: - type: boolean - default: false - snapshots: - type: boolean - default: false - executor: test-executor - parallelism: 4 - steps: - - custom_attach_workspace - - run: - name: Initialize Environment - command: ./.circleci/env.sh - - run: - name: Execute CLI E2E Tests - command: PATH=~/.npm-global/bin:$PATH node ./tests/legacy-cli/run_e2e --nb-shards=${CIRCLE_NODE_TOTAL} --shard=${CIRCLE_NODE_INDEX} <<# parameters.ve >>--ve<> <<# parameters.snapshots >>--ng-snapshots<> - - e2e-cli-node-10: - executor: - name: test-executor - nodeversion: "10.16" - parallelism: 4 - steps: - - custom_attach_workspace - - run: - name: Initialize Environment - command: | - ./.circleci/env.sh - # Ensure latest npm version to support local package repository - PATH=~/.npm-global/bin:$PATH npm install --global npm - - run: PATH=~/.npm-global/bin:$PATH node ./tests/legacy-cli/run_e2e --nb-shards=${CIRCLE_NODE_TOTAL} --shard=${CIRCLE_NODE_INDEX} - - test-browsers: - executor: - name: test-executor - environment: - E2E_BROWSERS: true - steps: - - custom_attach_workspace - - run: - name: Initialize Environment - command: ./.circleci/env.sh - - run: - name: Initialize Saucelabs - command: setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev) - - run: - name: Start Saucelabs Tunnel - command: ./scripts/saucelabs/start-tunnel.sh - background: true - # Waits for the Saucelabs tunnel to be ready. This ensures that we don't run tests - # too early without Saucelabs not being ready. - - run: ./scripts/saucelabs/wait-for-tunnel.sh - - run: PATH=~/.npm-global/bin:$PATH node ./tests/legacy-cli/run_e2e ./tests/legacy-cli/e2e/tests/misc/browsers.ts --ve - - run: PATH=~/.npm-global/bin:$PATH node ./tests/legacy-cli/run_e2e ./tests/legacy-cli/e2e/tests/misc/browsers.ts - - run: ./scripts/saucelabs/stop-tunnel.sh - - build: - executor: action-executor - steps: - - custom_attach_workspace - - run: yarn build - - # This is where we put all the misbehaving and flaky tests so we can fine-tune their conditions - # and rerun them faster. - flake-jail: - executor: test-executor - resource_class: medium - steps: - - custom_attach_workspace - - run: yarn webdriver-update - - run: yarn test-large --full --flakey - - run: yarn test-large --full --flakey --ve - - build-bazel: - executor: action-executor - resource_class: xlarge - steps: - - custom_attach_workspace - - setup_bazel_rbe - - run: sudo cp .circleci/bazel.rc /etc/bazel.bazelrc - - run: yarn bazel:test - - snapshot_publish: - executor: action-executor - steps: - - custom_attach_workspace - - run: - name: Decrypt Credentials - # Note: when changing the image, you might have to re-encrypt the credentials with a - # matching version of openssl. - # See https://stackoverflow.com/a/43847627/2116927 for more info. - command: | - openssl aes-256-cbc -d -in .circleci/github_token -k "${KEY}" -out ~/github_token -md md5 - - run: - name: Deployment to Snapshot - command: | - yarn admin snapshots --verbose --githubTokenFile=${HOME}/github_token - - publish: - executor: action-executor - steps: - - custom_attach_workspace - - run: - name: Decrypt Credentials - command: | - openssl aes-256-cbc -d -in .circleci/npm_token -k "${KEY}" -out ~/.npmrc - - run: - name: Deployment to NPM - command: | - yarn admin publish --verbose - - # Windows jobs - # CircleCI support for Windows jobs is still in preview. - # Docs: https://github.com/CircleCI-Public/windows-preview-docs - setup-and-build-win: - executor: windows-executor - steps: - - custom_attach_workspace - - setup_windows - - restore_cache: - keys: - - *cache_key_win - - *cache_key_fallback_win - - run: yarn install --frozen-lockfile - - run: yarn build - - save_cache: - key: *cache_key_win - paths: - # Get cache dir on windows via `yarn cache dir` - - C:\Users\circleci\AppData\Local\Yarn\Cache\v4 - # Only jobs downstream from this one will see the updated workspace - # https://circleci.com/blog/deep-diving-into-circleci-workspaces/ - - persist_to_workspace: - root: *workspace_location - paths: - - ./* - - test-win: - executor: windows-executor - steps: - - custom_attach_workspace - - setup_windows - - run: yarn test --full - # Run partial e2e suite on PRs only. Master will run the full e2e suite with sharding. - - run: if (Test-Path env:CIRCLE_PR_NUMBER) { node tests\legacy-cli\run_e2e.js "--glob=tests/{basic,ivy}/**" } - - e2e-cli-win: - executor: windows-executor - parallelism: 4 - steps: - - custom_attach_workspace - - setup_windows - - run: node tests\legacy-cli\run_e2e.js --nb-shards=$env:CIRCLE_NODE_TOTAL --shard=$env:CIRCLE_NODE_INDEX - -workflows: - version: 2 - default_workflow: - jobs: - # Linux jobs - - setup - - lint: - requires: - - setup - - validate: - requires: - - setup - - build: - requires: - - setup - filters: - branches: - ignore: - - /docs-preview/ - - build-bazel: - requires: - - build - - test: - requires: - - build - - test-large: - requires: - - build - - test-large: - name: test-large-ve - ve: true - glob: "packages/angular_devkit/@(build_angular|build_ng_packagr)/@(src|test)/@(build|browser)/*_spec_large.ts" - requires: - - build - - e2e-cli: - post-steps: - - store_artifacts: - path: /tmp/dist - destination: cli/new-production - requires: - - build - - e2e-cli: - name: e2e-cli-ve - ve: true - requires: - - build - - e2e-cli: - name: e2e-cli-ng-snapshots - snapshots: true - requires: - - e2e-cli - pre-steps: - - run: - name: Don't run expensive e2e snapshots tests for forks other than renovate-bot and angular - command: > - if [[ "$CIRCLE_PR_USERNAME" != "renovate-bot" ]] && - [[ "$CIRCLE_PROJECT_USERNAME" != "angular" || $CIRCLE_BRANCH != "master" ]]; then - circleci step halt - fi - - e2e-cli: - name: e2e-cli-ng-ve-snapshots - snapshots: true - ve: true - requires: - - e2e-cli - pre-steps: - - run: - name: Don't run expensive e2e snapshots tests for forks other than renovate-bot and angular - command: > - if [[ "$CIRCLE_PR_USERNAME" != "renovate-bot" ]] && - [[ "$CIRCLE_PROJECT_USERNAME" != "angular" || $CIRCLE_BRANCH != "master" ]]; then - circleci step halt - fi - - e2e-cli-node-10: - <<: *ignore_pull_requests - requires: - - e2e-cli - - test-browsers: - requires: - - build - - flake-jail: - requires: - - build - - # Windows jobs - # These jobs only run after their non-windows counterparts finish successfully. - # This isn't strictly necessary as there is no artifact dependency, but helps economize - # CI resources by not attempting to build when we know it should fail. - - setup-and-build-win: - requires: - # The Linux setup job also does checkout and rebase, which we get via the workspace. - - setup - - build - - test-win: - requires: - - setup-and-build-win - - test - - e2e-cli-win: - <<: *ignore_pull_requests - requires: - - setup-and-build-win - - e2e-cli - - # Publish jobs - - snapshot_publish: - <<: *ignore_pull_requests - requires: - - test - - build - - e2e-cli - - publish: - requires: - - test - - build - - e2e-cli - - snapshot_publish - filters: - tags: - only: /^v\d+/ - branches: - ignore: /.*/ diff --git a/.circleci/env-helpers.inc.sh b/.circleci/env-helpers.inc.sh deleted file mode 100644 index 5fa1263e112f..000000000000 --- a/.circleci/env-helpers.inc.sh +++ /dev/null @@ -1,73 +0,0 @@ -#################################################################################################### -# Helpers for defining environment variables for CircleCI. -# -# In CircleCI, each step runs in a new shell. The way to share ENV variables across steps is to -# export them from `$BASH_ENV`, which is automatically sourced at the beginning of every step (for -# the default `bash` shell). -# -# See also https://circleci.com/docs/2.0/env-vars/#using-bash_env-to-set-environment-variables. -#################################################################################################### - -# Set and print an environment variable. -# -# Use this function for setting environment variables that are public, i.e. it is OK for them to be -# visible to anyone through the CI logs. -# -# Usage: `setPublicVar ` -function setPublicVar() { - setSecretVar $1 "$2"; - echo "$1=$2"; -} - -# Set (without printing) an environment variable. -# -# Use this function for setting environment variables that are secret, i.e. should not be visible to -# everyone through the CI logs. -# -# Usage: `setSecretVar ` -function setSecretVar() { - # WARNING: Secrets (e.g. passwords, access tokens) should NOT be printed. - # (Keep original shell options to restore at the end.) - local -r originalShellOptions=$(set +o); - set +x -eu -o pipefail; - - echo "export $1=\"${2:-}\";" >> $BASH_ENV; - - # Restore original shell options. - eval "$originalShellOptions"; -} - - -# Create a function to set an environment variable, when called. -# -# Use this function for creating setter for public environment variables that require expensive or -# time-consuming computaions and may not be needed. When needed, you can call this function to set -# the environment variable (which will be available through `$BASH_ENV` from that point onwards). -# -# Arguments: -# - ``: The name of the environment variable. The generated setter function will be -# `setPublicVar_`. -# - ``: The code to run to compute the value for the variable. Since this code should be -# executed lazily, it must be properly escaped. For example: -# ```sh -# # DO NOT do this: -# createPublicVarSetter MY_VAR "$(whoami)"; # `whoami` will be evaluated eagerly -# -# # DO this isntead: -# createPublicVarSetter MY_VAR "\$(whoami)"; # `whoami` will NOT be evaluated eagerly -# ``` -# -# Usage: `createPublicVarSetter ` -# -# Example: -# ```sh -# createPublicVarSetter MY_VAR 'echo "FOO"'; -# echo $MY_VAR; # Not defined -# -# setPublicVar_MY_VAR; -# source $BASH_ENV; -# echo $MY_VAR; # FOO -# ``` -function createPublicVarSetter() { - echo "setPublicVar_$1() { setPublicVar $1 \"$2\"; }" >> $BASH_ENV; -} diff --git a/.circleci/env.sh b/.circleci/env.sh deleted file mode 100755 index 49c0ab18326a..000000000000 --- a/.circleci/env.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash - -# Variables -readonly projectDir=$(realpath "$(dirname ${BASH_SOURCE[0]})/..") -readonly envHelpersPath="$projectDir/.circleci/env-helpers.inc.sh"; - -# Load helpers and make them available everywhere (through `$BASH_ENV`). -source $envHelpersPath; -echo "source $envHelpersPath;" >> $BASH_ENV; - - -#################################################################################################### -# Define PUBLIC environment variables for CircleCI. -#################################################################################################### -# See https://circleci.com/docs/2.0/env-vars/#built-in-environment-variables for more info. -#################################################################################################### -setPublicVar PROJECT_ROOT "$projectDir"; - -#################################################################################################### -# Define SauceLabs environment variables for CircleCI. -#################################################################################################### -setPublicVar SAUCE_USERNAME "angular-ci"; -setSecretVar SAUCE_ACCESS_KEY "9b988f434ff8-fbca-8aa4-4ae3-35442987"; -setPublicVar SAUCE_LOG_FILE /tmp/angular/sauce-connect.log -setPublicVar SAUCE_READY_FILE /tmp/angular/sauce-connect-ready-file.lock -setPublicVar SAUCE_PID_FILE /tmp/angular/sauce-connect-pid-file.lock -setPublicVar SAUCE_TUNNEL_IDENTIFIER "angular-${CIRCLE_BUILD_NUM}-${CIRCLE_NODE_INDEX}" -# Amount of seconds we wait for sauceconnect to establish a tunnel instance. In order to not -# acquire CircleCI instances for too long if sauceconnect failed, we need a connect timeout. -setPublicVar SAUCE_READY_FILE_TIMEOUT 120 - -# Source `$BASH_ENV` to make the variables available immediately. -source $BASH_ENV; diff --git a/.circleci/gcp_token b/.circleci/gcp_token deleted file mode 100644 index 06773903e8d8..000000000000 Binary files a/.circleci/gcp_token and /dev/null differ diff --git a/.circleci/github_token b/.circleci/github_token deleted file mode 100644 index 450cb2c93f8c..000000000000 --- a/.circleci/github_token +++ /dev/null @@ -1 +0,0 @@ -Salted__zÈùº¬ö"Bõ¾Y¾’|‚ۍ¢V”QֳUzWò±/G…îR ¡e}j‘% þÿ¦<%öáÉÿ–¼ \ No newline at end of file diff --git a/.circleci/npm_token b/.circleci/npm_token deleted file mode 100644 index 5a1bb6303052..000000000000 --- a/.circleci/npm_token +++ /dev/null @@ -1 +0,0 @@ -Salted__°/¥ÙL Ž¡”ö¦°Â;ª…(.|©í¡ –ÚCŒàԒ�“þÖ5`h¢8Ðài8JÁo*´?}çû£3§0f´!Ð'ÛB¸̠œ"UƊ&K!¨%Áɵڤ \ No newline at end of file diff --git a/.circleci/windows-env.ps1 b/.circleci/windows-env.ps1 deleted file mode 100644 index d5ebc870ea27..000000000000 --- a/.circleci/windows-env.ps1 +++ /dev/null @@ -1,9 +0,0 @@ -# Install nodejs and yarn via Chocolatey. -choco install nodejs --version 12.1.0 --no-progress -choco install yarn --version 1.17.3 --no-progress - -# Add PATH modifications to the Powershell profile. This is the win equivalent of .bash_profile. -# https://docs.microsoft.com/en-us/previous-versions//bb613488(v=vs.85) -new-item -path $profile -itemtype file -force -# Paths for nodejs, npm, and yarn. Use single quotes to prevent interpolation. -Add-Content $profile '$Env:path += ";C:\Program Files\nodejs\;C:\Users\circleci\AppData\Roaming\npm\;C:\Program Files (x86)\Yarn\bin\;"' diff --git a/.editorconfig b/.editorconfig index 1c658dfbc777..c0a70d2acb14 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,6 +9,7 @@ indent_size = 2 insert_final_newline = true spaces_around_brackets = inside trim_trailing_whitespace = true +quote_type = single [*.md] insert_final_newline = false diff --git a/.gemini/config.yaml b/.gemini/config.yaml new file mode 100644 index 000000000000..795367b13a53 --- /dev/null +++ b/.gemini/config.yaml @@ -0,0 +1,13 @@ +have_fun: false +code_review: + disable: false + comment_severity_threshold: MEDIUM + max_review_comments: -1 + pull_request_opened: + help: false + summary: false + code_review: true + include_drafts: false +ignore_patterns: + - pnpm-lock.yaml + - CHANGELOG.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index b5135def5125..000000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,10 +0,0 @@ -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please help us process issues more efficiently by filing an -issue using one of the following templates: - -https://github.com/angular/angular-cli/issues/new/choose - -Thank you! - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.md b/.github/ISSUE_TEMPLATE/1-bug-report.md deleted file mode 100644 index 3e69b63b677c..000000000000 --- a/.github/ISSUE_TEMPLATE/1-bug-report.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -name: "\U0001F41EBug report" -about: Report a bug in Angular CLI ---- - - - -# 🐞 Bug report - -### Command (mark with an `x`) - - - -- [ ] new -- [ ] build -- [ ] serve -- [ ] test -- [ ] e2e -- [ ] generate -- [ ] add -- [ ] update -- [ ] lint -- [ ] xi18n -- [ ] run -- [ ] config -- [ ] help -- [ ] version -- [ ] doc - - -### Is this a regression? - - - Yes, the previous version in which this bug was not present was: .... - - -### Description - - A clear and concise description of the problem... - - -## 🔬 Minimal Reproduction - - -## 🔥 Exception or Error -

-
-
-
-
- - -## 🌍 Your Environment -

-
-
-
-
- -**Anything else relevant?** - - - diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.yml b/.github/ISSUE_TEMPLATE/1-bug-report.yml new file mode 100644 index 000000000000..5c4ea7d2cbdb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1-bug-report.yml @@ -0,0 +1,102 @@ +name: Bug report +description: Report a bug in Angular CLI +body: + - type: markdown + attributes: + value: | + Oh hi there! + + To expedite issue processing please search open and closed issues before submitting a new one. + Existing issues often contain information about workarounds, resolution, or progress updates. + - type: dropdown + id: command + attributes: + label: Command + description: Can you pin-point the command or commands that are effected by this bug? + options: + - add + - build + - config + - doc + - e2e + - extract-i18n + - generate + - help + - lint + - new + - other + - run + - serve + - test + - update + - version + multiple: true + validations: + required: true + - type: checkboxes + id: is-regression + attributes: + label: Is this a regression? + description: Did this behavior use to work in the previous version? + options: + - label: Yes, this behavior used to work in the previous version + - type: input + id: version-bug-was-not-present + attributes: + label: The previous version in which this bug was not present was + validations: + required: false + - type: textarea + id: description + attributes: + label: Description + description: A clear and concise description of the problem. + validations: + required: true + - type: textarea + id: minimal-reproduction + attributes: + label: Minimal Reproduction + description: | + Simple steps to reproduce this bug. + + **Please include:** + * commands run (including args) + * packages added + * related code changes + + + If reproduction steps are not enough for reproduction of your issue, please create a minimal GitHub repository with the reproduction of the issue. + A good way to make a minimal reproduction is to create a new app via `ng new repro-app` and add the minimum possible code to show the problem. + Share the link to the repo below along with step-by-step instructions to reproduce the problem, as well as expected and actual behavior. + + Issues that don't have enough info and can't be reproduced will be closed. + + You can read more about issue submission guidelines [here](https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-submitting-an-issue). + validations: + required: true + - type: textarea + id: exception-or-error + attributes: + label: Exception or Error + description: If the issue is accompanied by an exception or an error, please share it below. + render: text + validations: + required: false + - type: textarea + id: environment + attributes: + label: Your Environment + description: Run `ng version` and paste output below. + render: text + validations: + required: true + - type: textarea + id: other + attributes: + label: Anything else relevant? + description: | + Is this a browser specific issue? If so, please specify the browser and version. + Do any of these matter: operating system, IDE, package manager, HTTP server, ...? If so, please mention it below. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/2-feature-request.md b/.github/ISSUE_TEMPLATE/2-feature-request.md deleted file mode 100644 index 4c8292f45157..000000000000 --- a/.github/ISSUE_TEMPLATE/2-feature-request.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -name: "\U0001F680Feature request" -about: Suggest a feature for Angular CLI - ---- - - - -# 🚀 Feature request - - -### Command (mark with an `x`) - - -``` -- [ ] new -- [ ] build -- [ ] serve -- [ ] test -- [ ] e2e -- [ ] generate -- [ ] add -- [ ] update -- [ ] lint -- [ ] xi18n -- [ ] run -- [ ] config -- [ ] help -- [ ] version -- [ ] doc -``` - -### Description - A clear and concise description of the problem or missing capability... - - -### Describe the solution you'd like - If you have a solution in mind, please describe it. - - -### Describe alternatives you've considered - Have you considered any alternative solutions or workarounds? diff --git a/.github/ISSUE_TEMPLATE/2-feature-request.yml b/.github/ISSUE_TEMPLATE/2-feature-request.yml new file mode 100644 index 000000000000..4a01698e0f37 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/2-feature-request.yml @@ -0,0 +1,55 @@ +name: Feature request +description: Suggest a feature for Angular CLI +body: + - type: markdown + attributes: + value: | + Oh hi there! + + To expedite issue processing please search open and closed issues before submitting a new one. + Existing issues often contain information about workarounds, resolution, or progress updates. + - type: dropdown + id: command + attributes: + label: Command + description: Can you pin-point the command or commands that are relevant for this feature request? + options: + - add + - build + - config + - doc + - e2e + - extract-i18n + - generate + - help + - lint + - new + - run + - serve + - test + - update + - version + multiple: true + validations: + required: true + - type: textarea + id: description + attributes: + label: Description + description: A clear and concise description of the problem or missing capability. + validations: + required: true + - type: textarea + id: desired-solution + attributes: + label: Describe the solution you'd like + description: If you have a solution in mind, please describe it. + validations: + required: false + - type: textarea + id: alternatives + attributes: + label: Describe alternatives you've considered + description: Have you considered any alternative solutions or workarounds? + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/3-docs-bug.md b/.github/ISSUE_TEMPLATE/3-docs-bug.md deleted file mode 100644 index 7cd9ec28753a..000000000000 --- a/.github/ISSUE_TEMPLATE/3-docs-bug.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -name: "📚 Docs or angular.io issue report" -about: Report an issue in Angular's documentation or angular.io application - ---- - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please file any Docs or angular.io issues at: https://github.com/angular/angular/issues/new/choose - -For the time being, we keep Angular AIO issues in a separate repository. - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/4-security-issue-disclosure.md b/.github/ISSUE_TEMPLATE/4-security-issue-disclosure.md deleted file mode 100644 index b789da9f6da1..000000000000 --- a/.github/ISSUE_TEMPLATE/4-security-issue-disclosure.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -name: ⚠️Security issue disclosure -about: Report a security issue in Angular Framework, Material, or CLI - ---- - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please read https://angular.io/guide/security#report-issues on how to disclose security related issues. - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/5-support-request.md b/.github/ISSUE_TEMPLATE/5-support-request.md deleted file mode 100644 index f6e6e66ff893..000000000000 --- a/.github/ISSUE_TEMPLATE/5-support-request.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: "❓Support request" -about: Questions and requests for support - ---- - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please do not file questions or support requests on the GitHub issues tracker. - -You can get your questions answered using other communication channels. Please see: -https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#question - -Thank you! - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/6-angular-framework.md b/.github/ISSUE_TEMPLATE/6-angular-framework.md deleted file mode 100644 index 8a689c55de35..000000000000 --- a/.github/ISSUE_TEMPLATE/6-angular-framework.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -name: "⚡Angular Framework" -about: Issues and feature requests for Angular Framework - ---- - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please file any Angular Framework issues at: https://github.com/angular/angular/issues/new/choose - -For the time being, we keep Angular issues in a separate repository. - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/7-angular-material.md b/.github/ISSUE_TEMPLATE/7-angular-material.md deleted file mode 100644 index b023135b0cc5..000000000000 --- a/.github/ISSUE_TEMPLATE/7-angular-material.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -name: "\U0001F48EAngular Material" -about: Issues and feature requests for Angular Material - ---- - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 - -Please file any Angular Material issues at: https://github.com/angular/material2/issues/new - -For the time being, we keep Angular Material issues in a separate repository. - -🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑🛑 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000000..898698af3906 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,17 @@ +blank_issues_enabled: false +contact_links: + - name: Docs or angular.dev issue report + url: https://github.com/angular/angular/issues/new + about: Report an issue in Angular's documentation or angular.dev application + - name: Security issue disclosure + url: https://angular.dev/best-practices/security + about: Report a security issue in Angular Framework, Material, or CLI + - name: Support request + url: https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#question + about: Questions and requests for support. + - name: Angular Framework + url: https://github.com/angular/angular/issues/new/choose + about: Issues and feature requests for Angular Framework + - name: Angular Material + url: https://github.com/angular/components/issues/new/choose + about: Issues and feature requests for Angular Material diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000000..3214dde0a4f4 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,43 @@ +## PR Checklist + +Please check to confirm your PR fulfills the following requirements: + + + +- [ ] The commit message follows our guidelines: https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-commit-message-guidelines +- [ ] Tests for the changes have been added (for bug fixes / features) +- [ ] Docs have been added / updated (for bug fixes / features) + +## PR Type + +What kind of change does this PR introduce? + + + +- [ ] Bugfix +- [ ] Feature +- [ ] Code style update (formatting, local variables) +- [ ] Refactoring (no functional changes, no api changes) +- [ ] Build related changes +- [ ] CI related changes +- [ ] Documentation content changes +- [ ] Other... Please describe: + +## What is the current behavior? + + + +Issue Number: N/A + +## What is the new behavior? + + + +## Does this PR introduce a breaking change? + +- [ ] Yes +- [ ] No + + + +## Other information diff --git a/.github/SAVED_REPLIES.md b/.github/SAVED_REPLIES.md index 29e19832903c..dfce61802c0e 100644 --- a/.github/SAVED_REPLIES.md +++ b/.github/SAVED_REPLIES.md @@ -4,87 +4,87 @@ The following are canned responses that the Angular CLI team should use to close Since GitHub currently doesn't allow us to have a repository-wide or organization-wide list of [saved replies](https://help.github.com/articles/working-with-saved-replies/), these replies need to be maintained by individual team members. Since the responses can be modified in the future, all responses are versioned to simplify the process of keeping the responses up to date. - ## Angular CLI: Already Fixed (v1) + ``` Thanks for reporting this issue. Luckily, it has already been fixed in one of the recent releases. Please update to the most recent version to resolve the problem. If the problem persists in your application after upgrading, please open a new issue, provide a simple repository reproducing the problem, and describe the difference between the expected and current behavior. You can use `ng new repro-app` to create a new project where you reproduce the problem. ``` - ## Angular CLI: Don't Understand (v1) + ``` I'm sorry, but we don't understand the problem you are reporting. If the problem persists, please open a new issue, provide a simple repository reproducing the problem, and describe the difference between the expected and current behavior. You can use `ng new repro-app` to create a new project where you reproduce the problem. ``` - ## Angular CLI: Duplicate (v1.1) + ``` Thanks for reporting this issue. However, this issue is a duplicate of #. Please subscribe to that issue for future updates. ``` - ## Angular CLI: Insufficient Information Provided (v1) + ``` -Thanks for reporting this issue. However, you didn't provide sufficient information for us to understand and reproduce the problem. Please check out [our submission guidelines](https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#-submitting-an-issue) to understand why we can't act on issues that are lacking important information. +Thanks for reporting this issue. However, you didn't provide sufficient information for us to understand and reproduce the problem. Please check out [our submission guidelines](https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-submitting-an-issue) to understand why we can't act on issues that are lacking important information. If the problem persists, please file a new issue and ensure you provide all of the required information when filling out the issue template. ``` - ## Angular CLI: NPM install issue (v1) + ``` This seems like a problem with your node/npm and not with Angular CLI. Please have a look at the [fixing npm permissions page](https://docs.npmjs.com/getting-started/fixing-npm-permissions), [common errors page](https://docs.npmjs.com/troubleshooting/common-errors), [npm issue tracker](https://github.com/npm/npm/issues), or open a new issue if the problem you are experiencing isn't known. ``` - ## Angular CLI: Issue Outside of Angular CLI (v1.1) + ``` I'm sorry, but this issue is not caused by Angular CLI. Please contact the author(s) of the project or file an issue on their issue tracker. ``` - ## Angular CLI: Non-reproducible (v1) + ``` I'm sorry, but we can't reproduce the problem following the instructions you provided. Remember that we have a large number of issues to resolve, and have only a limited amount of time to reproduce your issue. Short, explicit instructions make it much more likely we'll be able to reproduce the problem so we can fix it. -If the problem persists, please open a new issue following [our submission guidelines](https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#-submitting-an-issue). +If the problem persists, please open a new issue following [our submission guidelines](https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-submitting-an-issue). A good way to make a minimal repro is to create a new app via `ng new repro-app` and adding the minimum possible code to show the problem. Then you can push this repository to github and link it here. ``` - ## Angular CLI: Obsolete (v1) + ``` Thanks for reporting this issue. This issue is now obsolete due to changes in the recent releases. Please update to the most recent Angular CLI version. If the problem persists after upgrading, please open a new issue, provide a simple repository reproducing the problem, and describe the difference between the expected and current behavior. ``` - ## Angular CLI: Support Request (v1) -``` -Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on [StackOverflow](http://stackoverflow.com/) using tag `angular-cli`. -If you are wondering why we don't resolve support issues via the issue tracker, please [check out this explanation](https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#-got-a-question-or-problem). ``` +Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on [StackOverflow](https://stackoverflow.com/) using tag `angular-cli`. +If you are wondering why we don't resolve support issues via the issue tracker, please [check out this explanation](https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-got-a-question-or-problem). +``` ## Angular CLI: Static Analysis errors (v1) + ``` Hello, errors like `Error encountered resolving symbol values statically` mean that there has been some problem in statically analyzing your app. Angular CLI always runs *some* static analysis, even in JIT mode, in order to discover lazy-loaded routes. This may cause a lot of static analysis errors to surface when importing your project into the CLI, or upgrading for older versions where we didn't run this kind of analysis. -Below are good resources on how to to debug these errors: +Below are good resources on how to debug these errors: - https://gist.github.com/chuckjaz/65dcc2fd5f4f5463e492ed0cb93bca60 - https://github.com/rangle/angular-2-aot-sandbox#aot-dos-and-donts @@ -93,8 +93,19 @@ In that case, please open an issue in https://github.com/angular/angular. ``` ## Angular CLI: Lockfiles (v1) + ``` I'd like to remind everyone that **you only have reproducible installs if you use a lockfile**. Both [NPM v5+](https://docs.npmjs.com/files/package-locks) and [Yarn](https://yarnpkg.com/lang/en/docs/yarn-lock/) support lockfiles. If your CI works one day but not the next and you did not change your code or `package.json`, it is likely because one of your dependencies had a bad release and you did not have a lockfile. **It is your responsibility as a library consumer to use lockfiles**. No one wants to do a release with bugs but it sometimes happens, and the best we can do is to fix it as fast as possible with a new release. When you have a couple of thousand total dependencies it is only a matter of time until one of them has a bad release. ``` + +## Angular CLI: Spam (v1) + +``` +Woah, looks like you've opened a lot of issues/PRs recently. While we appreciate contributions from the community, triaging and reviewing a large influx of content in a short time period takes time away from other ongoing projects. As a result, we're closing these issues/PRs to maintain the team's focus. + +Note that this is not necessarily a rejection of the goals or direction of any of these contributions in particular, so much as a reflection of the team's current capacity and priorities. + +You are welcome to open a smaller subset of issues/PRs in accordance with [our policy](https://github.com/angular/angular/blob/main/contributing-docs/spam.md) focused on the most important and impactful contributions and we will do our best to prioritize a response as soon as possible. +``` diff --git a/.github/_CODEOWNERS.tmp b/.github/_CODEOWNERS.tmp deleted file mode 100644 index 3e79d395914f..000000000000 --- a/.github/_CODEOWNERS.tmp +++ /dev/null @@ -1,17 +0,0 @@ -/packages/_/ @hansl @clydin -/packages/angular/pwa @hansl @Brocco -/packages/angular_devkit/architect/ @filipesilva @hansl -/packages/angular_devkit/architect_cli/ @filipesilva @hansl -/packages/angular_devkit/build_angular/ @filipesilva @clydin -/packages/angular_devkit/build_ng_packagr/ @filipesilva @clydin -/packages/angular_devkit/build_optimizer/ @filipesilva @clydin -/packages/angular_devkit/core/ @hansl @clydin -/packages/angular_devkit/schematics/ @hansl @Brocco -/packages/angular_devkit/schematics_cli/ @hansl @Brocco -/packages/ngtools/webpack/ @hansl @filipesilva @clydin -/packages/schematics/angular/ @hansl @Brocco -/packages/schematics/package_update/ @hansl @Brocco -/packages/schematics/schematics/ @hansl @Brocco -/packages/schematics/update/ @hansl @Brocco -/rules/ @hansl @clydin -/scripts/ @hansl @clydin diff --git a/.github/angular-robot.yml b/.github/angular-robot.yml index 8d06fa54ce8a..3e3a56a25603 100644 --- a/.github/angular-robot.yml +++ b/.github/angular-robot.yml @@ -5,20 +5,22 @@ merge: # the status will be added to your pull requests status: # set to true to disable - disabled: false + disabled: true # the name of the status - context: "ci/angular: merge status" + context: 'ci/angular: merge status' # text to show when all checks pass - successText: "All checks passed!" + successText: 'All checks passed!' # text to show when some checks are failing - failureText: "The following checks are failing:" + failureText: 'The following checks are failing:' # comment that will be added to a PR when there is a conflict, leave empty or set to false to disable - mergeConflictComment: "Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges. -\nPlease help to unblock it by resolving these conflicts. Thanks!" + mergeConflictComment: >- + Hi @{{PRAuthor}}! This PR has merge conflicts due to recent upstream merges. + + Please help to unblock it by resolving these conflicts. Thanks! # label to monitor - mergeLabel: "PR action: merge" + mergeLabel: 'action: merge' # list of checks that will determine if the merge label can be added checks: @@ -26,81 +28,65 @@ merge: noConflict: true # whether the PR should have all reviews completed. requireReviews: true - # list of labels that a PR needs to have, checked with a regexp (e.g. "PR target:" will work for the label "PR target: master") + # list of labels that a PR needs to have, checked with a regexp (e.g. "target:" will work for the label "target: major") requiredLabels: - - "PR target: *" - - "cla: yes" + - 'target: *' # list of labels that a PR shouldn't have, checked after the required labels with a regexp forbiddenLabels: - - "PR target: TBD" - - "PR action: cleanup" - - "PR action: review" - - "PR state: blocked" - - "cla: no" + - 'action: cleanup' + - 'action: review' + - 'PR state: blocked' # list of PR statuses that need to be successful - requiredStatuses: - - "ci/circleci: build" - - "ci/circleci: build-bazel" - - "ci/circleci: setup" - - "ci/circleci: setup-and-build-win" - - "ci/circleci: lint" - - "ci/circleci: validate" - - "ci/circleci: test" - - "ci/circleci: test-win" - - "ci/circleci: test-large" - - "ci/circleci: test-large-ve" - - "ci/circleci: e2e-cli" - - "ci/circleci: e2e-cli-ve" - - "ci/circleci: test-browsers" - - "ci/angular: size" - - "cla/google" + # NOTE: Required PR statuses are now exclusively handled via Github configuration + requiredStatuses: [] # the comment that will be added when the merge label is added despite failing checks, leave empty or set to false to disable # {{MERGE_LABEL}} will be replaced by the value of the mergeLabel option # {{PLACEHOLDER}} will be replaced by the list of failing checks - mergeRemovedComment: "I see that you just added the `{{MERGE_LABEL}}` label, but the following checks are still failing: -\n{{PLACEHOLDER}} -\n -\n**If you want your PR to be merged, it has to pass all the CI checks.** -\n -\nIf you can't get the PR to a green state due to flakes or broken master, please try rebasing to master and/or restarting the CI job. If that fails and you believe that the issue is not due to your change, please contact the caretaker and ask for help." + mergeRemovedComment: >- + I see that you just added the `{{MERGE_LABEL}}` label, but the following + checks are still failing: + + {{PLACEHOLDER}} + + **If you want your PR to be merged, it has to pass all the CI checks.** + If you can't get the PR to a green state due to flakes or broken `main`, + please try rebasing to `main` and/or restarting the CI job. If that fails + and you believe that the issue is not due to your change, please contact the + caretaker and ask for help. # options for the triage plugin triage: # set to true to disable - disabled: false + disabled: true # number of the milestone to apply when the issue has not been triaged yet needsTriageMilestone: 11, # number of the milestone to apply when the issue is triaged defaultMilestone: 12, # arrays of labels that determine if an issue has been triaged by the caretaker l1TriageLabels: - - - - "comp: *" + - - 'area: *' # arrays of labels that determine if an issue has been fully triaged l2TriageLabels: - - - - "type: bug/fix" - - "severity*" - - "freq*" - - "comp: *" - - - - "type: feature" - - "comp: *" - - - - "type: refactor" - - "comp: *" - - - - "type: RFC / Discussion / question" - - "comp: *" - - - - "type: docs" - - "comp: *" + - - 'type: bug/fix' + - 'severity*' + - 'freq*' + - 'area: *' + - - 'type: feature' + - 'area: *' + - - 'type: refactor' + - 'area: *' + - - 'type: RFC / Discussion / question' + - 'area: *' + - - 'type: docs' + - 'area: *' # Size checking size: - circleCiStatusName: "ci/circleci: e2e-cli" + # Size checking for production build is performed via the E2E test `build/prod-build` + disabled: true + circleCiStatusName: 'ci/circleci: e2e-cli' maxSizeIncrease: 10000 comment: false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000000..a01353b6bcf0 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 + +updates: + - package-ecosystem: 'npm' + directory: '/' + schedule: + interval: 'daily' + commit-message: + prefix: 'build' + labels: + - 'area: build & ci' + - 'target: patch' + - 'action: merge' + # Disable version updates + # This does not affect security updates + open-pull-requests-limit: 0 diff --git a/.github/shared-actions/windows-bazel-test/action.yml b/.github/shared-actions/windows-bazel-test/action.yml new file mode 100644 index 000000000000..7a5cf7c0297b --- /dev/null +++ b/.github/shared-actions/windows-bazel-test/action.yml @@ -0,0 +1,42 @@ +name: Native Windows Bazel E2E test +description: Runs an Angular CLI e2e Bazel test on native Windows +author: Angular + +inputs: + test_target_name: + description: E2E test target name. + required: true + e2e_temp_dir: + description: 'The temporary directory path for E2E tests.' + required: false + # Use D:\\ by default as it's much faster + # See: https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows + default: 'D:\\tmp_dir' + +runs: + using: 'composite' + steps: + - name: Set up temp directory + shell: bash + run: | + mkdir ${{ inputs.e2e_temp_dir }} + + - name: Convert symlinks for Windows host + shell: pwsh + run: | + $runfiles_dir = "./dist/bin/tests/${{inputs.test_target_name}}_/${{inputs.test_target_name}}.bat.runfiles" + + # Needed for resolution because Aspect/Bazel looks for repositories at `/external`. + # TODO(devversion): consult with Aspect on why this is needed. + Set-Location -Path "${runfiles_dir}\_main" + New-Item -ItemType SymbolicLink -Path "external" -Target ".." + + - name: Run CLI E2E tests + shell: bash + env: + BAZEL_BINDIR: '.' + E2E_TEMP: ${{ inputs.e2e_temp_dir }} + run: | + node ./scripts/windows-testing/parallel-executor.mjs \ + "./dist/bin/tests/${{ inputs.test_target_name }}_/${{ inputs.test_target_name }}.bat.runfiles" \ + ${{ inputs.test_target_name }} diff --git a/.github/workflows/assistant-to-the-branch-manager.yml b/.github/workflows/assistant-to-the-branch-manager.yml new file mode 100644 index 000000000000..88ab0c9cb883 --- /dev/null +++ b/.github/workflows/assistant-to-the-branch-manager.yml @@ -0,0 +1,23 @@ +name: DevInfra + +on: + push: + # zizmor: ignore[dangerous-triggers] - {Trigger is safe as workflow does not checkout untrusted code} + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review, labeled] + +# Declare default permissions as read only. +permissions: + contents: read + +jobs: + assistant_to_the_branch_manager: + runs-on: ubuntu-latest + if: github.event.repository.fork == false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: angular/dev-infra/github-actions/branch-manager@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000000..9b75f6085731 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,256 @@ +name: CI + +on: + push: + branches: + - main + - '[0-9]+.[0-9]+.x' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: {} + +defaults: + run: + shell: bash + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Generate JSON schema types + # Schema types are required to correctly lint the TypeScript code + run: pnpm run build-schema + - name: Run ESLint + run: pnpm lint --cache-strategy content + - name: Validate NgBot Configuration + run: pnpm ng-dev ngbot verify + - name: Validate Circular Dependencies + run: pnpm ts-circular-deps check + - name: Run Validation + run: pnpm admin validate + - name: Check tooling setup + run: pnpm check-tooling-setup + + build: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build release targets + run: pnpm ng-dev release build + + test: + needs: build + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Run module and package tests + run: pnpm bazel test -- //... -//tests/... + + e2e: + needs: test + strategy: + fail-fast: false + matrix: + node: [22, 24, 26] + subset: [esbuild, webpack] + shard: [0, 1, 2, 3, 4, 5] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + build-e2e-windows: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build E2E tests for Windows on Linux + run: | + pnpm bazel build \ + --config=e2e \ + //tests:e2e.webpack_node24 \ + //tests:e2e.esbuild_node24 \ + --platforms=tools:windows_x64 \ + --enable_runfiles + - name: Store built Windows E2E tests + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: win-e2e-build-artifacts + path: | + dist/bin/tests/** + !**/node_modules/** + retention-days: 1 + if-no-files-found: 'error' + + e2e-windows: + needs: build-e2e-windows + strategy: + fail-fast: false + matrix: + node: [24] + subset: [esbuild, webpack] + shard: [0, 1, 2, 3, 4, 5] + runs-on: windows-2025 + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Download built Windows E2E tests + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: win-e2e-build-artifacts + path: dist/bin/tests/ + - name: Run CLI E2E tests + uses: ./.github/shared-actions/windows-bazel-test + with: + test_target_name: e2e.${{ matrix.subset }}_node${{ matrix.node }} + env: + E2E_SHARD_TOTAL: 6 + E2E_SHARD_INDEX: ${{ matrix.shard }} + + e2e-package-managers: + needs: test + strategy: + fail-fast: false + matrix: + node: [22] + subset: [yarn, pnpm, bun] + shard: [0, 1, 2] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + e2e-snapshots: + needs: test + if: github.ref == 'refs/heads/main' + strategy: + fail-fast: false + matrix: + node: [22] + subset: [esbuild, webpack] + shard: [0, 1, 2, 3, 4, 5] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} + + browsers: + needs: build + runs-on: ubuntu-latest + name: Browser Compatibility Tests + env: + SAUCE_TUNNEL_IDENTIFIER: angular-cli-${{ github.workflow }}-${{ github.run_number }} + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Start Sauce Connect + uses: saucelabs/sauce-connect-action@cb88b508c6f9ff4d84490093733315dbd55de022 # v3 + timeout-minutes: 10 + with: + username: ${{ vars.SAUCE_USERNAME }} + accessKey: ${{ secrets.SAUCE_ACCESS_KEY }} + region: us-west-1 + tunnelName: ${{ env.SAUCE_TUNNEL_IDENTIFIER }} + proxyLocalhost: allow + # By default we disable SSL bumping for all requests. This is because SSL bumping is not needed + # for our test setup and in order to perform the SSL bumping, Saucelabs intercepts all HTTP + # requests in the tunnel VM and modifies them. This can cause flakiness as it makes all requests + # dependent on the SSL bumping middleware. + # See: https://wiki.saucelabs.com/display/DOCS/Troubleshooting+Sauce+Connect#TroubleshootingSauceConnect-DisablingSSLBumping + tlsPassthroughDomains: all + - name: Run E2E Browser tests + env: + SAUCE_USERNAME: ${{ vars.SAUCE_USERNAME }} + SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }} + run: pnpm bazel test --config=saucelabs //tests:e2e.saucelabs + + publish-snapshots: + needs: build + runs-on: ubuntu-latest + env: + CIRCLE_BRANCH: ${{ github.ref_name }} + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - run: pnpm admin snapshots --verbose + env: + SNAPSHOT_BUILDS_GITHUB_TOKEN: ${{ secrets.SNAPSHOT_BUILDS_GITHUB_TOKEN }} diff --git a/.github/workflows/dev-infra.yml b/.github/workflows/dev-infra.yml new file mode 100644 index 000000000000..9785ed13b344 --- /dev/null +++ b/.github/workflows/dev-infra.yml @@ -0,0 +1,36 @@ +name: DevInfra + +on: + # zizmor: ignore[dangerous-triggers] - {Trigger is safe as workflow does not checkout untrusted code} + pull_request_target: + types: [opened, synchronize, reopened] + issues: + types: [opened, reopened] + +# Declare default permissions as read only. +permissions: + contents: read + +jobs: + labels: + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: angular/dev-infra/github-actions/labeling/pull-request@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} + post_approval_changes: + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + steps: + - uses: angular/dev-infra/github-actions/post-approval-changes@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} + issue_labels: + if: github.event_name == 'issues' + runs-on: ubuntu-latest + steps: + - uses: angular/dev-infra/github-actions/labeling/issue@aba3adc53489fee586e2375ee4367ff30c947390 # main + with: + angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} + google-generative-ai-key: ${{ secrets.GOOGLE_GENERATIVE_AI_KEY }} diff --git a/.github/workflows/lock-closed.yml b/.github/workflows/lock-closed.yml deleted file mode 100644 index 2bc90deaeef2..000000000000 --- a/.github/workflows/lock-closed.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: Lock Inactive Issues - -on: - schedule: - # Run at 08:00 every day - - cron: '0 8 * * *' - -jobs: - lock_closed: - runs-on: ubuntu-latest - steps: - - uses: angular/dev-infra/github-actions/lock-closed@a4fd924 - with: - lock-bot-key: ${{ secrets.LOCK_BOT_PRIVATE_KEY }} diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml new file mode 100644 index 000000000000..5e15103a56b2 --- /dev/null +++ b/.github/workflows/perf.yml @@ -0,0 +1,60 @@ +name: Performance Tracking + +on: + push: + branches: + - main + # Run workflows for all releasable branches + - '[0-9]+.[0-9]+.x' + +permissions: + contents: 'read' + +defaults: + run: + shell: bash + +jobs: + list: + timeout-minutes: 3 + runs-on: ubuntu-latest + outputs: + workflows: ${{ steps.workflows.outputs.workflows }} + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - id: workflows + run: echo "workflows=$(pnpm --silent ng-dev perf workflows --list)" >> "$GITHUB_OUTPUT" + + workflow: + timeout-minutes: 30 + runs-on: ubuntu-latest + needs: list + permissions: + contents: 'read' + id-token: 'write' + strategy: + matrix: + workflow: ${{ fromJSON(needs.list.outputs.workflows) }} + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + # We utilize the google-github-actions/auth action to allow us to get an active credential using workflow + # identity federation. This allows us to request short lived credentials on demand, rather than storing + # credentials in secrets long term. More information can be found at: + # https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-google-cloud-platform + - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 + with: + project_id: 'internal-200822' + workload_identity_provider: 'projects/823469418460/locations/global/workloadIdentityPools/measurables-tracking/providers/angular' + service_account: 'measures-uploader@internal-200822.iam.gserviceaccount.com' + - run: pnpm ng-dev perf workflows --name "$WORKFLOW" --commit-sha "$COMMIT_SHA" + env: + WORKFLOW: ${{ matrix.workflow }} + COMMIT_SHA: ${{ github.sha }} diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 000000000000..c47d653e9721 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,217 @@ +name: Pull Request + +on: + pull_request: + types: [opened, synchronize, reopened] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: {} + +defaults: + run: + shell: bash + +jobs: + analyze: + runs-on: ubuntu-latest + outputs: + snapshots: ${{ steps.filter.outputs.snapshots }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + id: filter + with: + filters: | + snapshots: + - 'tests/e2e/ng-snapshot/package.json' + + lint: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup ESLint Caching + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .eslintcache + key: ${{ runner.os }}-${{ hashFiles('.eslintrc.json') }} + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Generate JSON schema types + # Schema types are required to correctly lint the TypeScript code + run: pnpm run build-schema + - name: Run ESLint + run: pnpm lint --cache-strategy content + - name: Validate NgBot Configuration + run: pnpm ng-dev ngbot verify + - name: Validate Circular Dependencies + run: pnpm ts-circular-deps check + - name: Run Validation + run: pnpm admin validate + - name: Check tooling setup + run: pnpm check-tooling-setup + - name: Check commit message + # Commit message validation is only done on pull requests as its too late to validate once + # it has been merged. + run: pnpm ng-dev commit-message validate-range ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} + - name: Check code format + # Code formatting checks are only done on pull requests as its too late to validate once + # it has been merged. + run: pnpm ng-dev format changed --check ${{ github.event.pull_request.base.sha }} + - name: Check Package Licenses + uses: angular/dev-infra/github-actions/linting/licenses@aba3adc53489fee586e2375ee4367ff30c947390 # main + + build: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build release targets + run: pnpm ng-dev release build + - name: Store PR release packages + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: packages + path: dist/releases/*.tgz + retention-days: 14 + + test: + needs: build + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Run module and package tests + run: pnpm bazel test -- //... -//tests/... + + e2e: + needs: build + strategy: + fail-fast: false + matrix: + node: [22] + subset: [esbuild, webpack] + shard: [0, 1, 2, 3, 4, 5] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + build-e2e-windows-subset: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build E2E tests for Windows on Linux + run: | + pnpm bazel build \ + --config=e2e \ + //tests:e2e.esbuild_node24 \ + --platforms=tools:windows_x64 \ + --enable_runfiles + - name: Store built Windows E2E tests + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: win-e2e-build-artifacts + path: | + dist/bin/tests/** + !**/node_modules/** + retention-days: 1 + if-no-files-found: 'error' + + e2e-windows-subset: + needs: build-e2e-windows-subset + runs-on: windows-2025 + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Download built Windows E2E tests + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: win-e2e-build-artifacts + path: dist/bin/tests/ + - name: Run CLI E2E tests + uses: ./.github/shared-actions/windows-bazel-test + with: + test_target_name: e2e.esbuild_node24 + env: + E2E_SHARD_TOTAL: 1 + TESTBRIDGE_TEST_ONLY: tests/basic/{build,rebuild,serve}.ts + + e2e-package-managers: + needs: build + strategy: + fail-fast: false + matrix: + node: [22] + subset: [yarn, pnpm, bun] + shard: [0, 1, 2] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + e2e-snapshots: + needs: [analyze, build] + if: needs.analyze.outputs.snapshots == 'true' + strategy: + fail-fast: false + matrix: + node: [22] + subset: [esbuild, webpack] + shard: [0, 1, 2, 3, 4, 5] + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@aba3adc53489fee586e2375ee4367ff30c947390 # main + - name: Run CLI E2E tests + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} diff --git a/.gitignore b/.gitignore index 1be6585d718b..83582f8ece43 100644 --- a/.gitignore +++ b/.gitignore @@ -4,11 +4,22 @@ test-project-host-* dist/ dist-schema/ +# Yarn +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + # IDEs jsconfig.json # Intellij IDEA/WebStorm # https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 +.idea/inspectionProfiles/ +.idea/**/compiler.xml +.idea/**/encodings.xml .idea/**/workspace.xml .idea/**/tasks.xml .idea/**/usage.statistics.xml @@ -20,7 +31,7 @@ jsconfig.json # VSCode # https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore -.vscode/ +.vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json @@ -37,6 +48,12 @@ tmp/ npm-debug.log* yarn-error.log* .ng_pkg_build/ +.ng-dev.log +.ng-dev.err*.log +.ng-dev.user* +.husky/_ +.bazelrc.user +.eslintcache # Mac OSX Finder files. **/.DS_Store diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 000000000000..de361903a541 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +pnpm --silent ng-dev commit-message pre-commit-validate --file $1; diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 000000000000..7f9d46b47835 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +pnpm --silent ng-dev format staged; diff --git a/.husky/prepare-commit-msg b/.husky/prepare-commit-msg new file mode 100755 index 000000000000..f4598b6d1b6e --- /dev/null +++ b/.husky/prepare-commit-msg @@ -0,0 +1 @@ +pnpm --silent ng-dev commit-message restore-commit-message-draft $1 $2; diff --git a/.idea/angular-cli.iml b/.idea/angular-cli.iml deleted file mode 100644 index 06c7515c99ff..000000000000 --- a/.idea/angular-cli.iml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 28a804d8932a..000000000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 6d8c965387b0..000000000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/.idea/runConfigurations/Large_Tests.xml b/.idea/runConfigurations/Large_Tests.xml deleted file mode 100644 index 3d4f25fb3a76..000000000000 --- a/.idea/runConfigurations/Large_Tests.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - diff --git a/etc/cli.angular.io/license.html b/etc/cli.angular.io/license.html deleted file mode 100644 index 0131cc303c40..000000000000 --- a/etc/cli.angular.io/license.html +++ /dev/null @@ -1,23 +0,0 @@ -
The MIT License
-
-Copyright (c) Google, Inc. All Rights Reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-
- diff --git a/etc/cli.angular.io/main.css b/etc/cli.angular.io/main.css deleted file mode 100644 index 61b0cb066543..000000000000 --- a/etc/cli.angular.io/main.css +++ /dev/null @@ -1 +0,0 @@ -body{font-family:"Roboto",Helvetica,sans-serif}h4,h5{font-size:30px;font-weight:400;line-height:40px;margin-bottom:15px;margin-top:15px}h5{font-size:16px;font-weight:300;line-height:28px;margin-bottom:25px;max-width:300px}.mdl-demo section.section--center{max-width:920px}.mdl-grid--no-spacing>.mdl-cell{width:100%}.mdl-layout--fixed-drawer>.mdl-layout__content{margin-left:0}.mdl-layout__header{background-color:#f44336;box-shadow:0 2px 5px 0 rgba(0,0,0,.26)}.mdl-layout__header a{color:#fff;text-decoration:none}.mdl-layout--fixed-drawer.is-upgraded:not(.is-small-screen)>.mdl-layout__header{margin-left:0;width:100%}.mdl-layout--fixed-drawer>.mdl-layout__header .mdl-layout__header-row{padding-left:25px;padding-right:0}.mdl-layout__drawer-button,.top-nav-wrapper label{display:none}@media (max-width:1024px){.mdl-layout__drawer-button{display:inline-block}}.mdl-layout__drawer{margin-top:65px;height:calc(100% - 65px)}@media (max-width:1024px){.mdl-layout__drawer{margin-top:0;height:100%}}.mdl-layout-title,.mdl-layout__title{font-size:16px;line-height:28px;letter-spacing:.02em}.microsite-name{display:inline-block;font-size:20px;margin-left:8px;margin-right:30px;text-transform:uppercase;-webkit-transform:translateY(3px);transform:translateY(3px)}.mdl-navigation__link{font-size:16px;text-transform:uppercase;text-decoration:none}.mdl-navigation__link:hover,.top-nav-wrapper label:hover{background-color:#d32f2f}.top-nav-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1}@media (max-width:800px){.top-nav-wrapper{display:block;position:absolute;right:0;top:0;width:100%}.top-nav-wrapper label{cursor:pointer;display:block;float:right;line-height:56px;padding:0 16px}.top-nav-wrapper nav{background:#d32f2f;clear:both;display:none;height:auto!important}.top-nav-wrapper nav a{display:block}.top-nav-wrapper .mdl-layout-spacer{display:none}input:checked+.top-nav-wrapper label{background:#d32f2f}input:checked+.top-nav-wrapper nav{display:block}}.hero-background{background:-webkit-linear-gradient(#d32f2f ,#f44336);background:linear-gradient(#d32f2f ,#f44336);color:#fff;margin-bottom:60px}.mdl-grid,.mdl-mega-footer--bottom-section .mdl-cell--9-col{-webkit-box-align:center;-ms-flex-align:center;align-items:center}.hero-container{padding:56px 0!important}@media (max-width:830px){.hero-container{text-align:center}}.logo-container{overflow:hidden;text-align:center}@media (max-width:840px){.tagline{max-width:100%}}.mdl-button{height:45px;line-height:45px;min-width:140px;padding:0 30px}.mdl-button--primary.mdl-button--primary.mdl-button--fab,.mdl-button--primary.mdl-button--primary.mdl-button--raised{background-color:#fff;color:#b71c1c}.features-list{width:920px;margin:0 0 23px;padding:15px 200px 15px 15px}@media (max-width:840px){.features-list{padding-right:15px}}.features-list h4{color:#37474f;font-size:28px;font-weight:500;line-height:32px;margin:0 0 16px;opacity:.87}.features-list p,footer ul a{font-size:16px;line-height:30px;opacity:.87}.button-container{margin-bottom:24px!important;text-align:center}.mdl-button--accent.mdl-button--accent.mdl-button--fab,.mdl-button--accent.mdl-button--accent.mdl-button--raised{background-color:#f44336;color:#fff}.mdl-mega-footer--bottom-section .mdl-cell--9-col{-webkit-box-pack:end;-ms-flex-pack:end;justify-content:flex-end;display:-webkit-box;display:-ms-flexbox;display:flex}.mdl-mega-footer--bottom-section,.mdl-mega-footer__bottom-section{background-color:#263238;bottom:0;color:#fff;padding-top:0;right:0}footer ul{font-size:14px;font-weight:400;letter-spacing:0;line-height:24px;list-style:none;padding:0}footer ul a{color:#fff;line-height:28px;padding:0;text-decoration:none}footer ul a:hover{text-decoration:underline}@media (max-width:830px){footer ul{background-color:rgba(0,0,0,.12);padding:8px;text-align:center}}.mdl-mega-footer--bottom-section{margin-bottom:0}.mdl-mega-footer--bottom-section p{font-size:12px;margin:0;opacity:.54}.mdl-mega-footer--bottom-section a{color:#fff;font-weight:400;padding:0;text-decoration:none}.power-text{text-align:right}@media (max-width:830px){.power-text{text-align:center;width:calc(100% - 16px)}}.mdl-base{height:100vh} diff --git a/etc/cli.angular.io/material.min.css b/etc/cli.angular.io/material.min.css deleted file mode 100644 index e750f8137205..000000000000 --- a/etc/cli.angular.io/material.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/** - * material-design-lite - Material Design Components in CSS, JS and HTML - * @version v1.1.3 - * @license Apache-2.0 - * @copyright 2015 Google, Inc. - * @link https://github.com/google/material-design-lite - */ -@charset "UTF-8";html{color:rgba(0,0,0,.87)}::-moz-selection{background:#b3d4fc;text-shadow:none}::selection{background:#b3d4fc;text-shadow:none}hr{display:block;height:1px;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0}audio,canvas,iframe,img,svg,video{vertical-align:middle}fieldset{border:0;margin:0;padding:0}textarea{resize:vertical}.browserupgrade{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.hidden{display:none!important}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}@media print{*,*:before,*:after,*:first-letter{background:transparent!important;color:#000!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href)")"}abbr[title]:after{content:" (" attr(title)")"}a[href^="#"]:after,a[href^="javascript:"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}a,.mdl-accordion,.mdl-button,.mdl-card,.mdl-checkbox,.mdl-dropdown-menu,.mdl-icon-toggle,.mdl-item,.mdl-radio,.mdl-slider,.mdl-switch,.mdl-tabs__tab{-webkit-tap-highlight-color:transparent;-webkit-tap-highlight-color:rgba(255,255,255,0)}html{width:100%;height:100%;-ms-touch-action:manipulation;touch-action:manipulation}body{width:100%;min-height:100%;margin:0}main{display:block}*[hidden]{display:none!important}html,body{font-family:"Helvetica","Arial",sans-serif;font-size:14px;font-weight:400;line-height:20px}h1,h2,h3,h4,h5,h6,p{padding:0}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-family:"Roboto","Helvetica","Arial",sans-serif;font-weight:400;line-height:1.35;letter-spacing:-.02em;opacity:.54;font-size:.6em}h1{font-size:56px;line-height:1.35;letter-spacing:-.02em;margin:24px 0}h1,h2{font-family:"Roboto","Helvetica","Arial",sans-serif;font-weight:400}h2{font-size:45px;line-height:48px}h2,h3{margin:24px 0}h3{font-size:34px;line-height:40px}h3,h4{font-family:"Roboto","Helvetica","Arial",sans-serif;font-weight:400}h4{font-size:24px;line-height:32px;-moz-osx-font-smoothing:grayscale;margin:24px 0 16px}h5{font-size:20px;font-weight:500;line-height:1;letter-spacing:.02em}h5,h6{font-family:"Roboto","Helvetica","Arial",sans-serif;margin:24px 0 16px}h6{font-size:16px;letter-spacing:.04em}h6,p{font-weight:400;line-height:24px}p{font-size:14px;letter-spacing:0;margin:0 0 16px}a{color:#ff4081;font-weight:500}blockquote{font-family:"Roboto","Helvetica","Arial",sans-serif;position:relative;font-size:24px;font-weight:300;font-style:italic;line-height:1.35;letter-spacing:.08em}blockquote:before{position:absolute;left:-.5em;content:'“'}blockquote:after{content:'”';margin-left:-.05em}mark{background-color:#f4ff81}dt{font-weight:700}address{font-size:12px;line-height:1;font-style:normal}address,ul,ol{font-weight:400;letter-spacing:0}ul,ol{font-size:14px;line-height:24px}.mdl-typography--display-4,.mdl-typography--display-4-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:112px;font-weight:300;line-height:1;letter-spacing:-.04em}.mdl-typography--display-4-color-contrast{opacity:.54}.mdl-typography--display-3,.mdl-typography--display-3-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:56px;font-weight:400;line-height:1.35;letter-spacing:-.02em}.mdl-typography--display-3-color-contrast{opacity:.54}.mdl-typography--display-2,.mdl-typography--display-2-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:45px;font-weight:400;line-height:48px}.mdl-typography--display-2-color-contrast{opacity:.54}.mdl-typography--display-1,.mdl-typography--display-1-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:34px;font-weight:400;line-height:40px}.mdl-typography--display-1-color-contrast{opacity:.54}.mdl-typography--headline,.mdl-typography--headline-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:24px;font-weight:400;line-height:32px;-moz-osx-font-smoothing:grayscale}.mdl-typography--headline-color-contrast{opacity:.87}.mdl-typography--title,.mdl-typography--title-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:20px;font-weight:500;line-height:1;letter-spacing:.02em}.mdl-typography--title-color-contrast{opacity:.87}.mdl-typography--subhead,.mdl-typography--subhead-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:16px;font-weight:400;line-height:24px;letter-spacing:.04em}.mdl-typography--subhead-color-contrast{opacity:.87}.mdl-typography--body-2,.mdl-typography--body-2-color-contrast{font-size:14px;font-weight:700;line-height:24px;letter-spacing:0}.mdl-typography--body-2-color-contrast{opacity:.87}.mdl-typography--body-1,.mdl-typography--body-1-color-contrast{font-size:14px;font-weight:400;line-height:24px;letter-spacing:0}.mdl-typography--body-1-color-contrast{opacity:.87}.mdl-typography--body-2-force-preferred-font,.mdl-typography--body-2-force-preferred-font-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:14px;font-weight:500;line-height:24px;letter-spacing:0}.mdl-typography--body-2-force-preferred-font-color-contrast{opacity:.87}.mdl-typography--body-1-force-preferred-font,.mdl-typography--body-1-force-preferred-font-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:14px;font-weight:400;line-height:24px;letter-spacing:0}.mdl-typography--body-1-force-preferred-font-color-contrast{opacity:.87}.mdl-typography--caption,.mdl-typography--caption-force-preferred-font{font-size:12px;font-weight:400;line-height:1;letter-spacing:0}.mdl-typography--caption-force-preferred-font{font-family:"Roboto","Helvetica","Arial",sans-serif}.mdl-typography--caption-color-contrast,.mdl-typography--caption-force-preferred-font-color-contrast{font-size:12px;font-weight:400;line-height:1;letter-spacing:0;opacity:.54}.mdl-typography--caption-force-preferred-font-color-contrast,.mdl-typography--menu{font-family:"Roboto","Helvetica","Arial",sans-serif}.mdl-typography--menu{font-size:14px;font-weight:500;line-height:1;letter-spacing:0}.mdl-typography--menu-color-contrast{opacity:.87}.mdl-typography--menu-color-contrast,.mdl-typography--button,.mdl-typography--button-color-contrast{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:14px;font-weight:500;line-height:1;letter-spacing:0}.mdl-typography--button,.mdl-typography--button-color-contrast{text-transform:uppercase}.mdl-typography--button-color-contrast{opacity:.87}.mdl-typography--text-left{text-align:left}.mdl-typography--text-right{text-align:right}.mdl-typography--text-center{text-align:center}.mdl-typography--text-justify{text-align:justify}.mdl-typography--text-nowrap{white-space:nowrap}.mdl-typography--text-lowercase{text-transform:lowercase}.mdl-typography--text-uppercase{text-transform:uppercase}.mdl-typography--text-capitalize{text-transform:capitalize}.mdl-typography--font-thin{font-weight:200!important}.mdl-typography--font-light{font-weight:300!important}.mdl-typography--font-regular{font-weight:400!important}.mdl-typography--font-medium{font-weight:500!important}.mdl-typography--font-bold{font-weight:700!important}.mdl-typography--font-black{font-weight:900!important}.material-icons{font-family:'Material Icons';font-weight:400;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;word-wrap:normal;-moz-font-feature-settings:'liga';font-feature-settings:'liga';-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}.mdl-color-text--red{color:#f44336 !important}.mdl-color--red{background-color:#f44336 !important}.mdl-color-text--red-50{color:#ffebee !important}.mdl-color--red-50{background-color:#ffebee !important}.mdl-color-text--red-100{color:#ffcdd2 !important}.mdl-color--red-100{background-color:#ffcdd2 !important}.mdl-color-text--red-200{color:#ef9a9a !important}.mdl-color--red-200{background-color:#ef9a9a !important}.mdl-color-text--red-300{color:#e57373 !important}.mdl-color--red-300{background-color:#e57373 !important}.mdl-color-text--red-400{color:#ef5350 !important}.mdl-color--red-400{background-color:#ef5350 !important}.mdl-color-text--red-500{color:#f44336 !important}.mdl-color--red-500{background-color:#f44336 !important}.mdl-color-text--red-600{color:#e53935 !important}.mdl-color--red-600{background-color:#e53935 !important}.mdl-color-text--red-700{color:#d32f2f !important}.mdl-color--red-700{background-color:#d32f2f !important}.mdl-color-text--red-800{color:#c62828 !important}.mdl-color--red-800{background-color:#c62828 !important}.mdl-color-text--red-900{color:#b71c1c !important}.mdl-color--red-900{background-color:#b71c1c !important}.mdl-color-text--red-A100{color:#ff8a80 !important}.mdl-color--red-A100{background-color:#ff8a80 !important}.mdl-color-text--red-A200{color:#ff5252 !important}.mdl-color--red-A200{background-color:#ff5252 !important}.mdl-color-text--red-A400{color:#ff1744 !important}.mdl-color--red-A400{background-color:#ff1744 !important}.mdl-color-text--red-A700{color:#d50000 !important}.mdl-color--red-A700{background-color:#d50000 !important}.mdl-color-text--pink{color:#e91e63 !important}.mdl-color--pink{background-color:#e91e63 !important}.mdl-color-text--pink-50{color:#fce4ec !important}.mdl-color--pink-50{background-color:#fce4ec !important}.mdl-color-text--pink-100{color:#f8bbd0 !important}.mdl-color--pink-100{background-color:#f8bbd0 !important}.mdl-color-text--pink-200{color:#f48fb1 !important}.mdl-color--pink-200{background-color:#f48fb1 !important}.mdl-color-text--pink-300{color:#f06292 !important}.mdl-color--pink-300{background-color:#f06292 !important}.mdl-color-text--pink-400{color:#ec407a !important}.mdl-color--pink-400{background-color:#ec407a !important}.mdl-color-text--pink-500{color:#e91e63 !important}.mdl-color--pink-500{background-color:#e91e63 !important}.mdl-color-text--pink-600{color:#d81b60 !important}.mdl-color--pink-600{background-color:#d81b60 !important}.mdl-color-text--pink-700{color:#c2185b !important}.mdl-color--pink-700{background-color:#c2185b !important}.mdl-color-text--pink-800{color:#ad1457 !important}.mdl-color--pink-800{background-color:#ad1457 !important}.mdl-color-text--pink-900{color:#880e4f !important}.mdl-color--pink-900{background-color:#880e4f !important}.mdl-color-text--pink-A100{color:#ff80ab !important}.mdl-color--pink-A100{background-color:#ff80ab !important}.mdl-color-text--pink-A200{color:#ff4081 !important}.mdl-color--pink-A200{background-color:#ff4081 !important}.mdl-color-text--pink-A400{color:#f50057 !important}.mdl-color--pink-A400{background-color:#f50057 !important}.mdl-color-text--pink-A700{color:#c51162 !important}.mdl-color--pink-A700{background-color:#c51162 !important}.mdl-color-text--purple{color:#9c27b0 !important}.mdl-color--purple{background-color:#9c27b0 !important}.mdl-color-text--purple-50{color:#f3e5f5 !important}.mdl-color--purple-50{background-color:#f3e5f5 !important}.mdl-color-text--purple-100{color:#e1bee7 !important}.mdl-color--purple-100{background-color:#e1bee7 !important}.mdl-color-text--purple-200{color:#ce93d8 !important}.mdl-color--purple-200{background-color:#ce93d8 !important}.mdl-color-text--purple-300{color:#ba68c8 !important}.mdl-color--purple-300{background-color:#ba68c8 !important}.mdl-color-text--purple-400{color:#ab47bc !important}.mdl-color--purple-400{background-color:#ab47bc !important}.mdl-color-text--purple-500{color:#9c27b0 !important}.mdl-color--purple-500{background-color:#9c27b0 !important}.mdl-color-text--purple-600{color:#8e24aa !important}.mdl-color--purple-600{background-color:#8e24aa !important}.mdl-color-text--purple-700{color:#7b1fa2 !important}.mdl-color--purple-700{background-color:#7b1fa2 !important}.mdl-color-text--purple-800{color:#6a1b9a !important}.mdl-color--purple-800{background-color:#6a1b9a !important}.mdl-color-text--purple-900{color:#4a148c !important}.mdl-color--purple-900{background-color:#4a148c !important}.mdl-color-text--purple-A100{color:#ea80fc !important}.mdl-color--purple-A100{background-color:#ea80fc !important}.mdl-color-text--purple-A200{color:#e040fb !important}.mdl-color--purple-A200{background-color:#e040fb !important}.mdl-color-text--purple-A400{color:#d500f9 !important}.mdl-color--purple-A400{background-color:#d500f9 !important}.mdl-color-text--purple-A700{color:#a0f !important}.mdl-color--purple-A700{background-color:#a0f !important}.mdl-color-text--deep-purple{color:#673ab7 !important}.mdl-color--deep-purple{background-color:#673ab7 !important}.mdl-color-text--deep-purple-50{color:#ede7f6 !important}.mdl-color--deep-purple-50{background-color:#ede7f6 !important}.mdl-color-text--deep-purple-100{color:#d1c4e9 !important}.mdl-color--deep-purple-100{background-color:#d1c4e9 !important}.mdl-color-text--deep-purple-200{color:#b39ddb !important}.mdl-color--deep-purple-200{background-color:#b39ddb !important}.mdl-color-text--deep-purple-300{color:#9575cd !important}.mdl-color--deep-purple-300{background-color:#9575cd !important}.mdl-color-text--deep-purple-400{color:#7e57c2 !important}.mdl-color--deep-purple-400{background-color:#7e57c2 !important}.mdl-color-text--deep-purple-500{color:#673ab7 !important}.mdl-color--deep-purple-500{background-color:#673ab7 !important}.mdl-color-text--deep-purple-600{color:#5e35b1 !important}.mdl-color--deep-purple-600{background-color:#5e35b1 !important}.mdl-color-text--deep-purple-700{color:#512da8 !important}.mdl-color--deep-purple-700{background-color:#512da8 !important}.mdl-color-text--deep-purple-800{color:#4527a0 !important}.mdl-color--deep-purple-800{background-color:#4527a0 !important}.mdl-color-text--deep-purple-900{color:#311b92 !important}.mdl-color--deep-purple-900{background-color:#311b92 !important}.mdl-color-text--deep-purple-A100{color:#b388ff !important}.mdl-color--deep-purple-A100{background-color:#b388ff !important}.mdl-color-text--deep-purple-A200{color:#7c4dff !important}.mdl-color--deep-purple-A200{background-color:#7c4dff !important}.mdl-color-text--deep-purple-A400{color:#651fff !important}.mdl-color--deep-purple-A400{background-color:#651fff !important}.mdl-color-text--deep-purple-A700{color:#6200ea !important}.mdl-color--deep-purple-A700{background-color:#6200ea !important}.mdl-color-text--indigo{color:#3f51b5 !important}.mdl-color--indigo{background-color:#3f51b5 !important}.mdl-color-text--indigo-50{color:#e8eaf6 !important}.mdl-color--indigo-50{background-color:#e8eaf6 !important}.mdl-color-text--indigo-100{color:#c5cae9 !important}.mdl-color--indigo-100{background-color:#c5cae9 !important}.mdl-color-text--indigo-200{color:#9fa8da !important}.mdl-color--indigo-200{background-color:#9fa8da !important}.mdl-color-text--indigo-300{color:#7986cb !important}.mdl-color--indigo-300{background-color:#7986cb !important}.mdl-color-text--indigo-400{color:#5c6bc0 !important}.mdl-color--indigo-400{background-color:#5c6bc0 !important}.mdl-color-text--indigo-500{color:#3f51b5 !important}.mdl-color--indigo-500{background-color:#3f51b5 !important}.mdl-color-text--indigo-600{color:#3949ab !important}.mdl-color--indigo-600{background-color:#3949ab !important}.mdl-color-text--indigo-700{color:#303f9f !important}.mdl-color--indigo-700{background-color:#303f9f !important}.mdl-color-text--indigo-800{color:#283593 !important}.mdl-color--indigo-800{background-color:#283593 !important}.mdl-color-text--indigo-900{color:#1a237e !important}.mdl-color--indigo-900{background-color:#1a237e !important}.mdl-color-text--indigo-A100{color:#8c9eff !important}.mdl-color--indigo-A100{background-color:#8c9eff !important}.mdl-color-text--indigo-A200{color:#536dfe !important}.mdl-color--indigo-A200{background-color:#536dfe !important}.mdl-color-text--indigo-A400{color:#3d5afe !important}.mdl-color--indigo-A400{background-color:#3d5afe !important}.mdl-color-text--indigo-A700{color:#304ffe !important}.mdl-color--indigo-A700{background-color:#304ffe !important}.mdl-color-text--blue{color:#2196f3 !important}.mdl-color--blue{background-color:#2196f3 !important}.mdl-color-text--blue-50{color:#e3f2fd !important}.mdl-color--blue-50{background-color:#e3f2fd !important}.mdl-color-text--blue-100{color:#bbdefb !important}.mdl-color--blue-100{background-color:#bbdefb !important}.mdl-color-text--blue-200{color:#90caf9 !important}.mdl-color--blue-200{background-color:#90caf9 !important}.mdl-color-text--blue-300{color:#64b5f6 !important}.mdl-color--blue-300{background-color:#64b5f6 !important}.mdl-color-text--blue-400{color:#42a5f5 !important}.mdl-color--blue-400{background-color:#42a5f5 !important}.mdl-color-text--blue-500{color:#2196f3 !important}.mdl-color--blue-500{background-color:#2196f3 !important}.mdl-color-text--blue-600{color:#1e88e5 !important}.mdl-color--blue-600{background-color:#1e88e5 !important}.mdl-color-text--blue-700{color:#1976d2 !important}.mdl-color--blue-700{background-color:#1976d2 !important}.mdl-color-text--blue-800{color:#1565c0 !important}.mdl-color--blue-800{background-color:#1565c0 !important}.mdl-color-text--blue-900{color:#0d47a1 !important}.mdl-color--blue-900{background-color:#0d47a1 !important}.mdl-color-text--blue-A100{color:#82b1ff !important}.mdl-color--blue-A100{background-color:#82b1ff !important}.mdl-color-text--blue-A200{color:#448aff !important}.mdl-color--blue-A200{background-color:#448aff !important}.mdl-color-text--blue-A400{color:#2979ff !important}.mdl-color--blue-A400{background-color:#2979ff !important}.mdl-color-text--blue-A700{color:#2962ff !important}.mdl-color--blue-A700{background-color:#2962ff !important}.mdl-color-text--light-blue{color:#03a9f4 !important}.mdl-color--light-blue{background-color:#03a9f4 !important}.mdl-color-text--light-blue-50{color:#e1f5fe !important}.mdl-color--light-blue-50{background-color:#e1f5fe !important}.mdl-color-text--light-blue-100{color:#b3e5fc !important}.mdl-color--light-blue-100{background-color:#b3e5fc !important}.mdl-color-text--light-blue-200{color:#81d4fa !important}.mdl-color--light-blue-200{background-color:#81d4fa !important}.mdl-color-text--light-blue-300{color:#4fc3f7 !important}.mdl-color--light-blue-300{background-color:#4fc3f7 !important}.mdl-color-text--light-blue-400{color:#29b6f6 !important}.mdl-color--light-blue-400{background-color:#29b6f6 !important}.mdl-color-text--light-blue-500{color:#03a9f4 !important}.mdl-color--light-blue-500{background-color:#03a9f4 !important}.mdl-color-text--light-blue-600{color:#039be5 !important}.mdl-color--light-blue-600{background-color:#039be5 !important}.mdl-color-text--light-blue-700{color:#0288d1 !important}.mdl-color--light-blue-700{background-color:#0288d1 !important}.mdl-color-text--light-blue-800{color:#0277bd !important}.mdl-color--light-blue-800{background-color:#0277bd !important}.mdl-color-text--light-blue-900{color:#01579b !important}.mdl-color--light-blue-900{background-color:#01579b !important}.mdl-color-text--light-blue-A100{color:#80d8ff !important}.mdl-color--light-blue-A100{background-color:#80d8ff !important}.mdl-color-text--light-blue-A200{color:#40c4ff !important}.mdl-color--light-blue-A200{background-color:#40c4ff !important}.mdl-color-text--light-blue-A400{color:#00b0ff !important}.mdl-color--light-blue-A400{background-color:#00b0ff !important}.mdl-color-text--light-blue-A700{color:#0091ea !important}.mdl-color--light-blue-A700{background-color:#0091ea !important}.mdl-color-text--cyan{color:#00bcd4 !important}.mdl-color--cyan{background-color:#00bcd4 !important}.mdl-color-text--cyan-50{color:#e0f7fa !important}.mdl-color--cyan-50{background-color:#e0f7fa !important}.mdl-color-text--cyan-100{color:#b2ebf2 !important}.mdl-color--cyan-100{background-color:#b2ebf2 !important}.mdl-color-text--cyan-200{color:#80deea !important}.mdl-color--cyan-200{background-color:#80deea !important}.mdl-color-text--cyan-300{color:#4dd0e1 !important}.mdl-color--cyan-300{background-color:#4dd0e1 !important}.mdl-color-text--cyan-400{color:#26c6da !important}.mdl-color--cyan-400{background-color:#26c6da !important}.mdl-color-text--cyan-500{color:#00bcd4 !important}.mdl-color--cyan-500{background-color:#00bcd4 !important}.mdl-color-text--cyan-600{color:#00acc1 !important}.mdl-color--cyan-600{background-color:#00acc1 !important}.mdl-color-text--cyan-700{color:#0097a7 !important}.mdl-color--cyan-700{background-color:#0097a7 !important}.mdl-color-text--cyan-800{color:#00838f !important}.mdl-color--cyan-800{background-color:#00838f !important}.mdl-color-text--cyan-900{color:#006064 !important}.mdl-color--cyan-900{background-color:#006064 !important}.mdl-color-text--cyan-A100{color:#84ffff !important}.mdl-color--cyan-A100{background-color:#84ffff !important}.mdl-color-text--cyan-A200{color:#18ffff !important}.mdl-color--cyan-A200{background-color:#18ffff !important}.mdl-color-text--cyan-A400{color:#00e5ff !important}.mdl-color--cyan-A400{background-color:#00e5ff !important}.mdl-color-text--cyan-A700{color:#00b8d4 !important}.mdl-color--cyan-A700{background-color:#00b8d4 !important}.mdl-color-text--teal{color:#009688 !important}.mdl-color--teal{background-color:#009688 !important}.mdl-color-text--teal-50{color:#e0f2f1 !important}.mdl-color--teal-50{background-color:#e0f2f1 !important}.mdl-color-text--teal-100{color:#b2dfdb !important}.mdl-color--teal-100{background-color:#b2dfdb !important}.mdl-color-text--teal-200{color:#80cbc4 !important}.mdl-color--teal-200{background-color:#80cbc4 !important}.mdl-color-text--teal-300{color:#4db6ac !important}.mdl-color--teal-300{background-color:#4db6ac !important}.mdl-color-text--teal-400{color:#26a69a !important}.mdl-color--teal-400{background-color:#26a69a !important}.mdl-color-text--teal-500{color:#009688 !important}.mdl-color--teal-500{background-color:#009688 !important}.mdl-color-text--teal-600{color:#00897b !important}.mdl-color--teal-600{background-color:#00897b !important}.mdl-color-text--teal-700{color:#00796b !important}.mdl-color--teal-700{background-color:#00796b !important}.mdl-color-text--teal-800{color:#00695c !important}.mdl-color--teal-800{background-color:#00695c !important}.mdl-color-text--teal-900{color:#004d40 !important}.mdl-color--teal-900{background-color:#004d40 !important}.mdl-color-text--teal-A100{color:#a7ffeb !important}.mdl-color--teal-A100{background-color:#a7ffeb !important}.mdl-color-text--teal-A200{color:#64ffda !important}.mdl-color--teal-A200{background-color:#64ffda !important}.mdl-color-text--teal-A400{color:#1de9b6 !important}.mdl-color--teal-A400{background-color:#1de9b6 !important}.mdl-color-text--teal-A700{color:#00bfa5 !important}.mdl-color--teal-A700{background-color:#00bfa5 !important}.mdl-color-text--green{color:#4caf50 !important}.mdl-color--green{background-color:#4caf50 !important}.mdl-color-text--green-50{color:#e8f5e9 !important}.mdl-color--green-50{background-color:#e8f5e9 !important}.mdl-color-text--green-100{color:#c8e6c9 !important}.mdl-color--green-100{background-color:#c8e6c9 !important}.mdl-color-text--green-200{color:#a5d6a7 !important}.mdl-color--green-200{background-color:#a5d6a7 !important}.mdl-color-text--green-300{color:#81c784 !important}.mdl-color--green-300{background-color:#81c784 !important}.mdl-color-text--green-400{color:#66bb6a !important}.mdl-color--green-400{background-color:#66bb6a !important}.mdl-color-text--green-500{color:#4caf50 !important}.mdl-color--green-500{background-color:#4caf50 !important}.mdl-color-text--green-600{color:#43a047 !important}.mdl-color--green-600{background-color:#43a047 !important}.mdl-color-text--green-700{color:#388e3c !important}.mdl-color--green-700{background-color:#388e3c !important}.mdl-color-text--green-800{color:#2e7d32 !important}.mdl-color--green-800{background-color:#2e7d32 !important}.mdl-color-text--green-900{color:#1b5e20 !important}.mdl-color--green-900{background-color:#1b5e20 !important}.mdl-color-text--green-A100{color:#b9f6ca !important}.mdl-color--green-A100{background-color:#b9f6ca !important}.mdl-color-text--green-A200{color:#69f0ae !important}.mdl-color--green-A200{background-color:#69f0ae !important}.mdl-color-text--green-A400{color:#00e676 !important}.mdl-color--green-A400{background-color:#00e676 !important}.mdl-color-text--green-A700{color:#00c853 !important}.mdl-color--green-A700{background-color:#00c853 !important}.mdl-color-text--light-green{color:#8bc34a !important}.mdl-color--light-green{background-color:#8bc34a !important}.mdl-color-text--light-green-50{color:#f1f8e9 !important}.mdl-color--light-green-50{background-color:#f1f8e9 !important}.mdl-color-text--light-green-100{color:#dcedc8 !important}.mdl-color--light-green-100{background-color:#dcedc8 !important}.mdl-color-text--light-green-200{color:#c5e1a5 !important}.mdl-color--light-green-200{background-color:#c5e1a5 !important}.mdl-color-text--light-green-300{color:#aed581 !important}.mdl-color--light-green-300{background-color:#aed581 !important}.mdl-color-text--light-green-400{color:#9ccc65 !important}.mdl-color--light-green-400{background-color:#9ccc65 !important}.mdl-color-text--light-green-500{color:#8bc34a !important}.mdl-color--light-green-500{background-color:#8bc34a !important}.mdl-color-text--light-green-600{color:#7cb342 !important}.mdl-color--light-green-600{background-color:#7cb342 !important}.mdl-color-text--light-green-700{color:#689f38 !important}.mdl-color--light-green-700{background-color:#689f38 !important}.mdl-color-text--light-green-800{color:#558b2f !important}.mdl-color--light-green-800{background-color:#558b2f !important}.mdl-color-text--light-green-900{color:#33691e !important}.mdl-color--light-green-900{background-color:#33691e !important}.mdl-color-text--light-green-A100{color:#ccff90 !important}.mdl-color--light-green-A100{background-color:#ccff90 !important}.mdl-color-text--light-green-A200{color:#b2ff59 !important}.mdl-color--light-green-A200{background-color:#b2ff59 !important}.mdl-color-text--light-green-A400{color:#76ff03 !important}.mdl-color--light-green-A400{background-color:#76ff03 !important}.mdl-color-text--light-green-A700{color:#64dd17 !important}.mdl-color--light-green-A700{background-color:#64dd17 !important}.mdl-color-text--lime{color:#cddc39 !important}.mdl-color--lime{background-color:#cddc39 !important}.mdl-color-text--lime-50{color:#f9fbe7 !important}.mdl-color--lime-50{background-color:#f9fbe7 !important}.mdl-color-text--lime-100{color:#f0f4c3 !important}.mdl-color--lime-100{background-color:#f0f4c3 !important}.mdl-color-text--lime-200{color:#e6ee9c !important}.mdl-color--lime-200{background-color:#e6ee9c !important}.mdl-color-text--lime-300{color:#dce775 !important}.mdl-color--lime-300{background-color:#dce775 !important}.mdl-color-text--lime-400{color:#d4e157 !important}.mdl-color--lime-400{background-color:#d4e157 !important}.mdl-color-text--lime-500{color:#cddc39 !important}.mdl-color--lime-500{background-color:#cddc39 !important}.mdl-color-text--lime-600{color:#c0ca33 !important}.mdl-color--lime-600{background-color:#c0ca33 !important}.mdl-color-text--lime-700{color:#afb42b !important}.mdl-color--lime-700{background-color:#afb42b !important}.mdl-color-text--lime-800{color:#9e9d24 !important}.mdl-color--lime-800{background-color:#9e9d24 !important}.mdl-color-text--lime-900{color:#827717 !important}.mdl-color--lime-900{background-color:#827717 !important}.mdl-color-text--lime-A100{color:#f4ff81 !important}.mdl-color--lime-A100{background-color:#f4ff81 !important}.mdl-color-text--lime-A200{color:#eeff41 !important}.mdl-color--lime-A200{background-color:#eeff41 !important}.mdl-color-text--lime-A400{color:#c6ff00 !important}.mdl-color--lime-A400{background-color:#c6ff00 !important}.mdl-color-text--lime-A700{color:#aeea00 !important}.mdl-color--lime-A700{background-color:#aeea00 !important}.mdl-color-text--yellow{color:#ffeb3b !important}.mdl-color--yellow{background-color:#ffeb3b !important}.mdl-color-text--yellow-50{color:#fffde7 !important}.mdl-color--yellow-50{background-color:#fffde7 !important}.mdl-color-text--yellow-100{color:#fff9c4 !important}.mdl-color--yellow-100{background-color:#fff9c4 !important}.mdl-color-text--yellow-200{color:#fff59d !important}.mdl-color--yellow-200{background-color:#fff59d !important}.mdl-color-text--yellow-300{color:#fff176 !important}.mdl-color--yellow-300{background-color:#fff176 !important}.mdl-color-text--yellow-400{color:#ffee58 !important}.mdl-color--yellow-400{background-color:#ffee58 !important}.mdl-color-text--yellow-500{color:#ffeb3b !important}.mdl-color--yellow-500{background-color:#ffeb3b !important}.mdl-color-text--yellow-600{color:#fdd835 !important}.mdl-color--yellow-600{background-color:#fdd835 !important}.mdl-color-text--yellow-700{color:#fbc02d !important}.mdl-color--yellow-700{background-color:#fbc02d !important}.mdl-color-text--yellow-800{color:#f9a825 !important}.mdl-color--yellow-800{background-color:#f9a825 !important}.mdl-color-text--yellow-900{color:#f57f17 !important}.mdl-color--yellow-900{background-color:#f57f17 !important}.mdl-color-text--yellow-A100{color:#ffff8d !important}.mdl-color--yellow-A100{background-color:#ffff8d !important}.mdl-color-text--yellow-A200{color:#ff0 !important}.mdl-color--yellow-A200{background-color:#ff0 !important}.mdl-color-text--yellow-A400{color:#ffea00 !important}.mdl-color--yellow-A400{background-color:#ffea00 !important}.mdl-color-text--yellow-A700{color:#ffd600 !important}.mdl-color--yellow-A700{background-color:#ffd600 !important}.mdl-color-text--amber{color:#ffc107 !important}.mdl-color--amber{background-color:#ffc107 !important}.mdl-color-text--amber-50{color:#fff8e1 !important}.mdl-color--amber-50{background-color:#fff8e1 !important}.mdl-color-text--amber-100{color:#ffecb3 !important}.mdl-color--amber-100{background-color:#ffecb3 !important}.mdl-color-text--amber-200{color:#ffe082 !important}.mdl-color--amber-200{background-color:#ffe082 !important}.mdl-color-text--amber-300{color:#ffd54f !important}.mdl-color--amber-300{background-color:#ffd54f !important}.mdl-color-text--amber-400{color:#ffca28 !important}.mdl-color--amber-400{background-color:#ffca28 !important}.mdl-color-text--amber-500{color:#ffc107 !important}.mdl-color--amber-500{background-color:#ffc107 !important}.mdl-color-text--amber-600{color:#ffb300 !important}.mdl-color--amber-600{background-color:#ffb300 !important}.mdl-color-text--amber-700{color:#ffa000 !important}.mdl-color--amber-700{background-color:#ffa000 !important}.mdl-color-text--amber-800{color:#ff8f00 !important}.mdl-color--amber-800{background-color:#ff8f00 !important}.mdl-color-text--amber-900{color:#ff6f00 !important}.mdl-color--amber-900{background-color:#ff6f00 !important}.mdl-color-text--amber-A100{color:#ffe57f !important}.mdl-color--amber-A100{background-color:#ffe57f !important}.mdl-color-text--amber-A200{color:#ffd740 !important}.mdl-color--amber-A200{background-color:#ffd740 !important}.mdl-color-text--amber-A400{color:#ffc400 !important}.mdl-color--amber-A400{background-color:#ffc400 !important}.mdl-color-text--amber-A700{color:#ffab00 !important}.mdl-color--amber-A700{background-color:#ffab00 !important}.mdl-color-text--orange{color:#ff9800 !important}.mdl-color--orange{background-color:#ff9800 !important}.mdl-color-text--orange-50{color:#fff3e0 !important}.mdl-color--orange-50{background-color:#fff3e0 !important}.mdl-color-text--orange-100{color:#ffe0b2 !important}.mdl-color--orange-100{background-color:#ffe0b2 !important}.mdl-color-text--orange-200{color:#ffcc80 !important}.mdl-color--orange-200{background-color:#ffcc80 !important}.mdl-color-text--orange-300{color:#ffb74d !important}.mdl-color--orange-300{background-color:#ffb74d !important}.mdl-color-text--orange-400{color:#ffa726 !important}.mdl-color--orange-400{background-color:#ffa726 !important}.mdl-color-text--orange-500{color:#ff9800 !important}.mdl-color--orange-500{background-color:#ff9800 !important}.mdl-color-text--orange-600{color:#fb8c00 !important}.mdl-color--orange-600{background-color:#fb8c00 !important}.mdl-color-text--orange-700{color:#f57c00 !important}.mdl-color--orange-700{background-color:#f57c00 !important}.mdl-color-text--orange-800{color:#ef6c00 !important}.mdl-color--orange-800{background-color:#ef6c00 !important}.mdl-color-text--orange-900{color:#e65100 !important}.mdl-color--orange-900{background-color:#e65100 !important}.mdl-color-text--orange-A100{color:#ffd180 !important}.mdl-color--orange-A100{background-color:#ffd180 !important}.mdl-color-text--orange-A200{color:#ffab40 !important}.mdl-color--orange-A200{background-color:#ffab40 !important}.mdl-color-text--orange-A400{color:#ff9100 !important}.mdl-color--orange-A400{background-color:#ff9100 !important}.mdl-color-text--orange-A700{color:#ff6d00 !important}.mdl-color--orange-A700{background-color:#ff6d00 !important}.mdl-color-text--deep-orange{color:#ff5722 !important}.mdl-color--deep-orange{background-color:#ff5722 !important}.mdl-color-text--deep-orange-50{color:#fbe9e7 !important}.mdl-color--deep-orange-50{background-color:#fbe9e7 !important}.mdl-color-text--deep-orange-100{color:#ffccbc !important}.mdl-color--deep-orange-100{background-color:#ffccbc !important}.mdl-color-text--deep-orange-200{color:#ffab91 !important}.mdl-color--deep-orange-200{background-color:#ffab91 !important}.mdl-color-text--deep-orange-300{color:#ff8a65 !important}.mdl-color--deep-orange-300{background-color:#ff8a65 !important}.mdl-color-text--deep-orange-400{color:#ff7043 !important}.mdl-color--deep-orange-400{background-color:#ff7043 !important}.mdl-color-text--deep-orange-500{color:#ff5722 !important}.mdl-color--deep-orange-500{background-color:#ff5722 !important}.mdl-color-text--deep-orange-600{color:#f4511e !important}.mdl-color--deep-orange-600{background-color:#f4511e !important}.mdl-color-text--deep-orange-700{color:#e64a19 !important}.mdl-color--deep-orange-700{background-color:#e64a19 !important}.mdl-color-text--deep-orange-800{color:#d84315 !important}.mdl-color--deep-orange-800{background-color:#d84315 !important}.mdl-color-text--deep-orange-900{color:#bf360c !important}.mdl-color--deep-orange-900{background-color:#bf360c !important}.mdl-color-text--deep-orange-A100{color:#ff9e80 !important}.mdl-color--deep-orange-A100{background-color:#ff9e80 !important}.mdl-color-text--deep-orange-A200{color:#ff6e40 !important}.mdl-color--deep-orange-A200{background-color:#ff6e40 !important}.mdl-color-text--deep-orange-A400{color:#ff3d00 !important}.mdl-color--deep-orange-A400{background-color:#ff3d00 !important}.mdl-color-text--deep-orange-A700{color:#dd2c00 !important}.mdl-color--deep-orange-A700{background-color:#dd2c00 !important}.mdl-color-text--brown{color:#795548 !important}.mdl-color--brown{background-color:#795548 !important}.mdl-color-text--brown-50{color:#efebe9 !important}.mdl-color--brown-50{background-color:#efebe9 !important}.mdl-color-text--brown-100{color:#d7ccc8 !important}.mdl-color--brown-100{background-color:#d7ccc8 !important}.mdl-color-text--brown-200{color:#bcaaa4 !important}.mdl-color--brown-200{background-color:#bcaaa4 !important}.mdl-color-text--brown-300{color:#a1887f !important}.mdl-color--brown-300{background-color:#a1887f !important}.mdl-color-text--brown-400{color:#8d6e63 !important}.mdl-color--brown-400{background-color:#8d6e63 !important}.mdl-color-text--brown-500{color:#795548 !important}.mdl-color--brown-500{background-color:#795548 !important}.mdl-color-text--brown-600{color:#6d4c41 !important}.mdl-color--brown-600{background-color:#6d4c41 !important}.mdl-color-text--brown-700{color:#5d4037 !important}.mdl-color--brown-700{background-color:#5d4037 !important}.mdl-color-text--brown-800{color:#4e342e !important}.mdl-color--brown-800{background-color:#4e342e !important}.mdl-color-text--brown-900{color:#3e2723 !important}.mdl-color--brown-900{background-color:#3e2723 !important}.mdl-color-text--grey{color:#9e9e9e !important}.mdl-color--grey{background-color:#9e9e9e !important}.mdl-color-text--grey-50{color:#fafafa !important}.mdl-color--grey-50{background-color:#fafafa !important}.mdl-color-text--grey-100{color:#f5f5f5 !important}.mdl-color--grey-100{background-color:#f5f5f5 !important}.mdl-color-text--grey-200{color:#eee !important}.mdl-color--grey-200{background-color:#eee !important}.mdl-color-text--grey-300{color:#e0e0e0 !important}.mdl-color--grey-300{background-color:#e0e0e0 !important}.mdl-color-text--grey-400{color:#bdbdbd !important}.mdl-color--grey-400{background-color:#bdbdbd !important}.mdl-color-text--grey-500{color:#9e9e9e !important}.mdl-color--grey-500{background-color:#9e9e9e !important}.mdl-color-text--grey-600{color:#757575 !important}.mdl-color--grey-600{background-color:#757575 !important}.mdl-color-text--grey-700{color:#616161 !important}.mdl-color--grey-700{background-color:#616161 !important}.mdl-color-text--grey-800{color:#424242 !important}.mdl-color--grey-800{background-color:#424242 !important}.mdl-color-text--grey-900{color:#212121 !important}.mdl-color--grey-900{background-color:#212121 !important}.mdl-color-text--blue-grey{color:#607d8b !important}.mdl-color--blue-grey{background-color:#607d8b !important}.mdl-color-text--blue-grey-50{color:#eceff1 !important}.mdl-color--blue-grey-50{background-color:#eceff1 !important}.mdl-color-text--blue-grey-100{color:#cfd8dc !important}.mdl-color--blue-grey-100{background-color:#cfd8dc !important}.mdl-color-text--blue-grey-200{color:#b0bec5 !important}.mdl-color--blue-grey-200{background-color:#b0bec5 !important}.mdl-color-text--blue-grey-300{color:#90a4ae !important}.mdl-color--blue-grey-300{background-color:#90a4ae !important}.mdl-color-text--blue-grey-400{color:#78909c !important}.mdl-color--blue-grey-400{background-color:#78909c !important}.mdl-color-text--blue-grey-500{color:#607d8b !important}.mdl-color--blue-grey-500{background-color:#607d8b !important}.mdl-color-text--blue-grey-600{color:#546e7a !important}.mdl-color--blue-grey-600{background-color:#546e7a !important}.mdl-color-text--blue-grey-700{color:#455a64 !important}.mdl-color--blue-grey-700{background-color:#455a64 !important}.mdl-color-text--blue-grey-800{color:#37474f !important}.mdl-color--blue-grey-800{background-color:#37474f !important}.mdl-color-text--blue-grey-900{color:#263238 !important}.mdl-color--blue-grey-900{background-color:#263238 !important}.mdl-color--black{background-color:#000 !important}.mdl-color-text--black{color:#000 !important}.mdl-color--white{background-color:#fff !important}.mdl-color-text--white{color:#fff !important}.mdl-color--primary{background-color:#3f51b5 !important}.mdl-color--primary-contrast{background-color:#fff !important}.mdl-color--primary-dark{background-color:#303f9f !important}.mdl-color--accent{background-color:#ff4081 !important}.mdl-color--accent-contrast{background-color:#fff !important}.mdl-color-text--primary{color:#3f51b5 !important}.mdl-color-text--primary-contrast{color:#fff !important}.mdl-color-text--primary-dark{color:#303f9f !important}.mdl-color-text--accent{color:#ff4081 !important}.mdl-color-text--accent-contrast{color:#fff !important}.mdl-ripple{background:#000;border-radius:50%;height:50px;left:0;opacity:0;pointer-events:none;position:absolute;top:0;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);width:50px;overflow:hidden}.mdl-ripple.is-animating{transition:transform .3s cubic-bezier(0,0,.2,1),width .3s cubic-bezier(0,0,.2,1),height .3s cubic-bezier(0,0,.2,1),opacity .6s cubic-bezier(0,0,.2,1);transition:transform .3s cubic-bezier(0,0,.2,1),width .3s cubic-bezier(0,0,.2,1),height .3s cubic-bezier(0,0,.2,1),opacity .6s cubic-bezier(0,0,.2,1),-webkit-transform .3s cubic-bezier(0,0,.2,1)}.mdl-ripple.is-visible{opacity:.3}.mdl-animation--default,.mdl-animation--fast-out-slow-in{transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-animation--linear-out-slow-in{transition-timing-function:cubic-bezier(0,0,.2,1)}.mdl-animation--fast-out-linear-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.mdl-badge{position:relative;white-space:nowrap;margin-right:24px}.mdl-badge:not([data-badge]){margin-right:auto}.mdl-badge[data-badge]:after{content:attr(data-badge);display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-content:center;-ms-flex-line-pack:center;align-content:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;position:absolute;top:-11px;right:-24px;font-family:"Roboto","Helvetica","Arial",sans-serif;font-weight:600;font-size:12px;width:22px;height:22px;border-radius:50%;background:#ff4081;color:#fff}.mdl-button .mdl-badge[data-badge]:after{top:-10px;right:-5px}.mdl-badge.mdl-badge--no-background[data-badge]:after{color:#ff4081;background:rgba(255,255,255,.2);box-shadow:0 0 1px gray}.mdl-badge.mdl-badge--overlap{margin-right:10px}.mdl-badge.mdl-badge--overlap:after{right:-10px}.mdl-button{background:0 0;border:none;border-radius:2px;color:#000;position:relative;height:36px;margin:0;min-width:64px;padding:0 16px;display:inline-block;font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:14px;font-weight:500;text-transform:uppercase;letter-spacing:0;overflow:hidden;will-change:box-shadow;transition:box-shadow .2s cubic-bezier(.4,0,1,1),background-color .2s cubic-bezier(.4,0,.2,1),color .2s cubic-bezier(.4,0,.2,1);outline:none;cursor:pointer;text-decoration:none;text-align:center;line-height:36px;vertical-align:middle}.mdl-button::-moz-focus-inner{border:0}.mdl-button:hover{background-color:rgba(158,158,158,.2)}.mdl-button:focus:not(:active){background-color:rgba(0,0,0,.12)}.mdl-button:active{background-color:rgba(158,158,158,.4)}.mdl-button.mdl-button--colored{color:#3f51b5}.mdl-button.mdl-button--colored:focus:not(:active){background-color:rgba(0,0,0,.12)}input.mdl-button[type="submit"]{-webkit-appearance:none}.mdl-button--raised{background:rgba(158,158,158,.2);box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-button--raised:active{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2);background-color:rgba(158,158,158,.4)}.mdl-button--raised:focus:not(:active){box-shadow:0 0 8px rgba(0,0,0,.18),0 8px 16px rgba(0,0,0,.36);background-color:rgba(158,158,158,.4)}.mdl-button--raised.mdl-button--colored{background:#3f51b5;color:#fff}.mdl-button--raised.mdl-button--colored:hover{background-color:#3f51b5}.mdl-button--raised.mdl-button--colored:active{background-color:#3f51b5}.mdl-button--raised.mdl-button--colored:focus:not(:active){background-color:#3f51b5}.mdl-button--raised.mdl-button--colored .mdl-ripple{background:#fff}.mdl-button--fab{border-radius:50%;font-size:24px;height:56px;margin:auto;min-width:56px;width:56px;padding:0;overflow:hidden;background:rgba(158,158,158,.2);box-shadow:0 1px 1.5px 0 rgba(0,0,0,.12),0 1px 1px 0 rgba(0,0,0,.24);position:relative;line-height:normal}.mdl-button--fab .material-icons{position:absolute;top:50%;left:50%;-webkit-transform:translate(-12px,-12px);transform:translate(-12px,-12px);line-height:24px;width:24px}.mdl-button--fab.mdl-button--mini-fab{height:40px;min-width:40px;width:40px}.mdl-button--fab .mdl-button__ripple-container{border-radius:50%;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-button--fab:active{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2);background-color:rgba(158,158,158,.4)}.mdl-button--fab:focus:not(:active){box-shadow:0 0 8px rgba(0,0,0,.18),0 8px 16px rgba(0,0,0,.36);background-color:rgba(158,158,158,.4)}.mdl-button--fab.mdl-button--colored{background:#ff4081;color:#fff}.mdl-button--fab.mdl-button--colored:hover{background-color:#ff4081}.mdl-button--fab.mdl-button--colored:focus:not(:active){background-color:#ff4081}.mdl-button--fab.mdl-button--colored:active{background-color:#ff4081}.mdl-button--fab.mdl-button--colored .mdl-ripple{background:#fff}.mdl-button--icon{border-radius:50%;font-size:24px;height:32px;margin-left:0;margin-right:0;min-width:32px;width:32px;padding:0;overflow:hidden;color:inherit;line-height:normal}.mdl-button--icon .material-icons{position:absolute;top:50%;left:50%;-webkit-transform:translate(-12px,-12px);transform:translate(-12px,-12px);line-height:24px;width:24px}.mdl-button--icon.mdl-button--mini-icon{height:24px;min-width:24px;width:24px}.mdl-button--icon.mdl-button--mini-icon .material-icons{top:0;left:0}.mdl-button--icon .mdl-button__ripple-container{border-radius:50%;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-button__ripple-container{display:block;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0;overflow:hidden}.mdl-button[disabled] .mdl-button__ripple-container .mdl-ripple,.mdl-button.mdl-button--disabled .mdl-button__ripple-container .mdl-ripple{background-color:transparent}.mdl-button--primary.mdl-button--primary{color:#3f51b5}.mdl-button--primary.mdl-button--primary .mdl-ripple{background:#fff}.mdl-button--primary.mdl-button--primary.mdl-button--raised,.mdl-button--primary.mdl-button--primary.mdl-button--fab{color:#fff;background-color:#3f51b5}.mdl-button--accent.mdl-button--accent{color:#ff4081}.mdl-button--accent.mdl-button--accent .mdl-ripple{background:#fff}.mdl-button--accent.mdl-button--accent.mdl-button--raised,.mdl-button--accent.mdl-button--accent.mdl-button--fab{color:#fff;background-color:#ff4081}.mdl-button[disabled][disabled],.mdl-button.mdl-button--disabled.mdl-button--disabled{color:rgba(0,0,0,.26);cursor:default;background-color:transparent}.mdl-button--fab[disabled][disabled],.mdl-button--fab.mdl-button--disabled.mdl-button--disabled{background-color:rgba(0,0,0,.12);color:rgba(0,0,0,.26)}.mdl-button--raised[disabled][disabled],.mdl-button--raised.mdl-button--disabled.mdl-button--disabled{background-color:rgba(0,0,0,.12);color:rgba(0,0,0,.26);box-shadow:none}.mdl-button--colored[disabled][disabled],.mdl-button--colored.mdl-button--disabled.mdl-button--disabled{color:rgba(0,0,0,.26)}.mdl-button .material-icons{vertical-align:middle}.mdl-card{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;font-size:16px;font-weight:400;min-height:200px;overflow:hidden;width:330px;z-index:1;position:relative;background:#fff;border-radius:2px;box-sizing:border-box}.mdl-card__media{background-color:#ff4081;background-repeat:repeat;background-position:50% 50%;background-size:cover;background-origin:padding-box;background-attachment:scroll;box-sizing:border-box}.mdl-card__title{-webkit-align-items:center;-ms-flex-align:center;align-items:center;color:#000;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-justify-content:stretch;-ms-flex-pack:stretch;justify-content:stretch;line-height:normal;padding:16px;-webkit-perspective-origin:165px 56px;perspective-origin:165px 56px;-webkit-transform-origin:165px 56px;transform-origin:165px 56px;box-sizing:border-box}.mdl-card__title.mdl-card--border{border-bottom:1px solid rgba(0,0,0,.1)}.mdl-card__title-text{-webkit-align-self:flex-end;-ms-flex-item-align:end;align-self:flex-end;color:inherit;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;font-size:24px;font-weight:300;line-height:normal;overflow:hidden;-webkit-transform-origin:149px 48px;transform-origin:149px 48px;margin:0}.mdl-card__subtitle-text{font-size:14px;color:rgba(0,0,0,.54);margin:0}.mdl-card__supporting-text{color:rgba(0,0,0,.54);font-size:1rem;line-height:18px;overflow:hidden;padding:16px;width:90%}.mdl-card__actions{font-size:16px;line-height:normal;width:100%;background-color:transparent;padding:8px;box-sizing:border-box}.mdl-card__actions.mdl-card--border{border-top:1px solid rgba(0,0,0,.1)}.mdl-card--expand{-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1}.mdl-card__menu{position:absolute;right:16px;top:16px}.mdl-checkbox{position:relative;z-index:1;vertical-align:middle;display:inline-block;box-sizing:border-box;width:100%;height:24px;margin:0;padding:0}.mdl-checkbox.is-upgraded{padding-left:24px}.mdl-checkbox__input{line-height:24px}.mdl-checkbox.is-upgraded .mdl-checkbox__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-checkbox__box-outline{position:absolute;top:3px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;margin:0;cursor:pointer;overflow:hidden;border:2px solid rgba(0,0,0,.54);border-radius:2px;z-index:2}.mdl-checkbox.is-checked .mdl-checkbox__box-outline{border:2px solid #3f51b5}fieldset[disabled] .mdl-checkbox .mdl-checkbox__box-outline,.mdl-checkbox.is-disabled .mdl-checkbox__box-outline{border:2px solid rgba(0,0,0,.26);cursor:auto}.mdl-checkbox__focus-helper{position:absolute;top:3px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;border-radius:50%;background-color:transparent}.mdl-checkbox.is-focused .mdl-checkbox__focus-helper{box-shadow:0 0 0 8px rgba(0,0,0,.1);background-color:rgba(0,0,0,.1)}.mdl-checkbox.is-focused.is-checked .mdl-checkbox__focus-helper{box-shadow:0 0 0 8px rgba(63,81,181,.26);background-color:rgba(63,81,181,.26)}.mdl-checkbox__tick-outline{position:absolute;top:0;left:0;height:100%;width:100%;-webkit-mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8ZGVmcz4KICAgIDxjbGlwUGF0aCBpZD0iY2xpcCI+CiAgICAgIDxwYXRoCiAgICAgICAgIGQ9Ik0gMCwwIDAsMSAxLDEgMSwwIDAsMCB6IE0gMC44NTM0Mzc1LDAuMTY3MTg3NSAwLjk1OTY4NzUsMC4yNzMxMjUgMC40MjkzNzUsMC44MDM0Mzc1IDAuMzIzMTI1LDAuOTA5Njg3NSAwLjIxNzE4NzUsMC44MDM0Mzc1IDAuMDQwMzEyNSwwLjYyNjg3NSAwLjE0NjU2MjUsMC41MjA2MjUgMC4zMjMxMjUsMC42OTc1IDAuODUzNDM3NSwwLjE2NzE4NzUgeiIKICAgICAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KICAgIDwvY2xpcFBhdGg+CiAgICA8bWFzayBpZD0ibWFzayIgbWFza1VuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgbWFza0NvbnRlbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giPgogICAgICA8cGF0aAogICAgICAgICBkPSJNIDAsMCAwLDEgMSwxIDEsMCAwLDAgeiBNIDAuODUzNDM3NSwwLjE2NzE4NzUgMC45NTk2ODc1LDAuMjczMTI1IDAuNDI5Mzc1LDAuODAzNDM3NSAwLjMyMzEyNSwwLjkwOTY4NzUgMC4yMTcxODc1LDAuODAzNDM3NSAwLjA0MDMxMjUsMC42MjY4NzUgMC4xNDY1NjI1LDAuNTIwNjI1IDAuMzIzMTI1LDAuNjk3NSAwLjg1MzQzNzUsMC4xNjcxODc1IHoiCiAgICAgICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmUiIC8+CiAgICA8L21hc2s+CiAgPC9kZWZzPgogIDxyZWN0CiAgICAgd2lkdGg9IjEiCiAgICAgaGVpZ2h0PSIxIgogICAgIHg9IjAiCiAgICAgeT0iMCIKICAgICBjbGlwLXBhdGg9InVybCgjY2xpcCkiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KPC9zdmc+Cg==");mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8ZGVmcz4KICAgIDxjbGlwUGF0aCBpZD0iY2xpcCI+CiAgICAgIDxwYXRoCiAgICAgICAgIGQ9Ik0gMCwwIDAsMSAxLDEgMSwwIDAsMCB6IE0gMC44NTM0Mzc1LDAuMTY3MTg3NSAwLjk1OTY4NzUsMC4yNzMxMjUgMC40MjkzNzUsMC44MDM0Mzc1IDAuMzIzMTI1LDAuOTA5Njg3NSAwLjIxNzE4NzUsMC44MDM0Mzc1IDAuMDQwMzEyNSwwLjYyNjg3NSAwLjE0NjU2MjUsMC41MjA2MjUgMC4zMjMxMjUsMC42OTc1IDAuODUzNDM3NSwwLjE2NzE4NzUgeiIKICAgICAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KICAgIDwvY2xpcFBhdGg+CiAgICA8bWFzayBpZD0ibWFzayIgbWFza1VuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgbWFza0NvbnRlbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giPgogICAgICA8cGF0aAogICAgICAgICBkPSJNIDAsMCAwLDEgMSwxIDEsMCAwLDAgeiBNIDAuODUzNDM3NSwwLjE2NzE4NzUgMC45NTk2ODc1LDAuMjczMTI1IDAuNDI5Mzc1LDAuODAzNDM3NSAwLjMyMzEyNSwwLjkwOTY4NzUgMC4yMTcxODc1LDAuODAzNDM3NSAwLjA0MDMxMjUsMC42MjY4NzUgMC4xNDY1NjI1LDAuNTIwNjI1IDAuMzIzMTI1LDAuNjk3NSAwLjg1MzQzNzUsMC4xNjcxODc1IHoiCiAgICAgICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmUiIC8+CiAgICA8L21hc2s+CiAgPC9kZWZzPgogIDxyZWN0CiAgICAgd2lkdGg9IjEiCiAgICAgaGVpZ2h0PSIxIgogICAgIHg9IjAiCiAgICAgeT0iMCIKICAgICBjbGlwLXBhdGg9InVybCgjY2xpcCkiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KPC9zdmc+Cg==");background:0 0;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:background}.mdl-checkbox.is-checked .mdl-checkbox__tick-outline{background:#3f51b5 url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8cGF0aAogICAgIGQ9Ik0gMC4wNDAzODA1OSwwLjYyNjc3NjcgMC4xNDY0NDY2MSwwLjUyMDcxMDY4IDAuNDI5Mjg5MzIsMC44MDM1NTMzOSAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IE0gMC4yMTcxNTcyOSwwLjgwMzU1MzM5IDAuODUzNTUzMzksMC4xNjcxNTcyOSAwLjk1OTYxOTQxLDAuMjczMjIzMyAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IgogICAgIGlkPSJyZWN0Mzc4MCIKICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lIiAvPgo8L3N2Zz4K")}fieldset[disabled] .mdl-checkbox.is-checked .mdl-checkbox__tick-outline,.mdl-checkbox.is-checked.is-disabled .mdl-checkbox__tick-outline{background:rgba(0,0,0,.26)url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8cGF0aAogICAgIGQ9Ik0gMC4wNDAzODA1OSwwLjYyNjc3NjcgMC4xNDY0NDY2MSwwLjUyMDcxMDY4IDAuNDI5Mjg5MzIsMC44MDM1NTMzOSAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IE0gMC4yMTcxNTcyOSwwLjgwMzU1MzM5IDAuODUzNTUzMzksMC4xNjcxNTcyOSAwLjk1OTYxOTQxLDAuMjczMjIzMyAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IgogICAgIGlkPSJyZWN0Mzc4MCIKICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lIiAvPgo8L3N2Zz4K")}.mdl-checkbox__label{position:relative;cursor:pointer;font-size:16px;line-height:24px;margin:0}fieldset[disabled] .mdl-checkbox .mdl-checkbox__label,.mdl-checkbox.is-disabled .mdl-checkbox__label{color:rgba(0,0,0,.26);cursor:auto}.mdl-checkbox__ripple-container{position:absolute;z-index:2;top:-6px;left:-10px;box-sizing:border-box;width:36px;height:36px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-checkbox__ripple-container .mdl-ripple{background:#3f51b5}fieldset[disabled] .mdl-checkbox .mdl-checkbox__ripple-container,.mdl-checkbox.is-disabled .mdl-checkbox__ripple-container{cursor:auto}fieldset[disabled] .mdl-checkbox .mdl-checkbox__ripple-container .mdl-ripple,.mdl-checkbox.is-disabled .mdl-checkbox__ripple-container .mdl-ripple{background:0 0}.mdl-data-table{position:relative;border:1px solid rgba(0,0,0,.12);border-collapse:collapse;white-space:nowrap;font-size:13px;background-color:#fff}.mdl-data-table thead{padding-bottom:3px}.mdl-data-table thead .mdl-data-table__select{margin-top:0}.mdl-data-table tbody tr{position:relative;height:48px;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:background-color}.mdl-data-table tbody tr.is-selected{background-color:#e0e0e0}.mdl-data-table tbody tr:hover{background-color:#eee}.mdl-data-table td{text-align:right}.mdl-data-table th{padding:0 18px 12px 18px;text-align:right}.mdl-data-table td:first-of-type,.mdl-data-table th:first-of-type{padding-left:24px}.mdl-data-table td:last-of-type,.mdl-data-table th:last-of-type{padding-right:24px}.mdl-data-table td{position:relative;height:48px;border-top:1px solid rgba(0,0,0,.12);border-bottom:1px solid rgba(0,0,0,.12);padding:12px 18px;box-sizing:border-box}.mdl-data-table td,.mdl-data-table td .mdl-data-table__select{vertical-align:middle}.mdl-data-table th{position:relative;vertical-align:bottom;text-overflow:ellipsis;font-weight:700;line-height:24px;letter-spacing:0;height:48px;font-size:12px;color:rgba(0,0,0,.54);padding-bottom:8px;box-sizing:border-box}.mdl-data-table th.mdl-data-table__header--sorted-ascending,.mdl-data-table th.mdl-data-table__header--sorted-descending{color:rgba(0,0,0,.87)}.mdl-data-table th.mdl-data-table__header--sorted-ascending:before,.mdl-data-table th.mdl-data-table__header--sorted-descending:before{font-family:'Material Icons';font-weight:400;font-style:normal;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;word-wrap:normal;-moz-font-feature-settings:'liga';font-feature-settings:'liga';-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased;font-size:16px;content:"\e5d8";margin-right:5px;vertical-align:sub}.mdl-data-table th.mdl-data-table__header--sorted-ascending:hover,.mdl-data-table th.mdl-data-table__header--sorted-descending:hover{cursor:pointer}.mdl-data-table th.mdl-data-table__header--sorted-ascending:hover:before,.mdl-data-table th.mdl-data-table__header--sorted-descending:hover:before{color:rgba(0,0,0,.26)}.mdl-data-table th.mdl-data-table__header--sorted-descending:before{content:"\e5db"}.mdl-data-table__select{width:16px}.mdl-data-table__cell--non-numeric.mdl-data-table__cell--non-numeric{text-align:left}.mdl-dialog{border:none;box-shadow:0 9px 46px 8px rgba(0,0,0,.14),0 11px 15px -7px rgba(0,0,0,.12),0 24px 38px 3px rgba(0,0,0,.2);width:280px}.mdl-dialog__title{padding:24px 24px 0;margin:0;font-size:2.5rem}.mdl-dialog__actions{padding:8px 8px 8px 24px;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row-reverse;-ms-flex-direction:row-reverse;flex-direction:row-reverse;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap}.mdl-dialog__actions>*{margin-right:8px;height:36px}.mdl-dialog__actions>*:first-child{margin-right:0}.mdl-dialog__actions--full-width{padding:0 0 8px}.mdl-dialog__actions--full-width>*{height:48px;-webkit-flex:0 0 100%;-ms-flex:0 0 100%;flex:0 0 100%;padding-right:16px;margin-right:0;text-align:right}.mdl-dialog__content{padding:20px 24px 24px;color:rgba(0,0,0,.54)}.mdl-mega-footer{padding:16px 40px;color:#9e9e9e;background-color:#424242}.mdl-mega-footer--top-section:after,.mdl-mega-footer--middle-section:after,.mdl-mega-footer--bottom-section:after,.mdl-mega-footer__top-section:after,.mdl-mega-footer__middle-section:after,.mdl-mega-footer__bottom-section:after{content:'';display:block;clear:both}.mdl-mega-footer--left-section,.mdl-mega-footer__left-section,.mdl-mega-footer--right-section,.mdl-mega-footer__right-section{margin-bottom:16px}.mdl-mega-footer--right-section a,.mdl-mega-footer__right-section a{display:block;margin-bottom:16px;color:inherit;text-decoration:none}@media screen and (min-width:760px){.mdl-mega-footer--left-section,.mdl-mega-footer__left-section{float:left}.mdl-mega-footer--right-section,.mdl-mega-footer__right-section{float:right}.mdl-mega-footer--right-section a,.mdl-mega-footer__right-section a{display:inline-block;margin-left:16px;line-height:36px;vertical-align:middle}}.mdl-mega-footer--social-btn,.mdl-mega-footer__social-btn{width:36px;height:36px;padding:0;margin:0;background-color:#9e9e9e;border:none}.mdl-mega-footer--drop-down-section,.mdl-mega-footer__drop-down-section{display:block;position:relative}@media screen and (min-width:760px){.mdl-mega-footer--drop-down-section,.mdl-mega-footer__drop-down-section{width:33%}.mdl-mega-footer--drop-down-section:nth-child(1),.mdl-mega-footer--drop-down-section:nth-child(2),.mdl-mega-footer__drop-down-section:nth-child(1),.mdl-mega-footer__drop-down-section:nth-child(2){float:left}.mdl-mega-footer--drop-down-section:nth-child(3),.mdl-mega-footer__drop-down-section:nth-child(3){float:right}.mdl-mega-footer--drop-down-section:nth-child(3):after,.mdl-mega-footer__drop-down-section:nth-child(3):after{clear:right}.mdl-mega-footer--drop-down-section:nth-child(4),.mdl-mega-footer__drop-down-section:nth-child(4){clear:right;float:right}.mdl-mega-footer--middle-section:after,.mdl-mega-footer__middle-section:after{content:'';display:block;clear:both}.mdl-mega-footer--bottom-section,.mdl-mega-footer__bottom-section{padding-top:0}}@media screen and (min-width:1024px){.mdl-mega-footer--drop-down-section,.mdl-mega-footer--drop-down-section:nth-child(3),.mdl-mega-footer--drop-down-section:nth-child(4),.mdl-mega-footer__drop-down-section,.mdl-mega-footer__drop-down-section:nth-child(3),.mdl-mega-footer__drop-down-section:nth-child(4){width:24%;float:left}}.mdl-mega-footer--heading-checkbox,.mdl-mega-footer__heading-checkbox{position:absolute;width:100%;height:55.8px;padding:32px;margin:-16px 0 0;cursor:pointer;z-index:1;opacity:0}.mdl-mega-footer--heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer__heading:after{font-family:'Material Icons';content:'\E5CE'}.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list{display:none}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading:after{font-family:'Material Icons';content:'\E5CF'}.mdl-mega-footer--heading,.mdl-mega-footer__heading{position:relative;width:100%;padding-right:39.8px;margin-bottom:16px;box-sizing:border-box;font-size:14px;line-height:23.8px;font-weight:500;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;color:#e0e0e0}.mdl-mega-footer--heading:after,.mdl-mega-footer__heading:after{content:'';position:absolute;top:0;right:0;display:block;width:23.8px;height:23.8px;background-size:cover}.mdl-mega-footer--link-list,.mdl-mega-footer__link-list{list-style:none;padding:0;margin:0 0 32px}.mdl-mega-footer--link-list:after,.mdl-mega-footer__link-list:after{clear:both;display:block;content:''}.mdl-mega-footer--link-list li,.mdl-mega-footer__link-list li{font-size:14px;font-weight:400;letter-spacing:0;line-height:20px}.mdl-mega-footer--link-list a,.mdl-mega-footer__link-list a{color:inherit;text-decoration:none;white-space:nowrap}@media screen and (min-width:760px){.mdl-mega-footer--heading-checkbox,.mdl-mega-footer__heading-checkbox{display:none}.mdl-mega-footer--heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer__heading:after{content:''}.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list{display:block}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading:after{content:''}}.mdl-mega-footer--bottom-section,.mdl-mega-footer__bottom-section{padding-top:16px;margin-bottom:16px}.mdl-logo{margin-bottom:16px;color:#fff}.mdl-mega-footer--bottom-section .mdl-mega-footer--link-list li,.mdl-mega-footer__bottom-section .mdl-mega-footer__link-list li{float:left;margin-bottom:0;margin-right:16px}@media screen and (min-width:760px){.mdl-logo{float:left;margin-bottom:0;margin-right:16px}}.mdl-mini-footer{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row wrap;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;padding:32px 16px;color:#9e9e9e;background-color:#424242}.mdl-mini-footer:after{content:'';display:block}.mdl-mini-footer .mdl-logo{line-height:36px}.mdl-mini-footer--link-list,.mdl-mini-footer__link-list{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row nowrap;-ms-flex-flow:row nowrap;flex-flow:row nowrap;list-style:none;margin:0;padding:0}.mdl-mini-footer--link-list li,.mdl-mini-footer__link-list li{margin-bottom:0;margin-right:16px}@media screen and (min-width:760px){.mdl-mini-footer--link-list li,.mdl-mini-footer__link-list li{line-height:36px}}.mdl-mini-footer--link-list a,.mdl-mini-footer__link-list a{color:inherit;text-decoration:none;white-space:nowrap}.mdl-mini-footer--left-section,.mdl-mini-footer__left-section{display:inline-block;-webkit-order:0;-ms-flex-order:0;order:0}.mdl-mini-footer--right-section,.mdl-mini-footer__right-section{display:inline-block;-webkit-order:1;-ms-flex-order:1;order:1}.mdl-mini-footer--social-btn,.mdl-mini-footer__social-btn{width:36px;height:36px;padding:0;margin:0;background-color:#9e9e9e;border:none}.mdl-icon-toggle{position:relative;z-index:1;vertical-align:middle;display:inline-block;height:32px;margin:0;padding:0}.mdl-icon-toggle__input{line-height:32px}.mdl-icon-toggle.is-upgraded .mdl-icon-toggle__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-icon-toggle__label{display:inline-block;position:relative;cursor:pointer;height:32px;width:32px;min-width:32px;color:#616161;border-radius:50%;padding:0;margin-left:0;margin-right:0;text-align:center;background-color:transparent;will-change:background-color;transition:background-color .2s cubic-bezier(.4,0,.2,1),color .2s cubic-bezier(.4,0,.2,1)}.mdl-icon-toggle__label.material-icons{line-height:32px;font-size:24px}.mdl-icon-toggle.is-checked .mdl-icon-toggle__label{color:#3f51b5}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__label{color:rgba(0,0,0,.26);cursor:auto;transition:none}.mdl-icon-toggle.is-focused .mdl-icon-toggle__label{background-color:rgba(0,0,0,.12)}.mdl-icon-toggle.is-focused.is-checked .mdl-icon-toggle__label{background-color:rgba(63,81,181,.26)}.mdl-icon-toggle__ripple-container{position:absolute;z-index:2;top:-2px;left:-2px;box-sizing:border-box;width:36px;height:36px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-icon-toggle__ripple-container .mdl-ripple{background:#616161}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__ripple-container{cursor:auto}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__ripple-container .mdl-ripple{background:0 0}.mdl-list{display:block;padding:8px 0;list-style:none}.mdl-list__item{font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:16px;font-weight:400;letter-spacing:.04em;line-height:1;min-height:48px;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;padding:16px;cursor:default;color:rgba(0,0,0,.87);overflow:hidden}.mdl-list__item,.mdl-list__item .mdl-list__item-primary-content{box-sizing:border-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-align-items:center;-ms-flex-align:center;align-items:center}.mdl-list__item .mdl-list__item-primary-content{-webkit-order:0;-ms-flex-order:0;order:0;-webkit-flex-grow:2;-ms-flex-positive:2;flex-grow:2;text-decoration:none}.mdl-list__item .mdl-list__item-primary-content .mdl-list__item-icon{margin-right:32px}.mdl-list__item .mdl-list__item-primary-content .mdl-list__item-avatar{margin-right:16px}.mdl-list__item .mdl-list__item-secondary-content{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:column;-ms-flex-flow:column;flex-flow:column;-webkit-align-items:flex-end;-ms-flex-align:end;align-items:flex-end;margin-left:16px}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-secondary-action label{display:inline}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-secondary-info{font-size:12px;font-weight:400;line-height:1;letter-spacing:0;color:rgba(0,0,0,.54)}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-sub-header{padding:0 0 0 16px}.mdl-list__item-icon,.mdl-list__item-icon.material-icons{height:24px;width:24px;font-size:24px;box-sizing:border-box;color:#757575}.mdl-list__item-avatar,.mdl-list__item-avatar.material-icons{height:40px;width:40px;box-sizing:border-box;border-radius:50%;background-color:#757575;font-size:40px;color:#fff}.mdl-list__item--two-line{height:72px}.mdl-list__item--two-line .mdl-list__item-primary-content{height:36px;line-height:20px;display:block}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-avatar{float:left}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-icon{float:left;margin-top:6px}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-secondary-content{height:36px}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-sub-title{font-size:14px;font-weight:400;letter-spacing:0;line-height:18px;color:rgba(0,0,0,.54);display:block;padding:0}.mdl-list__item--three-line{height:88px}.mdl-list__item--three-line .mdl-list__item-primary-content{height:52px;line-height:20px;display:block}.mdl-list__item--three-line .mdl-list__item-primary-content .mdl-list__item-avatar,.mdl-list__item--three-line .mdl-list__item-primary-content .mdl-list__item-icon{float:left}.mdl-list__item--three-line .mdl-list__item-secondary-content{height:52px}.mdl-list__item--three-line .mdl-list__item-text-body{font-size:14px;font-weight:400;letter-spacing:0;line-height:18px;height:52px;color:rgba(0,0,0,.54);display:block;padding:0}.mdl-menu__container{display:block;margin:0;padding:0;border:none;position:absolute;overflow:visible;height:0;width:0;visibility:hidden;z-index:-1}.mdl-menu__container.is-visible,.mdl-menu__container.is-animating{z-index:999;visibility:visible}.mdl-menu__outline{display:block;background:#fff;margin:0;padding:0;border:none;border-radius:2px;position:absolute;top:0;left:0;overflow:hidden;opacity:0;-webkit-transform:scale(0);transform:scale(0);-webkit-transform-origin:0 0;transform-origin:0 0;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);will-change:transform;transition:transform .3s cubic-bezier(.4,0,.2,1),opacity .2s cubic-bezier(.4,0,.2,1);transition:transform .3s cubic-bezier(.4,0,.2,1),opacity .2s cubic-bezier(.4,0,.2,1),-webkit-transform .3s cubic-bezier(.4,0,.2,1);z-index:-1}.mdl-menu__container.is-visible .mdl-menu__outline{opacity:1;-webkit-transform:scale(1);transform:scale(1);z-index:999}.mdl-menu__outline.mdl-menu--bottom-right{-webkit-transform-origin:100% 0;transform-origin:100% 0}.mdl-menu__outline.mdl-menu--top-left{-webkit-transform-origin:0 100%;transform-origin:0 100%}.mdl-menu__outline.mdl-menu--top-right{-webkit-transform-origin:100% 100%;transform-origin:100% 100%}.mdl-menu{position:absolute;list-style:none;top:0;left:0;height:auto;width:auto;min-width:124px;padding:8px 0;margin:0;opacity:0;clip:rect(0 0 0 0);z-index:-1}.mdl-menu__container.is-visible .mdl-menu{opacity:1;z-index:999}.mdl-menu.is-animating{transition:opacity .2s cubic-bezier(.4,0,.2,1),clip .3s cubic-bezier(.4,0,.2,1)}.mdl-menu.mdl-menu--bottom-right{left:auto;right:0}.mdl-menu.mdl-menu--top-left{top:auto;bottom:0}.mdl-menu.mdl-menu--top-right{top:auto;left:auto;bottom:0;right:0}.mdl-menu.mdl-menu--unaligned{top:auto;left:auto}.mdl-menu__item{display:block;border:none;color:rgba(0,0,0,.87);background-color:transparent;text-align:left;margin:0;padding:0 16px;outline-color:#bdbdbd;position:relative;overflow:hidden;font-size:14px;font-weight:400;letter-spacing:0;text-decoration:none;cursor:pointer;height:48px;line-height:48px;white-space:nowrap;opacity:0;transition:opacity .2s cubic-bezier(.4,0,.2,1);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-menu__container.is-visible .mdl-menu__item{opacity:1}.mdl-menu__item::-moz-focus-inner{border:0}.mdl-menu__item--full-bleed-divider{border-bottom:1px solid rgba(0,0,0,.12)}.mdl-menu__item[disabled],.mdl-menu__item[data-mdl-disabled]{color:#bdbdbd;background-color:transparent;cursor:auto}.mdl-menu__item[disabled]:hover,.mdl-menu__item[data-mdl-disabled]:hover{background-color:transparent}.mdl-menu__item[disabled]:focus,.mdl-menu__item[data-mdl-disabled]:focus{background-color:transparent}.mdl-menu__item[disabled] .mdl-ripple,.mdl-menu__item[data-mdl-disabled] .mdl-ripple{background:0 0}.mdl-menu__item:hover{background-color:#eee}.mdl-menu__item:focus{outline:none;background-color:#eee}.mdl-menu__item:active{background-color:#e0e0e0}.mdl-menu__item--ripple-container{display:block;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0;overflow:hidden}.mdl-progress{display:block;position:relative;height:4px;width:500px;max-width:100%}.mdl-progress>.bar{display:block;position:absolute;top:0;bottom:0;width:0%;transition:width .2s cubic-bezier(.4,0,.2,1)}.mdl-progress>.progressbar{background-color:#3f51b5;z-index:1;left:0}.mdl-progress>.bufferbar{background-image:linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);z-index:0;left:0}.mdl-progress>.auxbar{right:0}@supports (-webkit-appearance:none){.mdl-progress:not(.mdl-progress--indeterminate):not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate):not(.mdl-progress__indeterminate)>.auxbar{background-image:linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);-webkit-mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjEyIiBoZWlnaHQ9IjQiIHZpZXdQb3J0PSIwIDAgMTIgNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxlbGxpcHNlIGN4PSIyIiBjeT0iMiIgcng9IjIiIHJ5PSIyIj4KICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9ImN4IiBmcm9tPSIyIiB0bz0iLTEwIiBkdXI9IjAuNnMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIiAvPgogIDwvZWxsaXBzZT4KICA8ZWxsaXBzZSBjeD0iMTQiIGN5PSIyIiByeD0iMiIgcnk9IjIiIGNsYXNzPSJsb2FkZXIiPgogICAgPGFuaW1hdGUgYXR0cmlidXRlTmFtZT0iY3giIGZyb209IjE0IiB0bz0iMiIgZHVyPSIwLjZzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIgLz4KICA8L2VsbGlwc2U+Cjwvc3ZnPgo=");mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjEyIiBoZWlnaHQ9IjQiIHZpZXdQb3J0PSIwIDAgMTIgNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxlbGxpcHNlIGN4PSIyIiBjeT0iMiIgcng9IjIiIHJ5PSIyIj4KICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9ImN4IiBmcm9tPSIyIiB0bz0iLTEwIiBkdXI9IjAuNnMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIiAvPgogIDwvZWxsaXBzZT4KICA8ZWxsaXBzZSBjeD0iMTQiIGN5PSIyIiByeD0iMiIgcnk9IjIiIGNsYXNzPSJsb2FkZXIiPgogICAgPGFuaW1hdGUgYXR0cmlidXRlTmFtZT0iY3giIGZyb209IjE0IiB0bz0iMiIgZHVyPSIwLjZzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIgLz4KICA8L2VsbGlwc2U+Cjwvc3ZnPgo=")}}.mdl-progress:not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate)>.auxbar{background-image:linear-gradient(to right,rgba(255,255,255,.9),rgba(255,255,255,.9)),linear-gradient(to right,#3f51b5 ,#3f51b5)}.mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1{-webkit-animation-name:indeterminate1;animation-name:indeterminate1}.mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1,.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3{background-color:#3f51b5;-webkit-animation-duration:2s;animation-duration:2s;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;-webkit-animation-timing-function:linear;animation-timing-function:linear}.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3{background-image:none;-webkit-animation-name:indeterminate2;animation-name:indeterminate2}@-webkit-keyframes indeterminate1{0%{left:0%;width:0%}50%{left:25%;width:75%}75%{left:100%;width:0%}}@keyframes indeterminate1{0%{left:0%;width:0%}50%{left:25%;width:75%}75%{left:100%;width:0%}}@-webkit-keyframes indeterminate2{0%,50%{left:0%;width:0%}75%{left:0%;width:25%}100%{left:100%;width:0%}}@keyframes indeterminate2{0%,50%{left:0%;width:0%}75%{left:0%;width:25%}100%{left:100%;width:0%}}.mdl-navigation{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;box-sizing:border-box}.mdl-navigation__link{color:#424242;text-decoration:none;margin:0;font-size:14px;font-weight:400;line-height:24px;letter-spacing:0;opacity:.87}.mdl-navigation__link .material-icons{vertical-align:middle}.mdl-layout{width:100%;height:100%;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;overflow-y:auto;overflow-x:hidden;position:relative;-webkit-overflow-scrolling:touch}.mdl-layout.is-small-screen .mdl-layout--large-screen-only{display:none}.mdl-layout:not(.is-small-screen) .mdl-layout--small-screen-only{display:none}.mdl-layout__container{position:absolute;width:100%;height:100%}.mdl-layout__title,.mdl-layout-title{display:block;position:relative;font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:20px;line-height:1;letter-spacing:.02em;font-weight:400;box-sizing:border-box}.mdl-layout-spacer{-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1}.mdl-layout__drawer{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;width:240px;height:100%;max-height:100%;position:absolute;top:0;left:0;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);box-sizing:border-box;border-right:1px solid #e0e0e0;background:#fafafa;-webkit-transform:translateX(-250px);transform:translateX(-250px);-webkit-transform-style:preserve-3d;transform-style:preserve-3d;will-change:transform;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:transform;transition-property:transform,-webkit-transform;color:#424242;overflow:visible;overflow-y:auto;z-index:5}.mdl-layout__drawer.is-visible{-webkit-transform:translateX(0);transform:translateX(0)}.mdl-layout__drawer.is-visible~.mdl-layout__content.mdl-layout__content{overflow:hidden}.mdl-layout__drawer>*{-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0}.mdl-layout__drawer>.mdl-layout__title,.mdl-layout__drawer>.mdl-layout-title{line-height:64px;padding-left:40px}@media screen and (max-width:1024px){.mdl-layout__drawer>.mdl-layout__title,.mdl-layout__drawer>.mdl-layout-title{line-height:56px;padding-left:16px}}.mdl-layout__drawer .mdl-navigation{-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-align-items:stretch;-ms-flex-align:stretch;-ms-grid-row-align:stretch;align-items:stretch;padding-top:16px}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link{display:block;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;padding:16px 40px;margin:0;color:#757575}@media screen and (max-width:1024px){.mdl-layout__drawer .mdl-navigation .mdl-navigation__link{padding:16px}}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link:hover{background-color:#e0e0e0}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link--current{background-color:#000;color:#e0e0e0}@media screen and (min-width:1025px){.mdl-layout--fixed-drawer>.mdl-layout__drawer{-webkit-transform:translateX(0);transform:translateX(0)}}.mdl-layout__drawer-button{display:block;position:absolute;height:48px;width:48px;border:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;overflow:hidden;text-align:center;cursor:pointer;font-size:26px;line-height:50px;font-family:Helvetica,Arial,sans-serif;margin:10px 12px;top:0;left:0;color:#fff;z-index:4}.mdl-layout__header .mdl-layout__drawer-button{position:absolute;color:#fff;background-color:inherit}@media screen and (max-width:1024px){.mdl-layout__header .mdl-layout__drawer-button{margin:4px}}@media screen and (max-width:1024px){.mdl-layout__drawer-button{margin:4px;color:rgba(0,0,0,.5)}}@media screen and (min-width:1025px){.mdl-layout--fixed-drawer>.mdl-layout__drawer-button,.mdl-layout--no-desktop-drawer-button .mdl-layout__drawer-button{display:none}}.mdl-layout--no-drawer-button .mdl-layout__drawer-button{display:none}.mdl-layout__header{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-justify-content:flex-start;-ms-flex-pack:start;justify-content:flex-start;box-sizing:border-box;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;width:100%;margin:0;padding:0;border:none;min-height:64px;max-height:1000px;z-index:3;background-color:#3f51b5;color:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:max-height,box-shadow}@media screen and (max-width:1024px){.mdl-layout__header{min-height:56px}}.mdl-layout--fixed-drawer.is-upgraded:not(.is-small-screen)>.mdl-layout__header{margin-left:240px;width:calc(100% - 240px)}@media screen and (min-width:1025px){.mdl-layout--fixed-drawer>.mdl-layout__header .mdl-layout__header-row{padding-left:40px}}.mdl-layout__header>.mdl-layout-icon{position:absolute;left:40px;top:16px;height:32px;width:32px;overflow:hidden;z-index:3;display:block}@media screen and (max-width:1024px){.mdl-layout__header>.mdl-layout-icon{left:16px;top:12px}}.mdl-layout.has-drawer .mdl-layout__header>.mdl-layout-icon{display:none}.mdl-layout__header.is-compact{max-height:64px}@media screen and (max-width:1024px){.mdl-layout__header.is-compact{max-height:56px}}.mdl-layout__header.is-compact.has-tabs{height:112px}@media screen and (max-width:1024px){.mdl-layout__header.is-compact.has-tabs{min-height:104px}}@media screen and (max-width:1024px){.mdl-layout__header{display:none}.mdl-layout--fixed-header>.mdl-layout__header{display:-webkit-flex;display:-ms-flexbox;display:flex}}.mdl-layout__header--transparent.mdl-layout__header--transparent{background-color:transparent;box-shadow:none}.mdl-layout__header--seamed,.mdl-layout__header--scroll{box-shadow:none}.mdl-layout__header--waterfall{box-shadow:none;overflow:hidden}.mdl-layout__header--waterfall.is-casting-shadow{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-layout__header--waterfall.mdl-layout__header--waterfall-hide-top{-webkit-justify-content:flex-end;-ms-flex-pack:end;justify-content:flex-end}.mdl-layout__header-row{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;box-sizing:border-box;-webkit-align-self:stretch;-ms-flex-item-align:stretch;align-self:stretch;-webkit-align-items:center;-ms-flex-align:center;align-items:center;height:64px;margin:0;padding:0 40px 0 80px}.mdl-layout--no-drawer-button .mdl-layout__header-row{padding-left:40px}@media screen and (min-width:1025px){.mdl-layout--no-desktop-drawer-button .mdl-layout__header-row{padding-left:40px}}@media screen and (max-width:1024px){.mdl-layout__header-row{height:56px;padding:0 16px 0 72px}.mdl-layout--no-drawer-button .mdl-layout__header-row{padding-left:16px}}.mdl-layout__header-row>*{-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0}.mdl-layout__header--scroll .mdl-layout__header-row{width:100%}.mdl-layout__header-row .mdl-navigation{margin:0;padding:0;height:64px;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-align-items:center;-ms-flex-align:center;-ms-grid-row-align:center;align-items:center}@media screen and (max-width:1024px){.mdl-layout__header-row .mdl-navigation{height:56px}}.mdl-layout__header-row .mdl-navigation__link{display:block;color:#fff;line-height:64px;padding:0 24px}@media screen and (max-width:1024px){.mdl-layout__header-row .mdl-navigation__link{line-height:56px;padding:0 16px}}.mdl-layout__obfuscator{background-color:transparent;position:absolute;top:0;left:0;height:100%;width:100%;z-index:4;visibility:hidden;transition-property:background-color;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-layout__obfuscator.is-visible{background-color:rgba(0,0,0,.5);visibility:visible}@supports (pointer-events:auto){.mdl-layout__obfuscator{background-color:rgba(0,0,0,.5);opacity:0;transition-property:opacity;visibility:visible;pointer-events:none}.mdl-layout__obfuscator.is-visible{pointer-events:auto;opacity:1}}.mdl-layout__content{-ms-flex:0 1 auto;position:relative;display:inline-block;overflow-y:auto;overflow-x:hidden;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;z-index:1;-webkit-overflow-scrolling:touch}.mdl-layout--fixed-drawer>.mdl-layout__content{margin-left:240px}.mdl-layout__container.has-scrolling-header .mdl-layout__content{overflow:visible}@media screen and (max-width:1024px){.mdl-layout--fixed-drawer>.mdl-layout__content{margin-left:0}.mdl-layout__container.has-scrolling-header .mdl-layout__content{overflow-y:auto;overflow-x:hidden}}.mdl-layout__tab-bar{height:96px;margin:0;width:calc(100% - 112px);padding:0 0 0 56px;display:-webkit-flex;display:-ms-flexbox;display:flex;background-color:#3f51b5;overflow-y:hidden;overflow-x:scroll}.mdl-layout__tab-bar::-webkit-scrollbar{display:none}.mdl-layout--no-drawer-button .mdl-layout__tab-bar{padding-left:16px;width:calc(100% - 32px)}@media screen and (min-width:1025px){.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar{padding-left:16px;width:calc(100% - 32px)}}@media screen and (max-width:1024px){.mdl-layout__tab-bar{width:calc(100% - 60px);padding:0 0 0 60px}.mdl-layout--no-drawer-button .mdl-layout__tab-bar{width:calc(100% - 8px);padding-left:4px}}.mdl-layout--fixed-tabs .mdl-layout__tab-bar{padding:0;overflow:hidden;width:100%}.mdl-layout__tab-bar-container{position:relative;height:48px;width:100%;border:none;margin:0;z-index:2;-webkit-flex-grow:0;-ms-flex-positive:0;flex-grow:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;overflow:hidden}.mdl-layout__container>.mdl-layout__tab-bar-container{position:absolute;top:0;left:0}.mdl-layout__tab-bar-button{display:inline-block;position:absolute;top:0;height:48px;width:56px;z-index:4;text-align:center;background-color:#3f51b5;color:transparent;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar-button,.mdl-layout--no-drawer-button .mdl-layout__tab-bar-button{width:16px}.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar-button .material-icons,.mdl-layout--no-drawer-button .mdl-layout__tab-bar-button .material-icons{position:relative;left:-4px}@media screen and (max-width:1024px){.mdl-layout__tab-bar-button{display:none;width:60px}}.mdl-layout--fixed-tabs .mdl-layout__tab-bar-button{display:none}.mdl-layout__tab-bar-button .material-icons{line-height:48px}.mdl-layout__tab-bar-button.is-active{color:#fff}.mdl-layout__tab-bar-left-button{left:0}.mdl-layout__tab-bar-right-button{right:0}.mdl-layout__tab{margin:0;border:none;padding:0 24px;float:left;position:relative;display:block;-webkit-flex-grow:0;-ms-flex-positive:0;flex-grow:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;text-decoration:none;height:48px;line-height:48px;text-align:center;font-weight:500;font-size:14px;text-transform:uppercase;color:rgba(255,255,255,.6);overflow:hidden}@media screen and (max-width:1024px){.mdl-layout__tab{padding:0 12px}}.mdl-layout--fixed-tabs .mdl-layout__tab{float:none;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;padding:0}.mdl-layout.is-upgraded .mdl-layout__tab.is-active{color:#fff}.mdl-layout.is-upgraded .mdl-layout__tab.is-active::after{height:2px;width:100%;display:block;content:" ";bottom:0;left:0;position:absolute;background:#ff4081;-webkit-animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;transition:all 1s cubic-bezier(.4,0,1,1)}.mdl-layout__tab .mdl-layout__tab-ripple-container{display:block;position:absolute;height:100%;width:100%;left:0;top:0;z-index:1;overflow:hidden}.mdl-layout__tab .mdl-layout__tab-ripple-container .mdl-ripple{background-color:#fff}.mdl-layout__tab-panel{display:block}.mdl-layout.is-upgraded .mdl-layout__tab-panel{display:none}.mdl-layout.is-upgraded .mdl-layout__tab-panel.is-active{display:block}.mdl-radio{position:relative;font-size:16px;line-height:24px;display:inline-block;box-sizing:border-box;margin:0;padding-left:0}.mdl-radio.is-upgraded{padding-left:24px}.mdl-radio__button{line-height:24px}.mdl-radio.is-upgraded .mdl-radio__button{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-radio__outer-circle{position:absolute;top:4px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;margin:0;cursor:pointer;border:2px solid rgba(0,0,0,.54);border-radius:50%;z-index:2}.mdl-radio.is-checked .mdl-radio__outer-circle{border:2px solid #3f51b5}.mdl-radio__outer-circle fieldset[disabled] .mdl-radio,.mdl-radio.is-disabled .mdl-radio__outer-circle{border:2px solid rgba(0,0,0,.26);cursor:auto}.mdl-radio__inner-circle{position:absolute;z-index:1;margin:0;top:8px;left:4px;box-sizing:border-box;width:8px;height:8px;cursor:pointer;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transform:scale3d(0,0,0);transform:scale3d(0,0,0);border-radius:50%;background:#3f51b5}.mdl-radio.is-checked .mdl-radio__inner-circle{-webkit-transform:scale3d(1,1,1);transform:scale3d(1,1,1)}fieldset[disabled] .mdl-radio .mdl-radio__inner-circle,.mdl-radio.is-disabled .mdl-radio__inner-circle{background:rgba(0,0,0,.26);cursor:auto}.mdl-radio.is-focused .mdl-radio__inner-circle{box-shadow:0 0 0 10px rgba(0,0,0,.1)}.mdl-radio__label{cursor:pointer}fieldset[disabled] .mdl-radio .mdl-radio__label,.mdl-radio.is-disabled .mdl-radio__label{color:rgba(0,0,0,.26);cursor:auto}.mdl-radio__ripple-container{position:absolute;z-index:2;top:-9px;left:-13px;box-sizing:border-box;width:42px;height:42px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-radio__ripple-container .mdl-ripple{background:#3f51b5}fieldset[disabled] .mdl-radio .mdl-radio__ripple-container,.mdl-radio.is-disabled .mdl-radio__ripple-container{cursor:auto}fieldset[disabled] .mdl-radio .mdl-radio__ripple-container .mdl-ripple,.mdl-radio.is-disabled .mdl-radio__ripple-container .mdl-ripple{background:0 0}_:-ms-input-placeholder,:root .mdl-slider.mdl-slider.is-upgraded{-ms-appearance:none;height:32px;margin:0}.mdl-slider{width:calc(100% - 40px);margin:0 20px}.mdl-slider.is-upgraded{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:2px;background:0 0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;outline:0;padding:0;color:#3f51b5;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;z-index:1;cursor:pointer}.mdl-slider.is-upgraded::-moz-focus-outer{border:0}.mdl-slider.is-upgraded::-ms-tooltip{display:none}.mdl-slider.is-upgraded::-webkit-slider-runnable-track{background:0 0}.mdl-slider.is-upgraded::-moz-range-track{background:0 0;border:none}.mdl-slider.is-upgraded::-ms-track{background:0 0;color:transparent;height:2px;width:100%;border:none}.mdl-slider.is-upgraded::-ms-fill-lower{padding:0;background:linear-gradient(to right,transparent,transparent 16px,#3f51b5 16px,#3f51b5 0)}.mdl-slider.is-upgraded::-ms-fill-upper{padding:0;background:linear-gradient(to left,transparent,transparent 16px,rgba(0,0,0,.26)16px,rgba(0,0,0,.26)0)}.mdl-slider.is-upgraded::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;box-sizing:border-box;border-radius:50%;background:#3f51b5;border:none;transition:transform .18s cubic-bezier(.4,0,.2,1),border .18s cubic-bezier(.4,0,.2,1),box-shadow .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1);transition:transform .18s cubic-bezier(.4,0,.2,1),border .18s cubic-bezier(.4,0,.2,1),box-shadow .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1),-webkit-transform .18s cubic-bezier(.4,0,.2,1)}.mdl-slider.is-upgraded::-moz-range-thumb{-moz-appearance:none;width:12px;height:12px;box-sizing:border-box;border-radius:50%;background-image:none;background:#3f51b5;border:none}.mdl-slider.is-upgraded:focus:not(:active)::-webkit-slider-thumb{box-shadow:0 0 0 10px rgba(63,81,181,.26)}.mdl-slider.is-upgraded:focus:not(:active)::-moz-range-thumb{box-shadow:0 0 0 10px rgba(63,81,181,.26)}.mdl-slider.is-upgraded:active::-webkit-slider-thumb{background-image:none;background:#3f51b5;-webkit-transform:scale(1.5);transform:scale(1.5)}.mdl-slider.is-upgraded:active::-moz-range-thumb{background-image:none;background:#3f51b5;transform:scale(1.5)}.mdl-slider.is-upgraded::-ms-thumb{width:32px;height:32px;border:none;border-radius:50%;background:#3f51b5;transform:scale(.375);transition:transform .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1);transition:transform .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1),-webkit-transform .18s cubic-bezier(.4,0,.2,1)}.mdl-slider.is-upgraded:focus:not(:active)::-ms-thumb{background:radial-gradient(circle closest-side,#3f51b5 0%,#3f51b5 37.5%,rgba(63,81,181,.26)37.5%,rgba(63,81,181,.26)100%);transform:scale(1)}.mdl-slider.is-upgraded:active::-ms-thumb{background:#3f51b5;transform:scale(.5625)}.mdl-slider.is-upgraded.is-lowest-value::-webkit-slider-thumb{border:2px solid rgba(0,0,0,.26);background:0 0}.mdl-slider.is-upgraded.is-lowest-value::-moz-range-thumb{border:2px solid rgba(0,0,0,.26);background:0 0}.mdl-slider.is-upgraded.is-lowest-value+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-webkit-slider-thumb{box-shadow:0 0 0 10px rgba(0,0,0,.12);background:rgba(0,0,0,.12)}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-moz-range-thumb{box-shadow:0 0 0 10px rgba(0,0,0,.12);background:rgba(0,0,0,.12)}.mdl-slider.is-upgraded.is-lowest-value:active::-webkit-slider-thumb{border:1.6px solid rgba(0,0,0,.26);-webkit-transform:scale(1.5);transform:scale(1.5)}.mdl-slider.is-upgraded.is-lowest-value:active+.mdl-slider__background-flex>.mdl-slider__background-upper{left:9px}.mdl-slider.is-upgraded.is-lowest-value:active::-moz-range-thumb{border:1.5px solid rgba(0,0,0,.26);transform:scale(1.5)}.mdl-slider.is-upgraded.is-lowest-value::-ms-thumb{background:radial-gradient(circle closest-side,transparent 0%,transparent 66.67%,rgba(0,0,0,.26)66.67%,rgba(0,0,0,.26)100%)}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-ms-thumb{background:radial-gradient(circle closest-side,rgba(0,0,0,.12)0%,rgba(0,0,0,.12)25%,rgba(0,0,0,.26)25%,rgba(0,0,0,.26)37.5%,rgba(0,0,0,.12)37.5%,rgba(0,0,0,.12)100%);transform:scale(1)}.mdl-slider.is-upgraded.is-lowest-value:active::-ms-thumb{transform:scale(.5625);background:radial-gradient(circle closest-side,transparent 0%,transparent 77.78%,rgba(0,0,0,.26)77.78%,rgba(0,0,0,.26)100%)}.mdl-slider.is-upgraded.is-lowest-value::-ms-fill-lower{background:0 0}.mdl-slider.is-upgraded.is-lowest-value::-ms-fill-upper{margin-left:6px}.mdl-slider.is-upgraded.is-lowest-value:active::-ms-fill-upper{margin-left:9px}.mdl-slider.is-upgraded:disabled:focus::-webkit-slider-thumb,.mdl-slider.is-upgraded:disabled:active::-webkit-slider-thumb,.mdl-slider.is-upgraded:disabled::-webkit-slider-thumb{-webkit-transform:scale(.667);transform:scale(.667);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded:disabled:focus::-moz-range-thumb,.mdl-slider.is-upgraded:disabled:active::-moz-range-thumb,.mdl-slider.is-upgraded:disabled::-moz-range-thumb{transform:scale(.667);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded:disabled+.mdl-slider__background-flex>.mdl-slider__background-lower{background-color:rgba(0,0,0,.26);left:-6px}.mdl-slider.is-upgraded:disabled+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-webkit-slider-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-webkit-slider-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled::-webkit-slider-thumb{border:3px solid rgba(0,0,0,.26);background:0 0;-webkit-transform:scale(.667);transform:scale(.667)}.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-moz-range-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-moz-range-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled::-moz-range-thumb{border:3px solid rgba(0,0,0,.26);background:0 0;transform:scale(.667)}.mdl-slider.is-upgraded.is-lowest-value:disabled:active+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded:disabled:focus::-ms-thumb,.mdl-slider.is-upgraded:disabled:active::-ms-thumb,.mdl-slider.is-upgraded:disabled::-ms-thumb{transform:scale(.25);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-ms-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-ms-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled::-ms-thumb{transform:scale(.25);background:radial-gradient(circle closest-side,transparent 0%,transparent 50%,rgba(0,0,0,.26)50%,rgba(0,0,0,.26)100%)}.mdl-slider.is-upgraded:disabled::-ms-fill-lower{margin-right:6px;background:linear-gradient(to right,transparent,transparent 25px,rgba(0,0,0,.26)25px,rgba(0,0,0,.26)0)}.mdl-slider.is-upgraded:disabled::-ms-fill-upper{margin-left:6px}.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-ms-fill-upper{margin-left:6px}.mdl-slider__ie-container{height:18px;overflow:visible;border:none;margin:none;padding:none}.mdl-slider__container{height:18px;position:relative;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row}.mdl-slider__container,.mdl-slider__background-flex{background:0 0;display:-webkit-flex;display:-ms-flexbox;display:flex}.mdl-slider__background-flex{position:absolute;height:2px;width:calc(100% - 52px);top:50%;left:0;margin:0 26px;overflow:hidden;border:0;padding:0;-webkit-transform:translate(0,-1px);transform:translate(0,-1px)}.mdl-slider__background-lower{background:#3f51b5}.mdl-slider__background-lower,.mdl-slider__background-upper{-webkit-flex:0;-ms-flex:0;flex:0;position:relative;border:0;padding:0}.mdl-slider__background-upper{background:rgba(0,0,0,.26);transition:left .18s cubic-bezier(.4,0,.2,1)}.mdl-snackbar{position:fixed;bottom:0;left:50%;cursor:default;background-color:#323232;z-index:3;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;font-family:"Roboto","Helvetica","Arial",sans-serif;will-change:transform;-webkit-transform:translate(0,80px);transform:translate(0,80px);transition:transform .25s cubic-bezier(.4,0,1,1);transition:transform .25s cubic-bezier(.4,0,1,1),-webkit-transform .25s cubic-bezier(.4,0,1,1);pointer-events:none}@media (max-width:479px){.mdl-snackbar{width:100%;left:0;min-height:48px;max-height:80px}}@media (min-width:480px){.mdl-snackbar{min-width:288px;max-width:568px;border-radius:2px;-webkit-transform:translate(-50%,80px);transform:translate(-50%,80px)}}.mdl-snackbar--active{-webkit-transform:translate(0,0);transform:translate(0,0);pointer-events:auto;transition:transform .25s cubic-bezier(0,0,.2,1);transition:transform .25s cubic-bezier(0,0,.2,1),-webkit-transform .25s cubic-bezier(0,0,.2,1)}@media (min-width:480px){.mdl-snackbar--active{-webkit-transform:translate(-50%,0);transform:translate(-50%,0)}}.mdl-snackbar__text{padding:14px 12px 14px 24px;vertical-align:middle;color:#fff;float:left}.mdl-snackbar__action{background:0 0;border:none;color:#ff4081;float:right;padding:14px 24px 14px 12px;font-family:"Roboto","Helvetica","Arial",sans-serif;font-size:14px;font-weight:500;text-transform:uppercase;line-height:1;letter-spacing:0;overflow:hidden;outline:none;opacity:0;pointer-events:none;cursor:pointer;text-decoration:none;text-align:center;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center}.mdl-snackbar__action::-moz-focus-inner{border:0}.mdl-snackbar__action:not([aria-hidden]){opacity:1;pointer-events:auto}.mdl-spinner{display:inline-block;position:relative;width:28px;height:28px}.mdl-spinner:not(.is-upgraded).is-active:after{content:"Loading..."}.mdl-spinner.is-upgraded.is-active{-webkit-animation:mdl-spinner__container-rotate 1568.23529412ms linear infinite;animation:mdl-spinner__container-rotate 1568.23529412ms linear infinite}@-webkit-keyframes mdl-spinner__container-rotate{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes mdl-spinner__container-rotate{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.mdl-spinner__layer{position:absolute;width:100%;height:100%;opacity:0}.mdl-spinner__layer-1{border-color:#42a5f5}.mdl-spinner--single-color .mdl-spinner__layer-1{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-1{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-1-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-1-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-2{border-color:#f44336}.mdl-spinner--single-color .mdl-spinner__layer-2{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-2{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-2-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-2-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-3{border-color:#fdd835}.mdl-spinner--single-color .mdl-spinner__layer-3{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-3{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-3-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-3-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-4{border-color:#4caf50}.mdl-spinner--single-color .mdl-spinner__layer-4{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-4{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-4-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-4-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}@-webkit-keyframes mdl-spinner__fill-unfill-rotate{12.5%{-webkit-transform:rotate(135deg);transform:rotate(135deg)}25%{-webkit-transform:rotate(270deg);transform:rotate(270deg)}37.5%{-webkit-transform:rotate(405deg);transform:rotate(405deg)}50%{-webkit-transform:rotate(540deg);transform:rotate(540deg)}62.5%{-webkit-transform:rotate(675deg);transform:rotate(675deg)}75%{-webkit-transform:rotate(810deg);transform:rotate(810deg)}87.5%{-webkit-transform:rotate(945deg);transform:rotate(945deg)}to{-webkit-transform:rotate(1080deg);transform:rotate(1080deg)}}@keyframes mdl-spinner__fill-unfill-rotate{12.5%{-webkit-transform:rotate(135deg);transform:rotate(135deg)}25%{-webkit-transform:rotate(270deg);transform:rotate(270deg)}37.5%{-webkit-transform:rotate(405deg);transform:rotate(405deg)}50%{-webkit-transform:rotate(540deg);transform:rotate(540deg)}62.5%{-webkit-transform:rotate(675deg);transform:rotate(675deg)}75%{-webkit-transform:rotate(810deg);transform:rotate(810deg)}87.5%{-webkit-transform:rotate(945deg);transform:rotate(945deg)}to{-webkit-transform:rotate(1080deg);transform:rotate(1080deg)}}@-webkit-keyframes mdl-spinner__layer-1-fade-in-out{from,25%{opacity:.99}26%,89%{opacity:0}90%,100%{opacity:.99}}@keyframes mdl-spinner__layer-1-fade-in-out{from,25%{opacity:.99}26%,89%{opacity:0}90%,100%{opacity:.99}}@-webkit-keyframes mdl-spinner__layer-2-fade-in-out{from,15%{opacity:0}25%,50%{opacity:.99}51%{opacity:0}}@keyframes mdl-spinner__layer-2-fade-in-out{from,15%{opacity:0}25%,50%{opacity:.99}51%{opacity:0}}@-webkit-keyframes mdl-spinner__layer-3-fade-in-out{from,40%{opacity:0}50%,75%{opacity:.99}76%{opacity:0}}@keyframes mdl-spinner__layer-3-fade-in-out{from,40%{opacity:0}50%,75%{opacity:.99}76%{opacity:0}}@-webkit-keyframes mdl-spinner__layer-4-fade-in-out{from,65%{opacity:0}75%,90%{opacity:.99}100%{opacity:0}}@keyframes mdl-spinner__layer-4-fade-in-out{from,65%{opacity:0}75%,90%{opacity:.99}100%{opacity:0}}.mdl-spinner__gap-patch{position:absolute;box-sizing:border-box;top:0;left:45%;width:10%;height:100%;overflow:hidden;border-color:inherit}.mdl-spinner__gap-patch .mdl-spinner__circle{width:1000%;left:-450%}.mdl-spinner__circle-clipper{display:inline-block;position:relative;width:50%;height:100%;overflow:hidden;border-color:inherit}.mdl-spinner__circle-clipper .mdl-spinner__circle{width:200%}.mdl-spinner__circle{box-sizing:border-box;height:100%;border-width:3px;border-style:solid;border-color:inherit;border-bottom-color:transparent!important;border-radius:50%;-webkit-animation:none;animation:none;position:absolute;top:0;right:0;bottom:0;left:0}.mdl-spinner__left .mdl-spinner__circle{border-right-color:transparent!important;-webkit-transform:rotate(129deg);transform:rotate(129deg)}.mdl-spinner.is-active .mdl-spinner__left .mdl-spinner__circle{-webkit-animation:mdl-spinner__left-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__left-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__right .mdl-spinner__circle{left:-100%;border-left-color:transparent!important;-webkit-transform:rotate(-129deg);transform:rotate(-129deg)}.mdl-spinner.is-active .mdl-spinner__right .mdl-spinner__circle{-webkit-animation:mdl-spinner__right-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__right-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both}@-webkit-keyframes mdl-spinner__left-spin{from{-webkit-transform:rotate(130deg);transform:rotate(130deg)}50%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(130deg);transform:rotate(130deg)}}@keyframes mdl-spinner__left-spin{from{-webkit-transform:rotate(130deg);transform:rotate(130deg)}50%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(130deg);transform:rotate(130deg)}}@-webkit-keyframes mdl-spinner__right-spin{from{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}50%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}to{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}}@keyframes mdl-spinner__right-spin{from{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}50%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}to{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}}.mdl-switch{position:relative;z-index:1;vertical-align:middle;display:inline-block;box-sizing:border-box;width:100%;height:24px;margin:0;padding:0;overflow:visible;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-switch.is-upgraded{padding-left:28px}.mdl-switch__input{line-height:24px}.mdl-switch.is-upgraded .mdl-switch__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-switch__track{background:rgba(0,0,0,.26);position:absolute;left:0;top:5px;height:14px;width:36px;border-radius:14px;cursor:pointer}.mdl-switch.is-checked .mdl-switch__track{background:rgba(63,81,181,.5)}.mdl-switch__track fieldset[disabled] .mdl-switch,.mdl-switch.is-disabled .mdl-switch__track{background:rgba(0,0,0,.12);cursor:auto}.mdl-switch__thumb{background:#fafafa;position:absolute;left:0;top:2px;height:20px;width:20px;border-radius:50%;cursor:pointer;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:left}.mdl-switch.is-checked .mdl-switch__thumb{background:#3f51b5;left:16px;box-shadow:0 3px 4px 0 rgba(0,0,0,.14),0 3px 3px -2px rgba(0,0,0,.2),0 1px 8px 0 rgba(0,0,0,.12)}.mdl-switch__thumb fieldset[disabled] .mdl-switch,.mdl-switch.is-disabled .mdl-switch__thumb{background:#bdbdbd;cursor:auto}.mdl-switch__focus-helper{position:absolute;top:50%;left:50%;-webkit-transform:translate(-4px,-4px);transform:translate(-4px,-4px);display:inline-block;box-sizing:border-box;width:8px;height:8px;border-radius:50%;background-color:transparent}.mdl-switch.is-focused .mdl-switch__focus-helper{box-shadow:0 0 0 20px rgba(0,0,0,.1);background-color:rgba(0,0,0,.1)}.mdl-switch.is-focused.is-checked .mdl-switch__focus-helper{box-shadow:0 0 0 20px rgba(63,81,181,.26);background-color:rgba(63,81,181,.26)}.mdl-switch__label{position:relative;cursor:pointer;font-size:16px;line-height:24px;margin:0;left:24px}.mdl-switch__label fieldset[disabled] .mdl-switch,.mdl-switch.is-disabled .mdl-switch__label{color:#bdbdbd;cursor:auto}.mdl-switch__ripple-container{position:absolute;z-index:2;top:-12px;left:-14px;box-sizing:border-box;width:48px;height:48px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000);transition-duration:.4s;transition-timing-function:step-end;transition-property:left}.mdl-switch__ripple-container .mdl-ripple{background:#3f51b5}.mdl-switch__ripple-container fieldset[disabled] .mdl-switch,.mdl-switch.is-disabled .mdl-switch__ripple-container{cursor:auto}fieldset[disabled] .mdl-switch .mdl-switch__ripple-container .mdl-ripple,.mdl-switch.is-disabled .mdl-switch__ripple-container .mdl-ripple{background:0 0}.mdl-switch.is-checked .mdl-switch__ripple-container{left:2px}.mdl-tabs{display:block;width:100%}.mdl-tabs__tab-bar{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-content:space-between;-ms-flex-line-pack:justify;align-content:space-between;-webkit-align-items:flex-start;-ms-flex-align:start;align-items:flex-start;height:48px;padding:0;margin:0;border-bottom:1px solid #e0e0e0}.mdl-tabs__tab{margin:0;border:none;padding:0 24px;float:left;position:relative;display:block;text-decoration:none;height:48px;line-height:48px;text-align:center;font-weight:500;font-size:14px;text-transform:uppercase;color:rgba(0,0,0,.54);overflow:hidden}.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active{color:rgba(0,0,0,.87)}.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active:after{height:2px;width:100%;display:block;content:" ";bottom:0;left:0;position:absolute;background:#3f51b5;-webkit-animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;transition:all 1s cubic-bezier(.4,0,1,1)}.mdl-tabs__tab .mdl-tabs__ripple-container{display:block;position:absolute;height:100%;width:100%;left:0;top:0;z-index:1;overflow:hidden}.mdl-tabs__tab .mdl-tabs__ripple-container .mdl-ripple{background:#3f51b5}.mdl-tabs__panel{display:block}.mdl-tabs.is-upgraded .mdl-tabs__panel{display:none}.mdl-tabs.is-upgraded .mdl-tabs__panel.is-active{display:block}@-webkit-keyframes border-expand{0%{opacity:0;width:0}100%{opacity:1;width:100%}}@keyframes border-expand{0%{opacity:0;width:0}100%{opacity:1;width:100%}}.mdl-textfield{position:relative;font-size:16px;display:inline-block;box-sizing:border-box;width:300px;max-width:100%;margin:0;padding:20px 0}.mdl-textfield .mdl-button{position:absolute;bottom:20px}.mdl-textfield--align-right{text-align:right}.mdl-textfield--full-width{width:100%}.mdl-textfield--expandable{min-width:32px;width:auto;min-height:32px}.mdl-textfield__input{border:none;border-bottom:1px solid rgba(0,0,0,.12);display:block;font-size:16px;font-family:"Helvetica","Arial",sans-serif;margin:0;padding:4px 0;width:100%;background:0 0;text-align:left;color:inherit}.mdl-textfield__input[type="number"]{-moz-appearance:textfield}.mdl-textfield__input[type="number"]::-webkit-inner-spin-button,.mdl-textfield__input[type="number"]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.mdl-textfield.is-focused .mdl-textfield__input{outline:none}.mdl-textfield.is-invalid .mdl-textfield__input{border-color:#d50000;box-shadow:none}fieldset[disabled] .mdl-textfield .mdl-textfield__input,.mdl-textfield.is-disabled .mdl-textfield__input{background-color:transparent;border-bottom:1px dotted rgba(0,0,0,.12);color:rgba(0,0,0,.26)}.mdl-textfield textarea.mdl-textfield__input{display:block}.mdl-textfield__label{bottom:0;color:rgba(0,0,0,.26);font-size:16px;left:0;right:0;pointer-events:none;position:absolute;display:block;top:24px;width:100%;overflow:hidden;white-space:nowrap;text-align:left}.mdl-textfield.is-dirty .mdl-textfield__label,.mdl-textfield.has-placeholder .mdl-textfield__label{visibility:hidden}.mdl-textfield--floating-label .mdl-textfield__label{transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-textfield--floating-label.has-placeholder .mdl-textfield__label{transition:none}fieldset[disabled] .mdl-textfield .mdl-textfield__label,.mdl-textfield.is-disabled.is-disabled .mdl-textfield__label{color:rgba(0,0,0,.26)}.mdl-textfield--floating-label.is-focused .mdl-textfield__label,.mdl-textfield--floating-label.is-dirty .mdl-textfield__label,.mdl-textfield--floating-label.has-placeholder .mdl-textfield__label{color:#3f51b5;font-size:12px;top:4px;visibility:visible}.mdl-textfield--floating-label.is-focused .mdl-textfield__expandable-holder .mdl-textfield__label,.mdl-textfield--floating-label.is-dirty .mdl-textfield__expandable-holder .mdl-textfield__label,.mdl-textfield--floating-label.has-placeholder .mdl-textfield__expandable-holder .mdl-textfield__label{top:-16px}.mdl-textfield--floating-label.is-invalid .mdl-textfield__label{color:#d50000;font-size:12px}.mdl-textfield__label:after{background-color:#3f51b5;bottom:20px;content:'';height:2px;left:45%;position:absolute;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);visibility:hidden;width:10px}.mdl-textfield.is-focused .mdl-textfield__label:after{left:0;visibility:visible;width:100%}.mdl-textfield.is-invalid .mdl-textfield__label:after{background-color:#d50000}.mdl-textfield__error{color:#d50000;position:absolute;font-size:12px;margin-top:3px;visibility:hidden;display:block}.mdl-textfield.is-invalid .mdl-textfield__error{visibility:visible}.mdl-textfield__expandable-holder{display:inline-block;position:relative;margin-left:32px;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);display:inline-block;max-width:.1px}.mdl-textfield.is-focused .mdl-textfield__expandable-holder,.mdl-textfield.is-dirty .mdl-textfield__expandable-holder{max-width:600px}.mdl-textfield__expandable-holder .mdl-textfield__label:after{bottom:0}.mdl-tooltip{-webkit-transform:scale(0);transform:scale(0);-webkit-transform-origin:top center;transform-origin:top center;will-change:transform;z-index:999;background:rgba(97,97,97,.9);border-radius:2px;color:#fff;display:inline-block;font-size:10px;font-weight:500;line-height:14px;max-width:170px;position:fixed;top:-500px;left:-500px;padding:8px;text-align:center}.mdl-tooltip.is-active{-webkit-animation:pulse 200ms cubic-bezier(0,0,.2,1)forwards;animation:pulse 200ms cubic-bezier(0,0,.2,1)forwards}.mdl-tooltip--large{line-height:14px;font-size:14px;padding:16px}@-webkit-keyframes pulse{0%{-webkit-transform:scale(0);transform:scale(0);opacity:0}50%{-webkit-transform:scale(.99);transform:scale(.99)}100%{-webkit-transform:scale(1);transform:scale(1);opacity:1;visibility:visible}}@keyframes pulse{0%{-webkit-transform:scale(0);transform:scale(0);opacity:0}50%{-webkit-transform:scale(.99);transform:scale(.99)}100%{-webkit-transform:scale(1);transform:scale(1);opacity:1;visibility:visible}}.mdl-shadow--2dp{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-shadow--3dp{box-shadow:0 3px 4px 0 rgba(0,0,0,.14),0 3px 3px -2px rgba(0,0,0,.2),0 1px 8px 0 rgba(0,0,0,.12)}.mdl-shadow--4dp{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2)}.mdl-shadow--6dp{box-shadow:0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12),0 3px 5px -1px rgba(0,0,0,.2)}.mdl-shadow--8dp{box-shadow:0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12),0 5px 5px -3px rgba(0,0,0,.2)}.mdl-shadow--16dp{box-shadow:0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12),0 8px 10px -5px rgba(0,0,0,.2)}.mdl-shadow--24dp{box-shadow:0 9px 46px 8px rgba(0,0,0,.14),0 11px 15px -7px rgba(0,0,0,.12),0 24px 38px 3px rgba(0,0,0,.2)}.mdl-grid{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row wrap;-ms-flex-flow:row wrap;flex-flow:row wrap;margin:0 auto;-webkit-align-items:stretch;-ms-flex-align:stretch;align-items:stretch}.mdl-grid.mdl-grid--no-spacing{padding:0}.mdl-cell{box-sizing:border-box}.mdl-cell--top{-webkit-align-self:flex-start;-ms-flex-item-align:start;align-self:flex-start}.mdl-cell--middle{-webkit-align-self:center;-ms-flex-item-align:center;align-self:center}.mdl-cell--bottom{-webkit-align-self:flex-end;-ms-flex-item-align:end;align-self:flex-end}.mdl-cell--stretch{-webkit-align-self:stretch;-ms-flex-item-align:stretch;align-self:stretch}.mdl-grid.mdl-grid--no-spacing>.mdl-cell{margin:0}.mdl-cell--order-1{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12{-webkit-order:12;-ms-flex-order:12;order:12}@media (max-width:479px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:100%}.mdl-cell--hide-phone{display:none!important}.mdl-cell--order-1-phone.mdl-cell--order-1-phone{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-phone.mdl-cell--order-2-phone{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-phone.mdl-cell--order-3-phone{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-phone.mdl-cell--order-4-phone{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-phone.mdl-cell--order-5-phone{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-phone.mdl-cell--order-6-phone{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-phone.mdl-cell--order-7-phone{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-phone.mdl-cell--order-8-phone{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-phone.mdl-cell--order-9-phone{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-phone.mdl-cell--order-10-phone{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-phone.mdl-cell--order-11-phone{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-phone.mdl-cell--order-12-phone{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-phone.mdl-cell--1-col-phone{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-phone.mdl-cell--1-col-phone{width:25%}.mdl-cell--2-col,.mdl-cell--2-col-phone.mdl-cell--2-col-phone{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-phone.mdl-cell--2-col-phone{width:50%}.mdl-cell--3-col,.mdl-cell--3-col-phone.mdl-cell--3-col-phone{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-phone.mdl-cell--3-col-phone{width:75%}.mdl-cell--4-col,.mdl-cell--4-col-phone.mdl-cell--4-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-phone.mdl-cell--4-col-phone{width:100%}.mdl-cell--5-col,.mdl-cell--5-col-phone.mdl-cell--5-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-phone.mdl-cell--5-col-phone{width:100%}.mdl-cell--6-col,.mdl-cell--6-col-phone.mdl-cell--6-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-phone.mdl-cell--6-col-phone{width:100%}.mdl-cell--7-col,.mdl-cell--7-col-phone.mdl-cell--7-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-phone.mdl-cell--7-col-phone{width:100%}.mdl-cell--8-col,.mdl-cell--8-col-phone.mdl-cell--8-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-phone.mdl-cell--8-col-phone{width:100%}.mdl-cell--9-col,.mdl-cell--9-col-phone.mdl-cell--9-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-phone.mdl-cell--9-col-phone{width:100%}.mdl-cell--10-col,.mdl-cell--10-col-phone.mdl-cell--10-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-phone.mdl-cell--10-col-phone{width:100%}.mdl-cell--11-col,.mdl-cell--11-col-phone.mdl-cell--11-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-phone.mdl-cell--11-col-phone{width:100%}.mdl-cell--12-col,.mdl-cell--12-col-phone.mdl-cell--12-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-phone.mdl-cell--12-col-phone{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-phone.mdl-cell--1-offset-phone{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-phone.mdl-cell--1-offset-phone{margin-left:25%}.mdl-cell--2-offset,.mdl-cell--2-offset-phone.mdl-cell--2-offset-phone{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-phone.mdl-cell--2-offset-phone{margin-left:50%}.mdl-cell--3-offset,.mdl-cell--3-offset-phone.mdl-cell--3-offset-phone{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-phone.mdl-cell--3-offset-phone{margin-left:75%}}@media (min-width:480px) and (max-width:839px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:50%}.mdl-cell--hide-tablet{display:none!important}.mdl-cell--order-1-tablet.mdl-cell--order-1-tablet{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-tablet.mdl-cell--order-2-tablet{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-tablet.mdl-cell--order-3-tablet{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-tablet.mdl-cell--order-4-tablet{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-tablet.mdl-cell--order-5-tablet{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-tablet.mdl-cell--order-6-tablet{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-tablet.mdl-cell--order-7-tablet{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-tablet.mdl-cell--order-8-tablet{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-tablet.mdl-cell--order-9-tablet{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-tablet.mdl-cell--order-10-tablet{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-tablet.mdl-cell--order-11-tablet{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-tablet.mdl-cell--order-12-tablet{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-tablet.mdl-cell--1-col-tablet{width:calc(12.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-tablet.mdl-cell--1-col-tablet{width:12.5%}.mdl-cell--2-col,.mdl-cell--2-col-tablet.mdl-cell--2-col-tablet{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-tablet.mdl-cell--2-col-tablet{width:25%}.mdl-cell--3-col,.mdl-cell--3-col-tablet.mdl-cell--3-col-tablet{width:calc(37.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-tablet.mdl-cell--3-col-tablet{width:37.5%}.mdl-cell--4-col,.mdl-cell--4-col-tablet.mdl-cell--4-col-tablet{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-tablet.mdl-cell--4-col-tablet{width:50%}.mdl-cell--5-col,.mdl-cell--5-col-tablet.mdl-cell--5-col-tablet{width:calc(62.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-tablet.mdl-cell--5-col-tablet{width:62.5%}.mdl-cell--6-col,.mdl-cell--6-col-tablet.mdl-cell--6-col-tablet{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-tablet.mdl-cell--6-col-tablet{width:75%}.mdl-cell--7-col,.mdl-cell--7-col-tablet.mdl-cell--7-col-tablet{width:calc(87.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-tablet.mdl-cell--7-col-tablet{width:87.5%}.mdl-cell--8-col,.mdl-cell--8-col-tablet.mdl-cell--8-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-tablet.mdl-cell--8-col-tablet{width:100%}.mdl-cell--9-col,.mdl-cell--9-col-tablet.mdl-cell--9-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-tablet.mdl-cell--9-col-tablet{width:100%}.mdl-cell--10-col,.mdl-cell--10-col-tablet.mdl-cell--10-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-tablet.mdl-cell--10-col-tablet{width:100%}.mdl-cell--11-col,.mdl-cell--11-col-tablet.mdl-cell--11-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-tablet.mdl-cell--11-col-tablet{width:100%}.mdl-cell--12-col,.mdl-cell--12-col-tablet.mdl-cell--12-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-tablet.mdl-cell--12-col-tablet{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-tablet.mdl-cell--1-offset-tablet{margin-left:calc(12.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-tablet.mdl-cell--1-offset-tablet{margin-left:12.5%}.mdl-cell--2-offset,.mdl-cell--2-offset-tablet.mdl-cell--2-offset-tablet{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-tablet.mdl-cell--2-offset-tablet{margin-left:25%}.mdl-cell--3-offset,.mdl-cell--3-offset-tablet.mdl-cell--3-offset-tablet{margin-left:calc(37.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-tablet.mdl-cell--3-offset-tablet{margin-left:37.5%}.mdl-cell--4-offset,.mdl-cell--4-offset-tablet.mdl-cell--4-offset-tablet{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset-tablet.mdl-cell--4-offset-tablet{margin-left:50%}.mdl-cell--5-offset,.mdl-cell--5-offset-tablet.mdl-cell--5-offset-tablet{margin-left:calc(62.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset-tablet.mdl-cell--5-offset-tablet{margin-left:62.5%}.mdl-cell--6-offset,.mdl-cell--6-offset-tablet.mdl-cell--6-offset-tablet{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset-tablet.mdl-cell--6-offset-tablet{margin-left:75%}.mdl-cell--7-offset,.mdl-cell--7-offset-tablet.mdl-cell--7-offset-tablet{margin-left:calc(87.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset-tablet.mdl-cell--7-offset-tablet{margin-left:87.5%}}@media (min-width:840px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(33.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:33.3333333333%}.mdl-cell--hide-desktop{display:none!important}.mdl-cell--order-1-desktop.mdl-cell--order-1-desktop{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-desktop.mdl-cell--order-2-desktop{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-desktop.mdl-cell--order-3-desktop{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-desktop.mdl-cell--order-4-desktop{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-desktop.mdl-cell--order-5-desktop{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-desktop.mdl-cell--order-6-desktop{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-desktop.mdl-cell--order-7-desktop{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-desktop.mdl-cell--order-8-desktop{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-desktop.mdl-cell--order-9-desktop{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-desktop.mdl-cell--order-10-desktop{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-desktop.mdl-cell--order-11-desktop{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-desktop.mdl-cell--order-12-desktop{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-desktop.mdl-cell--1-col-desktop{width:calc(8.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-desktop.mdl-cell--1-col-desktop{width:8.3333333333%}.mdl-cell--2-col,.mdl-cell--2-col-desktop.mdl-cell--2-col-desktop{width:calc(16.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-desktop.mdl-cell--2-col-desktop{width:16.6666666667%}.mdl-cell--3-col,.mdl-cell--3-col-desktop.mdl-cell--3-col-desktop{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-desktop.mdl-cell--3-col-desktop{width:25%}.mdl-cell--4-col,.mdl-cell--4-col-desktop.mdl-cell--4-col-desktop{width:calc(33.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-desktop.mdl-cell--4-col-desktop{width:33.3333333333%}.mdl-cell--5-col,.mdl-cell--5-col-desktop.mdl-cell--5-col-desktop{width:calc(41.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-desktop.mdl-cell--5-col-desktop{width:41.6666666667%}.mdl-cell--6-col,.mdl-cell--6-col-desktop.mdl-cell--6-col-desktop{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-desktop.mdl-cell--6-col-desktop{width:50%}.mdl-cell--7-col,.mdl-cell--7-col-desktop.mdl-cell--7-col-desktop{width:calc(58.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-desktop.mdl-cell--7-col-desktop{width:58.3333333333%}.mdl-cell--8-col,.mdl-cell--8-col-desktop.mdl-cell--8-col-desktop{width:calc(66.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-desktop.mdl-cell--8-col-desktop{width:66.6666666667%}.mdl-cell--9-col,.mdl-cell--9-col-desktop.mdl-cell--9-col-desktop{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-desktop.mdl-cell--9-col-desktop{width:75%}.mdl-cell--10-col,.mdl-cell--10-col-desktop.mdl-cell--10-col-desktop{width:calc(83.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-desktop.mdl-cell--10-col-desktop{width:83.3333333333%}.mdl-cell--11-col,.mdl-cell--11-col-desktop.mdl-cell--11-col-desktop{width:calc(91.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-desktop.mdl-cell--11-col-desktop{width:91.6666666667%}.mdl-cell--12-col,.mdl-cell--12-col-desktop.mdl-cell--12-col-desktop{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-desktop.mdl-cell--12-col-desktop{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-desktop.mdl-cell--1-offset-desktop{margin-left:calc(8.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-desktop.mdl-cell--1-offset-desktop{margin-left:8.3333333333%}.mdl-cell--2-offset,.mdl-cell--2-offset-desktop.mdl-cell--2-offset-desktop{margin-left:calc(16.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-desktop.mdl-cell--2-offset-desktop{margin-left:16.6666666667%}.mdl-cell--3-offset,.mdl-cell--3-offset-desktop.mdl-cell--3-offset-desktop{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-desktop.mdl-cell--3-offset-desktop{margin-left:25%}.mdl-cell--4-offset,.mdl-cell--4-offset-desktop.mdl-cell--4-offset-desktop{margin-left:calc(33.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset-desktop.mdl-cell--4-offset-desktop{margin-left:33.3333333333%}.mdl-cell--5-offset,.mdl-cell--5-offset-desktop.mdl-cell--5-offset-desktop{margin-left:calc(41.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset-desktop.mdl-cell--5-offset-desktop{margin-left:41.6666666667%}.mdl-cell--6-offset,.mdl-cell--6-offset-desktop.mdl-cell--6-offset-desktop{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset-desktop.mdl-cell--6-offset-desktop{margin-left:50%}.mdl-cell--7-offset,.mdl-cell--7-offset-desktop.mdl-cell--7-offset-desktop{margin-left:calc(58.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset-desktop.mdl-cell--7-offset-desktop{margin-left:58.3333333333%}.mdl-cell--8-offset,.mdl-cell--8-offset-desktop.mdl-cell--8-offset-desktop{margin-left:calc(66.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--8-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--8-offset-desktop.mdl-cell--8-offset-desktop{margin-left:66.6666666667%}.mdl-cell--9-offset,.mdl-cell--9-offset-desktop.mdl-cell--9-offset-desktop{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--9-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--9-offset-desktop.mdl-cell--9-offset-desktop{margin-left:75%}.mdl-cell--10-offset,.mdl-cell--10-offset-desktop.mdl-cell--10-offset-desktop{margin-left:calc(83.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--10-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--10-offset-desktop.mdl-cell--10-offset-desktop{margin-left:83.3333333333%}.mdl-cell--11-offset,.mdl-cell--11-offset-desktop.mdl-cell--11-offset-desktop{margin-left:calc(91.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--11-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--11-offset-desktop.mdl-cell--11-offset-desktop{margin-left:91.6666666667%}} -/*# sourceMappingURL=material.min.css.map */ diff --git a/etc/cli.angular.io/theme.css b/etc/cli.angular.io/theme.css deleted file mode 100644 index b6a336e98b0c..000000000000 --- a/etc/cli.angular.io/theme.css +++ /dev/null @@ -1 +0,0 @@ -.console{width:360px;max-width:92vw;margin-left:15px;margin-right:40px;text-align:left;border-radius:5px;margin-bottom:10px}@media (max-width:830px){.console{margin-right:auto;margin-left:auto}}.console__head{overflow:hidden;background-color:#d5d5d5;padding:8px 15px;border-top-left-radius:5px;border-top-right-radius:5px}.console__dot{float:left;width:12px;height:12px;border-radius:50%;margin-right:7px;box-shadow:0 1px 1px 0 rgba(0,0,0,.2)}.console__dot--red{background-color:#ff6057}.console__dot--yellow{background-color:#ffc22e}.console__dot--green{background-color:#28ca40}.console__body{background-color:#1e1e1e;padding:30px 17px 20px;border-bottom-left-radius:5px;border-bottom-right-radius:5px}.console__prompt{display:block;margin-bottom:15px;font-family:"Source Code Pro",monospace;font-size:15px}.console__prompt::before{content:">";padding-right:15px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-base{height:100vh} diff --git a/etc/rules/README.md b/etc/rules/README.md deleted file mode 100644 index 616923160a2b..000000000000 --- a/etc/rules/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# TsLint Rules - -This folder contains custom TsLint rules specific to this repository. diff --git a/etc/rules/Rule.ts b/etc/rules/Rule.ts deleted file mode 100644 index 43a7df63b777..000000000000 --- a/etc/rules/Rule.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - - -// An empty rule so that tslint does not error on rules '//' (which are comments). -export class Rule extends Lint.Rules.AbstractRule { - public static metadata: Lint.IRuleMetadata = { - ruleName: '//', - type: 'typescript', - description: ``, - rationale: '', - options: null, - optionsDescription: `Not configurable.`, - typescriptOnly: false, - }; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return []; - } -} diff --git a/etc/rules/defocusRule.ts b/etc/rules/defocusRule.ts deleted file mode 100644 index 0634596fa24f..000000000000 --- a/etc/rules/defocusRule.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -/* - * Taken from https://github.com/Sergiioo/tslint-defocus - * Copyright (c) 2016 Sergio Annecchiarico - * MIT - https://github.com/Sergiioo/tslint-defocus/blob/master/LICENSE - */ - -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - -export class Rule extends Lint.Rules.AbstractRule { - - public static metadata: Lint.IRuleMetadata = { - ruleName: 'defocus', - description: "Bans the use of `fdescribe` and 'fit' Jasmine functions.", - rationale: 'It is all too easy to mistakenly commit a focussed Jasmine test suite or spec.', - options: null, - optionsDescription: 'Not configurable.', - type: 'functionality', - typescriptOnly: false, - }; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithFunction(sourceFile, walk); - } -} - -function walk(ctx: Lint.WalkContext) { - return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void { - if (node.kind === ts.SyntaxKind.CallExpression) { - const expression = (node as ts.CallExpression).expression; - const functionName = expression.getText(); - bannedFunctions.forEach((banned) => { - if (banned === functionName) { - ctx.addFailureAtNode(expression, failureMessage(functionName)); - } - }); - } - - return ts.forEachChild(node, cb); - }); -} - -const bannedFunctions: ReadonlyArray = ['fdescribe', 'fit']; - -const failureMessage = (functionName: string) => { - return `Calls to '${functionName}' are not allowed.`; -}; diff --git a/etc/rules/importGroupsRule.ts b/etc/rules/importGroupsRule.ts deleted file mode 100644 index c53fcba8c7d2..000000000000 --- a/etc/rules/importGroupsRule.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - - -export class Rule extends Lint.Rules.AbstractRule { - public static metadata: Lint.IRuleMetadata = { - ruleName: 'import-groups', - type: 'style', - description: `Ensure imports are grouped.`, - rationale: `Imports can be grouped or not depending on a project. A group is a sequence of - import statements separated by blank lines.`, - options: null, - optionsDescription: `Not configurable.`, - typescriptOnly: false, - }; - - public static FAILURE_STRING = 'You need to keep imports grouped.'; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); - } -} - - -class Walker extends Lint.RuleWalker { - walk(sourceFile: ts.SourceFile) { - super.walk(sourceFile); - - const statements = sourceFile.statements; - const imports = statements.filter(s => s.kind == ts.SyntaxKind.ImportDeclaration); - const nonImports = statements.filter(s => s.kind != ts.SyntaxKind.ImportDeclaration); - - for (let i = 1; i < imports.length; i++) { - const node = imports[i]; - const previous = imports[i - 1]; - - if (previous && previous.kind == ts.SyntaxKind.ImportDeclaration) { - const nodeLine = sourceFile.getLineAndCharacterOfPosition(node.getStart()); - const previousLine = sourceFile.getLineAndCharacterOfPosition(previous.getEnd()); - - if (previousLine.line < nodeLine.line - 1) { - if (nonImports.some(s => s.getStart() > previous.getEnd() - && s.getStart() < node.getStart())) { - // Ignore imports with non-imports statements in between. - continue; - } - - this.addFailureAt( - node.getStart(), - node.getWidth(), - Rule.FAILURE_STRING, - Lint.Replacement.deleteFromTo(previous.getEnd() + 1, node.getStart()), - ); - } - } - } - } -} diff --git a/etc/rules/noGlobalTslintDisableRule.ts b/etc/rules/noGlobalTslintDisableRule.ts deleted file mode 100644 index fea185ec7928..000000000000 --- a/etc/rules/noGlobalTslintDisableRule.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as path from 'path'; -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - - -export class Rule extends Lint.Rules.AbstractRule { - public static metadata: Lint.IRuleMetadata = { - ruleName: 'no-global-tslint-disable', - type: 'style', - description: `Ensure global tslint disable are only used for unit tests.`, - rationale: `Some projects want to disallow tslint disable and only use per-line ones.`, - options: null, - optionsDescription: `Not configurable.`, - typescriptOnly: false, - }; - - public static FAILURE_STRING = 'tslint:disable is not allowed in this context.'; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); - } -} - - -class Walker extends Lint.RuleWalker { - private _findComments(node: ts.Node): ts.CommentRange[] { - return ([] as ts.CommentRange[]).concat( - ts.getLeadingCommentRanges(node.getFullText(), 0) || [], - ts.getTrailingCommentRanges(node.getFullText(), 0) || [], - node.getChildren().reduce((acc, n) => { - return acc.concat(this._findComments(n)); - }, [] as ts.CommentRange[]), - ); - } - - walk(sourceFile: ts.SourceFile) { - super.walk(sourceFile); - - // Ignore spec files. - if (sourceFile.fileName.match(/_spec(_large)?.ts$/)) { - return; - } - // Ignore benchmark files. - if (sourceFile.fileName.match(/_benchmark.ts$/)) { - return; - } - - // TODO(filipesilva): remove this once the files are cleaned up. - // Ignore Angular CLI files files. - if (sourceFile.fileName.includes('/angular-cli-files/')) { - return; - } - - const scriptsPath = path.join(process.cwd(), 'scripts').replace(/\\/g, '/'); - if (sourceFile.fileName.startsWith(scriptsPath)) { - return; - } - - // Find all comment nodes. - const ranges = this._findComments(sourceFile); - ranges.forEach(range => { - const text = sourceFile.getFullText().substring(range.pos, range.end); - let i = text.indexOf('tslint:disable:'); - - while (i != -1) { - this.addFailureAt(range.pos + i + 1, range.pos + i + 15, Rule.FAILURE_STRING); - i = text.indexOf('tslint:disable:', i + 1); - } - }); - } -} diff --git a/etc/rules/singleEofLineRule.ts b/etc/rules/singleEofLineRule.ts deleted file mode 100644 index b2882e43ffb9..000000000000 --- a/etc/rules/singleEofLineRule.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as Lint from 'tslint'; -import * as ts from 'typescript'; - - -export class Rule extends Lint.Rules.AbstractRule { - public static metadata: Lint.IRuleMetadata = { - ruleName: 'single-eof-line', - type: 'style', - description: `Ensure the file ends with a single new line.`, - rationale: `This is similar to eofline, but ensure an exact count instead of just any new - line.`, - options: null, - optionsDescription: `Two integers indicating minimum and maximum number of new lines.`, - typescriptOnly: false, - }; - - public static FAILURE_STRING = 'You need to have a single blank line at end of file.'; - - public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { - const length = sourceFile.text.length; - if (length === 0) { - // Allow empty files. - return []; - } - - const matchEof = /\r?\n((\r?\n)*)$/.exec(sourceFile.text); - if (!matchEof) { - const lines = sourceFile.getLineStarts(); - const fix = Lint.Replacement.appendText( - length, - sourceFile.text[lines[1] - 2] === '\r' ? '\r\n' : '\n', - ); - - return [ - new Lint.RuleFailure(sourceFile, length, length, Rule.FAILURE_STRING, this.ruleName, fix), - ]; - } else if (matchEof[1]) { - const lines = sourceFile.getLineStarts(); - const fix = Lint.Replacement.replaceFromTo( - matchEof.index, - length, - sourceFile.text[lines[1] - 2] === '\r' ? '\r\n' : '\n', - ); - - return [ - new Lint.RuleFailure(sourceFile, length, length, Rule.FAILURE_STRING, this.ruleName, fix), - ]; - } - - return []; - } -} diff --git a/etc/rules/tsconfig.json b/etc/rules/tsconfig.json deleted file mode 100644 index dce8cbca6f6f..000000000000 --- a/etc/rules/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - // This tsconfig is to help only build the tslint rules instead of the whole project. Makes - // things faster. - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../../dist/etc/rules", - "baseUrl": "" - }, - "exclude": [ - ] -} diff --git a/goldens/BUILD.bazel b/goldens/BUILD.bazel new file mode 100644 index 000000000000..711154f524b1 --- /dev/null +++ b/goldens/BUILD.bazel @@ -0,0 +1,10 @@ +load("@bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin") + +package(default_visibility = ["//visibility:public"]) + +copy_to_bin( + name = "public-api", + srcs = glob([ + "public-api/**/*.md", + ]), +) diff --git a/goldens/circular-deps/packages.json b/goldens/circular-deps/packages.json new file mode 100644 index 000000000000..fe51488c7066 --- /dev/null +++ b/goldens/circular-deps/packages.json @@ -0,0 +1 @@ +[] diff --git a/goldens/public-api/angular/build/index.api.md b/goldens/public-api/angular/build/index.api.md new file mode 100644 index 000000000000..6ef310c78e9e --- /dev/null +++ b/goldens/public-api/angular/build/index.api.md @@ -0,0 +1,256 @@ +## API Report File for "@angular/build" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BuilderContext } from '@angular-devkit/architect'; +import { BuilderOutput } from '@angular-devkit/architect'; +import type { ConfigOptions } from 'karma'; +import type http from 'node:http'; +import type { OutputFile } from 'esbuild'; +import type { Plugin as Plugin_2 } from 'esbuild'; + +// @public (undocumented) +export interface ApplicationBuilderExtensions { + // (undocumented) + codePlugins?: Plugin_2[]; + // (undocumented) + indexHtmlTransformer?: IndexHtmlTransform; +} + +// @public +export type ApplicationBuilderOptions = { + allowedCommonJsDependencies?: string[]; + aot?: boolean; + appShell?: boolean; + assets?: AssetPattern[]; + baseHref?: string; + browser?: string; + budgets?: Budget[]; + clearScreen?: boolean; + conditions?: string[]; + crossOrigin?: CrossOrigin; + define?: { + [key: string]: string; + }; + deleteOutputPath?: boolean; + deployUrl?: string; + externalDependencies?: string[]; + extractLicenses?: boolean; + fileReplacements?: FileReplacement[]; + i18nDuplicateTranslation?: I18NTranslation; + i18nMissingTranslation?: I18NTranslation; + index?: IndexUnion; + inlineStyleLanguage?: InlineStyleLanguage; + loader?: { + [key: string]: any; + }; + localize?: Localize; + namedChunks?: boolean; + optimization?: OptimizationUnion; + outputHashing?: OutputHashing; + outputMode?: OutputMode; + outputPath?: OutputPathUnion; + poll?: number; + polyfills?: string[]; + prerender?: PrerenderUnion; + preserveSymlinks?: boolean; + progress?: boolean; + scripts?: ScriptElement[]; + security?: Security; + server?: Serv; + serviceWorker?: Serv; + sourceMap?: SourceMapUnion; + ssr?: SsrUnion; + statsJson?: boolean; + stylePreprocessorOptions?: StylePreprocessorOptions; + styles?: StyleElement[]; + subresourceIntegrity?: boolean; + tsConfig: string; + verbose?: boolean; + watch?: boolean; + webWorkerTsConfig?: string; +}; + +// @public +export function buildApplication(options: ApplicationBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions): AsyncIterable; + +// @public (undocumented) +export interface BuildOutputAsset { + // (undocumented) + destination: string; + // (undocumented) + source: string; +} + +// @public (undocumented) +export interface BuildOutputFile extends OutputFile { + // (undocumented) + clone: () => BuildOutputFile; + // (undocumented) + readonly size: number; + // (undocumented) + type: BuildOutputFileType; +} + +// @public (undocumented) +export enum BuildOutputFileType { + // (undocumented) + Browser = 0, + // (undocumented) + Media = 1, + // (undocumented) + Root = 4, + // (undocumented) + ServerApplication = 2, + // (undocumented) + ServerRoot = 3 +} + +// @public +export type DevServerBuilderOptions = { + allowedHosts?: AllowedHosts; + buildTarget: string; + define?: { + [key: string]: string; + }; + headers?: { + [key: string]: string; + }; + hmr?: boolean; + host?: string; + inspect?: Inspect; + liveReload?: boolean; + open?: boolean; + poll?: number; + port?: number; + prebundle?: PrebundleUnion; + proxyConfig?: string; + servePath?: string; + ssl?: boolean; + sslCert?: string; + sslKey?: string; + verbose?: boolean; + watch?: boolean; +}; + +// @public +export interface DevServerBuilderOutput extends BuilderOutput { + // (undocumented) + address?: string; + // (undocumented) + baseUrl: string; + // (undocumented) + port?: number; +} + +// @public +export function executeDevServerBuilder(options: DevServerBuilderOptions, context: BuilderContext, extensions?: { + buildPlugins?: Plugin_2[]; + middleware?: ((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void) => void)[]; + indexHtmlTransformer?: IndexHtmlTransform; +}): AsyncIterable; + +// @public +export function executeExtractI18nBuilder(options: ExtractI18nBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions): Promise; + +// @public +export function executeKarmaBuilder(options: KarmaBuilderOptions, context: BuilderContext, transforms?: KarmaBuilderTransformsOptions): AsyncIterable; + +// @public @deprecated +export function executeNgPackagrBuilder(options: NgPackagrBuilderOptions, context: BuilderContext): AsyncIterableIterator; + +// @public +export function executeUnitTestBuilder(options: UnitTestBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions): AsyncIterable; + +// @public +export type ExtractI18nBuilderOptions = { + buildTarget?: string; + format?: Format_2; + i18nDuplicateTranslation?: I18NDuplicateTranslation; + outFile?: string; + outputPath?: string; + progress?: boolean; +}; + +// @public +export type KarmaBuilderOptions = { + aot?: boolean; + assets?: AssetPattern_2[]; + browsers?: Browsers; + codeCoverage?: boolean; + codeCoverageExclude?: string[]; + define?: { + [key: string]: string; + }; + exclude?: string[]; + externalDependencies?: string[]; + fileReplacements?: FileReplacement_2[]; + include?: string[]; + inlineStyleLanguage?: InlineStyleLanguage_2; + karmaConfig?: string; + loader?: { + [key: string]: any; + }; + main?: string; + poll?: number; + polyfills?: string[]; + preserveSymlinks?: boolean; + progress?: boolean; + reporters?: string[]; + scripts?: ScriptElement_2[]; + sourceMap?: SourceMapUnion_2; + stylePreprocessorOptions?: StylePreprocessorOptions_2; + styles?: StyleElement_2[]; + tsConfig: string; + watch?: boolean; + webWorkerTsConfig?: string; +}; + +// @public @deprecated +export type NgPackagrBuilderOptions = { + poll?: number; + project?: string; + tsConfig?: string; + watch?: boolean; +}; + +// @public +export type UnitTestBuilderOptions = { + browserViewport?: string; + browsers?: [string, ...string[]]; + buildTarget?: string; + coverage?: boolean; + coverageExclude?: string[]; + coverageInclude?: string[]; + coverageReporters?: SchemaCoverageReporter[]; + coverageThresholds?: CoverageThresholds; + coverageWatermarks?: CoverageWatermarks; + debug?: boolean; + dumpVirtualFiles?: boolean; + exclude?: string[]; + filter?: string; + headless?: boolean; + include?: string[]; + isolate?: boolean; + listTests?: boolean; + outputFile?: string; + polyfills?: string[]; + progress?: boolean; + providersFile?: string; + quiet?: boolean; + reporters?: SchemaReporter[]; + runner?: Runner; + runnerArgs?: string[]; + runnerConfig?: RunnerConfig; + setupFiles?: string[]; + splitting?: boolean; + tsConfig?: string; + ui?: boolean; + watch?: boolean; +}; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular/ssr/index.api.md b/goldens/public-api/angular/ssr/index.api.md new file mode 100644 index 000000000000..852187d5290b --- /dev/null +++ b/goldens/public-api/angular/ssr/index.api.md @@ -0,0 +1,102 @@ +## API Report File for "@angular/ssr" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { DefaultExport } from '@angular/router'; +import { EnvironmentProviders } from '@angular/core'; +import { InjectionToken } from '@angular/core'; +import { Provider } from '@angular/core'; +import { Type } from '@angular/core'; + +// @public +export class AngularAppEngine { + constructor(options?: AngularAppEngineOptions); + handle(request: Request, requestContext?: unknown): Promise; + static ɵallowStaticRouteRender: boolean; + static ɵdisableAllowedHostsCheck: boolean; + static ɵhooks: Hooks; +} + +// @public +export interface AngularAppEngineOptions { + allowedHosts?: readonly string[]; + trustProxyHeaders?: boolean | readonly string[]; +} + +// @public +export function createRequestHandler(handler: RequestHandlerFunction): RequestHandlerFunction; + +// @public +export const IS_DISCOVERING_ROUTES: InjectionToken; + +// @public +export enum PrerenderFallback { + Client = 1, + None = 2, + Server = 0 +} + +// @public +export function provideServerRendering(...features: ServerRenderingFeature[]): EnvironmentProviders; + +// @public +export function provideServerRendering(options: ServerRenderingOptions, ...features: ServerRenderingFeature[]): EnvironmentProviders; + +// @public +export enum RenderMode { + Client = 1, + Prerender = 2, + Server = 0 +} + +// @public +export type RequestHandlerFunction = (request: Request) => Promise | null | Response; + +// @public +export interface ServerRenderingOptions { + maxResponseBodySize: number; +} + +// @public +export type ServerRoute = ServerRouteClient | ServerRoutePrerender | ServerRoutePrerenderWithParams | ServerRouteServer; + +// @public +export interface ServerRouteClient extends ServerRouteCommon { + renderMode: RenderMode.Client; +} + +// @public +export interface ServerRouteCommon { + headers?: Record; + path: string; + status?: number; +} + +// @public +export interface ServerRoutePrerender extends Omit { + fallback?: never; + renderMode: RenderMode.Prerender; +} + +// @public +export interface ServerRoutePrerenderWithParams extends Omit { + fallback?: PrerenderFallback; + getPrerenderParams: () => Promise[]>; +} + +// @public +export interface ServerRouteServer extends ServerRouteCommon { + renderMode: RenderMode.Server; +} + +// @public +export function withAppShell(component: Type | (() => Promise | DefaultExport>>)): ServerRenderingFeature; + +// @public +export function withRoutes(routes: ServerRoute[]): ServerRenderingFeature; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular/ssr/node/index.api.md b/goldens/public-api/angular/ssr/node/index.api.md new file mode 100644 index 000000000000..06b61ab1fdcb --- /dev/null +++ b/goldens/public-api/angular/ssr/node/index.api.md @@ -0,0 +1,71 @@ +## API Report File for "@angular/ssr_node" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { ApplicationRef } from '@angular/core'; +import { BootstrapContext } from '@angular/platform-browser'; +import { Http2ServerRequest } from 'node:http2'; +import { Http2ServerResponse } from 'node:http2'; +import { IncomingMessage } from 'node:http'; +import { ServerResponse } from 'node:http'; +import { StaticProvider } from '@angular/core'; +import { Type } from '@angular/core'; + +// @public +export class AngularNodeAppEngine { + constructor(options?: AngularNodeAppEngineOptions); + handle(request: IncomingMessage | Http2ServerRequest | Request, requestContext?: unknown): Promise; +} + +// @public +export interface AngularNodeAppEngineOptions extends AngularAppEngineOptions { +} + +// @public @deprecated +export class CommonEngine { + constructor(options?: CommonEngineOptions | undefined); + render(opts: CommonEngineRenderOptions): Promise; +} + +// @public @deprecated (undocumented) +export interface CommonEngineOptions { + allowedHosts?: readonly string[]; + bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise); + enablePerformanceProfiler?: boolean; + providers?: StaticProvider[]; +} + +// @public @deprecated (undocumented) +export interface CommonEngineRenderOptions { + bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise); + // (undocumented) + document?: string; + // (undocumented) + documentFilePath?: string; + inlineCriticalCss?: boolean; + providers?: StaticProvider[]; + publicPath?: string; + // (undocumented) + url?: string; +} + +// @public +export function createNodeRequestHandler(handler: T): T; + +// @public +export function createWebRequestFromNodeRequest(nodeRequest: IncomingMessage | Http2ServerRequest, trustProxyHeaders?: boolean | readonly string[]): Request; + +// @public +export function isMainModule(url: string): boolean; + +// @public +export type NodeRequestHandlerFunction = (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => Promise | void; + +// @public +export function writeResponseToNodeResponse(source: Response, destination: ServerResponse | Http2ServerResponse): Promise; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/architect/index.api.md b/goldens/public-api/angular_devkit/architect/index.api.md new file mode 100644 index 000000000000..4d486e84e5aa --- /dev/null +++ b/goldens/public-api/angular_devkit/architect/index.api.md @@ -0,0 +1,553 @@ +## API Report File for "@angular-devkit/architect" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BaseException } from '@angular-devkit/core'; +import { json } from '@angular-devkit/core'; +import { JsonObject } from '@angular-devkit/core'; +import { JsonValue } from '@angular-devkit/core'; +import { logging } from '@angular-devkit/core'; +import { Observable } from 'rxjs'; +import { ObservableInput } from 'rxjs'; +import { Observer } from 'rxjs'; +import { schema } from '@angular-devkit/core'; + +// @public (undocumented) +export class Architect { + constructor(_host: ArchitectHost, registry?: json.schema.SchemaRegistry, additionalJobRegistry?: Registry); + // (undocumented) + has(name: JobName): Observable; + // (undocumented) + scheduleBuilder(name: string, options: json.JsonObject, scheduleOptions?: ScheduleOptions): Promise; + // (undocumented) + scheduleTarget(target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions): Promise; +} + +// @public +export interface Builder { + // (undocumented) + [BuilderSymbol]: true; + // (undocumented) + [BuilderVersionSymbol]: string; + // (undocumented) + __OptionT: OptionT; + // (undocumented) + handler: JobHandler; +} + +// @public +export interface BuilderContext { + addTeardown(teardown: () => Promise | void): void; + builder: BuilderInfo; + currentDirectory: string; + getBuilderNameForTarget(target: Target): Promise; + // (undocumented) + getProjectMetadata(projectName: string): Promise; + // (undocumented) + getProjectMetadata(target: Target): Promise; + getTargetOptions(target: Target): Promise; + id: number; + logger: logging.LoggerApi; + reportProgress(current: number, total?: number, status?: string): void; + reportRunning(): void; + reportStatus(status: string): void; + scheduleBuilder(builderName: string, options?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Promise; + scheduleTarget(target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Promise; + target?: Target; + validateOptions(options: json.JsonObject, builderName: string): Promise; + workspaceRoot: string; +} + +// @public +export interface BuilderHandlerFn { + (input: A, context: BuilderContext): BuilderOutputLike; +} + +// @public +export type BuilderInfo = json.JsonObject & { + builderName: string; + description: string; + optionSchema: json.schema.JsonSchema; +}; + +// @public +export type BuilderInput = json.JsonObject & Schema; + +// @public (undocumented) +export type BuilderOutput = json.JsonObject & Schema_2; + +// @public +export type BuilderOutputLike = ObservableInput | BuilderOutput; + +// @public (undocumented) +export type BuilderProgress = json.JsonObject & Schema_3 & TypedBuilderProgress; + +// @public +export type BuilderProgressReport = BuilderProgress & { + target?: Target; + builder: BuilderInfo; +}; + +// @public (undocumented) +export enum BuilderProgressState { + // (undocumented) + Error = "error", + // (undocumented) + Running = "running", + // (undocumented) + Stopped = "stopped", + // (undocumented) + Waiting = "waiting" +} + +// @public (undocumented) +export type BuilderRegistry = Registry; + +// @public +export interface BuilderRun { + id: number; + info: BuilderInfo; + lastOutput: Promise; + output: Observable; + progress: Observable; + result: Promise; + stop(): Promise; +} + +// @public (undocumented) +class ChannelAlreadyExistException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export function createBuilder(fn: BuilderHandlerFn): Builder; + +// @public +function createDispatcher(options?: Partial>): JobDispatcher; + +// @public +function createJobFactory(loader: () => Promise>, options?: Partial): JobHandler; + +// @public +function createJobHandler(fn: SimpleJobHandlerFn, options?: Partial): JobHandler; + +// @public +function createLoggerJob(job: JobHandler, logger: logging.LoggerApi): JobHandler; + +// @public +class FallbackRegistry implements Registry { + constructor(_fallbacks?: Registry[]); + // (undocumented) + addFallback(registry: Registry): void; + // (undocumented) + protected _fallbacks: Registry[]; + // (undocumented) + get(name: JobName): Observable | null>; +} + +// @public (undocumented) +export function fromAsyncIterable(iterable: AsyncIterable): Observable; + +// @public (undocumented) +export function isBuilderOutput(obj: any): obj is BuilderOutput; + +// @public (undocumented) +function isJobHandler(value: unknown): value is JobHandler; + +// @public +interface Job { + readonly argument: ArgumentT; + readonly description: Observable; + getChannel(name: string, schema?: schema.JsonSchema): Observable; + readonly inboundBus: Observer>; + readonly input: Observer; + readonly outboundBus: Observable>; + readonly output: Observable; + ping(): Observable; + readonly state: JobState; + stop(): void; +} + +// @public (undocumented) +class JobArgumentSchemaValidationError extends schema.SchemaValidationException { + constructor(errors?: schema.SchemaValidatorError[]); +} + +// @public +interface JobDescription extends JsonObject { + // (undocumented) + readonly argument: DeepReadonly; + // (undocumented) + readonly input: DeepReadonly; + // (undocumented) + readonly name: JobName; + // (undocumented) + readonly output: DeepReadonly; +} + +// @public +interface JobDispatcher extends JobHandler { + addConditionalJob(predicate: (args: A) => boolean, name: string): void; + setDefaultJob(name: JobName | null | JobHandler): void; +} + +// @public (undocumented) +class JobDoesNotExistException extends BaseException { + constructor(name: JobName); +} + +// @public +interface JobHandler { + // (undocumented) + (argument: ArgT, context: JobHandlerContext): Observable>; + // (undocumented) + jobDescription: Partial; +} + +// @public +interface JobHandlerContext { + // (undocumented) + readonly dependencies: Job[]; + // (undocumented) + readonly description: JobDescription; + // (undocumented) + readonly inboundBus: Observable>; + // (undocumented) + readonly scheduler: Scheduler_2; +} + +// @public (undocumented) +type JobInboundMessage = JobInboundMessagePing | JobInboundMessageStop | JobInboundMessageInput; + +// @public +interface JobInboundMessageBase extends JsonObject { + readonly kind: JobInboundMessageKind; +} + +// @public +interface JobInboundMessageInput extends JobInboundMessageBase { + // (undocumented) + readonly kind: JobInboundMessageKind.Input; + readonly value: InputT; +} + +// @public +enum JobInboundMessageKind { + // (undocumented) + Input = "in", + // (undocumented) + Ping = "ip", + // (undocumented) + Stop = "is" +} + +// @public +interface JobInboundMessagePing extends JobInboundMessageBase { + readonly id: number; + // (undocumented) + readonly kind: JobInboundMessageKind.Ping; +} + +// @public (undocumented) +class JobInboundMessageSchemaValidationError extends schema.SchemaValidationException { + constructor(errors?: schema.SchemaValidatorError[]); +} + +// @public +interface JobInboundMessageStop extends JobInboundMessageBase { + // (undocumented) + readonly kind: JobInboundMessageKind.Stop; +} + +// @public +type JobName = string; + +// @public (undocumented) +class JobNameAlreadyRegisteredException extends BaseException { + constructor(name: JobName); +} + +// @public +type JobOutboundMessage = JobOutboundMessageOnReady | JobOutboundMessageStart | JobOutboundMessageOutput | JobOutboundMessageChannelCreate | JobOutboundMessageChannelMessage | JobOutboundMessageChannelError | JobOutboundMessageChannelComplete | JobOutboundMessageEnd | JobOutboundMessagePong; + +// @public +interface JobOutboundMessageBase { + readonly description: JobDescription; + readonly kind: JobOutboundMessageKind; +} + +// @public +interface JobOutboundMessageChannelBase extends JobOutboundMessageBase { + readonly name: string; +} + +// @public +interface JobOutboundMessageChannelComplete extends JobOutboundMessageChannelBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.ChannelComplete; +} + +// @public +interface JobOutboundMessageChannelCreate extends JobOutboundMessageChannelBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.ChannelCreate; +} + +// @public +interface JobOutboundMessageChannelError extends JobOutboundMessageChannelBase { + readonly error: JsonValue; + // (undocumented) + readonly kind: JobOutboundMessageKind.ChannelError; +} + +// @public +interface JobOutboundMessageChannelMessage extends JobOutboundMessageChannelBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.ChannelMessage; + readonly message: JsonValue; +} + +// @public +interface JobOutboundMessageEnd extends JobOutboundMessageBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.End; +} + +// @public +enum JobOutboundMessageKind { + // (undocumented) + ChannelComplete = "cc", + // (undocumented) + ChannelCreate = "cn", + // (undocumented) + ChannelError = "ce", + // (undocumented) + ChannelMessage = "cm", + // (undocumented) + End = "e", + // (undocumented) + OnReady = "c", + // (undocumented) + Output = "o", + // (undocumented) + Pong = "p", + // (undocumented) + Start = "s" +} + +// @public +interface JobOutboundMessageOnReady extends JobOutboundMessageBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.OnReady; +} + +// @public +interface JobOutboundMessageOutput extends JobOutboundMessageBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.Output; + readonly value: OutputT; +} + +// @public +interface JobOutboundMessagePong extends JobOutboundMessageBase { + readonly id: number; + // (undocumented) + readonly kind: JobOutboundMessageKind.Pong; +} + +// @public +interface JobOutboundMessageStart extends JobOutboundMessageBase { + // (undocumented) + readonly kind: JobOutboundMessageKind.Start; +} + +// @public (undocumented) +class JobOutputSchemaValidationError extends schema.SchemaValidationException { + constructor(errors?: schema.SchemaValidatorError[]); +} + +declare namespace jobs { + export { + strategy, + isJobHandler, + JobName, + JobHandler, + JobHandlerContext, + JobDescription, + JobInboundMessageKind, + JobInboundMessageBase, + JobInboundMessagePing, + JobInboundMessageStop, + JobInboundMessageInput, + JobInboundMessage, + JobOutboundMessageKind, + JobOutboundMessageBase, + JobOutboundMessageOnReady, + JobOutboundMessageStart, + JobOutboundMessageOutput, + JobOutboundMessageChannelBase, + JobOutboundMessageChannelMessage, + JobOutboundMessageChannelError, + JobOutboundMessageChannelCreate, + JobOutboundMessageChannelComplete, + JobOutboundMessageEnd, + JobOutboundMessagePong, + JobOutboundMessage, + JobState, + Job, + ScheduleJobOptions, + Registry, + Scheduler_2 as Scheduler, + createJobHandler, + createJobFactory, + createLoggerJob, + ChannelAlreadyExistException, + SimpleJobHandlerContext, + SimpleJobHandlerFn, + JobNameAlreadyRegisteredException, + JobDoesNotExistException, + createDispatcher, + JobDispatcher, + FallbackRegistry, + RegisterJobOptions, + SimpleJobRegistry, + JobArgumentSchemaValidationError, + JobInboundMessageSchemaValidationError, + JobOutputSchemaValidationError, + SimpleScheduler + } +} +export { jobs } + +// @public +enum JobState { + Ended = "ended", + Errored = "errored", + Queued = "queued", + Ready = "ready", + Started = "started" +} + +// @public (undocumented) +type JobStrategy = (handler: JobHandler, options?: Partial>) => JobHandler; + +// @public +function memoize(replayMessages?: boolean): JobStrategy; + +// @public +interface RegisterJobOptions extends Partial { +} + +// @public (undocumented) +interface Registry { + get(name: JobName): Observable | null>; +} + +// @public +function reuse(replayMessages?: boolean): JobStrategy; + +// @public +interface ScheduleJobOptions { + dependencies?: Job | Job[]; +} + +// @public (undocumented) +export interface ScheduleOptions { + // (undocumented) + logger?: logging.Logger; +} + +// @public +interface Scheduler_2 { + getDescription(name: JobName): Observable; + has(name: JobName): Observable; + pause(): () => void; + schedule(name: JobName, argument: A, options?: ScheduleJobOptions): Job; +} + +// @public +export function scheduleTargetAndForget(context: BuilderContext, target: Target, overrides?: json.JsonObject, scheduleOptions?: ScheduleOptions_2): Observable; + +// @public +function serialize(): JobStrategy; + +// @public +interface SimpleJobHandlerContext extends JobHandlerContext { + // (undocumented) + addTeardown(teardown: () => Promise | void): void; + // (undocumented) + createChannel: (name: string) => Observer; + // (undocumented) + input: Observable; +} + +// @public +type SimpleJobHandlerFn = (input: A, context: SimpleJobHandlerContext) => O | Promise | Observable; + +// @public +class SimpleJobRegistry implements Registry { + // (undocumented) + get(name: JobName): Observable | null>; + getJobNames(): JobName[]; + register(name: JobName, handler: JobHandler, options?: RegisterJobOptions): void; + register(handler: JobHandler, options?: RegisterJobOptions & { + name: string; + }): void; + // (undocumented) + protected _register(name: JobName, handler: JobHandler, options: RegisterJobOptions): void; +} + +// @public +class SimpleScheduler implements Scheduler_2 { + constructor(_jobRegistry: Registry, _schemaRegistry?: schema.SchemaRegistry); + getDescription(name: JobName): Observable; + has(name: JobName): Observable; + // (undocumented) + protected _jobRegistry: Registry; + pause(): () => void; + schedule(name: JobName, argument: A, options?: ScheduleJobOptions): Job; + // (undocumented) + protected _scheduleJob(name: JobName, argument: A, options: ScheduleJobOptions, waitable: Observable): Job; + // (undocumented) + protected _schemaRegistry: schema.SchemaRegistry; +} + +declare namespace strategy { + export { + serialize, + reuse, + memoize, + JobStrategy + } +} + +// @public (undocumented) +export type Target = json.JsonObject & Target_2; + +// @public +export function targetFromTargetString(specifier: string, abbreviatedProjectName?: string, abbreviatedTargetName?: string): Target; + +// @public +export function targetStringFromTarget(input: Target): string; + +// @public +export type TypedBuilderProgress = { + state: BuilderProgressState.Stopped; +} | { + state: BuilderProgressState.Error; + error: json.JsonValue; +} | { + state: BuilderProgressState.Waiting; + status?: string; +} | { + state: BuilderProgressState.Running; + status?: string; + current: number; + total?: number; +}; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/architect/node/index.api.md b/goldens/public-api/angular_devkit/architect/node/index.api.md new file mode 100644 index 000000000000..059423576f71 --- /dev/null +++ b/goldens/public-api/angular_devkit/architect/node/index.api.md @@ -0,0 +1,73 @@ +## API Report File for "@angular-devkit/architect_node" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BaseException } from '@angular-devkit/core'; +import { json } from '@angular-devkit/core'; +import { JsonObject } from '@angular-devkit/core'; +import { JsonValue } from '@angular-devkit/core'; +import { logging } from '@angular-devkit/core'; +import { Observable } from 'rxjs'; +import { Observer } from 'rxjs'; +import { schema } from '@angular-devkit/core'; +import { workspaces } from '@angular-devkit/core'; + +declare namespace jobs { + export { + NodeModuleJobRegistry + } +} +export { jobs } + +// @public (undocumented) +class NodeModuleJobRegistry implements jobs_2.Registry { + get(name: jobs_2.JobName): Observable | null>; + // (undocumented) + protected _resolve(name: string): string | null; +} + +// @public (undocumented) +export type NodeModulesBuilderInfo = BuilderInfo & { + import: string; +}; + +// @public (undocumented) +export interface WorkspaceHost { + // (undocumented) + getBuilderName(project: string, target: string): Promise; + // (undocumented) + getDefaultConfigurationName(project: string, target: string): Promise; + // (undocumented) + getMetadata(project: string): Promise; + // (undocumented) + getOptions(project: string, target: string, configuration?: string): Promise; + // (undocumented) + hasTarget(project: string, target: string): Promise; +} + +// @public (undocumented) +export class WorkspaceNodeModulesArchitectHost implements ArchitectHost { + constructor(workspaceHost: WorkspaceHost, _root: string); + constructor(workspace: workspaces.WorkspaceDefinition, _root: string); + // (undocumented) + getBuilderNameForTarget(target: Target_2): Promise; + // (undocumented) + getCurrentDirectory(): Promise; + // (undocumented) + getOptionsForTarget(target: Target_2): Promise; + // (undocumented) + getProjectMetadata(target: Target_2 | string): Promise; + // (undocumented) + getWorkspaceRoot(): Promise; + // (undocumented) + loadBuilder(info: NodeModulesBuilderInfo): Promise; + resolveBuilder(builderStr: string, basePath?: string, seenBuilders?: Set): Promise; + // (undocumented) + protected _root: string; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/architect/testing/index.api.md b/goldens/public-api/angular_devkit/architect/testing/index.api.md new file mode 100644 index 000000000000..23cc6fe8cd7a --- /dev/null +++ b/goldens/public-api/angular_devkit/architect/testing/index.api.md @@ -0,0 +1,76 @@ +## API Report File for "@angular-devkit/architect_testing" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { json } from '@angular-devkit/core'; +import { JsonObject } from '@angular-devkit/core'; +import { JsonValue } from '@angular-devkit/core'; +import { NodeJsSyncHost } from '@angular-devkit/core/node'; +import { Observable } from 'rxjs'; +import { Observer } from 'rxjs'; +import { Path } from '@angular-devkit/core'; +import { PathFragment } from '@angular-devkit/core'; +import { schema } from '@angular-devkit/core'; +import { Stats } from 'node:fs'; +import { virtualFs } from '@angular-devkit/core'; + +// @public (undocumented) +export class TestingArchitectHost implements ArchitectHost { + constructor(workspaceRoot?: string, currentDirectory?: string, _backendHost?: ArchitectHost | null); + // (undocumented) + addBuilder(builderName: string, builder: Builder, description?: string, optionSchema?: json.schema.JsonSchema): void; + // (undocumented) + addBuilderFromPackage(packageName: string): Promise; + // (undocumented) + addTarget(target: Target, builderName: string, options?: json.JsonObject): void; + // (undocumented) + currentDirectory: string; + // (undocumented) + getBuilderNameForTarget(target: Target): Promise; + // (undocumented) + getCurrentDirectory(): Promise; + // (undocumented) + getOptionsForTarget(target: Target): Promise; + // (undocumented) + getProjectMetadata(target: Target | string): Promise; + // (undocumented) + getWorkspaceRoot(): Promise; + // (undocumented) + loadBuilder(info: BuilderInfo): Promise; + resolveBuilder(builderName: string): Promise; + // (undocumented) + workspaceRoot: string; +} + +// @public @deprecated (undocumented) +export class TestProjectHost extends NodeJsSyncHost { + constructor(_templateRoot: Path); + // (undocumented) + appendToFile(path: string, str: string): void; + // (undocumented) + copyFile(from: string, to: string): void; + // (undocumented) + fileMatchExists(dir: string, regex: RegExp): PathFragment | undefined; + // (undocumented) + initialize(): Observable; + // (undocumented) + replaceInFile(path: string, match: RegExp | string, replacement: string): void; + // (undocumented) + restore(): Observable; + // (undocumented) + root(): Path; + // (undocumented) + scopedSync(): virtualFs.SyncDelegateHost; + // (undocumented) + protected _templateRoot: Path; + // (undocumented) + writeMultipleFiles(files: { + [path: string]: string | ArrayBufferLike | Buffer; + }): void; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/build_angular/index.api.md b/goldens/public-api/angular_devkit/build_angular/index.api.md new file mode 100644 index 000000000000..9414547a18e6 --- /dev/null +++ b/goldens/public-api/angular_devkit/build_angular/index.api.md @@ -0,0 +1,355 @@ +## API Report File for "@angular-devkit/build-angular" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { ApplicationBuilderOptions } from '@angular/build'; +import { buildApplication } from '@angular/build'; +import { BuilderContext } from '@angular-devkit/architect'; +import { BuilderOutput } from '@angular-devkit/architect'; +import type { ConfigOptions } from 'karma'; +import { Configuration } from 'webpack'; +import { DevServerBuilderOutput } from '@angular/build'; +import type http from 'node:http'; +import { IndexHtmlTransform } from '@angular/build/private'; +import { Observable } from 'rxjs'; +import type { Plugin as Plugin_2 } from 'esbuild'; +import webpack from 'webpack'; +import { WebpackLoggingCallback } from '@angular-devkit/build-webpack'; + +export { ApplicationBuilderOptions } + +// @public (undocumented) +export type AssetPattern = AssetPatternObject | string; + +// @public (undocumented) +export type AssetPatternObject = { + followSymlinks?: boolean; + glob: string; + ignore?: string[]; + input: string; + output?: string; +}; + +// @public +export type BrowserBuilderOptions = { + allowedCommonJsDependencies?: string[]; + aot?: boolean; + assets?: AssetPattern[]; + baseHref?: string; + budgets?: Budget[]; + buildOptimizer?: boolean; + commonChunk?: boolean; + crossOrigin?: CrossOrigin; + deleteOutputPath?: boolean; + deployUrl?: string; + extractLicenses?: boolean; + fileReplacements?: FileReplacement[]; + i18nDuplicateTranslation?: I18NTranslation; + i18nMissingTranslation?: I18NTranslation; + index: IndexUnion; + inlineStyleLanguage?: InlineStyleLanguage_2; + localize?: Localize; + main: string; + namedChunks?: boolean; + ngswConfigPath?: string; + optimization?: OptimizationUnion; + outputHashing?: OutputHashing; + outputPath: string; + poll?: number; + polyfills?: Polyfills_2; + preserveSymlinks?: boolean; + progress?: boolean; + resourcesOutputPath?: string; + scripts?: ScriptElement_2[]; + serviceWorker?: boolean; + sourceMap?: SourceMapUnion; + statsJson?: boolean; + stylePreprocessorOptions?: StylePreprocessorOptions; + styles?: StyleElement_2[]; + subresourceIntegrity?: boolean; + tsConfig: string; + vendorChunk?: boolean; + verbose?: boolean; + watch?: boolean; + webWorkerTsConfig?: string; +}; + +// @public +export type BrowserBuilderOutput = BuilderOutput & { + stats: BuildEventStats; + baseOutputPath: string; + outputs: { + locale?: string; + path: string; + baseHref?: string; + }[]; +}; + +// @public (undocumented) +export type Budget = { + baseline?: string; + error?: string; + maximumError?: string; + maximumWarning?: string; + minimumError?: string; + minimumWarning?: string; + name?: string; + type: Type; + warning?: string; +}; + +export { buildApplication } + +// @public +export enum CrossOrigin { + // (undocumented) + Anonymous = "anonymous", + // (undocumented) + None = "none", + // (undocumented) + UseCredentials = "use-credentials" +} + +// @public +export type DevServerBuilderOptions = { + allowedHosts?: string[]; + buildTarget: string; + disableHostCheck?: boolean; + forceEsbuild?: boolean; + headers?: { + [key: string]: string; + }; + hmr?: boolean; + host?: string; + inspect?: Inspect; + liveReload?: boolean; + open?: boolean; + poll?: number; + port?: number; + prebundle?: PrebundleUnion; + proxyConfig?: string; + publicHost?: string; + servePath?: string; + ssl?: boolean; + sslCert?: string; + sslKey?: string; + verbose?: boolean; + watch?: boolean; +}; + +export { DevServerBuilderOutput } + +// @public +export function executeBrowserBuilder(options: BrowserBuilderOptions, context: BuilderContext, transforms?: { + webpackConfiguration?: ExecutionTransformer; + logging?: WebpackLoggingCallback; + indexHtml?: IndexHtmlTransform; +}): Observable; + +// @public +export function executeDevServerBuilder(options: DevServerBuilderOptions, context: BuilderContext, transforms?: { + webpackConfiguration?: ExecutionTransformer; + logging?: WebpackLoggingCallback; + indexHtml?: IndexHtmlTransform; +}, extensions?: { + buildPlugins?: Plugin_2[]; + middleware?: ((req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void) => void)[]; + builderSelector?: (info: BuilderSelectorInfo, logger: BuilderContext['logger']) => string; +}): Observable; + +// @public +export function executeExtractI18nBuilder(options: ExtractI18nBuilderOptions, context: BuilderContext, transforms?: { + webpackConfiguration?: ExecutionTransformer; +}): Promise; + +// @public +export function executeKarmaBuilder(options: KarmaBuilderOptions, context: BuilderContext, transforms?: { + webpackConfiguration?: ExecutionTransformer; + karmaOptions?: (options: KarmaConfigOptions) => KarmaConfigOptions; +}): Observable; + +// @public @deprecated +export function executeNgPackagrBuilder(options: NgPackagrBuilderOptions, context: BuilderContext): Observable; + +// @public +export function executeServerBuilder(options: ServerBuilderOptions, context: BuilderContext, transforms?: { + webpackConfiguration?: ExecutionTransformer; +}): Observable; + +// @public (undocumented) +export function executeSSRDevServerBuilder(options: SSRDevServerBuilderOptions, context: BuilderContext): Observable; + +// @public +export type ExecutionTransformer = (input: T) => T | Promise; + +// @public +export type ExtractI18nBuilderOptions = { + buildTarget?: string; + format?: Format; + i18nDuplicateTranslation?: I18NDuplicateTranslation; + outFile?: string; + outputPath?: string; + progress?: boolean; +}; + +// @public (undocumented) +export type FileReplacement = { + replace?: string; + replaceWith?: string; + src?: string; + with?: string; +}; + +// @public +export type KarmaBuilderOptions = { + aot?: boolean; + assets?: AssetPattern_2[]; + browsers?: Browsers; + builderMode?: BuilderMode; + codeCoverage?: boolean; + codeCoverageExclude?: string[]; + exclude?: string[]; + fileReplacements?: FileReplacement_2[]; + include?: string[]; + inlineStyleLanguage?: InlineStyleLanguage; + karmaConfig?: string; + main?: string; + poll?: number; + polyfills?: Polyfills; + preserveSymlinks?: boolean; + progress?: boolean; + reporters?: string[]; + scripts?: ScriptElement[]; + sourceMap?: SourceMapUnion_2; + stylePreprocessorOptions?: StylePreprocessorOptions_2; + styles?: StyleElement[]; + tsConfig: string; + watch?: boolean; + webWorkerTsConfig?: string; +}; + +// @public (undocumented) +export type KarmaConfigOptions = ConfigOptions & { + buildWebpack?: unknown; + configFile?: string; +}; + +// @public @deprecated +export type NgPackagrBuilderOptions = { + poll?: number; + project: string; + tsConfig?: string; + watch?: boolean; +}; + +// @public (undocumented) +export type OptimizationObject = { + fonts?: FontsUnion; + scripts?: boolean; + styles?: StylesUnion; +}; + +// @public +export type OptimizationUnion = boolean | OptimizationObject; + +// @public +export enum OutputHashing { + // (undocumented) + All = "all", + // (undocumented) + Bundles = "bundles", + // (undocumented) + Media = "media", + // (undocumented) + None = "none" +} + +// @public (undocumented) +export type ServerBuilderOptions = { + assets?: AssetPattern_3[]; + buildOptimizer?: boolean; + deleteOutputPath?: boolean; + deployUrl?: string; + externalDependencies?: string[]; + extractLicenses?: boolean; + fileReplacements?: FileReplacement_3[]; + i18nDuplicateTranslation?: I18NTranslation_2; + i18nMissingTranslation?: I18NTranslation_2; + inlineStyleLanguage?: InlineStyleLanguage_3; + localize?: Localize_2; + main: string; + namedChunks?: boolean; + optimization?: OptimizationUnion_2; + outputHashing?: OutputHashing_2; + outputPath: string; + poll?: number; + preserveSymlinks?: boolean; + progress?: boolean; + resourcesOutputPath?: string; + sourceMap?: SourceMapUnion_3; + statsJson?: boolean; + stylePreprocessorOptions?: StylePreprocessorOptions_3; + tsConfig: string; + vendorChunk?: boolean; + verbose?: boolean; + watch?: boolean; +}; + +// @public +export type ServerBuilderOutput = BuilderOutput & { + baseOutputPath: string; + outputPath: string; + outputs: { + locale?: string; + path: string; + }[]; +}; + +// @public (undocumented) +export type SourceMapObject = { + hidden?: boolean; + scripts?: boolean; + styles?: boolean; + vendor?: boolean; +}; + +// @public +export type SourceMapUnion = boolean | SourceMapObject; + +// @public (undocumented) +export type SSRDevServerBuilderOptions = Schema; + +// @public (undocumented) +export type SSRDevServerBuilderOutput = BuilderOutput & { + baseUrl?: string; + port?: string; +}; + +// @public +export type StylePreprocessorOptions = { + includePaths?: string[]; +}; + +// @public +export enum Type { + // (undocumented) + All = "all", + // (undocumented) + AllScript = "allScript", + // (undocumented) + Any = "any", + // (undocumented) + AnyComponentStyle = "anyComponentStyle", + // (undocumented) + AnyScript = "anyScript", + // (undocumented) + Bundle = "bundle", + // (undocumented) + Initial = "initial" +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/build_webpack/index.api.md b/goldens/public-api/angular_devkit/build_webpack/index.api.md new file mode 100644 index 000000000000..3e7ebf07873b --- /dev/null +++ b/goldens/public-api/angular_devkit/build_webpack/index.api.md @@ -0,0 +1,80 @@ +## API Report File for "@angular-devkit/build-webpack" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BuilderContext } from '@angular-devkit/architect'; +import { BuilderOutput } from '@angular-devkit/architect'; +import type { Configuration } from 'webpack-dev-server'; +import { Observable } from 'rxjs'; +import type webpack from 'webpack'; +import type WebpackDevServer from 'webpack-dev-server'; + +// @public (undocumented) +export type BuildResult = BuilderOutput & { + emittedFiles?: EmittedFiles[]; + webpackStats?: webpack.StatsCompilation; + outputPath: string; +}; + +// @public (undocumented) +export type DevServerBuildOutput = BuildResult & { + port: number; + family: string; + address: string; +}; + +// @public (undocumented) +export interface EmittedFiles { + // (undocumented) + asset?: boolean; + // (undocumented) + extension: string; + // (undocumented) + file: string; + // (undocumented) + id?: string; + // (undocumented) + initial: boolean; + // (undocumented) + name?: string; +} + +// @public @deprecated (undocumented) +export function runWebpack(config: webpack.Configuration, context: BuilderContext, options?: { + logging?: WebpackLoggingCallback; + webpackFactory?: WebpackFactory; + shouldProvideStats?: boolean; +}): Observable; + +// @public @deprecated (undocumented) +export function runWebpackDevServer(config: webpack.Configuration, context: BuilderContext, options?: { + shouldProvideStats?: boolean; + devServerConfig?: Configuration; + logging?: WebpackLoggingCallback; + webpackFactory?: WebpackFactory; + webpackDevServerFactory?: WebpackDevServerFactory; +}): Observable; + +// @public (undocumented) +export type WebpackBuilderSchema = Schema; + +// @public (undocumented) +export type WebpackDevServerFactory = typeof WebpackDevServer; + +// @public (undocumented) +export interface WebpackFactory { + // (undocumented) + (config: webpack.Configuration): Observable | webpack.Compiler | null; +} + +// @public (undocumented) +export interface WebpackLoggingCallback { + // (undocumented) + (stats: webpack.Stats, config: webpack.Configuration): void; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/core/index.api.md b/goldens/public-api/angular_devkit/core/index.api.md new file mode 100644 index 000000000000..d86a826c566f --- /dev/null +++ b/goldens/public-api/angular_devkit/core/index.api.md @@ -0,0 +1,1400 @@ +## API Report File for "@angular-devkit/core" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { ErrorObject } from 'ajv'; +import { Format } from 'ajv'; +import { Observable } from 'rxjs'; +import { ObservableInput } from 'rxjs'; +import { Operator } from 'rxjs'; +import { PartialObserver } from 'rxjs'; +import { Position } from 'source-map'; +import { Subject } from 'rxjs'; +import { Subscription } from 'rxjs'; +import { ValidateFunction } from 'ajv'; + +// @public (undocumented) +function addUndefinedDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue; + +// @public (undocumented) +function addUndefinedObjectDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue; + +// @public +class AliasHost extends ResolverHost { + // (undocumented) + get aliases(): Map; + // (undocumented) + protected _aliases: Map; + // (undocumented) + protected _resolve(path: Path): Path; +} + +// @public (undocumented) +export function asPosixPath(path: Path): PosixPath; + +// @public (undocumented) +export function asWindowsPath(path: Path): WindowsPath; + +// @public +export class BaseException extends Error { + constructor(message?: string); +} + +// @public +export function basename(path: Path): PathFragment; + +// @public (undocumented) +function buildJsonPointer(fragments: string[]): JsonPointer; + +// @public +function camelize(str: string): string; + +// @public +function capitalize(str: string): string; + +// @public (undocumented) +export class CircularDependencyFoundException extends BaseException { + constructor(); +} + +// @public +function classify(str: string): string; + +// @public +class CordHost extends SimpleMemoryHost { + constructor(_back: ReadonlyHost); + // (undocumented) + protected _back: ReadonlyHost; + // (undocumented) + get backend(): ReadonlyHost; + // (undocumented) + get capabilities(): HostCapabilities; + clone(): CordHost; + commit(host: Host, force?: boolean): Observable; + create(path: Path, content: FileBuffer): Observable; + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + protected _filesToCreate: Set; + // (undocumented) + protected _filesToDelete: Set; + // (undocumented) + protected _filesToOverwrite: Set; + // (undocumented) + protected _filesToRename: Map; + // (undocumented) + protected _filesToRenameRevert: Map; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + overwrite(path: Path, content: FileBuffer): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + records(): CordHostRecord[]; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + stat(path: Path): Observable | null; + // (undocumented) + watch(path: Path, options?: HostWatchOptions): null; + // (undocumented) + willCreate(path: Path): boolean; + // (undocumented) + willDelete(path: Path): boolean; + // (undocumented) + willOverwrite(path: Path): boolean; + // (undocumented) + willRename(path: Path): boolean; + // (undocumented) + willRenameTo(path: Path, to: Path): boolean; + // (undocumented) + write(path: Path, content: FileBuffer): Observable; +} + +// @public (undocumented) +interface CordHostCreate { + // (undocumented) + content: FileBuffer; + // (undocumented) + kind: 'create'; + // (undocumented) + path: Path; +} + +// @public (undocumented) +interface CordHostDelete { + // (undocumented) + kind: 'delete'; + // (undocumented) + path: Path; +} + +// @public (undocumented) +interface CordHostOverwrite { + // (undocumented) + content: FileBuffer; + // (undocumented) + kind: 'overwrite'; + // (undocumented) + path: Path; +} + +// @public (undocumented) +type CordHostRecord = CordHostCreate | CordHostOverwrite | CordHostRename | CordHostDelete; + +// @public (undocumented) +interface CordHostRename { + // (undocumented) + from: Path; + // (undocumented) + kind: 'rename'; + // (undocumented) + to: Path; +} + +// @public (undocumented) +class CoreSchemaRegistry implements SchemaRegistry { + constructor(formats?: SchemaFormat[]); + // (undocumented) + addFormat(format: SchemaFormat): void; + addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; + addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; + // (undocumented) + addSmartDefaultProvider(source: string, provider: SmartDefaultProvider): void; + compile(schema: JsonSchema): Promise; + // (undocumented) + registerUriHandler(handler: UriHandler): void; + // (undocumented) + protected _resolver(ref: string, validate?: ValidateFunction): { + context?: ValidateFunction; + schema?: JsonObject; + }; + // (undocumented) + usePromptProvider(provider: PromptProvider): void; + // (undocumented) + useXDeprecatedProvider(onUsage: (message: string) => void): void; + ɵflatten(schema: JsonObject): Promise; +} + +// @public (undocumented) +function createSyncHost(handler: SyncHostHandler): Host; + +// @public (undocumented) +function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost; + +// @public +function dasherize(str: string): string; + +// @public +function decamelize(str: string): string; + +// @public @deprecated (undocumented) +export function deepCopy(value: T): T; + +// @public (undocumented) +type DefinitionCollectionListener = (name: string, newValue: V | undefined, collection: DefinitionCollection) => void; + +// @public (undocumented) +export class DependencyNotFoundException extends BaseException { + constructor(); +} + +// @public +export function dirname(path: Path): Path; + +// @public (undocumented) +class Empty implements ReadonlyHost { + // (undocumented) + readonly capabilities: HostCapabilities; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + stat(path: Path): Observable | null>; +} + +// @public (undocumented) +export function extname(path: Path): string; + +// @public (undocumented) +export class FileAlreadyExistException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +type FileBuffer = ArrayBuffer; + +// @public (undocumented) +type FileBufferLike = ArrayBufferLike; + +// @public @deprecated (undocumented) +function fileBufferToString(fileBuffer: FileBuffer): string; + +// @public (undocumented) +export class FileDoesNotExistException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export function fragment(path: string): PathFragment; + +// @public (undocumented) +export function getSystemPath(path: Path): string; + +// @public (undocumented) +function getTypesOfSchema(schema: JsonSchema): Set; + +// @public (undocumented) +interface Host extends ReadonlyHost { + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + watch(path: Path, options?: HostWatchOptions): Observable | null; + // (undocumented) + write(path: Path, content: FileBufferLike): Observable; +} + +// @public (undocumented) +interface HostCapabilities { + // (undocumented) + synchronous: boolean; +} + +// @public (undocumented) +interface HostWatchEvent { + // (undocumented) + readonly path: Path; + // (undocumented) + readonly time: Date; + // (undocumented) + readonly type: HostWatchEventType; +} + +// @public (undocumented) +enum HostWatchEventType { + // (undocumented) + Changed = 0, + // (undocumented) + Created = 1, + // (undocumented) + Deleted = 2, + // (undocumented) + Renamed = 3 +} + +// @public (undocumented) +interface HostWatchOptions { + // (undocumented) + readonly persistent?: boolean; + // (undocumented) + readonly recursive?: boolean; +} + +// @public (undocumented) +function indentBy(indentations: number): TemplateTag; + +// @public (undocumented) +class IndentLogger extends Logger { + constructor(name: string, parent?: Logger | null, indentation?: string); +} + +// @public (undocumented) +export class InvalidPathException extends BaseException { + constructor(path: string); +} + +// @public +export function isAbsolute(p: Path): boolean; + +// @public (undocumented) +export function isJsonArray(value: JsonValue): value is JsonArray; + +// @public (undocumented) +export function isJsonObject(value: JsonValue): value is JsonObject; + +// @public (undocumented) +function isJsonSchema(value: unknown): value is JsonSchema; + +// @public @deprecated +export function isPromise(obj: any): obj is Promise; + +// @public +export function join(p1: Path, ...others: string[]): Path; + +// @public (undocumented) +function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer; + +declare namespace json { + export { + schema, + isJsonObject, + isJsonArray, + JsonArray, + JsonObject, + JsonValue + } +} +export { json } + +// @public +export interface JsonArray extends Array { +} + +// @public (undocumented) +export interface JsonObject { + // (undocumented) + [prop: string]: JsonValue; +} + +// @public (undocumented) +type JsonPointer = string & { + __PRIVATE_DEVKIT_JSON_POINTER: void; +}; + +// @public +type JsonSchema = JsonObject | boolean; + +// @public (undocumented) +interface JsonSchemaVisitor { + // (undocumented) + (current: JsonObject | JsonArray, pointer: JsonPointer, parentSchema?: JsonObject | JsonArray, index?: string): void; +} + +// @public (undocumented) +export type JsonValue = boolean | string | number | JsonArray | JsonObject | null; + +// @public (undocumented) +interface JsonVisitor { + // (undocumented) + (value: JsonValue, pointer: JsonPointer, schema?: JsonObject, root?: JsonObject | JsonArray): Observable | JsonValue; +} + +// @public (undocumented) +class LevelCapLogger extends LevelTransformLogger { + constructor(name: string, parent: Logger | null, levelCap: LogLevel); + // (undocumented) + readonly levelCap: LogLevel; + // (undocumented) + static levelMap: { + [cap: string]: { + [level: string]: string; + }; + }; + // (undocumented) + readonly name: string; + // (undocumented) + readonly parent: Logger | null; +} + +// @public (undocumented) +class LevelTransformLogger extends Logger { + constructor(name: string, parent: Logger | null, levelTransform: (level: LogLevel) => LogLevel); + // (undocumented) + createChild(name: string): Logger; + // (undocumented) + readonly levelTransform: (level: LogLevel) => LogLevel; + // (undocumented) + log(level: LogLevel, message: string, metadata?: JsonObject): void; + // (undocumented) + readonly name: string; + // (undocumented) + readonly parent: Logger | null; +} + +// @public +function levenshtein(a: string, b: string): number; + +// @public (undocumented) +interface LogEntry extends LoggerMetadata { + // (undocumented) + level: LogLevel; + // (undocumented) + message: string; + // (undocumented) + timestamp: number; +} + +// @public (undocumented) +class Logger extends Observable implements LoggerApi { + constructor(name: string, parent?: Logger | null); + // (undocumented) + asApi(): LoggerApi; + // (undocumented) + complete(): void; + // (undocumented) + createChild(name: string): Logger; + // (undocumented) + debug(message: string, metadata?: JsonObject): void; + // (undocumented) + error(message: string, metadata?: JsonObject): void; + // (undocumented) + fatal(message: string, metadata?: JsonObject): void; + // (undocumented) + forEach(next: (value: LogEntry) => void, promiseCtor?: PromiseConstructorLike): Promise; + // (undocumented) + info(message: string, metadata?: JsonObject): void; + // (undocumented) + lift(operator: Operator): Observable; + // (undocumented) + log(level: LogLevel, message: string, metadata?: JsonObject): void; + // (undocumented) + protected _metadata: LoggerMetadata; + // (undocumented) + readonly name: string; + // (undocumented) + next(entry: LogEntry): void; + // (undocumented) + protected get _observable(): Observable; + protected set _observable(v: Observable); + // (undocumented) + readonly parent: Logger | null; + // (undocumented) + protected readonly _subject: Subject; + // (undocumented) + subscribe(): Subscription; + // (undocumented) + subscribe(observer: PartialObserver): Subscription; + // (undocumented) + subscribe(next?: (value: LogEntry) => void, error?: (error: Error) => void, complete?: () => void): Subscription; + // (undocumented) + toString(): string; + // (undocumented) + warn(message: string, metadata?: JsonObject): void; +} + +// @public (undocumented) +interface LoggerApi { + // (undocumented) + createChild(name: string): Logger; + // (undocumented) + debug(message: string, metadata?: JsonObject): void; + // (undocumented) + error(message: string, metadata?: JsonObject): void; + // (undocumented) + fatal(message: string, metadata?: JsonObject): void; + // (undocumented) + info(message: string, metadata?: JsonObject): void; + // (undocumented) + log(level: LogLevel, message: string, metadata?: JsonObject): void; + // (undocumented) + warn(message: string, metadata?: JsonObject): void; +} + +// @public (undocumented) +interface LoggerMetadata extends JsonObject { + // (undocumented) + name: string; + // (undocumented) + path: string[]; +} + +declare namespace logging { + export { + IndentLogger, + LevelTransformLogger, + LevelCapLogger, + LoggerMetadata, + LogEntry, + LoggerApi, + LogLevel, + Logger, + NullLogger, + TransformLogger + } +} +export { logging } + +// @public (undocumented) +type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; + +// @public +function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema; + +// @public +export function noCacheNormalize(path: string): Path; + +// @public +export function normalize(path: string): Path; + +// @public +export const NormalizedRoot: Path; + +// @public +export const NormalizedSep: Path; + +// @public (undocumented) +class NullLogger extends Logger { + constructor(parent?: Logger | null); + // (undocumented) + asApi(): LoggerApi; +} + +// @public (undocumented) +function oneLine(strings: TemplateStringsArray, ...values: any[]): string; + +// @public (undocumented) +function parseJsonPointer(pointer: JsonPointer): string[]; + +// @public @deprecated (undocumented) +export class PartiallyOrderedSet { + // (undocumented) + [Symbol.iterator](): IterableIterator; + // (undocumented) + get [Symbol.toStringTag](): 'PartiallyOrderedSet'; + // (undocumented) + add(item: T, deps?: Set | T[]): this; + // (undocumented) + protected _checkCircularDependencies(item: T, deps: Set): void; + // (undocumented) + clear(): void; + // (undocumented) + delete(item: T): boolean; + entries(): IterableIterator<[T, T]>; + // (undocumented) + forEach(callbackfn: (value: T, value2: T, set: PartiallyOrderedSet) => void, thisArg?: any): void; + // (undocumented) + has(item: T): boolean; + keys(): IterableIterator; + // (undocumented) + get size(): number; + values(): IterableIterator; +} + +// @public +export type Path = string & { + __PRIVATE_DEVKIT_PATH: void; +}; + +// @public (undocumented) +export const path: TemplateTag; + +// @public (undocumented) +export class PathCannotBeFragmentException extends BaseException { + constructor(path: string); +} + +// @public +export type PathFragment = Path & { + __PRIVATE_DEVKIT_PATH_FRAGMENT: void; +}; + +// @public (undocumented) +export class PathIsDirectoryException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export class PathIsFileException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export class PathMustBeAbsoluteException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +class PatternMatchingHost extends ResolverHost { + // (undocumented) + addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void; + // (undocumented) + protected _patterns: Map; + // (undocumented) + protected _resolve(path: Path): Path; +} + +// @public (undocumented) +export type PosixPath = string & { + __PRIVATE_DEVKIT_POSIX_PATH: void; +}; + +// @public +export class PriorityQueue { + constructor(_comparator: (x: T, y: T) => number); + // (undocumented) + clear(): void; + // (undocumented) + peek(): T | undefined; + // (undocumented) + pop(): T | undefined; + // (undocumented) + push(item: T): void; + // (undocumented) + get size(): number; + // (undocumented) + toArray(): Array; +} + +// @public (undocumented) +interface ProjectDefinition { + // (undocumented) + readonly extensions: Record; + // (undocumented) + prefix?: string; + // (undocumented) + root: string; + // (undocumented) + sourceRoot?: string; + // (undocumented) + readonly targets: TargetDefinitionCollection; +} + +// @public (undocumented) +class ProjectDefinitionCollection extends DefinitionCollection { + constructor(initial?: Record, listener?: DefinitionCollectionListener); + // (undocumented) + add(definition: { + name: string; + root: string; + sourceRoot?: string; + prefix?: string; + targets?: Record; + [key: string]: unknown; + }): ProjectDefinition; + // (undocumented) + set(name: string, value: ProjectDefinition): this; +} + +// @public (undocumented) +interface PromptDefinition { + // (undocumented) + default?: string | string[] | number | boolean | null; + // (undocumented) + id: string; + // (undocumented) + items?: Array; + // (undocumented) + message: string; + // (undocumented) + multiselect?: boolean; + // (undocumented) + propertyTypes: Set; + // (undocumented) + raw?: string | JsonObject; + // (undocumented) + type: string; + // (undocumented) + validator?: (value: JsonValue) => boolean | string | Promise; +} + +// @public (undocumented) +type PromptProvider = (definitions: Array) => ObservableInput<{ + [id: string]: JsonValue; +}>; + +// @public (undocumented) +interface ReadonlyHost { + // (undocumented) + readonly capabilities: HostCapabilities; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + stat(path: Path): Observable | null> | null; +} + +// @public +function readWorkspace(path: string, host: WorkspaceHost, format?: WorkspaceFormat): Promise<{ + workspace: WorkspaceDefinition; +}>; + +// @public (undocumented) +interface ReferenceResolver { + // (undocumented) + (ref: string, context?: ContextT): { + context?: ContextT; + schema?: JsonObject; + }; +} + +// @public +export function relative(from: Path, to: Path): Path; + +// @public (undocumented) +type ReplacementFunction = (path: Path) => Path; + +// @public +export function resetNormalizeCache(): void; + +// @public +export function resolve(p1: Path, p2: Path): Path; + +// @public +abstract class ResolverHost implements Host { + constructor(_delegate: Host); + // (undocumented) + get capabilities(): HostCapabilities; + // (undocumented) + protected _delegate: Host; + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + protected abstract _resolve(path: Path): Path; + // (undocumented) + stat(path: Path): Observable | null> | null; + // (undocumented) + watch(path: Path, options?: HostWatchOptions): Observable | null; + // (undocumented) + write(path: Path, content: FileBuffer): Observable; +} + +// @public +class SafeReadonlyHost implements ReadonlyHost { + constructor(_delegate: ReadonlyHost); + // (undocumented) + get capabilities(): HostCapabilities; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + stat(path: Path): Observable | null> | null; +} + +declare namespace schema { + export { + transforms, + JsonPointer, + SchemaValidatorResult, + SchemaValidatorError, + SchemaValidatorOptions, + SchemaValidator, + SchemaFormatter, + SchemaFormat, + SmartDefaultProvider, + SchemaKeywordValidator, + PromptDefinition, + PromptProvider, + SchemaRegistry, + JsonSchemaVisitor, + JsonVisitor, + buildJsonPointer, + joinJsonPointer, + parseJsonPointer, + UriHandler, + SchemaValidationException, + CoreSchemaRegistry, + isJsonSchema, + mergeSchemas, + JsonSchema, + visitJson, + visitJsonSchema, + ReferenceResolver, + getTypesOfSchema + } +} +export { schema } + +// @public (undocumented) +interface SchemaFormat { + // (undocumented) + formatter: SchemaFormatter; + // (undocumented) + name: string; +} + +// @public (undocumented) +type SchemaFormatter = Format; + +// @public (undocumented) +interface SchemaKeywordValidator { + // (undocumented) + (data: JsonValue, schema: JsonValue, parent: JsonObject | JsonArray | undefined, parentProperty: string | number | undefined, pointer: JsonPointer, rootData: JsonValue): boolean | Observable; +} + +// @public (undocumented) +interface SchemaRegistry { + // (undocumented) + addFormat(format: SchemaFormat): void; + addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; + addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; + // (undocumented) + addSmartDefaultProvider(source: string, provider: SmartDefaultProvider): void; + // (undocumented) + compile(schema: Object): Promise; + // (undocumented) + usePromptProvider(provider: PromptProvider): void; + // (undocumented) + useXDeprecatedProvider(onUsage: (message: string) => void): void; + // (undocumented) + ɵflatten(schema: JsonObject | string): Promise; +} + +// @public (undocumented) +class SchemaValidationException extends BaseException { + constructor(errors?: SchemaValidatorError[], baseMessage?: string); + // (undocumented) + static createMessages(errors?: SchemaValidatorError[]): string[]; + // (undocumented) + readonly errors: SchemaValidatorError[]; +} + +// @public (undocumented) +interface SchemaValidator { + // (undocumented) + (data: JsonValue, options?: SchemaValidatorOptions): Promise; +} + +// @public (undocumented) +type SchemaValidatorError = Partial; + +// @public (undocumented) +interface SchemaValidatorOptions { + // (undocumented) + applyPostTransforms?: boolean; + // (undocumented) + applyPreTransforms?: boolean; + // (undocumented) + withPrompts?: boolean; +} + +// @public (undocumented) +interface SchemaValidatorResult { + // (undocumented) + data: JsonValue; + // (undocumented) + errors?: SchemaValidatorError[]; + // (undocumented) + success: boolean; +} + +// @public (undocumented) +class ScopedHost extends ResolverHost { + constructor(delegate: Host, _root?: Path); + // (undocumented) + protected _resolve(path: Path): Path; + // (undocumented) + protected _root: Path; +} + +// @public (undocumented) +class SimpleMemoryHost implements Host<{}> { + constructor(); + // (undocumented) + protected _cache: Map>; + // (undocumented) + get capabilities(): HostCapabilities; + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + protected _delete(path: Path): void; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + protected _exists(path: Path): boolean; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + protected _isDirectory(path: Path): boolean; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + protected _isFile(path: Path): boolean; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + protected _list(path: Path): PathFragment[]; + // (undocumented) + protected _newDirStats(): Stats; + // (undocumented) + protected _newFileStats(content: FileBuffer, oldStats?: Stats): Stats; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + protected _read(path: Path): FileBuffer; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + protected _rename(from: Path, to: Path): void; + // (undocumented) + reset(): void; + // (undocumented) + stat(path: Path): Observable | null> | null; + // (undocumented) + protected _stat(path: Path): Stats | null; + // (undocumented) + protected _toAbsolute(path: Path): Path; + // (undocumented) + protected _updateWatchers(path: Path, type: HostWatchEventType): void; + // (undocumented) + watch(path: Path, options?: HostWatchOptions): Observable | null; + // (undocumented) + protected _watch(path: Path, options?: HostWatchOptions): Observable; + // (undocumented) + write(path: Path, content: FileBuffer): Observable; + protected _write(path: Path, content: FileBuffer): void; +} + +// @public (undocumented) +interface SimpleMemoryHostStats { + // (undocumented) + readonly content: FileBuffer | null; + // (undocumented) + inspect(): string; +} + +// @public (undocumented) +interface SmartDefaultProvider { + // (undocumented) + (schema: JsonObject): T | Observable; +} + +// @public +export function split(path: Path): PathFragment[]; + +// @public (undocumented) +type Stats = T & { + isFile(): boolean; + isDirectory(): boolean; + readonly size: number; + readonly atime: Date; + readonly mtime: Date; + readonly ctime: Date; + readonly birthtime: Date; +}; + +declare namespace strings { + export { + decamelize, + dasherize, + camelize, + classify, + underscore, + capitalize, + levenshtein + } +} +export { strings } + +// @public @deprecated (undocumented) +function stringToFileBuffer(str: string): FileBuffer; + +// @public (undocumented) +function stripIndent(strings: TemplateStringsArray, ...values: any[]): string; + +// @public (undocumented) +function stripIndents(strings: TemplateStringsArray, ...values: any[]): string; + +// @public +class SyncDelegateHost { + constructor(_delegate: Host); + // (undocumented) + get capabilities(): HostCapabilities; + // (undocumented) + get delegate(): Host; + // (undocumented) + protected _delegate: Host; + // (undocumented) + delete(path: Path): void; + // (undocumented) + protected _doSyncCall(observable: Observable): ResultT; + // (undocumented) + exists(path: Path): boolean; + // (undocumented) + isDirectory(path: Path): boolean; + // (undocumented) + isFile(path: Path): boolean; + // (undocumented) + list(path: Path): PathFragment[]; + // (undocumented) + read(path: Path): FileBuffer; + // (undocumented) + rename(from: Path, to: Path): void; + // (undocumented) + stat(path: Path): Stats | null; + // (undocumented) + watch(path: Path, options?: HostWatchOptions): Observable | null; + // (undocumented) + write(path: Path, content: FileBufferLike): void; +} + +// @public (undocumented) +interface SyncHostHandler { + // (undocumented) + delete(path: Path): void; + // (undocumented) + exists(path: Path): boolean; + // (undocumented) + isDirectory(path: Path): boolean; + // (undocumented) + isFile(path: Path): boolean; + // (undocumented) + list(path: Path): PathFragment[]; + // (undocumented) + read(path: Path): FileBuffer; + // (undocumented) + rename(from: Path, to: Path): void; + // (undocumented) + stat(path: Path): Stats | null; + // (undocumented) + write(path: Path, content: FileBufferLike): void; +} + +// @public (undocumented) +class SynchronousDelegateExpectedException extends BaseException { + constructor(); +} + +declare namespace tags { + export { + oneLine, + indentBy, + stripIndent, + stripIndents, + trimNewlines, + TemplateTag + } +} +export { tags } + +// @public (undocumented) +interface TargetDefinition { + // (undocumented) + builder: string; + // (undocumented) + configurations?: Record | undefined>; + // (undocumented) + defaultConfiguration?: string; + // (undocumented) + options?: Record; +} + +// @public (undocumented) +class TargetDefinitionCollection extends DefinitionCollection { + constructor(initial?: Record, listener?: DefinitionCollectionListener); + // (undocumented) + add(definition: { + name: string; + } & TargetDefinition): TargetDefinition; + // (undocumented) + set(name: string, value: TargetDefinition): this; +} + +// @public +export function template(content: string, options?: TemplateOptions): (input: T) => string; + +// @public +export interface TemplateAst { + // (undocumented) + children: TemplateAstNode[]; + // (undocumented) + content: string; + // (undocumented) + fileName: string; +} + +// @public +export interface TemplateAstBase { + // (undocumented) + end: Position; + // (undocumented) + start: Position; +} + +// @public +export interface TemplateAstComment extends TemplateAstBase { + // (undocumented) + kind: 'comment'; + // (undocumented) + text: string; +} + +// @public +export interface TemplateAstContent extends TemplateAstBase { + // (undocumented) + content: string; + // (undocumented) + kind: 'content'; +} + +// @public +export interface TemplateAstEscape extends TemplateAstBase { + // (undocumented) + expression: string; + // (undocumented) + kind: 'escape'; +} + +// @public +export interface TemplateAstEvaluate extends TemplateAstBase { + // (undocumented) + expression: string; + // (undocumented) + kind: 'evaluate'; +} + +// @public +export interface TemplateAstInterpolate extends TemplateAstBase { + // (undocumented) + expression: string; + // (undocumented) + kind: 'interpolate'; +} + +// @public (undocumented) +export type TemplateAstNode = TemplateAstContent | TemplateAstEvaluate | TemplateAstComment | TemplateAstEscape | TemplateAstInterpolate; + +// @public (undocumented) +export interface TemplateOptions { + // (undocumented) + fileName?: string; + // (undocumented) + module?: boolean | { + exports: {}; + }; + // (undocumented) + sourceMap?: boolean; + // (undocumented) + sourceRoot?: string; + // (undocumented) + sourceURL?: string; +} + +// @public +export function templateParser(sourceText: string, fileName: string): TemplateAst; + +// @public +interface TemplateTag { + // (undocumented) + (template: TemplateStringsArray, ...substitutions: any[]): R; +} + +declare namespace test { + export { + TestLogRecord, + TestHost + } +} + +// @public (undocumented) +class TestHost extends SimpleMemoryHost { + // (undocumented) + $exists(path: string): boolean; + // (undocumented) + $isDirectory(path: string): boolean; + // (undocumented) + $isFile(path: string): boolean; + // (undocumented) + $list(path: string): PathFragment[]; + // (undocumented) + $read(path: string): string; + // (undocumented) + $write(path: string, content: string): void; + constructor(map?: { + [path: string]: string; + }); + // (undocumented) + clearRecords(): void; + // (undocumented) + clone(): TestHost; + // (undocumented) + protected _delete(path: Path): void; + // (undocumented) + protected _exists(path: Path): boolean; + // (undocumented) + get files(): Path[]; + // (undocumented) + protected _isDirectory(path: Path): boolean; + // (undocumented) + protected _isFile(path: Path): boolean; + // (undocumented) + protected _list(path: Path): PathFragment[]; + // (undocumented) + protected _read(path: Path): ArrayBuffer; + // (undocumented) + get records(): TestLogRecord[]; + // (undocumented) + protected _records: TestLogRecord[]; + // (undocumented) + protected _rename(from: Path, to: Path): void; + // (undocumented) + protected _stat(path: Path): Stats | null; + // (undocumented) + get sync(): SyncDelegateHost<{}>; + // (undocumented) + protected _sync: SyncDelegateHost<{}> | null; + // (undocumented) + protected _watch(path: Path, options?: HostWatchOptions): Observable; + // (undocumented) + protected _write(path: Path, content: FileBuffer): void; +} + +// @public (undocumented) +type TestLogRecord = { + kind: 'write' | 'read' | 'delete' | 'list' | 'exists' | 'isDirectory' | 'isFile' | 'stat' | 'watch'; + path: Path; +} | { + kind: 'rename'; + from: Path; + to: Path; +}; + +// @public (undocumented) +class TransformLogger extends Logger { + constructor(name: string, transform: (stream: Observable) => Observable, parent?: Logger | null); +} + +declare namespace transforms { + export { + addUndefinedObjectDefaults, + addUndefinedDefaults + } +} + +// @public (undocumented) +function trimNewlines(strings: TemplateStringsArray, ...values: any[]): string; + +// @public +function underscore(str: string): string; + +// @public (undocumented) +export class UnknownException extends BaseException { + constructor(message: string); +} + +// @public (undocumented) +type UriHandler = (uri: string) => Observable | Promise | null | undefined; + +declare namespace virtualFs { + export { + test, + AliasHost, + stringToFileBuffer, + fileBufferToString, + createSyncHost, + SyncHostHandler, + Empty, + FileBuffer, + FileBufferLike, + HostWatchOptions, + HostWatchEventType, + Stats, + HostWatchEvent, + HostCapabilities, + ReadonlyHost, + Host, + SimpleMemoryHostStats, + SimpleMemoryHost, + ReplacementFunction, + PatternMatchingHost, + CordHostCreate, + CordHostOverwrite, + CordHostRename, + CordHostDelete, + CordHostRecord, + CordHost, + SafeReadonlyHost, + ScopedHost, + SynchronousDelegateExpectedException, + SyncDelegateHost, + ResolverHost + } +} +export { virtualFs } + +// @public +function visitJson(json: JsonValue, visitor: JsonVisitor, schema?: JsonSchema, refResolver?: ReferenceResolver, context?: ContextT): Observable; + +// @public (undocumented) +function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor): void; + +// @public (undocumented) +export type WindowsPath = string & { + __PRIVATE_DEVKIT_WINDOWS_PATH: void; +}; + +// @public (undocumented) +interface WorkspaceDefinition { + // (undocumented) + readonly extensions: Record; + // (undocumented) + readonly projects: ProjectDefinitionCollection; +} + +// @public +enum WorkspaceFormat { + // (undocumented) + JSON = 0 +} + +// @public (undocumented) +interface WorkspaceHost { + // (undocumented) + isDirectory(path: string): Promise; + // (undocumented) + isFile(path: string): Promise; + // (undocumented) + readFile(path: string): Promise; + // (undocumented) + writeFile(path: string, data: string): Promise; +} + +declare namespace workspaces { + export { + WorkspaceHost, + createWorkspaceHost, + WorkspaceFormat, + readWorkspace, + writeWorkspace, + WorkspaceDefinition, + ProjectDefinition, + TargetDefinition, + DefinitionCollectionListener, + ProjectDefinitionCollection, + TargetDefinitionCollection + } +} +export { workspaces } + +// @public +function writeWorkspace(workspace: WorkspaceDefinition, host: WorkspaceHost, path?: string, format?: WorkspaceFormat): Promise; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/core/node/index.api.md b/goldens/public-api/angular_devkit/core/node/index.api.md new file mode 100644 index 000000000000..9fcdee9770cb --- /dev/null +++ b/goldens/public-api/angular_devkit/core/node/index.api.md @@ -0,0 +1,77 @@ +## API Report File for "@angular-devkit/core_node" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { Observable } from 'rxjs'; +import { Operator } from 'rxjs'; +import { PartialObserver } from 'rxjs'; +import { Stats as Stats_2 } from 'node:fs'; +import { Subject } from 'rxjs'; +import { Subscription } from 'rxjs'; + +// @public @deprecated +export function createConsoleLogger(verbose?: boolean, stdout?: ProcessOutput, stderr?: ProcessOutput, colors?: Partial string>>): logging.Logger; + +// @public +export class NodeJsAsyncHost implements virtualFs.Host { + // (undocumented) + get capabilities(): virtualFs.HostCapabilities; + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + stat(path: Path): Observable>; + // (undocumented) + watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable | null; + // (undocumented) + write(path: Path, content: virtualFs.FileBuffer): Observable; +} + +// @public +export class NodeJsSyncHost implements virtualFs.Host { + // (undocumented) + get capabilities(): virtualFs.HostCapabilities; + // (undocumented) + delete(path: Path): Observable; + // (undocumented) + exists(path: Path): Observable; + // (undocumented) + isDirectory(path: Path): Observable; + // (undocumented) + isFile(path: Path): Observable; + // (undocumented) + list(path: Path): Observable; + // (undocumented) + read(path: Path): Observable; + // (undocumented) + rename(from: Path, to: Path): Observable; + // (undocumented) + stat(path: Path): Observable>; + // (undocumented) + watch(path: Path, _options?: virtualFs.HostWatchOptions): Observable | null; + // (undocumented) + write(path: Path, content: virtualFs.FileBuffer): Observable; +} + +// @public (undocumented) +export interface ProcessOutput { + // (undocumented) + write(buffer: string | Buffer): boolean; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/core/node/testing/index.api.md b/goldens/public-api/angular_devkit/core/node/testing/index.api.md new file mode 100644 index 000000000000..116019d266a1 --- /dev/null +++ b/goldens/public-api/angular_devkit/core/node/testing/index.api.md @@ -0,0 +1,27 @@ +## API Report File for "@angular-devkit/core_node_testing" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import * as fs from 'node:fs'; +import { Observable } from 'rxjs'; + +// @public +export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost { + constructor(); + // (undocumented) + get files(): Path[]; + // (undocumented) + get root(): Path; + // (undocumented) + protected _root: Path; + // (undocumented) + get sync(): virtualFs.SyncDelegateHost; + // (undocumented) + protected _sync?: virtualFs.SyncDelegateHost; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/schematics/index.api.md b/goldens/public-api/angular_devkit/schematics/index.api.md new file mode 100644 index 000000000000..efb5da7c8166 --- /dev/null +++ b/goldens/public-api/angular_devkit/schematics/index.api.md @@ -0,0 +1,1065 @@ +## API Report File for "@angular-devkit/schematics" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BaseException } from '@angular-devkit/core'; +import { JsonValue } from '@angular-devkit/core'; +import { logging } from '@angular-devkit/core'; +import { Observable } from 'rxjs'; +import { Path } from '@angular-devkit/core'; +import { PathFragment } from '@angular-devkit/core'; +import { schema } from '@angular-devkit/core'; +import { strings } from '@angular-devkit/core'; +import { Subject } from 'rxjs'; +import { Url } from 'node:url'; +import { virtualFs } from '@angular-devkit/core'; + +// @public (undocumented) +export type Action = CreateFileAction | OverwriteFileAction | RenameFileAction | DeleteFileAction; + +// @public (undocumented) +export interface ActionBase { + // (undocumented) + readonly id: number; + // (undocumented) + readonly parent: number; + // (undocumented) + readonly path: Path; +} + +// @public (undocumented) +export class ActionList implements Iterable { + // (undocumented) + [Symbol.iterator](): IterableIterator; + // (undocumented) + protected _action(action: Partial): void; + // (undocumented) + create(path: Path, content: Buffer): void; + // (undocumented) + delete(path: Path): void; + // (undocumented) + find(predicate: (value: Action) => boolean): Action | null; + // (undocumented) + forEach(fn: (value: Action, index: number, array: Action[]) => void, thisArg?: {}): void; + // (undocumented) + get(i: number): Action; + // (undocumented) + has(action: Action): boolean; + // (undocumented) + get length(): number; + // (undocumented) + optimize(): void; + // (undocumented) + overwrite(path: Path, content: Buffer): void; + // (undocumented) + push(action: Action): void; + // (undocumented) + rename(path: Path, to: Path): void; +} + +// @public +export function apply(source: Source, rules: Rule[]): Source; + +// @public (undocumented) +export function applyContentTemplate(options: T): FileOperator; + +// @public (undocumented) +export function applyPathTemplate(data: T, options?: PathTemplateOptions): FileOperator; + +// @public (undocumented) +export function applyTemplates(options: T): Rule; + +// @public (undocumented) +export function applyToSubtree(path: string, rules: Rule[]): Rule; + +// @public (undocumented) +export function asSource(rule: Rule): Source; + +// @public (undocumented) +export type AsyncFileOperator = (tree: FileEntry) => Observable; + +// @public +abstract class BaseWorkflow implements Workflow { + constructor(options: BaseWorkflowOptions); + // (undocumented) + get context(): Readonly; + // (undocumented) + protected _context: WorkflowExecutionContext[]; + // (undocumented) + protected _createSinks(): Sink[]; + // (undocumented) + protected _dryRun: boolean; + // (undocumented) + get engine(): Engine<{}, {}>; + // (undocumented) + protected _engine: Engine<{}, {}>; + // (undocumented) + get engineHost(): EngineHost<{}, {}>; + // (undocumented) + protected _engineHost: EngineHost<{}, {}>; + // (undocumented) + execute(options: Partial & RequiredWorkflowExecutionContext): Observable; + // (undocumented) + protected _force: boolean; + // (undocumented) + protected _host: virtualFs.Host; + // (undocumented) + get lifeCycle(): Observable; + // (undocumented) + protected _lifeCycle: Subject; + // (undocumented) + get registry(): schema.SchemaRegistry; + // (undocumented) + protected _registry: schema.CoreSchemaRegistry; + // (undocumented) + get reporter(): Observable; + // (undocumented) + protected _reporter: Subject; +} + +// @public (undocumented) +interface BaseWorkflowOptions { + // (undocumented) + dryRun?: boolean; + // (undocumented) + engineHost: EngineHost<{}, {}>; + // (undocumented) + force?: boolean; + // (undocumented) + host: virtualFs.Host; + // (undocumented) + registry?: schema.CoreSchemaRegistry; +} + +// @public (undocumented) +export function branchAndMerge(rule: Rule, strategy?: MergeStrategy): Rule; + +// @public (undocumented) +export function callRule(rule: Rule, input: Tree_2 | Observable, context: SchematicContext): Observable; + +// @public (undocumented) +export function callSource(source: Source, context: SchematicContext): Observable; + +// @public +export function chain(rules: Iterable | AsyncIterable): Rule; + +// @public (undocumented) +export class CircularCollectionException extends BaseException { + constructor(name: string); +} + +// @public +export interface Collection { + // (undocumented) + readonly baseDescriptions?: Array>; + // (undocumented) + createSchematic(name: string, allowPrivate?: boolean): Schematic; + // (undocumented) + readonly description: CollectionDescription; + // (undocumented) + listSchematicNames(includeHidden?: boolean): string[]; +} + +// @public +export type CollectionDescription = CollectionMetadataT & { + readonly name: string; + readonly extends?: string[]; +}; + +// @public (undocumented) +export class CollectionImpl implements Collection { + constructor(_description: CollectionDescription, _engine: SchematicEngine, baseDescriptions?: CollectionDescription[] | undefined); + // (undocumented) + readonly baseDescriptions?: CollectionDescription[] | undefined; + // (undocumented) + createSchematic(name: string, allowPrivate?: boolean): Schematic; + // (undocumented) + get description(): CollectionDescription; + // (undocumented) + listSchematicNames(includeHidden?: boolean): string[]; + // (undocumented) + get name(): string; +} + +// @public (undocumented) +export function composeFileOperators(operators: FileOperator[]): FileOperator; + +// @public (undocumented) +export class ContentHasMutatedException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export function contentTemplate(options: T): Rule; + +// @public (undocumented) +export interface CreateFileAction extends ActionBase { + // (undocumented) + readonly content: Buffer; + // (undocumented) + readonly kind: 'c'; +} + +// @public (undocumented) +export interface DelegateTree { +} + +// @public (undocumented) +export class DelegateTree implements Tree_2 { + // (undocumented) + [TreeSymbol]: () => DelegateTree; + constructor(_other: Tree_2); + // (undocumented) + get actions(): Action[]; + // (undocumented) + apply(action: Action, strategy?: MergeStrategy): void; + // (undocumented) + beginUpdate(path: string): UpdateRecorder; + // (undocumented) + branch(): Tree_2; + // (undocumented) + commitUpdate(record: UpdateRecorder): void; + // (undocumented) + create(path: string, content: Buffer | string): void; + // (undocumented) + delete(path: string): void; + // (undocumented) + exists(path: string): boolean; + // (undocumented) + get(path: string): FileEntry | null; + // (undocumented) + getDir(path: string): DirEntry; + // (undocumented) + merge(other: Tree_2, strategy?: MergeStrategy): void; + // (undocumented) + protected _other: Tree_2; + // (undocumented) + overwrite(path: string, content: Buffer | string): void; + // (undocumented) + read(path: string): Buffer | null; + // (undocumented) + readJson(path: string): JsonValue; + // (undocumented) + readText(path: string): string; + // (undocumented) + rename(from: string, to: string): void; + // (undocumented) + get root(): DirEntry; + // (undocumented) + visit(visitor: FileVisitor): void; +} + +// @public (undocumented) +export interface DeleteFileAction extends ActionBase { + // (undocumented) + readonly kind: 'd'; +} + +// @public (undocumented) +export interface DirEntry { + // (undocumented) + dir(name: PathFragment): DirEntry; + // (undocumented) + file(name: PathFragment): FileEntry | null; + // (undocumented) + readonly parent: DirEntry | null; + // (undocumented) + readonly path: Path; + // (undocumented) + readonly subdirs: PathFragment[]; + // (undocumented) + readonly subfiles: PathFragment[]; + // (undocumented) + visit(visitor: FileVisitor): void; +} + +// @public (undocumented) +export interface DryRunCreateEvent { + // (undocumented) + content: ArrayBufferLike; + // (undocumented) + kind: 'create'; + // (undocumented) + path: string; +} + +// @public (undocumented) +export interface DryRunDeleteEvent { + // (undocumented) + kind: 'delete'; + // (undocumented) + path: string; +} + +// @public (undocumented) +export interface DryRunErrorEvent { + // (undocumented) + description: 'alreadyExist' | 'doesNotExist'; + // (undocumented) + kind: 'error'; + // (undocumented) + path: string; +} + +// @public (undocumented) +export type DryRunEvent = DryRunErrorEvent | DryRunDeleteEvent | DryRunCreateEvent | DryRunUpdateEvent | DryRunRenameEvent; + +// @public (undocumented) +export interface DryRunRenameEvent { + // (undocumented) + kind: 'rename'; + // (undocumented) + path: string; + // (undocumented) + to: string; +} + +// @public (undocumented) +export class DryRunSink extends HostSink { + constructor(host: virtualFs.Host, force?: boolean); + // (undocumented) + _done(): Observable; + // (undocumented) + protected _fileAlreadyExistException(path: string): void; + // (undocumented) + protected _fileAlreadyExistExceptionSet: Set; + // (undocumented) + protected _fileDoesNotExistException(path: string): void; + // (undocumented) + protected _fileDoesNotExistExceptionSet: Set; + // (undocumented) + readonly reporter: Observable; + // (undocumented) + protected _subject: Subject; +} + +// @public (undocumented) +export interface DryRunUpdateEvent { + // (undocumented) + content: ArrayBufferLike; + // (undocumented) + kind: 'update'; + // (undocumented) + path: string; +} + +// @public +export function empty(): Source; + +// @public (undocumented) +export class EmptyTree extends HostTree { + constructor(); +} + +// @public +export interface Engine { + // (undocumented) + createCollection(name: string, requester?: Collection): Collection; + // (undocumented) + createContext(schematic: Schematic, parent?: Partial>, executionOptions?: Partial): TypedSchematicContext; + // (undocumented) + createSchematic(name: string, collection: Collection): Schematic; + // (undocumented) + createSourceFromUrl(url: Url, context: TypedSchematicContext): Source; + // (undocumented) + readonly defaultMergeStrategy: MergeStrategy; + // (undocumented) + executePostTasks(): Observable; + // (undocumented) + transformOptions(schematic: Schematic, options: OptionT, context?: TypedSchematicContext): Observable; + // (undocumented) + readonly workflow: Workflow | null; +} + +// @public +export interface EngineHost { + // (undocumented) + createCollectionDescription(name: string, requester?: CollectionDescription): CollectionDescription; + // (undocumented) + createSchematicDescription(name: string, collection: CollectionDescription): SchematicDescription | null; + // (undocumented) + createSourceFromUrl(url: Url, context: TypedSchematicContext): Source | null; + // (undocumented) + createTaskExecutor(name: string): Observable; + // (undocumented) + readonly defaultMergeStrategy?: MergeStrategy; + // (undocumented) + getSchematicRuleFactory(schematic: SchematicDescription, collection: CollectionDescription): RuleFactory; + // (undocumented) + hasTaskExecutor(name: string): boolean; + // (undocumented) + listSchematicNames(collection: CollectionDescription, includeHidden?: boolean): string[]; + // (undocumented) + transformContext(context: TypedSchematicContext): TypedSchematicContext | void; + // (undocumented) + transformOptions(schematic: SchematicDescription, options: OptionT, context?: TypedSchematicContext): Observable; +} + +// @public (undocumented) +export interface ExecutionOptions { + // (undocumented) + interactive: boolean; + // (undocumented) + scope: string; +} + +// @public +export function externalSchematic(collectionName: string, schematicName: string, options: OptionT, executionOptions?: Partial): Rule; + +// @public (undocumented) +export class FileAlreadyExistException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export class FileDoesNotExistException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export interface FileEntry { + // (undocumented) + readonly content: Buffer; + // (undocumented) + readonly path: Path; +} + +// @public +export type FileOperator = (entry: FileEntry) => FileEntry | null; + +// @public (undocumented) +export interface FilePredicate { + // (undocumented) + (path: Path, entry?: Readonly | null): T; +} + +// @public (undocumented) +export type FileVisitor = FilePredicate; + +// @public (undocumented) +export const FileVisitorCancelToken: symbol; + +// @public (undocumented) +export function filter(predicate: FilePredicate): Rule; + +// @public (undocumented) +export class FilterHostTree extends HostTree { + constructor(tree: HostTree, filter?: FilePredicate); +} + +// @public (undocumented) +export function forEach(operator: FileOperator): Rule; + +declare namespace formats { + export { + htmlSelectorFormat, + pathFormat, + standardFormats + } +} +export { formats } + +// @public (undocumented) +export class HostCreateTree extends HostTree { + constructor(host: virtualFs.ReadonlyHost); +} + +// @public (undocumented) +export class HostDirEntry implements DirEntry { + constructor(parent: DirEntry | null, path: Path, _host: virtualFs.SyncDelegateHost, _tree: Tree_2); + // (undocumented) + dir(name: PathFragment): DirEntry; + // (undocumented) + file(name: PathFragment): FileEntry | null; + // (undocumented) + protected _host: virtualFs.SyncDelegateHost; + // (undocumented) + readonly parent: DirEntry | null; + // (undocumented) + readonly path: Path; + // (undocumented) + get subdirs(): PathFragment[]; + // (undocumented) + get subfiles(): PathFragment[]; + // (undocumented) + protected _tree: Tree_2; + // (undocumented) + visit(visitor: FileVisitor): void; +} + +// @public (undocumented) +export class HostSink extends SimpleSinkBase { + constructor(_host: virtualFs.Host, _force?: boolean); + // (undocumented) + protected _createFile(path: Path, content: Buffer): Observable; + // (undocumented) + protected _deleteFile(path: Path): Observable; + // (undocumented) + _done(): Observable; + // (undocumented) + protected _filesToCreate: Map; + // (undocumented) + protected _filesToDelete: Set; + // (undocumented) + protected _filesToRename: Set<[Path, Path]>; + // (undocumented) + protected _filesToUpdate: Map; + // (undocumented) + protected _force: boolean; + // (undocumented) + protected _host: virtualFs.Host; + // (undocumented) + protected _overwriteFile(path: Path, content: Buffer): Observable; + // (undocumented) + protected _renameFile(from: Path, to: Path): Observable; + // (undocumented) + protected _validateCreateAction(action: CreateFileAction): Observable; + // (undocumented) + protected _validateFileExists(p: Path): Observable; +} + +// @public (undocumented) +export interface HostTree { +} + +// @public (undocumented) +export class HostTree implements Tree_2 { + // (undocumented) + [TreeSymbol]: () => HostTree; + constructor(_backend?: virtualFs.ReadonlyHost<{}>); + // (undocumented) + get actions(): Action[]; + // (undocumented) + apply(action: Action, strategy?: MergeStrategy): void; + // (undocumented) + protected _backend: virtualFs.ReadonlyHost<{}>; + // (undocumented) + beginUpdate(path: string): UpdateRecorder; + // (undocumented) + branch(): Tree_2; + // (undocumented) + commitUpdate(record: UpdateRecorder): void; + // (undocumented) + create(path: string, content: Buffer | string): void; + // (undocumented) + delete(path: string): void; + // (undocumented) + exists(path: string): boolean; + // (undocumented) + get(path: string): FileEntry | null; + // (undocumented) + getDir(path: string): DirEntry; + // (undocumented) + static isHostTree(tree: Tree_2): tree is HostTree; + // (undocumented) + merge(other: Tree_2, strategy?: MergeStrategy): void; + // (undocumented) + protected _normalizePath(path: string): Path; + // (undocumented) + overwrite(path: string, content: Buffer | string): void; + // (undocumented) + read(path: string): Buffer | null; + // (undocumented) + readJson(path: string): JsonValue; + // (undocumented) + readText(path: string): string; + // (undocumented) + rename(from: string, to: string): void; + // (undocumented) + get root(): DirEntry; + // (undocumented) + visit(visitor: FileVisitor): void; + // (undocumented) + protected _willCreate(path: Path): boolean; + // (undocumented) + protected _willDelete(path: Path): boolean; + // (undocumented) + protected _willOverwrite(path: Path): boolean; + // (undocumented) + protected _willRename(path: Path): boolean; +} + +// @public (undocumented) +const htmlSelectorFormat: schema.SchemaFormat; + +// @public (undocumented) +export class InvalidPipeException extends BaseException { + constructor(name: string); +} + +// @public +export class InvalidRuleResultException extends BaseException { + constructor(value?: {}); +} + +// @public (undocumented) +export class InvalidSchematicsNameException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class InvalidSourceResultException extends BaseException { + constructor(value?: {}); +} + +// @public (undocumented) +export class InvalidUpdateRecordException extends BaseException { + constructor(); +} + +// @public (undocumented) +export function isContentAction(action: Action): action is CreateFileAction | OverwriteFileAction; + +// @public (undocumented) +interface LifeCycleEvent { + // (undocumented) + kind: 'start' | 'end' | 'workflow-start' | 'workflow-end' | 'post-tasks-start' | 'post-tasks-end'; +} + +// @public (undocumented) +export class MergeConflictException extends BaseException { + constructor(path: string); +} + +// @public (undocumented) +export enum MergeStrategy { + // (undocumented) + AllowCreationConflict = 4, + // (undocumented) + AllowDeleteConflict = 8, + // (undocumented) + AllowOverwriteConflict = 2, + // (undocumented) + ContentOnly = 2, + // (undocumented) + Default = 0, + // (undocumented) + Error = 1, + // (undocumented) + Overwrite = 14 +} + +// @public +export function mergeWith(source: Source, strategy?: MergeStrategy): Rule; + +// @public (undocumented) +export function move(from: string, to: string): Rule; + +// @public (undocumented) +export function move(to: string): Rule; + +// @public (undocumented) +export function noop(): Rule; + +// @public (undocumented) +export class OptionIsNotDefinedException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export interface OverwriteFileAction extends ActionBase { + // (undocumented) + readonly content: Buffer; + // (undocumented) + readonly kind: 'o'; +} + +// @public (undocumented) +export function partitionApplyMerge(predicate: FilePredicate, ruleYes: Rule, ruleNo?: Rule): Rule; + +// @public (undocumented) +const pathFormat: schema.SchemaFormat; + +// @public (undocumented) +export function pathTemplate(options: T): Rule; + +// @public (undocumented) +export type PathTemplateData = { + [key: string]: PathTemplateValue | PathTemplateData | PathTemplatePipeFunction; +}; + +// @public (undocumented) +export interface PathTemplateOptions { + // (undocumented) + interpolationEnd: string; + // (undocumented) + interpolationStart: string; + // (undocumented) + pipeSeparator?: string; +} + +// @public (undocumented) +export type PathTemplatePipeFunction = (x: string) => PathTemplateValue; + +// @public (undocumented) +export type PathTemplateValue = boolean | string | number | undefined; + +// @public (undocumented) +export class PrivateSchematicException extends BaseException { + constructor(name: string, collection: CollectionDescription<{}>); +} + +// @public (undocumented) +export interface RandomOptions { + // (undocumented) + multi?: boolean | number; + // (undocumented) + multiFiles?: boolean | number; + // (undocumented) + root?: string; +} + +// @public (undocumented) +export interface RenameFileAction extends ActionBase { + // (undocumented) + readonly kind: 'r'; + // (undocumented) + readonly to: Path; +} + +// @public +export function renameTemplateFiles(): Rule; + +// @public (undocumented) +interface RequiredWorkflowExecutionContext { + // (undocumented) + collection: string; + // (undocumented) + options: object; + // (undocumented) + schematic: string; +} + +// @public (undocumented) +export type Rule = (tree: Tree_2, context: SchematicContext) => Tree_2 | Observable | Rule | Promise | void; + +// @public +export type RuleFactory = (options: T) => Rule; + +// @public +export interface Schematic { + // (undocumented) + call(options: OptionT, host: Observable, parentContext?: Partial>, executionOptions?: Partial): Observable; + // (undocumented) + readonly collection: Collection; + // (undocumented) + readonly description: SchematicDescription; +} + +// @public +export function schematic(schematicName: string, options: OptionT, executionOptions?: Partial): Rule; + +// @public +export type SchematicContext = TypedSchematicContext<{}, {}>; + +// @public +export type SchematicDescription = SchematicMetadataT & { + readonly collection: CollectionDescription; + readonly name: string; + readonly private?: boolean; + readonly hidden?: boolean; +}; + +// @public (undocumented) +export class SchematicEngine implements Engine { + constructor(_host: EngineHost, _workflow?: Workflow | undefined); + // (undocumented) + createCollection(name: string, requester?: Collection): Collection; + // (undocumented) + createContext(schematic: Schematic, parent?: Partial>, executionOptions?: Partial): TypedSchematicContext; + // (undocumented) + createSchematic(name: string, collection: Collection, allowPrivate?: boolean): Schematic; + // (undocumented) + createSourceFromUrl(url: Url, context: TypedSchematicContext): Source; + // (undocumented) + get defaultMergeStrategy(): MergeStrategy; + // (undocumented) + executePostTasks(): Observable; + // (undocumented) + listSchematicNames(collection: Collection, includeHidden?: boolean): string[]; + // (undocumented) + transformOptions(schematic: Schematic, options: OptionT, context?: TypedSchematicContext): Observable; + // (undocumented) + get workflow(): Workflow | null; + // (undocumented) + protected _workflow?: Workflow | undefined; +} + +// @public (undocumented) +export class SchematicEngineConflictingException extends BaseException { + constructor(); +} + +// @public (undocumented) +export class SchematicImpl implements Schematic { + constructor(_description: SchematicDescription, _factory: RuleFactory<{}>, _collection: Collection, _engine: Engine); + // (undocumented) + call(options: OptionT, host: Observable, parentContext?: Partial>, executionOptions?: Partial): Observable; + // (undocumented) + get collection(): Collection; + // (undocumented) + get description(): SchematicDescription; +} + +// @public (undocumented) +export class SchematicsException extends BaseException { +} + +// @public (undocumented) +export abstract class SimpleSinkBase implements Sink { + // (undocumented) + commit(tree: Tree_2): Observable; + // (undocumented) + commitSingleAction(action: Action): Observable; + // (undocumented) + protected abstract _createFile(path: string, content: Buffer): Observable; + // (undocumented) + protected abstract _deleteFile(path: string): Observable; + // (undocumented) + protected abstract _done(): Observable; + // (undocumented) + protected _fileAlreadyExistException(path: string): void; + // (undocumented) + protected _fileDoesNotExistException(path: string): void; + // (undocumented) + protected abstract _overwriteFile(path: string, content: Buffer): Observable; + // (undocumented) + postCommit: () => void | Observable; + // (undocumented) + postCommitAction: (action: Action) => void | Observable; + // (undocumented) + preCommit: () => void | Observable; + // (undocumented) + preCommitAction: (action: Action) => void | Action | PromiseLike | Observable; + // (undocumented) + protected abstract _renameFile(path: string, to: string): Observable; + // (undocumented) + protected _validateCreateAction(action: CreateFileAction): Observable; + // (undocumented) + protected _validateDeleteAction(action: DeleteFileAction): Observable; + // (undocumented) + protected abstract _validateFileExists(p: string): Observable; + // (undocumented) + protected _validateOverwriteAction(action: OverwriteFileAction): Observable; + // (undocumented) + protected _validateRenameAction(action: RenameFileAction): Observable; + // (undocumented) + validateSingleAction(action: Action): Observable; +} + +// @public (undocumented) +export interface Sink { + // (undocumented) + commit(tree: Tree_2): Observable; +} + +// @public +export type Source = (context: SchematicContext) => Tree_2 | Observable; + +// @public +export function source(tree: Tree_2): Source; + +// @public (undocumented) +const standardFormats: schema.SchemaFormat[]; + +export { strings } + +// @public (undocumented) +export interface TaskConfiguration { + // (undocumented) + dependencies?: Array; + // (undocumented) + name: string; + // (undocumented) + options?: T; +} + +// @public (undocumented) +export interface TaskConfigurationGenerator { + // (undocumented) + toConfiguration(): TaskConfiguration; +} + +// @public (undocumented) +export type TaskExecutor = (options: T | undefined, context: SchematicContext) => Promise | Observable; + +// @public (undocumented) +export interface TaskExecutorFactory { + // (undocumented) + create(options?: T): Promise | Observable; + // (undocumented) + readonly name: string; +} + +// @public (undocumented) +export interface TaskId { + // (undocumented) + readonly id: number; +} + +// @public (undocumented) +export interface TaskInfo { + // (undocumented) + readonly configuration: TaskConfiguration; + // (undocumented) + readonly context: SchematicContext; + // (undocumented) + readonly id: number; + // (undocumented) + readonly priority: number; +} + +// @public (undocumented) +export class TaskScheduler { + constructor(_context: SchematicContext); + // (undocumented) + finalize(): ReadonlyArray; + // (undocumented) + schedule(taskConfiguration: TaskConfiguration): TaskId; +} + +// @public (undocumented) +export function template(options: T): Rule; + +// @public (undocumented) +export const TEMPLATE_FILENAME_RE: RegExp; + +// @public (undocumented) +export type Tree = Tree_2; + +// @public (undocumented) +export const Tree: TreeConstructor; + +// @public (undocumented) +export interface TreeConstructor { + // (undocumented) + branch(tree: Tree_2): Tree_2; + // (undocumented) + empty(): Tree_2; + // (undocumented) + merge(tree: Tree_2, other: Tree_2, strategy?: MergeStrategy): Tree_2; + // (undocumented) + optimize(tree: Tree_2): Tree_2; + // (undocumented) + partition(tree: Tree_2, predicate: FilePredicate): [Tree_2, Tree_2]; +} + +// @public (undocumented) +export const TreeSymbol: symbol; + +// @public +export interface TypedSchematicContext { + // (undocumented) + addTask(task: TaskConfigurationGenerator, dependencies?: Array): TaskId; + // (undocumented) + readonly debug: boolean; + // (undocumented) + readonly engine: Engine; + // (undocumented) + readonly interactive: boolean; + // (undocumented) + readonly logger: logging.LoggerApi; + // (undocumented) + readonly schematic: Schematic; + // (undocumented) + readonly strategy: MergeStrategy; +} + +// @public (undocumented) +export class UnimplementedException extends BaseException { + constructor(); +} + +// @public (undocumented) +export class UnknownActionException extends BaseException { + constructor(action: Action); +} + +// @public (undocumented) +export class UnknownCollectionException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class UnknownPipeException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class UnknownSchematicException extends BaseException { + constructor(name: string, collection: CollectionDescription<{}>); +} + +// @public (undocumented) +export class UnknownTaskDependencyException extends BaseException { + constructor(id: TaskId); +} + +// @public (undocumented) +export class UnknownUrlSourceProtocol extends BaseException { + constructor(url: string); +} + +// @public (undocumented) +export class UnregisteredTaskException extends BaseException { + constructor(name: string, schematic?: SchematicDescription<{}, {}>); +} + +// @public (undocumented) +export class UnsuccessfulWorkflowExecution extends BaseException { + constructor(); +} + +// @public (undocumented) +export interface UpdateRecorder { + // (undocumented) + insertLeft(index: number, content: Buffer | string): UpdateRecorder; + // (undocumented) + insertRight(index: number, content: Buffer | string): UpdateRecorder; + // (undocumented) + remove(index: number, length: number): UpdateRecorder; +} + +// @public (undocumented) +export function url(urlString: string): Source; + +// @public (undocumented) +export function when(predicate: FilePredicate, operator: FileOperator): FileOperator; + +// @public (undocumented) +interface Workflow { + // (undocumented) + readonly context: Readonly; + // (undocumented) + execute(options: Partial & RequiredWorkflowExecutionContext): Observable; +} + +declare namespace workflow { + export { + BaseWorkflowOptions, + BaseWorkflow, + RequiredWorkflowExecutionContext, + WorkflowExecutionContext, + LifeCycleEvent, + Workflow + } +} +export { workflow } + +// @public (undocumented) +interface WorkflowExecutionContext extends RequiredWorkflowExecutionContext { + // (undocumented) + allowPrivate?: boolean; + // (undocumented) + debug: boolean; + // (undocumented) + logger: logging.Logger; + // (undocumented) + parentContext?: Readonly; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/schematics/tasks/index.api.md b/goldens/public-api/angular_devkit/schematics/tasks/index.api.md new file mode 100644 index 000000000000..ad9b7d8d7f0b --- /dev/null +++ b/goldens/public-api/angular_devkit/schematics/tasks/index.api.md @@ -0,0 +1,54 @@ +## API Report File for "@angular-devkit/schematics_tasks" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public (undocumented) +export class NodePackageInstallTask implements TaskConfigurationGenerator { + constructor(workingDirectory?: string); + constructor(options: NodePackageInstallTaskOptions); + // (undocumented) + allowScripts: boolean; + // (undocumented) + hideOutput: boolean; + // (undocumented) + packageManager?: string; + // (undocumented) + packageName?: string; + // (undocumented) + quiet: boolean; + // (undocumented) + toConfiguration(): TaskConfiguration; + // (undocumented) + workingDirectory?: string; +} + +// @public (undocumented) +export class RepositoryInitializerTask implements TaskConfigurationGenerator { + constructor(workingDirectory?: string | undefined, commitOptions?: CommitOptions | undefined); + // (undocumented) + commitOptions?: CommitOptions | undefined; + // (undocumented) + toConfiguration(): TaskConfiguration; + // (undocumented) + workingDirectory?: string | undefined; +} + +// @public (undocumented) +export class RunSchematicTask implements TaskConfigurationGenerator> { + constructor(s: string, o: T); + constructor(c: string, s: string, o: T); + // (undocumented) + protected _collection: string | null; + // (undocumented) + protected _options: T; + // (undocumented) + protected _schematic: string; + // (undocumented) + toConfiguration(): TaskConfiguration>; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/schematics/testing/index.api.md b/goldens/public-api/angular_devkit/schematics/testing/index.api.md new file mode 100644 index 000000000000..abf89972c862 --- /dev/null +++ b/goldens/public-api/angular_devkit/schematics/testing/index.api.md @@ -0,0 +1,43 @@ +## API Report File for "@angular-devkit/schematics_testing" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { JsonValue } from '@angular-devkit/core'; +import { logging } from '@angular-devkit/core'; +import { Observable } from 'rxjs'; +import { Path } from '@angular-devkit/core'; +import { PathFragment } from '@angular-devkit/core'; +import { Url } from 'node:url'; + +// @public (undocumented) +export class SchematicTestRunner { + constructor(_collectionName: string, collectionPath: string); + // (undocumented) + callRule(rule: Rule, tree: Tree_2, parentContext?: Partial): Observable; + // (undocumented) + get engine(): SchematicEngine<{}, {}>; + // (undocumented) + get logger(): logging.Logger; + // (undocumented) + registerCollection(collectionName: string, collectionPath: string): void; + // (undocumented) + runExternalSchematic(collectionName: string, schematicName: string, opts?: SchematicSchemaT, tree?: Tree_2): Promise; + // (undocumented) + runSchematic(schematicName: string, opts?: SchematicSchemaT, tree?: Tree_2): Promise; + // (undocumented) + get tasks(): TaskConfiguration[]; +} + +// @public (undocumented) +export class UnitTestTree extends DelegateTree { + // (undocumented) + get files(): string[]; + // (undocumented) + readContent(path: string): string; +} + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/angular_devkit/schematics/tools/index.api.md b/goldens/public-api/angular_devkit/schematics/tools/index.api.md new file mode 100644 index 000000000000..c93e3ec27762 --- /dev/null +++ b/goldens/public-api/angular_devkit/schematics/tools/index.api.md @@ -0,0 +1,280 @@ +## API Report File for "@angular-devkit/schematics_tools" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { BaseException } from '@angular-devkit/core'; +import { JsonObject } from '@angular-devkit/core'; +import { JsonValue } from '@angular-devkit/core'; +import { logging } from '@angular-devkit/core'; +import { Observable } from 'rxjs'; +import { Path } from '@angular-devkit/core'; +import { PathFragment } from '@angular-devkit/core'; +import { schema } from '@angular-devkit/core'; +import { Subject } from 'rxjs'; +import { Url } from 'node:url'; +import { virtualFs } from '@angular-devkit/core'; + +// @public (undocumented) +export class CollectionCannotBeResolvedException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class CollectionMissingFieldsException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class CollectionMissingSchematicsMapException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export type ContextTransform = (context: FileSystemSchematicContext) => FileSystemSchematicContext; + +// @public +export class ExportStringRef { + constructor(ref: string, parentPath?: string, inner?: boolean); + // (undocumented) + get module(): string; + // (undocumented) + get path(): string; + // (undocumented) + get ref(): T | undefined; +} + +// @public (undocumented) +export class FactoryCannotBeResolvedException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export type FileSystemCollection = Collection; + +// @public (undocumented) +export type FileSystemCollectionDesc = CollectionDescription; + +// @public (undocumented) +export interface FileSystemCollectionDescription { + // (undocumented) + readonly encapsulation?: boolean; + // (undocumented) + readonly name: string; + // (undocumented) + readonly path: string; + // (undocumented) + readonly schematics: { + [name: string]: FileSystemSchematicDesc; + }; + // (undocumented) + readonly version?: string; +} + +// @public +export type FileSystemEngine = Engine; + +// @public +export class FileSystemEngineHost extends FileSystemEngineHostBase { + constructor(_root: string); + // (undocumented) + createTaskExecutor(name: string): Observable; + // (undocumented) + hasTaskExecutor(name: string): boolean; + // (undocumented) + protected _resolveCollectionPath(name: string): string; + // (undocumented) + protected _resolveReferenceString(refString: string, parentPath: string): { + ref: RuleFactory<{}>; + path: string; + } | null; + // (undocumented) + protected _root: string; + // (undocumented) + protected _transformCollectionDescription(name: string, desc: Partial): FileSystemCollectionDesc; + // (undocumented) + protected _transformSchematicDescription(name: string, _collection: FileSystemCollectionDesc, desc: Partial): FileSystemSchematicDesc; +} + +// @public +export abstract class FileSystemEngineHostBase implements FileSystemEngineHost_2 { + // (undocumented) + createCollectionDescription(name: string, requester?: FileSystemCollectionDesc): FileSystemCollectionDesc; + // (undocumented) + createSchematicDescription(name: string, collection: FileSystemCollectionDesc): FileSystemSchematicDesc | null; + // (undocumented) + createSourceFromUrl(url: Url): Source | null; + // (undocumented) + createTaskExecutor(name: string): Observable; + // (undocumented) + getSchematicRuleFactory(schematic: FileSystemSchematicDesc, _collection: FileSystemCollectionDesc): RuleFactory; + // (undocumented) + hasTaskExecutor(name: string): boolean; + // (undocumented) + listSchematicNames(collection: FileSystemCollectionDesc, includeHidden?: boolean): string[]; + // (undocumented) + registerContextTransform(t: ContextTransform): void; + // (undocumented) + registerOptionsTransform(t: OptionTransform): void; + // (undocumented) + registerTaskExecutor(factory: TaskExecutorFactory, options?: T): void; + // (undocumented) + protected abstract _resolveCollectionPath(name: string, requester?: string): string; + // (undocumented) + protected abstract _resolveReferenceString(name: string, parentPath: string, collectionDescription: FileSystemCollectionDesc): { + ref: RuleFactory<{}>; + path: string; + } | null; + // (undocumented) + protected abstract _transformCollectionDescription(name: string, desc: Partial): FileSystemCollectionDesc; + // (undocumented) + transformContext(context: FileSystemSchematicContext): FileSystemSchematicContext; + // (undocumented) + transformOptions(schematic: FileSystemSchematicDesc, options: OptionT, context?: FileSystemSchematicContext): Observable; + // (undocumented) + protected abstract _transformSchematicDescription(name: string, collection: FileSystemCollectionDesc, desc: Partial): FileSystemSchematicDesc; +} + +// @public (undocumented) +export type FileSystemSchematic = Schematic; + +// @public (undocumented) +export type FileSystemSchematicContext = TypedSchematicContext; + +// @public (undocumented) +export type FileSystemSchematicDesc = SchematicDescription; + +// @public (undocumented) +export interface FileSystemSchematicDescription extends FileSystemSchematicJsonDescription { + // (undocumented) + readonly factoryFn: RuleFactory<{}>; + // (undocumented) + readonly path: string; + // (undocumented) + readonly schemaJson?: JsonObject; +} + +// @public (undocumented) +export interface FileSystemSchematicJsonDescription { + // (undocumented) + readonly aliases?: string[]; + // (undocumented) + readonly collection: FileSystemCollectionDescription; + // (undocumented) + readonly description: string; + // (undocumented) + readonly extends?: string; + // (undocumented) + readonly factory: string; + // (undocumented) + readonly name: string; + // (undocumented) + readonly schema?: string; +} + +// @public (undocumented) +export class InvalidCollectionJsonException extends BaseException { + constructor(_name: string, path: string, jsonException?: Error); +} + +// @public +export class NodeModulesEngineHost extends FileSystemEngineHostBase { + constructor(paths?: string[] | undefined); + // (undocumented) + protected _resolveCollectionPath(name: string, requester?: string): string; + // (undocumented) + protected _resolveReferenceString(refString: string, parentPath: string, collectionDescription?: FileSystemCollectionDesc): { + ref: RuleFactory<{}>; + path: string; + } | null; + // (undocumented) + protected _transformCollectionDescription(name: string, desc: Partial): FileSystemCollectionDesc; + // (undocumented) + protected _transformSchematicDescription(name: string, _collection: FileSystemCollectionDesc, desc: Partial): FileSystemSchematicDesc; +} + +// @public +export class NodeModulesTestEngineHost extends NodeModulesEngineHost { + // (undocumented) + clearTasks(): void; + // (undocumented) + registerCollection(name: string, path: string): void; + // (undocumented) + protected _resolveCollectionPath(name: string, requester?: string): string; + // (undocumented) + get tasks(): TaskConfiguration[]; + // (undocumented) + transformContext(context: FileSystemSchematicContext): FileSystemSchematicContext; +} + +// @public (undocumented) +export class NodePackageDoesNotSupportSchematics extends BaseException { + constructor(name: string); +} + +// @public +export class NodeWorkflow extends workflow.BaseWorkflow { + constructor(root: string, options: NodeWorkflowOptions); + constructor(host: virtualFs.Host, options: NodeWorkflowOptions & { + root?: Path; + }); + // (undocumented) + get engine(): FileSystemEngine; + // (undocumented) + get engineHost(): NodeModulesEngineHost; +} + +// @public (undocumented) +export interface NodeWorkflowOptions { + // (undocumented) + dryRun?: boolean; + // (undocumented) + engineHostCreator?: (options: NodeWorkflowOptions) => NodeModulesEngineHost; + // (undocumented) + force?: boolean; + // (undocumented) + optionTransforms?: OptionTransform | null, object>[]; + // (undocumented) + packageManager?: string; + // (undocumented) + packageManagerForce?: boolean; + // (undocumented) + packageRegistry?: string; + // (undocumented) + registry?: schema.CoreSchemaRegistry; + // (undocumented) + resolvePaths?: string[]; + // (undocumented) + schemaValidation?: boolean; +} + +// @public (undocumented) +export type OptionTransform = (schematic: FileSystemSchematicDescription, options: T, context?: FileSystemSchematicContext) => Observable | PromiseLike | R; + +// @public (undocumented) +export class SchematicMissingDescriptionException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class SchematicMissingFactoryException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class SchematicMissingFieldsException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export class SchematicNameCollisionException extends BaseException { + constructor(name: string); +} + +// @public (undocumented) +export function validateOptionsWithSchema(registry: schema.SchemaRegistry): (schematic: FileSystemSchematicDescription, options: T, context?: FileSystemSchematicContext) => Observable; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/goldens/public-api/ngtools/webpack/index.api.md b/goldens/public-api/ngtools/webpack/index.api.md new file mode 100644 index 000000000000..a2c25e8c74f5 --- /dev/null +++ b/goldens/public-api/ngtools/webpack/index.api.md @@ -0,0 +1,56 @@ +## API Report File for "@ngtools/webpack" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import type { Compiler } from 'webpack'; +import type { CompilerOptions } from '@angular/compiler-cli'; +import type { LoaderContext } from 'webpack'; + +// @public @deprecated (undocumented) +function angularWebpackLoader(this: LoaderContext, content: string, map: string): void; +export default angularWebpackLoader; + +// @public @deprecated (undocumented) +export const AngularWebpackLoaderPath: string; + +// @public @deprecated (undocumented) +export class AngularWebpackPlugin { + constructor(options?: Partial); + // (undocumented) + apply(compiler: Compiler): void; + // (undocumented) + get options(): AngularWebpackPluginOptions; +} + +// @public @deprecated (undocumented) +export interface AngularWebpackPluginOptions { + // (undocumented) + compilerOptions?: CompilerOptions; + // (undocumented) + directTemplateLoading: boolean; + // (undocumented) + emitClassMetadata: boolean; + // (undocumented) + emitNgModuleScope: boolean; + // (undocumented) + emitSetClassDebugInfo?: boolean; + // (undocumented) + fileReplacements: Record; + // (undocumented) + inlineStyleFileExtension?: string; + // (undocumented) + jitMode: boolean; + // (undocumented) + substitutions: Record; + // (undocumented) + tsconfig: string; +} + +// @public @deprecated (undocumented) +export const imageDomains: Set; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/lib/README.md b/lib/README.md deleted file mode 100644 index a48231235dea..000000000000 --- a/lib/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# `/lib` Folder - -This folder includes bootstrap code for the various tools included in this repository. Also -included is the packages meta-information package in `packages.ts`. This is used to read and -understand all the monorepo information (contained in the `.monorepo.json` file, and `package.json` -files across the repo). - -`bootstrap-local.js` should be included when running files from this repository without compiling -first. It allows for compiling and loading packages in memory directly from the repo. Not only -does the `devkit-admin` scripts use this to include the library, but also all binaries linked -locally (like `schematics` and `ng`), when not using the npm published packages. diff --git a/lib/bootstrap-local.js b/lib/bootstrap-local.js deleted file mode 100644 index 3c3762655e61..000000000000 --- a/lib/bootstrap-local.js +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -/* eslint-disable no-console */ -'use strict'; -const debug = require('debug'); -const debugLocal = debug('ng:local'); -const debugBuildEjs = debug('ng:local:build:ejs'); -const debugBuildSchema = debug('ng:local:build:schema'); -const debugBuildTs = debug('ng:local:build:ts'); - -const child_process = require('child_process'); -const fs = require('fs'); -const path = require('path'); -const temp = require('temp'); -const ts = require('typescript'); - -const tmpRoot = temp.mkdirSync('angular-devkit-'); - -debugLocal('starting bootstrap local'); - -// This processes any extended configs -const compilerOptions = ts.getParsedCommandLineOfConfigFile( - path.join(__dirname, '../tsconfig-test.json'), - { }, - ts.sys, -).options; - -// Check if we need to profile this CLI run. -let profiler = null; -if (process.env['DEVKIT_PROFILING']) { - debugLocal('setup profiling'); - try { - profiler = require('v8-profiler-node8'); - } catch (err) { - throw new Error(`Could not require 'v8-profiler-node8'. You must install it separetely with` + - `'npm install v8-profiler-node8 --no-save.\n\nOriginal error:\n\n${err}`); - } - - profiler.startProfiling(); - - function exitHandler(options, _err) { - if (options.cleanup) { - const cpuProfile = profiler.stopProfiling(); - const profileData = JSON.stringify(cpuProfile); - const filePath = path.resolve(process.cwd(), process.env.DEVKIT_PROFILING) + '.cpuprofile'; - - debugLocal('saving profiling data'); - console.log(`Profiling data saved in "${filePath}": ${profileData.length} bytes`); - fs.writeFileSync(filePath, profileData); - } - - if (options.exit) { - process.exit(); - } - } - - process.on('exit', exitHandler.bind(null, { cleanup: true })); - process.on('SIGINT', exitHandler.bind(null, { exit: true })); - process.on('uncaughtException', exitHandler.bind(null, { exit: true })); -} - -if (process.env['DEVKIT_LONG_STACK_TRACE']) { - debugLocal('setup long stack trace'); - Error.stackTraceLimit = Infinity; -} - -global._DevKitIsLocal = true; -global._DevKitRoot = path.resolve(__dirname, '..'); - - -const oldRequireTs = require.extensions['.ts']; -require.extensions['.ts'] = function (m, filename) { - // If we're in node module, either call the old hook or simply compile the - // file without transpilation. We do not touch node_modules/**. - // To account for Yarn workspaces symlinks, we much check the real path. - if (fs.realpathSync(filename).match(/node_modules/)) { - if (oldRequireTs) { - return oldRequireTs(m, filename); - } - return m._compile(fs.readFileSync(filename).toString(), filename); - } - - debugBuildTs(filename); - - // Node requires all require hooks to be sync. - const source = fs.readFileSync(filename).toString(); - - try { - let result = ts.transpile(source, compilerOptions, filename); - - debugBuildTs('done'); - - // Send it to node to execute. - return m._compile(result, filename); - } catch (err) { - console.error('Error while running script "' + filename + '":'); - console.error(err.stack); - throw err; - } -}; - - -require.extensions['.ejs'] = function (m, filename) { - debugBuildEjs(filename); - - const source = fs.readFileSync(filename).toString(); - const template = require('@angular-devkit/core').template; - const result = template(source, { sourceURL: filename, sourceMap: true }); - - debugBuildEjs('done'); - return m._compile(result.source.replace(/return/, 'module.exports.default = '), filename); -}; - -const builtinModules = Object.keys(process.binding('natives')); -const packages = require('./packages').packages; -// If we're running locally, meaning npm linked. This is basically "developer mode". -if (!__dirname.match(new RegExp(`\\${path.sep}node_modules\\${path.sep}`))) { - - // We mock the module loader so that we can fake our packages when running locally. - const Module = require('module'); - const oldLoad = Module._load; - const oldResolve = Module._resolveFilename; - - Module._resolveFilename = function (request, parent) { - let resolved = null; - let exception; - try { - resolved = oldResolve.call(this, request, parent); - } catch (e) { - exception = e; - } - - if (request in packages) { - return packages[request].main; - } else if (builtinModules.includes(request)) { - // It's a native Node module. - return oldResolve.call(this, request, parent); - } else if (resolved && resolved.match(/[\\\/]node_modules[\\\/]/)) { - return resolved; - } else { - const match = Object.keys(packages).find(pkgName => request.startsWith(pkgName + '/')); - if (match) { - const p = path.join(packages[match].root, request.substr(match.length)); - return oldResolve.call(this, p, parent); - } else if (!resolved) { - if (exception) { - throw exception; - } else { - return resolved; - } - } else { - // Because loading `.ts` ends up AFTER `.json` in the require() logic, requiring a file that has both `.json` - // and `.ts` versions will only get the `.json` content (which wouldn't happen if the .ts was compiled to - // JavaScript). We load `.ts` files first here to avoid this conflict. It's hacky, but so is the rest of this - // file. - const maybeTsPath = resolved.endsWith('.json') && resolved.replace(/\.json$/, '.ts'); - if (maybeTsPath && !request.endsWith('.json')) { - // If the file exists, return its path. If it doesn't, run the quicktype runner on it and return the content. - if (fs.existsSync(maybeTsPath)) { - return maybeTsPath; - } else { - debugBuildSchema('%s', resolved); - - // This script has the be synchronous, so we spawnSync instead of, say, requiring the runner and calling - // the method directly. - const tmpJsonSchemaPath = path.join(tmpRoot, maybeTsPath.replace(/[^0-9a-zA-Z.]/g, '_')); - try { - if (!fs.existsSync(tmpJsonSchemaPath)) { - const quicktypeRunnerPath = path.join(__dirname, '../tools/quicktype_runner.js'); - child_process.spawnSync('node', [quicktypeRunnerPath, resolved, tmpJsonSchemaPath]); - } - - debugBuildSchema('done'); - return tmpJsonSchemaPath; - } catch (_) { - // Just return resolvedPath and let Node deals with it. - console.log(_); - process.exit(99); - } - } - } - - return resolved; - } - } - }; -} - - -// Set the resolve hook to allow resolution of packages from a local dev environment. -require('@angular-devkit/core/node/resolve').setResolveHook(function(request, options) { - try { - if (request in packages) { - if (options.resolvePackageJson) { - return path.join(packages[request].root, 'package.json'); - } else { - return packages[request].main; - } - } else { - const match = Object.keys(packages).find(function(pkgName) { - return request.startsWith(pkgName + '/'); - }); - - if (match) { - return path.join(packages[match].root, request.substr(match[0].length)); - } else { - return null; - } - } - } catch (_) { - return null; - } -}); diff --git a/lib/packages.ts b/lib/packages.ts deleted file mode 100644 index 2f3d49373802..000000000000 --- a/lib/packages.ts +++ /dev/null @@ -1,254 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable-next-line:no-implicit-dependencies -import { JsonObject } from '@angular-devkit/core'; -import { execSync } from 'child_process'; -import * as fs from 'fs'; -import * as path from 'path'; -import * as ts from 'typescript'; - -const distRoot = path.join(__dirname, '../dist'); -const { versions: monorepoVersions, packages: monorepoPackages } = require('../.monorepo.json'); - - -export interface PackageInfo { - name: string; - root: string; - bin: { [name: string]: string}; - relative: string; - main: string; - dist: string; - build: string; - tar: string; - private: boolean; - experimental: boolean; - packageJson: JsonObject; - dependencies: string[]; - reverseDependencies: string[]; - - snapshot: boolean; - snapshotRepo: string; - snapshotHash: string; - - version: string; -} -export type PackageMap = { [name: string]: PackageInfo }; - - -function loadPackageJson(p: string) { - const root = require('../package.json'); - const pkg = require(p); - - for (const key of Object.keys(root)) { - switch (key) { - // Keep the following keys from the package.json of the package itself. - case 'bin': - case 'description': - case 'dependencies': - case 'name': - case 'main': - case 'peerDependencies': - case 'optionalDependencies': - case 'typings': - case 'version': - case 'private': - case 'workspaces': - case 'resolutions': - case 'scripts': - continue; - - // Remove the following keys from the package.json. - case 'devDependencies': - delete pkg[key]; - continue; - - // Merge the following keys with the root package.json. - case 'keywords': - const a = pkg[key] || []; - const b = Object.keys( - root[key].concat(a).reduce((acc: {[k: string]: boolean}, curr: string) => { - acc[curr] = true; - - return acc; - }, {})); - pkg[key] = b; - break; - - // Overwrite engines to a common default. - case 'engines': - pkg['engines'] = { - 'node': '>= 10.13.0', - 'npm': '>= 6.11.0', - 'pnpm': '>= 3.2.0', - 'yarn': '>= 1.13.0', - }; - break; - - // Overwrite the package's key with to root one. - default: - pkg[key] = root[key]; - } - } - - return pkg; -} - - -function _findAllPackageJson(dir: string, exclude: RegExp): string[] { - const result: string[] = []; - fs.readdirSync(dir) - .forEach(fileName => { - const p = path.join(dir, fileName); - - if (exclude.test(p)) { - return; - } else if (/[\/\\]node_modules[\/\\]/.test(p)) { - return; - } else if (fileName == 'package.json') { - result.push(p); - } else if (fs.statSync(p).isDirectory() && fileName != 'node_modules') { - result.push(..._findAllPackageJson(p, exclude)); - } - }); - - return result; -} - - -const tsConfigPath = path.join(__dirname, '../tsconfig.json'); -const tsConfig = ts.readConfigFile(tsConfigPath, ts.sys.readFile); -const pattern = '^(' - + (tsConfig.config.exclude as string[]) - .map(ex => path.join(path.dirname(tsConfigPath), ex)) - .map(ex => '(' - + ex - .replace(/[\-\[\]{}()+?./\\^$|]/g, '\\$&') - .replace(/(\\\\|\\\/)\*\*/g, '((\/|\\\\).+?)?') - .replace(/\*/g, '[^/\\\\]*') - + ')') - .join('|') - + ')($|/|\\\\)'; -const excludeRe = new RegExp(pattern); - -// Find all the package.json that aren't excluded from tsconfig. -const packageJsonPaths = _findAllPackageJson(path.join(__dirname, '..'), excludeRe) - // Remove the root package.json. - .filter(p => p != path.join(__dirname, '../package.json')); - - -function _exec(cmd: string) { - return execSync(cmd).toString().trim(); -} - - -let gitShaCache: string; -function _getSnapshotHash(_pkg: PackageInfo): string { - if (!gitShaCache) { - gitShaCache = _exec('git log --format=%h -n1'); - } - - return gitShaCache; -} - - -let stableVersion = ''; -let experimentalVersion = ''; -function _getVersionFromGit(experimental: boolean): string { - if (stableVersion && experimentalVersion) { - return experimental ? experimentalVersion : stableVersion; - } - - const hasLocalChanges = _exec(`git status --porcelain`) != ''; - const scmVersionTagRaw = _exec(`git describe --match v[0-9].[0-9].[0-9]* --abbrev=7 --tags`) - .slice(1); - stableVersion = scmVersionTagRaw.replace(/-([0-9]+)-g/, '+$1.'); - if (hasLocalChanges) { - stableVersion += stableVersion.includes('+') ? '.with-local-changes' : '+with-local-changes'; - } - - experimentalVersion = `0.${stableVersion.replace(/^(\d+)\.(\d+)/, (_, major, minor) => { - return '' + (parseInt(major, 10) * 100 + parseInt(minor, 10)); - })}`; - - return experimental ? experimentalVersion : stableVersion; -} - - -// All the supported packages. Go through the packages directory and create a map of -// name => PackageInfo. This map is partial as it lacks some information that requires the -// map itself to finish building. -export const packages: PackageMap = - packageJsonPaths - .map(pkgPath => ({ root: path.dirname(pkgPath) })) - .reduce((packages: PackageMap, pkg) => { - const pkgRoot = pkg.root; - const packageJson = loadPackageJson(path.join(pkgRoot, 'package.json')); - const name = packageJson['name']; - if (!name) { - // Only build the entry if there's a package name. - return packages; - } - if (!(name in monorepoPackages)) { - throw new Error( - `Package ${name} found in ${JSON.stringify(pkg.root)}, not found in .monorepo.json.`, - ); - } - - const bin: {[name: string]: string} = {}; - Object.keys(packageJson['bin'] || {}).forEach(binName => { - let p = path.resolve(pkg.root, packageJson['bin'][binName]); - if (!fs.existsSync(p)) { - p = p.replace(/\.js$/, '.ts'); - } - bin[binName] = p; - }); - - const experimental = !!packageJson.private || !!packageJson.experimental; - - packages[name] = { - build: path.join(distRoot, pkgRoot.substr(path.dirname(__dirname).length)), - dist: path.join(distRoot, name), - root: pkgRoot, - relative: path.relative(path.dirname(__dirname), pkgRoot), - main: path.resolve(pkgRoot, 'src/index.ts'), - private: !!packageJson.private, - experimental, - // yarn doesn't take kindly to @ in tgz filenames - // https://github.com/yarnpkg/yarn/issues/6339 - tar: path.join(distRoot, name.replace(/\/|@/g, '_') + '.tgz'), - bin, - name, - packageJson, - - snapshot: !!monorepoPackages[name].snapshotRepo, - snapshotRepo: monorepoPackages[name].snapshotRepo, - get snapshotHash() { - return _getSnapshotHash(this); - }, - - dependencies: [], - reverseDependencies: [], - get version() { - return _getVersionFromGit(experimental); - }, - }; - - return packages; - }, {}); - - -// Update with dependencies. -for (const pkgName of Object.keys(packages)) { - const pkg = packages[pkgName]; - const pkgJson = require(path.join(pkg.root, 'package.json')); - pkg.dependencies = Object.keys(packages).filter(name => { - return name in (pkgJson.dependencies || {}) - || name in (pkgJson.devDependencies || {}); - }); - pkg.dependencies.forEach(depName => packages[depName].reverseDependencies.push(pkgName)); -} diff --git a/modules/testing/builder/BUILD.bazel b/modules/testing/builder/BUILD.bazel new file mode 100644 index 000000000000..45c39358c29c --- /dev/null +++ b/modules/testing/builder/BUILD.bazel @@ -0,0 +1,55 @@ +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defaults.bzl", "jasmine_test", "ts_project") + +package(default_visibility = ["//visibility:public"]) + +npm_link_all_packages() + +ts_project( + name = "builder", + testonly = True, + srcs = glob( + include = [ + "src/**/*.ts", + ], + exclude = [ + "src/**/*_spec.ts", + ], + ), + data = [ + # Needed at runtime by some builder tests relying on SSR being + # resolvable in the test project. + ":node_modules/@angular/ssr", + ":node_modules/browser-sync", + ":node_modules/istanbul-lib-instrument", + ":node_modules/jsdom", + ":node_modules/ng-packagr", + ":node_modules/vitest", + ":node_modules/@vitest/coverage-v8", + ] + glob(["projects/**/*"]), + deps = [ + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + ":node_modules/rxjs", + "//:node_modules/@types/node", + ], +) + +ts_project( + name = "unit_test_lib", + testonly = True, + srcs = glob( + include = [ + "src/**/*_spec.ts", + ], + ), + deps = [ + ":builder", + ":node_modules/@angular-devkit/architect", + ], +) + +jasmine_test( + name = "test", + data = [":unit_test_lib"], +) diff --git a/modules/testing/builder/package.json b/modules/testing/builder/package.json new file mode 100644 index 000000000000..90cac3e57679 --- /dev/null +++ b/modules/testing/builder/package.json @@ -0,0 +1,15 @@ +{ + "devDependencies": { + "@angular-devkit/architect": "workspace:*", + "@angular-devkit/build-angular": "workspace:*", + "@angular-devkit/core": "workspace:*", + "@angular/ssr": "workspace:*", + "@vitest/coverage-v8": "5.1.1", + "browser-sync": "3.0.4", + "istanbul-lib-instrument": "6.0.3", + "jsdom": "31.0.1", + "ng-packagr": "22.3.0-rc.0", + "rxjs": "7.8.2", + "vitest": "5.1.1" + } +} diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/.editorconfig b/modules/testing/builder/projects/hello-world-app/.editorconfig similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/.editorconfig rename to modules/testing/builder/projects/hello-world-app/.editorconfig diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/.gitignore b/modules/testing/builder/projects/hello-world-app/.gitignore similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/.gitignore rename to modules/testing/builder/projects/hello-world-app/.gitignore diff --git a/modules/testing/builder/projects/hello-world-app/README.md b/modules/testing/builder/projects/hello-world-app/README.md new file mode 100644 index 000000000000..c2795c8bcc94 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/README.md @@ -0,0 +1,27 @@ +# HelloWorldApp + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.7.0-beta.1. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate --help` to see all the available schematics you can generate. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to setup and run the end-to-end tests. + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/main/README.md). diff --git a/modules/testing/builder/projects/hello-world-app/angular.json b/modules/testing/builder/projects/hello-world-app/angular.json new file mode 100644 index 000000000000..9ab612b8b2c5 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/angular.json @@ -0,0 +1,177 @@ +{ + "$schema": "../../../../packages/angular_devkit/core/src/workspace/workspace-schema.json", + "version": 1, + "newProjectRoot": "./projects", + "cli": { + "cache": { + "enabled": false + } + }, + "schematics": {}, + "projects": { + "app": { + "root": "src", + "sourceRoot": "src", + "projectType": "application", + "prefix": "app", + "schematics": {}, + "targets": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.app.json", + "progress": false, + "sourceMap": false, + "aot": false, + "vendorChunk": true, + "buildOptimizer": false, + "optimization": false, + "extractLicenses": false, + "namedChunks": true, + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true + }, + "inline-critical-css": { + "optimization": { + "styles": { + "minify": true, + "inlineCritical": true + }, + "scripts": true, + "fonts": true + } + }, + "sw": { + "ngswConfigPath": "src/ngsw-config.json", + "serviceWorker": true + } + } + }, + "server": { + "builder": "@angular-devkit/build-angular:server", + "options": { + "outputPath": "dist-server", + "main": "src/main.server.ts", + "tsConfig": "src/tsconfig.server.json", + "progress": false, + "sourceMap": true, + "optimization": false, + "extractLicenses": false + }, + "configurations": { + "production": { + "outputHashing": "media", + "sourceMap": false, + "optimization": true + } + } + }, + "app-shell": { + "builder": "@angular-devkit/build-angular:app-shell", + "options": { + "browserTarget": "app:build", + "serverTarget": "app:server" + }, + "configurations": { + "production": { + "browserTarget": "app:build:production" + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "buildTarget": "app:build", + "watch": false + }, + "configurations": { + "production": { + "buildTarget": "app:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "buildTarget": "app:build", + "progress": false, + "outputPath": "src" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "polyfills": [ + "zone.js", + "zone.js/testing" + ], + "tsConfig": "src/tsconfig.spec.json", + "karmaConfig": "karma.conf.js", + "browsers": "ChromeHeadlessCI", + "progress": false, + "watch": false, + "styles": [ + { + "input": "src/styles.css" + } + ], + "scripts": [], + "assets": [ + "src/favicon.ico", + "src/assets" + ] + } + }, + "serve-ssr": { + "builder": "@angular-devkit/build-angular:ssr-dev-server", + "options": { + "browserTarget": "app:build", + "serverTarget": "app:server", + "watch": false, + "progress": false + }, + "configurations": { + "production": { + "browserTarget": "app:build:production", + "serverTarget": "app:server:production" + } + } + }, + "prerender": { + "builder": "@angular-devkit/build-angular:prerender", + "options": { + "browserTarget": "app:build", + "serverTarget": "app:server" + }, + "configurations": { + "production": { + "browserTarget": "app:build:production", + "serverTarget": "app:server:production" + } + } + } + } + } + } +} diff --git a/modules/testing/builder/projects/hello-world-app/karma.conf.js b/modules/testing/builder/projects/hello-world-app/karma.conf.js new file mode 100644 index 000000000000..d3206bd4cf87 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/karma.conf.js @@ -0,0 +1,56 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +const path = require('path'); + +// Resolve from relative paths to absolute paths within the bazel runfiles tree +// so subprocesses spawned in a different working directory can still find them. +process.env.CHROME_BIN = process.env.CHROME_BIN ? path.resolve(path.join(process.cwd(), '..', '..', '..'), process.env.CHROME_BIN) : require('puppeteer').executablePath(); + +module.exports = function(config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage'), + require('@angular-devkit/build-angular/plugins/karma'), + ], + jasmineHtmlReporter: { + suppressAll: true // removes the duplicated traces + }, + coverageReporter: { + dir: path.join(__dirname, './coverage'), + subdir: '.', + reporters: [ + {type: 'lcov'}, + ], + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + customLaunchers: { + ChromeHeadlessCI: { + base: 'ChromeHeadless', + flags: [ + '--disable-gpu', + '--no-sandbox' + ], + }, + }, + singleRun: false, + }); +}; diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/app/app.component.css b/modules/testing/builder/projects/hello-world-app/src/app/app.component.css similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/app/app.component.css rename to modules/testing/builder/projects/hello-world-app/src/app/app.component.css diff --git a/modules/testing/builder/projects/hello-world-app/src/app/app.component.html b/modules/testing/builder/projects/hello-world-app/src/app/app.component.html new file mode 100644 index 000000000000..fe14e2bc127c --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/app/app.component.html @@ -0,0 +1,22 @@ + +
+

+ Welcome to {{ title }}! +

+ Angular Logo +
+

Here are some links to help you start:

+
+ +

i18n test

+ diff --git a/modules/testing/builder/projects/hello-world-app/src/app/app.component.spec.ts b/modules/testing/builder/projects/hello-world-app/src/app/app.component.spec.ts new file mode 100644 index 000000000000..37e8de10ba72 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/app/app.component.spec.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { TestBed } from '@angular/core/testing'; +import { AppComponent } from './app.component'; +describe('AppComponent', () => { + beforeEach(() => TestBed.configureTestingModule({ + declarations: [AppComponent], + })); + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); + }); + it(`should have as title 'app'`, () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('app'); + }); + it('should render title in a h1 tag', () => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); + }); +}); diff --git a/modules/testing/builder/projects/hello-world-app/src/app/app.component.ts b/modules/testing/builder/projects/hello-world-app/src/app/app.component.ts new file mode 100644 index 000000000000..93a041e8aec7 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/app/app.component.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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'; + +@Component({ + selector: 'app-root', + standalone: false, + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'], +}) +export class AppComponent { + title = 'app'; +} diff --git a/modules/testing/builder/projects/hello-world-app/src/app/app.module.server.ts b/modules/testing/builder/projects/hello-world-app/src/app/app.module.server.ts new file mode 100644 index 000000000000..76fd51151562 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/app/app.module.server.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { ServerModule } from '@angular/platform-server'; + +import { AppModule } from './app.module'; +import { AppComponent } from './app.component'; + +@NgModule({ + imports: [ + AppModule, + ServerModule, + ], + bootstrap: [AppComponent], +}) +export class AppServerModule {} diff --git a/modules/testing/builder/projects/hello-world-app/src/app/app.module.ts b/modules/testing/builder/projects/hello-world-app/src/app/app.module.ts new file mode 100644 index 000000000000..d8060d5ac4c9 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/app/app.module.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; + + +import { AppComponent } from './app.component'; + + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/assets/.gitkeep b/modules/testing/builder/projects/hello-world-app/src/assets/.gitkeep similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/assets/.gitkeep rename to modules/testing/builder/projects/hello-world-app/src/assets/.gitkeep diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/favicon.ico b/modules/testing/builder/projects/hello-world-app/src/favicon.ico similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/favicon.ico rename to modules/testing/builder/projects/hello-world-app/src/favicon.ico diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/index.html b/modules/testing/builder/projects/hello-world-app/src/index.html similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/index.html rename to modules/testing/builder/projects/hello-world-app/src/index.html diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/src/locale/messages.xlf b/modules/testing/builder/projects/hello-world-app/src/locale/messages.xlf similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/src/locale/messages.xlf rename to modules/testing/builder/projects/hello-world-app/src/locale/messages.xlf diff --git a/modules/testing/builder/projects/hello-world-app/src/main.server.ts b/modules/testing/builder/projects/hello-world-app/src/main.server.ts new file mode 100644 index 000000000000..0c26cf60e980 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/main.server.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { AppServerModule } from './app/app.module.server'; +export default AppServerModule; +export { AppServerModule }; diff --git a/modules/testing/builder/projects/hello-world-app/src/main.ts b/modules/testing/builder/projects/hello-world-app/src/main.ts new file mode 100644 index 000000000000..d975b48d7808 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/main.ts @@ -0,0 +1,15 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { platformBrowser } from '@angular/platform-browser'; + +import { AppModule } from './app/app.module'; + +platformBrowser() + .bootstrapModule(AppModule) + .catch(err => console.log(err)); diff --git a/modules/testing/builder/projects/hello-world-app/src/ngsw-config.json b/modules/testing/builder/projects/hello-world-app/src/ngsw-config.json new file mode 100644 index 000000000000..789b03bdf7ce --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/ngsw-config.json @@ -0,0 +1,30 @@ +{ + "$schema": "../node_modules/@angular/service-worker/config/schema.json", + "index": "/index.html", + "assetGroups": [ + { + "name": "app", + "installMode": "prefetch", + "resources": { + "files": [ + "/favicon.ico", + "/index.html", + "/manifest.webmanifest", + "/*.css", + "/*.js" + ] + } + }, + { + "name": "assets", + "installMode": "lazy", + "updateMode": "prefetch", + "resources": { + "files": [ + "/assets/**", + "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" + ] + } + } + ] +} diff --git a/modules/testing/builder/projects/hello-world-app/src/polyfills.ts b/modules/testing/builder/projects/hello-world-app/src/polyfills.ts new file mode 100644 index 000000000000..eb77e392ee4e --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/polyfills.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.dev/reference/versions#browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + */ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags.ts'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js'; // Included with Angular CLI. + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/spectrum.png b/modules/testing/builder/projects/hello-world-app/src/spectrum.png similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/spectrum.png rename to modules/testing/builder/projects/hello-world-app/src/spectrum.png diff --git a/tests/angular_devkit/build_angular/hello-world-app-ve/src/styles.css b/modules/testing/builder/projects/hello-world-app/src/styles.css similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app-ve/src/styles.css rename to modules/testing/builder/projects/hello-world-app/src/styles.css diff --git a/modules/testing/builder/projects/hello-world-app/src/tsconfig.app.json b/modules/testing/builder/projects/hello-world-app/src/tsconfig.app.json new file mode 100644 index 000000000000..a76843b689fb --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/tsconfig.app.json @@ -0,0 +1,14 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "types": ["@angular/localize"] + }, + "files": [ + "main.ts", + "polyfills.ts" + ], + "include": [ + "**/*.d.ts" + ] +} diff --git a/modules/testing/builder/projects/hello-world-app/src/tsconfig.server.json b/modules/testing/builder/projects/hello-world-app/src/tsconfig.server.json new file mode 100644 index 000000000000..3fd4df49c45d --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/tsconfig.server.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.app.json", + "compilerOptions": { + "outDir": "../dist-server", + "types": ["@angular/localize", "node", "@types/express"] + }, + "files": [ + "main.server.ts" + ] +} diff --git a/modules/testing/builder/projects/hello-world-app/src/tsconfig.spec.json b/modules/testing/builder/projects/hello-world-app/src/tsconfig.spec.json new file mode 100644 index 000000000000..a42459f71db5 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/tsconfig.spec.json @@ -0,0 +1,17 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/spec", + "types": [ + "jasmine", + "@angular/localize" + ] + }, + "files": [ + "polyfills.ts" + ], + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/modules/testing/builder/projects/hello-world-app/src/typings.d.ts b/modules/testing/builder/projects/hello-world-app/src/typings.d.ts new file mode 100644 index 000000000000..161056781dc0 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/src/typings.d.ts @@ -0,0 +1,13 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* SystemJS module definition */ +declare var module: NodeModule; +interface NodeModule { + id: string; +} diff --git a/modules/testing/builder/projects/hello-world-app/tsconfig.json b/modules/testing/builder/projects/hello-world-app/tsconfig.json new file mode 100644 index 000000000000..4f9890cb8e7d --- /dev/null +++ b/modules/testing/builder/projects/hello-world-app/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "bundler", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "skipLibCheck": true, + "target": "es2022", + "module": "es2022", + "lib": [ + "es2022", + "dom" + ] + }, + "angularCompilerOptions": { + "enableIvy": true, + "disableTypeScriptVersionCheck": true, + "strictTemplates": true + } +} diff --git a/modules/testing/builder/projects/hello-world-lib/.gitignore b/modules/testing/builder/projects/hello-world-lib/.gitignore new file mode 100644 index 000000000000..e0406551d1ea --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/.gitignore @@ -0,0 +1,43 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc + +# dependencies +/node_modules + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# misc +/.angular/cache +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +testem.log +/typings + +# e2e +/e2e/*.js +/e2e/*.map + +# System Files +.DS_Store +Thumbs.db diff --git a/modules/testing/builder/projects/hello-world-lib/angular.json b/modules/testing/builder/projects/hello-world-lib/angular.json new file mode 100644 index 000000000000..9925e3d08f14 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/angular.json @@ -0,0 +1,29 @@ +{ + "$schema": "../../../../packages/angular_devkit/core/src/workspace/workspace-schema.json", + "version": 1, + "cli": { + "cache": { + "enabled": false + } + }, + "projects": { + "lib": { + "root": "projects/lib", + "projectType": "library", + "targets": { + "build": { + "builder": "@angular-devkit/build-angular:ng-packagr", + "options": { + "project": "projects/lib/ng-package.json", + "tsConfig": "projects/lib/tsconfig.lib.json" + }, + "configurations": { + "production": { + "tsConfig": "projects/lib/tsconfig.lib.prod.json" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/karma.conf.js b/modules/testing/builder/projects/hello-world-lib/projects/lib/karma.conf.js new file mode 100644 index 000000000000..5573d103b26e --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/karma.conf.js @@ -0,0 +1,48 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage-istanbul-reporter'), + require('@angular-devkit/build-angular/plugins/karma') + ], + jasmineHtmlReporter: { + suppressAll: true // removes the duplicated traces + }, + coverageIstanbulReporter: { + dir: require('path').join(__dirname, 'coverage'), + reports: ['html', 'lcovonly'], + fixWebpackSourcePaths: true + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + customLaunchers: { + ChromeHeadlessCI: { + base: 'ChromeHeadless', + flags: [ + '--disable-gpu', + '--no-sandbox' + ], + } + }, + singleRun: false + }); +}; diff --git a/tests/angular_devkit/build_ng_packagr/ng-packaged-ve/projects/lib/ng-package.json b/modules/testing/builder/projects/hello-world-lib/projects/lib/ng-package.json similarity index 100% rename from tests/angular_devkit/build_ng_packagr/ng-packaged-ve/projects/lib/ng-package.json rename to modules/testing/builder/projects/hello-world-lib/projects/lib/ng-package.json diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/package.json b/modules/testing/builder/projects/hello-world-lib/projects/lib/package.json new file mode 100644 index 000000000000..c8105b2c16b4 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/package.json @@ -0,0 +1,8 @@ +{ + "name": "lib", + "version": "0.0.1", + "peerDependencies": { + "@angular/common": "^22.2.0-next", + "@angular/core": "^22.2.0-next" + } +} \ No newline at end of file diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.spec.ts b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.spec.ts new file mode 100644 index 000000000000..dbdec32d37c2 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.spec.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LibComponent } from './lib.component'; + +describe('LibComponent', () => { + let component: LibComponent; + let fixture: ComponentFixture; + + beforeEach(() => TestBed.configureTestingModule({ + declarations: [LibComponent] + })); + + beforeEach(() => { + fixture = TestBed.createComponent(LibComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.ts b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.ts new file mode 100644 index 000000000000..3e1ee2aebd2b --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.component.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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'; + +@Component({ + selector: 'lib', + template: ` +

+ lib works! +

+ `, + styles: [] +}) +export class LibComponent { + +} diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.spec.ts b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.spec.ts new file mode 100644 index 000000000000..1bc021e00abb --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.spec.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { TestBed, inject } from '@angular/core/testing'; + +import { LibService } from './lib.service'; + +describe('LibService', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [LibService] + }); + }); + + it('should be created', inject([LibService], (service: LibService) => { + expect(service).toBeTruthy(); + })); +}); diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.ts b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.ts new file mode 100644 index 000000000000..20c9f8075e86 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/lib/lib.service.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Injectable } from '@angular/core'; + +@Injectable() +export class LibService { + + testEs2016() { + return ['foo', 'bar'].includes('foo'); + } + +} diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/src/public-api.ts b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/public-api.ts new file mode 100644 index 000000000000..b641e95d8900 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/src/public-api.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* + * Public API Surface of lib + */ + +export * from './lib/lib.service'; +export * from './lib/lib.component'; diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.json b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.json new file mode 100644 index 000000000000..23e851ac9c8b --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "declaration": true, + "inlineSources": true, + "types": [] + }, + "exclude": [ + "**/*.spec.ts" + ] +} diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.prod.json b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.prod.json new file mode 100644 index 000000000000..2a2faa884cf3 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.lib.prod.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.lib.json", + "compilerOptions": { + "declarationMap": false + }, + "angularCompilerOptions": { + "compilationMode": "partial" + } +} diff --git a/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.spec.json b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.spec.json new file mode 100644 index 000000000000..eae9b9ae9c29 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/projects/lib/tsconfig.spec.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": [ + "jasmine" + ] + }, + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/modules/testing/builder/projects/hello-world-lib/tsconfig.json b/modules/testing/builder/projects/hello-world-lib/tsconfig.json new file mode 100644 index 000000000000..8ccae14cd594 --- /dev/null +++ b/modules/testing/builder/projects/hello-world-lib/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "bundler", + "experimentalDecorators": true, + "target": "es2015", + "module": "es2022", + "useDefineForClassFields": false, + "lib": [ + "es2022", + "dom" + ] + }, + "angularCompilerOptions": { + "enableIvy": true, + "disableTypeScriptVersionCheck": true + } +} diff --git a/modules/testing/builder/src/builder-harness.ts b/modules/testing/builder/src/builder-harness.ts new file mode 100644 index 000000000000..570939cecd7f --- /dev/null +++ b/modules/testing/builder/src/builder-harness.ts @@ -0,0 +1,550 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* eslint-disable import/no-extraneous-dependencies */ + +import { + BuilderContext, + BuilderHandlerFn, + BuilderInfo, + BuilderOutput, + BuilderOutputLike, + BuilderProgressReport, + BuilderRun, + ScheduleOptions, + Target, + fromAsyncIterable, + isBuilderOutput, +} from '@angular-devkit/architect'; +import { WorkspaceHost } from '@angular-devkit/architect/node'; +import { TestProjectHost } from '@angular-devkit/architect/testing'; +import { getSystemPath, json, logging } from '@angular-devkit/core'; +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import fs from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { + Observable, + Subject, + catchError, + finalize, + firstValueFrom, + lastValueFrom, + map, + mergeMap, + from as observableFrom, + of as observableOf, + shareReplay, +} from 'rxjs'; +import { BuilderWatcherFactory, WatcherNotifier } from './file-watching'; + +export interface BuilderHarnessExecutionResult { + result?: T; + error?: Error; + logs: readonly logging.LogEntry[]; +} + +export interface BuilderHarnessExecutionOptions { + configuration: string; + outputLogsOnFailure: boolean; + outputLogsOnException: boolean; + useNativeFileWatching: boolean; + signal: AbortSignal; + additionalExecuteArguments: unknown[]; +} + +interface BuilderHandlerFnWithVarArgs extends BuilderHandlerFn { + (input: T, context: BuilderContext, ...args: unknown[]): BuilderOutputLike; +} + +/** + * The default set of fields provided to all builders executed via the BuilderHarness. + * `root` and `sourceRoot` are required for most Angular builders to function. + * `cli.cache.enabled` set to false provides improved test isolation guarantees by disabling + * the Webpack caching. + */ +const DEFAULT_PROJECT_METADATA = { + root: '.', + sourceRoot: 'src', + cli: { + cache: { + enabled: false, + }, + }, +}; + +export class BuilderHarness { + private readonly builderInfo: BuilderInfo; + private schemaRegistry = new json.schema.CoreSchemaRegistry(); + private projectName = 'test'; + private projectMetadata: Record = DEFAULT_PROJECT_METADATA; + private targetName?: string; + private options = new Map(); + private builderTargets = new Map< + string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { handler: BuilderHandlerFn; info: BuilderInfo; options: json.JsonObject } + >(); + private watcherNotifier?: WatcherNotifier; + + constructor( + private readonly builderHandler: BuilderHandlerFn, + private readonly host: TestProjectHost, + builderInfo?: Partial, + ) { + // Generate default pseudo builder info for test purposes + this.builderInfo = { + builderName: builderHandler.name, + description: '', + optionSchema: true, + ...builderInfo, + }; + + if (builderInfo?.builderName?.startsWith('@angular/build:')) { + this.schemaRegistry.addPostTransform(json.schema.transforms.addUndefinedObjectDefaults); + } else { + this.schemaRegistry.addPostTransform(json.schema.transforms.addUndefinedDefaults); + } + } + + resolvePath(path: string): string { + return join(getSystemPath(this.host.root()), path); + } + + resetProjectMetadata(): void { + this.projectMetadata = DEFAULT_PROJECT_METADATA; + } + + useProject(name: string, metadata: Record = {}): this { + if (!name) { + throw new Error('Project name cannot be an empty string.'); + } + + this.projectName = name; + this.projectMetadata = metadata; + + return this; + } + + useTarget(name: string, baseOptions: T): this { + if (!name) { + throw new Error('Target name cannot be an empty string.'); + } + + this.targetName = name; + this.options.set(null, baseOptions); + + return this; + } + + withConfiguration(configuration: string, options: T): this { + this.options.set(configuration, options); + + return this; + } + + withBuilderTarget( + target: string, + handler: BuilderHandlerFn, + options?: O, + info?: Partial, + ): this { + this.builderTargets.set(target, { + handler, + options: options || {}, + info: { builderName: handler.name, description: '', optionSchema: true, ...info }, + }); + + return this; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + modifyTarget( + targetName: string, + modifier: (options: O) => O | void, + ): this { + const target = this.builderTargets.get(targetName); + if (!target) { + throw new Error(`Target "${targetName}" not found.`); + } + + const newOptions = modifier(target.options as O); + if (newOptions) { + target.options = newOptions as json.JsonObject; + } + + return this; + } + + execute( + options: Partial = {}, + ): Observable { + const { + configuration, + outputLogsOnException = true, + outputLogsOnFailure = true, + useNativeFileWatching = false, + } = options; + + const targetOptions = { + ...this.options.get(null), + ...((configuration && this.options.get(configuration)) ?? {}), + }; + + if (!useNativeFileWatching) { + if (this.watcherNotifier) { + throw new Error('Only one harness execution at a time is supported.'); + } + this.watcherNotifier = new WatcherNotifier(); + } + + const contextHost: ContextHost = { + findBuilderByTarget: async (project, target) => { + this.validateProjectName(project); + if (target === this.targetName) { + return { + info: this.builderInfo, + handler: this.builderHandler as BuilderHandlerFn, + }; + } + + const builderTarget = this.builderTargets.get(target); + if (builderTarget) { + return { info: builderTarget.info, handler: builderTarget.handler }; + } + + throw new Error('Project target does not exist.'); + }, + async getBuilderName(project, target) { + return (await this.findBuilderByTarget(project, target)).info.builderName; + }, + getMetadata: async (project) => { + this.validateProjectName(project); + + return this.projectMetadata as json.JsonObject; + }, + getOptions: async (project, target, configuration) => { + this.validateProjectName(project); + if (target === this.targetName) { + return (this.options.get(configuration ?? null) ?? {}) as json.JsonObject; + } else if (configuration !== undefined) { + // Harness builder targets currently do not support configurations + return {}; + } else { + return this.builderTargets.get(target)?.options || {}; + } + }, + hasTarget: async (project, target) => { + this.validateProjectName(project); + + return this.targetName === target || this.builderTargets.has(target); + }, + getDefaultConfigurationName: async (_project, _target) => { + return undefined; + }, + validate: async (options, builderName) => { + let schema; + if (builderName === this.builderInfo.builderName) { + schema = this.builderInfo.optionSchema; + } else { + for (const [, value] of this.builderTargets) { + if (value.info.builderName === builderName) { + schema = value.info.optionSchema; + break; + } + } + } + + const validator = await this.schemaRegistry.compile(schema ?? true); + const { data } = await validator(options); + + return data as json.JsonObject; + }, + }; + const context = new HarnessBuilderContext( + this.builderInfo, + this.resolvePath('.'), + contextHost, + options.signal, + useNativeFileWatching ? undefined : this.watcherNotifier, + ); + if (this.targetName !== undefined) { + context.target = { + project: this.projectName, + target: this.targetName, + configuration: configuration as string, + }; + } + + const logs: logging.LogEntry[] = []; + const logger$ = context.logger.subscribe((e) => logs.push(e)); + + return observableFrom(this.schemaRegistry.compile(this.builderInfo.optionSchema)).pipe( + mergeMap((validator) => validator(targetOptions)), + map((validationResult) => validationResult.data), + mergeMap((data) => + convertBuilderOutputToObservable( + (this.builderHandler as BuilderHandlerFnWithVarArgs)( + data as T & json.JsonObject, + context, + ...(options.additionalExecuteArguments ?? []), + ), + ), + ), + map((buildResult) => ({ result: buildResult, error: undefined })), + catchError((error) => { + if (outputLogsOnException) { + // eslint-disable-next-line no-console + console.error(logs.map((entry) => entry.message).join('\n')); + // eslint-disable-next-line no-console + console.error(error); + } + + return observableOf({ result: undefined, error }); + }), + map(({ result, error }) => { + if (outputLogsOnFailure && result?.success === false && logs.length > 0) { + // eslint-disable-next-line no-console + console.error(logs.map((entry) => entry.message).join('\n')); + } + + // Capture current logs and clear for next + const currentLogs = logs.slice(); + logs.length = 0; + + return { result, error, logs: currentLogs }; + }), + finalize(() => { + this.watcherNotifier = undefined; + logger$.unsubscribe(); + + for (const teardown of context.teardowns) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + teardown(); + } + }), + ); + } + + async executeOnce( + options?: Partial, + ): Promise { + // Return the first result + return firstValueFrom(this.execute(options)); + } + + async appendToFile(path: string, content: string): Promise { + await this.writeFile(path, this.readFile(path).concat(content)); + } + + async writeFile(path: string, content: string | Buffer): Promise { + const fullPath = this.resolvePath(path); + + await fs.mkdir(dirname(fullPath), { recursive: true }); + await fs.writeFile(fullPath, content, 'utf-8'); + + this.watcherNotifier?.notify([{ path: fullPath, type: 'modified' }]); + } + + async writeFiles(files: Record): Promise { + const watchEvents = this.watcherNotifier + ? ([] as { path: string; type: 'modified' | 'deleted' }[]) + : undefined; + + for (const [path, content] of Object.entries(files)) { + const fullPath = this.resolvePath(path); + + await fs.mkdir(dirname(fullPath), { recursive: true }); + await fs.writeFile(fullPath, content, 'utf-8'); + + watchEvents?.push({ path: fullPath, type: 'modified' }); + } + + if (watchEvents) { + this.watcherNotifier?.notify(watchEvents); + } + } + + async removeFile(path: string): Promise { + const fullPath = this.resolvePath(path); + + await fs.unlink(fullPath); + + this.watcherNotifier?.notify([{ path: fullPath, type: 'deleted' }]); + } + + async modifyFile( + path: string, + modifier: (content: string) => string | Promise, + ): Promise { + const content = this.readFile(path); + await this.writeFile(path, await modifier(content)); + } + + hasFile(path: string): boolean { + const fullPath = this.resolvePath(path); + + return existsSync(fullPath); + } + + hasDirectory(path: string): boolean { + const fullPath = this.resolvePath(path); + + return statSync(fullPath, { throwIfNoEntry: false })?.isDirectory() ?? false; + } + + hasFileMatch(directory: string, pattern: RegExp): boolean { + const fullPath = this.resolvePath(directory); + + return readdirSync(fullPath).some((name) => pattern.test(name)); + } + + readFile(path: string): string { + const fullPath = this.resolvePath(path); + + return readFileSync(fullPath, 'utf-8'); + } + + private validateProjectName(name: string): void { + if (name !== this.projectName) { + throw new Error(`Project "${name}" does not exist.`); + } + } +} + +interface ContextHost extends WorkspaceHost { + findBuilderByTarget( + project: string, + target: string, + ): Promise<{ info: BuilderInfo; handler: BuilderHandlerFn }>; + validate(options: json.JsonObject, builderName: string): Promise; +} + +class HarnessBuilderContext implements BuilderContext { + id = Math.trunc(Math.random() * 1000000); + logger = new logging.Logger(`builder-harness-${this.id}`); + workspaceRoot: string; + currentDirectory: string; + target?: Target; + + teardowns: (() => Promise | void)[] = []; + + constructor( + public builder: BuilderInfo, + basePath: string, + private readonly contextHost: ContextHost, + public readonly signal: AbortSignal | undefined, + public readonly watcherFactory: BuilderWatcherFactory | undefined, + ) { + this.workspaceRoot = this.currentDirectory = basePath; + } + + addTeardown(teardown: () => Promise | void): void { + this.teardowns.push(teardown); + } + + async getBuilderNameForTarget(target: Target): Promise { + return this.contextHost.getBuilderName(target.project, target.target); + } + + async getProjectMetadata(targetOrName: Target | string): Promise { + const project = typeof targetOrName === 'string' ? targetOrName : targetOrName.project; + + return this.contextHost.getMetadata(project); + } + + async getTargetOptions(target: Target): Promise { + return this.contextHost.getOptions(target.project, target.target, target.configuration); + } + + // Unused by builders in this package + async scheduleBuilder( + builderName: string, + options?: json.JsonObject, + scheduleOptions?: ScheduleOptions, + ): Promise { + throw new Error('Not Implemented.'); + } + + async scheduleTarget( + target: Target, + overrides?: json.JsonObject, + scheduleOptions?: ScheduleOptions, + ): Promise { + const { info, handler } = await this.contextHost.findBuilderByTarget( + target.project, + target.target, + ); + const targetOptions = await this.validateOptions( + { + ...(await this.getTargetOptions(target)), + ...overrides, + }, + info.builderName, + ); + + const context = new HarnessBuilderContext( + info, + this.workspaceRoot, + this.contextHost, + this.signal, + this.watcherFactory, + ); + context.target = target; + context.logger = scheduleOptions?.logger || this.logger.createChild(''); + + const progressSubject = new Subject(); + const output = convertBuilderOutputToObservable(handler(targetOptions, context)); + + const run: BuilderRun = { + id: context.id, + info, + progress: progressSubject.asObservable(), + async stop() { + for (const teardown of context.teardowns) { + await teardown(); + } + progressSubject.complete(); + }, + output: output.pipe(shareReplay()), + get result() { + return firstValueFrom(this.output); + }, + get lastOutput() { + return lastValueFrom(this.output); + }, + }; + + return run; + } + + async validateOptions( + options: json.JsonObject, + builderName: string, + ): Promise { + return this.contextHost.validate(options, builderName) as unknown as T; + } + + // Unused report methods + reportRunning(): void {} + reportStatus(): void {} + reportProgress(): void {} +} + +function isAsyncIterable(obj: unknown): obj is AsyncIterable { + return !!obj && typeof (obj as AsyncIterable)[Symbol.asyncIterator] === 'function'; +} + +function convertBuilderOutputToObservable(output: BuilderOutputLike): Observable { + if (isBuilderOutput(output)) { + return observableOf(output); + } else if (isAsyncIterable(output)) { + return fromAsyncIterable(output); + } else { + return observableFrom(output); + } +} diff --git a/modules/testing/builder/src/builder-harness_spec.ts b/modules/testing/builder/src/builder-harness_spec.ts new file mode 100644 index 000000000000..860764f567f8 --- /dev/null +++ b/modules/testing/builder/src/builder-harness_spec.ts @@ -0,0 +1,137 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* eslint-disable import/no-extraneous-dependencies */ + +import { TestProjectHost } from '@angular-devkit/architect/testing'; +import { BuilderHarness } from './builder-harness'; + +describe('BuilderHarness', () => { + let mockHost: TestProjectHost; + + beforeEach(() => { + mockHost = jasmine.createSpyObj('TestProjectHost', ['root']); + (mockHost.root as jasmine.Spy).and.returnValue('.'); + }); + + it('uses the provided builder handler', async () => { + const mockHandler = jasmine.createSpy().and.returnValue({ success: true }); + + const harness = new BuilderHarness(mockHandler, mockHost); + + await harness.executeOnce(); + + expect(mockHandler).toHaveBeenCalled(); + }); + + it('provides the builder output result when executing', async () => { + const mockHandler = jasmine.createSpy().and.returnValue({ success: false, property: 'value' }); + + const harness = new BuilderHarness(mockHandler, mockHost); + const { result } = await harness.executeOnce(); + + expect(result).toBeDefined(); + expect(result?.success).toBeFalse(); + expect(result?.property).toBe('value'); + }); + + it('does not show builder logs on console when a builder succeeds', async () => { + const consoleErrorMock = spyOn(console, 'error'); + + const harness = new BuilderHarness(async (_, context) => { + context.logger.warn('TEST WARNING'); + + return { success: true }; + }, mockHost); + + const { result } = await harness.executeOnce(); + + expect(result).toBeDefined(); + expect(result?.success).toBeTrue(); + + expect(consoleErrorMock).not.toHaveBeenCalledWith(jasmine.stringMatching('TEST WARNING')); + }); + + it('shows builder logs on console when a builder fails', async () => { + const consoleErrorMock = spyOn(console, 'error'); + + const harness = new BuilderHarness(async (_, context) => { + context.logger.warn('TEST WARNING'); + + return { success: false }; + }, mockHost); + + const { result } = await harness.executeOnce(); + + expect(result).toBeDefined(); + expect(result?.success).toBeFalse(); + + expect(consoleErrorMock).toHaveBeenCalledWith(jasmine.stringMatching('TEST WARNING')); + }); + + it('does not show builder logs on console when a builder fails and outputLogsOnFailure: false', async () => { + const consoleErrorMock = spyOn(console, 'error'); + + const harness = new BuilderHarness(async (_, context) => { + context.logger.warn('TEST WARNING'); + + return { success: false }; + }, mockHost); + + const { result } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result).toBeDefined(); + expect(result?.success).toBeFalse(); + + expect(consoleErrorMock).not.toHaveBeenCalledWith(jasmine.stringMatching('TEST WARNING')); + }); + + it('provides and logs the builder output exception when builder throws', async () => { + const mockHandler = jasmine.createSpy().and.throwError(new Error('Builder Error')); + const consoleErrorMock = spyOn(console, 'error'); + + const harness = new BuilderHarness(mockHandler, mockHost); + const { result, error } = await harness.executeOnce(); + + expect(result).toBeUndefined(); + expect(error).toEqual(jasmine.objectContaining({ message: 'Builder Error' })); + expect(consoleErrorMock).toHaveBeenCalledWith(jasmine.stringMatching('Builder Error')); + }); + + it('does not log exception with outputLogsOnException false when builder throws', async () => { + const mockHandler = jasmine.createSpy().and.throwError(new Error('Builder Error')); + const consoleErrorMock = spyOn(console, 'error'); + + const harness = new BuilderHarness(mockHandler, mockHost); + const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); + + expect(result).toBeUndefined(); + expect(error).toEqual(jasmine.objectContaining({ message: 'Builder Error' })); + expect(consoleErrorMock).not.toHaveBeenCalledWith(jasmine.stringMatching('Builder Error')); + }); + + it('supports executing a target from within a builder', async () => { + const mockHandler = jasmine.createSpy().and.returnValue({ success: true }); + + const harness = new BuilderHarness(async (_, context) => { + const run = await context.scheduleTarget({ project: 'test', target: 'another' }); + expect(await run.result).toEqual(jasmine.objectContaining({ success: true })); + await run.stop(); + + return { success: true }; + }, mockHost); + harness.withBuilderTarget('another', mockHandler); + + const { result } = await harness.executeOnce(); + + expect(result).toBeDefined(); + expect(result?.success).toBeTrue(); + + expect(mockHandler).toHaveBeenCalled(); + }); +}); diff --git a/modules/testing/builder/src/dev_prod_mode.ts b/modules/testing/builder/src/dev_prod_mode.ts new file mode 100644 index 000000000000..520de82d771b --- /dev/null +++ b/modules/testing/builder/src/dev_prod_mode.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { BuilderHarness } from './builder-harness'; + +export const GOOD_TARGET = './src/good.js'; +export const BAD_TARGET = './src/bad.js'; + +/** Setup project for use of conditional imports. */ +export async function setupConditionImport(harness: BuilderHarness) { + // Files that can be used as targets for the conditional import. + await harness.writeFile('src/good.ts', `export const VALUE = 'good-value';`); + await harness.writeFile('src/bad.ts', `export const VALUE = 'bad-value';`); + await harness.writeFile('src/wrong.ts', `export const VALUE = 1;`); + + // Simple application file that accesses conditional code. + await harness.writeFile( + 'src/main.ts', + `import {VALUE} from '#target'; +console.log(VALUE); +console.log(VALUE.length); +export default 42 as any; +`, + ); + + // Ensure that good/bad can be resolved from tsconfig. + const tsconfig = JSON.parse(harness.readFile('src/tsconfig.app.json')) as TypeScriptConfig; + tsconfig.compilerOptions.moduleResolution = 'bundler'; + tsconfig.files.push('good.ts', 'bad.ts', 'wrong.ts'); + await harness.writeFile('src/tsconfig.app.json', JSON.stringify(tsconfig)); +} + +/** Update package.json with the given mapping for #target. */ +export async function setTargetMapping(harness: BuilderHarness, mapping: unknown) { + await harness.writeFile( + 'package.json', + JSON.stringify({ + name: 'ng-test-app', + imports: { + '#target': mapping, + }, + }), + ); +} + +interface TypeScriptConfig { + compilerOptions: { + moduleResolution: string; + }; + files: string[]; +} diff --git a/modules/testing/builder/src/file-watching.ts b/modules/testing/builder/src/file-watching.ts new file mode 100644 index 000000000000..6d10706d6919 --- /dev/null +++ b/modules/testing/builder/src/file-watching.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +type BuilderWatcherCallback = ( + events: Array<{ path: string; type: 'created' | 'modified' | 'deleted'; time?: number }>, +) => void; + +interface BuilderWatcherFactory { + watch( + files: Iterable, + directories: Iterable, + callback: BuilderWatcherCallback, + ): { close(): void }; +} + +class WatcherDescriptor { + constructor( + readonly files: ReadonlySet, + readonly directories: ReadonlySet, + readonly callback: BuilderWatcherCallback, + ) {} + + shouldNotify(path: string): boolean { + return true; + } +} + +export class WatcherNotifier implements BuilderWatcherFactory { + private readonly descriptors = new Set(); + + notify(events: Iterable<{ path: string; type: 'modified' | 'deleted' }>): void { + for (const descriptor of this.descriptors) { + for (const { path } of events) { + if (descriptor.shouldNotify(path)) { + descriptor.callback([...events]); + break; + } + } + } + } + + watch( + files: Iterable, + directories: Iterable, + callback: BuilderWatcherCallback, + ): { close(): void } { + const descriptor = new WatcherDescriptor(new Set(files), new Set(directories), callback); + this.descriptors.add(descriptor); + + return { close: () => this.descriptors.delete(descriptor) }; + } +} + +export type { BuilderWatcherFactory }; diff --git a/modules/testing/builder/src/index.ts b/modules/testing/builder/src/index.ts new file mode 100644 index 000000000000..3ee4220781d9 --- /dev/null +++ b/modules/testing/builder/src/index.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + BuilderHarness, + type BuilderHarnessExecutionOptions, + type BuilderHarnessExecutionResult, +} from './builder-harness'; +export { + type HarnessFileMatchers, + JasmineBuilderHarness, + describeBuilder, + expectLog, + expectNoLog, +} from './jasmine-helpers'; +export * from './test-utils'; diff --git a/modules/testing/builder/src/jasmine-helpers.ts b/modules/testing/builder/src/jasmine-helpers.ts new file mode 100644 index 000000000000..bd1943ae3ea1 --- /dev/null +++ b/modules/testing/builder/src/jasmine-helpers.ts @@ -0,0 +1,223 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderHandlerFn } from '@angular-devkit/architect'; +import { json, logging } from '@angular-devkit/core'; +import { readFileSync } from 'node:fs'; +import { concatMap, count, debounceTime, firstValueFrom, take, timeout } from 'rxjs'; +import { + BuilderHarness, + BuilderHarnessExecutionOptions, + BuilderHarnessExecutionResult, +} from './builder-harness'; +import { host } from './test-utils'; + +/** + * Maximum time for single build/rebuild + * This accounts for CI variability. + */ +export const BUILD_TIMEOUT = 30_000; + +const optionSchemaCache = new Map(); + +let counter = 0; + +export function describeBuilder( + builderHandler: BuilderHandlerFn, + options: { name?: string; schemaPath: string }, + specDefinitions: (harness: JasmineBuilderHarness) => void, +): void { + let optionSchema = optionSchemaCache.get(options.schemaPath); + if (optionSchema === undefined) { + optionSchema = JSON.parse(readFileSync(options.schemaPath, 'utf8')) as json.schema.JsonSchema; + optionSchemaCache.set(options.schemaPath, optionSchema); + } + const harness = new JasmineBuilderHarness(builderHandler, host, { + builderName: options.name, + optionSchema, + }); + + // The counter is needed to avoid duplicate describe names as they are not allowed. + describe((options.name || builderHandler.name) + ` (Suite: ${counter++})`, () => { + beforeEach(async () => { + harness.resetProjectMetadata(); + + await host.initialize().toPromise(); + }); + + afterEach(() => host.restore().toPromise()); + + specDefinitions(harness); + }); +} + +export class JasmineBuilderHarness extends BuilderHarness { + expectFile(path: string): HarnessFileMatchers { + return expectFile(path, this); + } + expectDirectory(path: string): HarnessDirectoryMatchers { + return expectDirectory(path, this); + } + + async executeWithCases( + cases: (( + executionResult: BuilderHarnessExecutionResult, + index: number, + ) => void | Promise)[], + options?: Partial & { timeout?: number }, + ): Promise { + const executionCount = await firstValueFrom( + this.execute(options).pipe( + timeout(options?.timeout ?? BUILD_TIMEOUT), + debounceTime(100), // This is needed as sometimes 2 events for the same change fire with webpack. + concatMap(async (result, index) => await cases[index](result, index)), + take(cases.length), + count(), + ), + ); + + expect(executionCount).toBe(cases.length); + } +} + +export interface HarnessFileMatchers { + toExist(): boolean; + toNotExist(): boolean; + readonly content: jasmine.ArrayLikeMatchers; + readonly size: jasmine.Matchers; +} + +export interface HarnessDirectoryMatchers { + toExist(): boolean; + toNotExist(): boolean; +} + +/** + * Add a Jasmine expectation filter to an expectation that always fails with a message. + * @param base The base expectation (`expect(...)`) to use. + * @param message The message to provide in the expectation failure. + */ +function createFailureExpectation(base: T, message: string): T { + // Needed typings are not included in the Jasmine types + const expectation = base as T & { + expector: { + addFilter(filter: { + selectComparisonFunc(): () => { pass: boolean; message: string }; + }): typeof expectation.expector; + }; + }; + expectation.expector = expectation.expector.addFilter({ + selectComparisonFunc() { + return () => ({ + pass: false, + message, + }); + }, + }); + + return expectation; +} + +export function expectFile(path: string, harness: BuilderHarness): HarnessFileMatchers { + return { + toExist() { + const exists = harness.hasFile(path); + expect(exists) + .withContext('Expected file to exist: ' + path) + .toBeTrue(); + + return exists; + }, + toNotExist() { + const exists = harness.hasFile(path); + expect(exists) + .withContext('Expected file to exist: ' + path) + .toBeFalse(); + + return !exists; + }, + get content() { + try { + return expect(harness.readFile(path)).withContext(`With file content for '${path}'`); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== 'ENOENT') { + throw e; + } + + // File does not exist so always fail the expectation + return createFailureExpectation( + expect(''), + `Expected file content but file does not exist: '${path}'`, + ); + } + }, + get size() { + try { + return expect(Buffer.byteLength(harness.readFile(path))).withContext( + `With file size for '${path}'`, + ); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== 'ENOENT') { + throw e; + } + + // File does not exist so always fail the expectation + return createFailureExpectation( + expect(0), + `Expected file size but file does not exist: '${path}'`, + ); + } + }, + }; +} + +export function expectDirectory( + path: string, + harness: BuilderHarness, +): HarnessDirectoryMatchers { + return { + toExist() { + const exists = harness.hasDirectory(path); + expect(exists) + .withContext('Expected directory to exist: ' + path) + .toBeTrue(); + + return exists; + }, + toNotExist() { + const exists = harness.hasDirectory(path); + expect(exists) + .withContext('Expected directory to not exist: ' + path) + .toBeFalse(); + + return !exists; + }, + }; +} + +export function expectLog(logs: readonly logging.LogEntry[], message: string | RegExp) { + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(message), + }), + ); +} + +export function expectNoLog( + logs: readonly logging.LogEntry[], + message: string | RegExp, + failureMessage?: string, +) { + expect(logs) + .withContext(failureMessage ?? '') + .not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(message), + }), + ); +} diff --git a/modules/testing/builder/src/test-utils.ts b/modules/testing/builder/src/test-utils.ts new file mode 100644 index 000000000000..63ded0215c90 --- /dev/null +++ b/modules/testing/builder/src/test-utils.ts @@ -0,0 +1,183 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* eslint-disable import/no-extraneous-dependencies */ + +import { Architect, BuilderOutput, ScheduleOptions, Target } from '@angular-devkit/architect'; +import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; +import { TestProjectHost, TestingArchitectHost } from '@angular-devkit/architect/testing'; +import { + Path, + getSystemPath, + join, + json, + normalize, + schema, + virtualFs, + workspaces, +} from '@angular-devkit/core'; +import path from 'node:path'; +import { firstValueFrom } from 'rxjs'; + +// Default timeout for large specs is 60s. +jasmine.DEFAULT_TIMEOUT_INTERVAL = 60_000; + +export const workspaceRoot = join(normalize(__dirname), `../projects/hello-world-app/`); +export const host = new TestProjectHost(workspaceRoot); +export const outputPath: Path = normalize('dist'); + +export const browserTargetSpec = { project: 'app', target: 'build' }; +export const devServerTargetSpec = { project: 'app', target: 'serve' }; +export const extractI18nTargetSpec = { project: 'app', target: 'extract-i18n' }; +export const karmaTargetSpec = { project: 'app', target: 'test' }; +export const tslintTargetSpec = { project: 'app', target: 'lint' }; + +export async function createArchitect(workspaceRoot: Path) { + const registry = new schema.CoreSchemaRegistry(); + registry.addPostTransform(schema.transforms.addUndefinedDefaults); + const workspaceSysPath = getSystemPath(workspaceRoot); + + // The download path is relative (set from Starlark), so before potentially + // changing directories, or executing inside a temporary directory, ensure + // the path is absolute. + if (process.env['PUPPETEER_DOWNLOAD_PATH']) { + process.env.PUPPETEER_DOWNLOAD_PATH = path.resolve(process.env['PUPPETEER_DOWNLOAD_PATH']); + } + + const { workspace } = await workspaces.readWorkspace( + workspaceSysPath, + workspaces.createWorkspaceHost(host), + ); + const architectHost = new TestingArchitectHost( + workspaceSysPath, + workspaceSysPath, + new WorkspaceNodeModulesArchitectHost(workspace, workspaceSysPath), + ); + const architect = new Architect(architectHost, registry); + + return { + workspace, + architectHost, + architect, + }; +} + +export interface BrowserBuildOutput { + output: BuilderOutput; + files: { [file: string]: Promise }; +} + +export async function browserBuild( + architect: Architect, + host: virtualFs.Host, + target: Target, + overrides?: json.JsonObject, + scheduleOptions?: ScheduleOptions, +): Promise { + const run = await architect.scheduleTarget(target, overrides, scheduleOptions); + const output = await run.result; + expect(output.success).toBe(true); + + if (!output.success) { + await run.stop(); + + return { + output, + files: {}, + }; + } + + const [{ path }] = output.outputs; + expect(path).toBeTruthy(); + const outputPath = normalize(path); + + const fileNames = await firstValueFrom(host.list(outputPath)); + const files = fileNames.reduce((acc: { [name: string]: Promise }, path) => { + let cache: Promise | null = null; + Object.defineProperty(acc, path, { + enumerable: true, + get() { + if (cache) { + return cache; + } + if (!fileNames.includes(path)) { + return Promise.reject('No file named ' + path); + } + cache = firstValueFrom(host.read(join(outputPath, path))).then((content) => + virtualFs.fileBufferToString(content), + ); + + return cache; + }, + }); + + return acc; + }, {}); + + await run.stop(); + + return { + output, + files, + }; +} + +export const lazyModuleFiles: { [path: string]: string } = { + 'src/app/lazy/lazy-routing.module.ts': ` + import { NgModule } from '@angular/core'; + import { Routes, RouterModule } from '@angular/router'; + + const routes: Routes = []; + + @NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] + }) + export class LazyRoutingModule { } + `, + 'src/app/lazy/lazy.module.ts': ` + import { NgModule } from '@angular/core'; + import { CommonModule } from '@angular/common'; + + import { LazyRoutingModule } from './lazy-routing.module'; + + @NgModule({ + imports: [ + CommonModule, + LazyRoutingModule + ], + declarations: [] + }) + export class LazyModule { } + `, +}; + +export const lazyModuleFnImport: { [path: string]: string } = { + 'src/app/app.module.ts': ` + import { BrowserModule } from '@angular/platform-browser'; + import { NgModule } from '@angular/core'; + + import { AppComponent } from './app.component'; + import { RouterModule } from '@angular/router'; + + @NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + RouterModule.forRoot([ + { path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) } + ]) + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } +`, +}; diff --git a/package.json b/package.json index 0254c47fd72f..6914111fafe8 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,8 @@ { "name": "@angular/devkit-repo", - "version": "0.0.0", + "version": "22.4.0-next.0", "private": true, "description": "Software Development Kit for Angular", - "bin": { - "architect": "./bin/architect", - "benchmark": "./bin/benchmark", - "build-optimizer": "./bin/build-optimizer", - "devkit-admin": "./bin/devkit-admin", - "ng": "./bin/ng", - "schematics": "./bin/schematics" - }, "keywords": [ "angular", "Angular CLI", @@ -19,33 +11,30 @@ "Angular DevKit" ], "scripts": { - "admin": "node ./bin/devkit-admin", - "bazel:format": "find . -type f \\( -name \"*.bzl\" -or -name WORKSPACE -or -name BUILD -or -name BUILD.bazel \\) ! -path \"*/node_modules/*\" | xargs buildifier -v --warnings=attr-cfg,attr-license,attr-non-empty,attr-output-default,attr-single-file,constant-glob,ctx-args,depset-iteration,depset-union,dict-concatenation,duplicated-name,filetype,git-repository,http-archive,integer-division,load,load-on-top,native-build,native-package,output-group,package-name,package-on-top,positional-args,redefined-variable,repository-name,same-origin-load,string-iteration,unused-variable", - "bazel:lint": "yarn bazel:format --lint=warn", - "bazel:lint-fix": "yarn bazel:format --lint=fix", - "bazel:test": "bazel test //...", - "build": "npm run admin -- build", - "build-tsc": "tsc -p tsconfig.json", - "debug:test": "node --inspect-brk ./bin/devkit-admin test", - "debug:test-large": "node --inspect-brk ./bin/devkit-admin test --large --spec-reporter", - "fix": "npm run admin -- lint --fix", - "lint": "npm run admin -- lint", - "templates": "node ./bin/devkit-admin templates", - "test": "node ./bin/devkit-admin test", - "test-large": "node ./bin/devkit-admin test --large --spec-reporter", - "validate": "node ./bin/devkit-admin validate", - "validate-commits": "./bin/devkit-admin validate-commits", - "preinstall": "node ./tools/yarn/check-yarn.js", - "//webdriver-update-README": "ChromeDriver version must match Puppeteer Chromium version, see https://github.com/GoogleChrome/puppeteer/releases http://chromedriver.chromium.org/downloads", - "webdriver-update": "webdriver-manager update --standalone false --gecko false --versions.chrome 79.0.3945.16" + "admin": "node --no-warnings=ExperimentalWarning --experimental-transform-types ./scripts/devkit-admin.mts", + "bazel": "bazelisk", + "test": "bazel test //packages/...", + "build": "pnpm --silent admin build", + "benchmark": "node --no-warnings=ExperimentalWarning --experimental-transform-types --expose-gc ./scripts/devkit-admin.mts benchmark", + "build-schema": "bazel build //... --build_tag_filters schema --symlink_prefix dist-schema/", + "lint": "eslint --cache --max-warnings=0", + "templates": "pnpm --silent admin templates", + "validate": "pnpm --silent admin validate", + "postinstall": "husky", + "ts-circular-deps": "ng-dev ts-circular-deps --config ./scripts/circular-deps-test.conf.mjs", + "check-tooling-setup": "tsc --project .ng-dev/tsconfig.json", + "diff-release-package": "node scripts/diff-release-package.mts" }, "repository": { "type": "git", - "url": "https://github.com/angular/angular-cli.git" + "url": "git+https://github.com/angular/angular-cli.git" }, + "packageManager": "pnpm@12.21.0", "engines": { - "node": ">=10.13.0 <13.0.0", - "yarn": ">=1.17.3 <2.0.0" + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "Please use pnpm instead of NPM to install dependencies", + "yarn": "Please use pnpm instead of Yarn to install dependencies", + "pnpm": "12.21.0" }, "author": "Angular Authors", "license": "MIT", @@ -53,103 +42,102 @@ "url": "https://github.com/angular/angular-cli/issues" }, "homepage": "https://github.com/angular/angular-cli", - "workspaces": { - "packages": [ - "packages/angular/*", - "packages/angular_devkit/*", - "packages/ngtools/*", - "packages/schematics/*" - ], - "nohoist": [ - "@angular/compiler-cli" - ] - }, "dependencies": { - "@types/debug": "^4.1.2", - "@types/node-fetch": "^2.1.6", - "@types/progress": "^2.0.3", - "@types/universal-analytics": "^0.4.2", - "@types/uuid": "^3.4.4", - "debug": "^4.1.1", - "glob": "^7.0.3", - "node-fetch": "^2.2.0", - "prettier": "^1.16.4", - "puppeteer": "2.0.0", - "quicktype-core": "^6.0.15", - "temp": "^0.9.0", - "tslint": "^5.15.0", - "typescript": "3.6.4" + "@angular/compiler-cli": "22.3.0-rc.0", + "typescript": "6.0.3" }, "devDependencies": { - "@angular/compiler": "9.0.0-rc.2", - "@angular/compiler-cli": "9.0.0-rc.2", - "@bazel/bazel": "1.0.0", - "@bazel/buildifier": "0.29.0", - "@bazel/jasmine": "0.39.0", - "@bazel/karma": "0.39.0", - "@bazel/labs": "0.39.0", - "@bazel/typescript": "0.39.0", - "@types/babel__core": "7.1.3", - "@types/browserslist": "^4.4.0", - "@types/caniuse-lite": "^1.0.0", - "@types/clean-css": "^4.2.1", - "@types/copy-webpack-plugin": "^4.4.1", - "@types/express": "^4.16.0", - "@types/fast-json-stable-stringify": "^2.0.0", - "@types/find-cache-dir": "^2.0.0", - "@types/glob": "^7.0.0", - "@types/inquirer": "^0.0.44", - "@types/jasmine": "~3.4.0", - "@types/karma": "^3.0.2", - "@types/loader-utils": "^1.1.3", - "@types/minimist": "^1.2.0", - "@types/node": "10.12.30", - "@types/request": "^2.47.1", - "@types/rimraf": "^2.0.2", - "@types/semver": "^6.0.0", - "@types/webpack": "^4.32.1", - "@types/webpack-dev-server": "^3.1.7", - "@types/webpack-sources": "^0.1.5", - "@yarnpkg/lockfile": "1.1.0", - "ajv": "6.10.2", - "ansi-colors": "3.2.4", - "common-tags": "^1.8.0", - "conventional-changelog": "^1.1.0", - "conventional-commits-parser": "^3.0.0", - "gh-got": "^8.0.1", - "git-raw-commits": "^2.0.0", - "husky": "^1.3.1", - "jasmine": "^3.3.1", - "jasmine-spec-reporter": "^4.2.1", - "karma": "~4.4.0", - "karma-jasmine": "^2.0.1", - "karma-jasmine-html-reporter": "^1.4.0", - "license-checker": "^20.1.0", - "minimatch": "^3.0.4", - "minimist": "^1.2.0", - "npm-registry-client": "8.6.0", - "ora": "^4.0.2", - "pacote": "10.1.3", - "pidtree": "^0.3.0", - "pidusage": "^2.0.17", - "rxjs": "6.5.3", - "sauce-connect-proxy": "https://saucelabs.com/downloads/sc-4.5.4-linux.tar.gz", - "semver": "6.3.0", - "source-map": "^0.7.3", - "source-map-support": "^0.5.0", - "spdx-satisfies": "^4.0.0", - "tar": "^4.4.4", - "through2": "^2.0.3", - "tree-kill": "^1.2.0", - "ts-api-guardian": "0.4.6", - "ts-node": "^5.0.0", - "tslint-no-circular-imports": "^0.7.0", - "tslint-sonarts": "1.9.0", - "verdaccio": "4.3.4" + "@angular/animations": "22.3.0-rc.0", + "@angular/cdk": "22.4.0-next.0", + "@angular/common": "22.3.0-rc.0", + "@angular/compiler": "22.3.0-rc.0", + "@angular/core": "22.3.0-rc.0", + "@angular/forms": "22.3.0-rc.0", + "@angular/localize": "22.3.0-rc.0", + "@angular/material": "22.4.0-next.0", + "@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#4d3f549e803d585302ceb4d813c07ba4fe3adc1d", + "@angular/platform-browser": "22.3.0-rc.0", + "@angular/platform-server": "22.3.0-rc.0", + "@angular/router": "22.3.0-rc.0", + "@angular/service-worker": "22.3.0-rc.0", + "@babel/core": "8.1.2", + "@bazel/bazelisk": "1.28.1", + "@bazel/buildifier": "8.2.1", + "@bazel/ibazel": "^0.28.0", + "@eslint/compat": "2.1.1", + "@eslint/eslintrc": "3.3.7", + "@eslint/js": "10.0.1", + "@rollup/plugin-commonjs": "^29.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "16.0.3", + "@rollup/wasm-node": "4.68.7", + "@stylistic/eslint-plugin": "^6.0.0", + "@tony.ganchev/eslint-plugin-header": "~3.4.0", + "@types/babel__core": "7.20.5", + "@types/babel__generator": "^7.6.8", + "@types/browser-sync": "^2.27.0", + "@types/express": "~5.0.1", + "@types/http-proxy": "^1.17.4", + "@types/jasmine": "~6.0.0", + "@types/jasmine-reporters": "^2", + "@types/karma": "^6.3.0", + "@types/less": "^3.0.3", + "@types/loader-utils": "^3.0.0", + "@types/lodash": "^4.17.0", + "@types/node": "^22.12.0", + "@types/npm-package-arg": "^6.1.0", + "@types/picomatch": "^4.0.0", + "@types/progress": "^2.0.3", + "@types/semver": "^7.3.12", + "@types/yargs": "^17.0.20", + "@types/yargs-parser": "^21.0.0", + "@typescript-eslint/eslint-plugin": "8.73.0", + "@typescript-eslint/parser": "8.73.0", + "ajv": "8.20.0", + "buffer": "6.0.3", + "esbuild": "0.28.2", + "esbuild-wasm": "0.28.2", + "eslint": "10.15.0", + "eslint-config-prettier": "10.1.8", + "eslint-plugin-import": "2.32.0", + "express": "5.3.0", + "fast-glob": "3.3.3", + "globals": "17.14.0", + "http-proxy": "^1.18.1", + "http-proxy-middleware": "4.2.2", + "husky": "9.1.7", + "jasmine": "~6.3.0", + "jasmine-core": "~6.3.0", + "jasmine-reporters": "^2.5.2", + "jasmine-spec-reporter": "~7.0.0", + "karma": "~6.4.0", + "karma-chrome-launcher": "~3.2.0", + "karma-coverage": "~2.2.0", + "karma-jasmine": "~5.1.0", + "karma-jasmine-html-reporter": "~2.3.0", + "karma-source-map-support": "1.4.0", + "lodash": "^4.17.21", + "magic-string": "1.4.5", + "prettier": "^3.0.0", + "puppeteer": "25.18.1", + "quicktype-core": "26.0.0", + "rollup": "4.68.7", + "rollup-plugin-dts": "6.5.1", + "rollup-plugin-sourcemaps2": "0.5.10", + "semver": "7.8.6", + "source-map-support": "0.5.21", + "tslib": "2.9.1", + "undici": "8.12.4", + "verdaccio": "6.11.3", + "verdaccio-auth-memory": "^13.0.0", + "zone.js": "^0.16.0" }, - "husky": { - "hooks": { - "pre-push": "node ./bin/devkit-admin hooks/pre-push" + "dependenciesMeta": { + "esbuild": { + "built": true + }, + "puppeteer": { + "built": true } } } diff --git a/packages/README.md b/packages/README.md index 82160f26a4f6..aab7eadc1c92 100644 --- a/packages/README.md +++ b/packages/README.md @@ -2,8 +2,7 @@ This folder is the root of all defined packages in this repository. -Packages that are marked as `private: true` will not be published to NPM. These are limited to the -`_` subfolder. +Packages that are marked as `private: true` will not be published to NPM. -This folder includes a directory for every scope in NPM, without the `@` sign. Then one folder +This folder includes a directory for every scope in NPM, without the `@` sign. Then one folder per package, which contains the `package.json`. diff --git a/packages/_/benchmark/package.json b/packages/_/benchmark/package.json deleted file mode 100644 index ba691f860a1a..000000000000 --- a/packages/_/benchmark/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@_/benchmark", - "version": "0.0.0", - "description": "CLI tool for Angular", - "main": "src/index.js", - "typings": "src/index.d.ts", - "scripts": { - "preinstall": "echo DO NOT INSTALL THIS PROJECT, ONLY THE ROOT PROJECT. && exit 1" - }, - "private": true -} diff --git a/packages/_/benchmark/src/benchmark.ts b/packages/_/benchmark/src/benchmark.ts deleted file mode 100644 index 7c22abe0136f..000000000000 --- a/packages/_/benchmark/src/benchmark.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -declare const global: { - benchmarkReporter: { - reportBenchmark: Function, - }, -}; - - -const kNanosecondsPerSeconds = 1e9; -const kBenchmarkIterationMaxCount = 10000; -const kBenchmarkTimeoutInMsec = 5000; -const kWarmupIterationCount = 100; -const kTopMetricCount = 5; - - -function _run(fn: (i: number) => void, collector: number[]) { - const timeout = Date.now(); - // Gather the first 5 seconds runs, or kMaxNumberOfIterations runs whichever comes first - // (soft timeout). - for (let i = 0; - i < kBenchmarkIterationMaxCount && (Date.now() - timeout) < kBenchmarkTimeoutInMsec; - i++) { - // Start time. - const start = process.hrtime(); - fn(i); - // Get the stop difference time. - const diff = process.hrtime(start); - - // Add to metrics. - collector.push(diff[0] * kNanosecondsPerSeconds + diff[1]); - } -} - - -function _stats(metrics: number[]) { - metrics.sort((a, b) => a - b); - - const count = metrics.length; - const middle = count / 2; - const mean = Number.isInteger(middle) - ? metrics[middle] : ((metrics[middle - 0.5] + metrics[middle + 0.5]) / 2); - const total = metrics.reduce((acc, curr) => acc + curr, 0); - const average = total / count; - - return { - count: count, - fastest: metrics.slice(0, kTopMetricCount), - slowest: metrics.reverse().slice(0, kTopMetricCount), - mean, - average, - }; -} - - -export function benchmark(name: string, fn: (i: number) => void, base?: (i: number) => void) { - it(name + ' (time in nanoseconds)', (done) => { - process.nextTick(() => { - for (let i = 0; i < kWarmupIterationCount; i++) { - // Warm it up. - fn(i); - } - - const reporter = global.benchmarkReporter; - const metrics: number[] = []; - const baseMetrics: number[] = []; - - _run(fn, metrics); - if (base) { - _run(base, baseMetrics); - } - - reporter.reportBenchmark({ - ..._stats(metrics), - base: base ? _stats(baseMetrics) : null, - }); - - done(); - }); - }); -} diff --git a/packages/_/benchmark/src/index.ts b/packages/_/benchmark/src/index.ts deleted file mode 100644 index df56b2754b0b..000000000000 --- a/packages/_/benchmark/src/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './benchmark'; diff --git a/packages/_/devkit/collection.json b/packages/_/devkit/collection.json deleted file mode 100644 index 0353b644307c..000000000000 --- a/packages/_/devkit/collection.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "schematics": { - "package": { - "factory": "./package/factory", - "schema": "./package/schema.json", - "description": "Create an empty schematic project or add a blank schematic to the current project." - } - } -} diff --git a/packages/_/devkit/package.json b/packages/_/devkit/package.json deleted file mode 100644 index 23b4a671ac7e..000000000000 --- a/packages/_/devkit/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "devkit", - "version": "0.0.0", - "description": "Schematics specific to DevKit (used internally, not released)", - "scripts": { - "preinstall": "echo DO NOT INSTALL THIS PROJECT, ONLY THE ROOT PROJECT. && exit 1" - }, - "schematics": "./collection.json", - "private": true, - "dependencies": { - "@angular-devkit/core": "0.0.0", - "@angular-devkit/schematics": "0.0.0" - } -} diff --git a/packages/_/devkit/package/factory.ts b/packages/_/devkit/package/factory.ts deleted file mode 100644 index 9068a3d4ac24..000000000000 --- a/packages/_/devkit/package/factory.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { JsonAstObject, JsonValue, parseJsonAst } from '@angular-devkit/core'; -import { - Rule, - Tree, - UpdateRecorder, - apply, - chain, - mergeWith, - template, - url, -} from '@angular-devkit/schematics'; -import { Schema } from './schema'; - - -function appendPropertyInAstObject( - recorder: UpdateRecorder, - node: JsonAstObject, - propertyName: string, - value: JsonValue, - indent = 4, -) { - const indentStr = '\n' + new Array(indent + 1).join(' '); - - if (node.properties.length > 0) { - // Insert comma. - const last = node.properties[node.properties.length - 1]; - recorder.insertRight(last.start.offset + last.text.replace(/\s+$/, '').length, ','); - } - - recorder.insertLeft( - node.end.offset - 1, - ' ' - + `"${propertyName}": ${JSON.stringify(value, null, 2).replace(/\n/g, indentStr)}` - + indentStr.slice(0, -2), - ); -} - -function addPackageToMonorepo(options: Schema, path: string): Rule { - return (tree: Tree) => { - const collectionJsonContent = tree.read('/.monorepo.json'); - if (!collectionJsonContent) { - throw new Error('Could not find monorepo.json'); - } - const collectionJsonAst = parseJsonAst(collectionJsonContent.toString('utf-8')); - if (collectionJsonAst.kind !== 'object') { - throw new Error('Invalid monorepo content.'); - } - - const packages = collectionJsonAst.properties.find(x => x.key.value == 'packages'); - if (!packages) { - throw new Error('Cannot find packages key in monorepo.'); - } - if (packages.value.kind != 'object') { - throw new Error('Invalid packages key.'); - } - - const readmeUrl = `https://github.com/angular/angular-cli/blob/master/${path}/README.md`; - - const recorder = tree.beginUpdate('/.monorepo.json'); - appendPropertyInAstObject( - recorder, - packages.value, - options.name, - { - name: options.displayName, - links: [{ label: 'README', url: readmeUrl }], - version: '0.0.1', - hash: '', - }, - ); - tree.commitUpdate(recorder); - }; -} - - -export default function (options: Schema): Rule { - const path = 'packages/' - + options.name - .replace(/^@/, '') - .replace(/-/g, '_'); - - // Verify if we need to create a full project, or just add a new schematic. - const source = apply(url('./project-files'), [ - template({ - ...options as object, - dot: '.', - path, - }), - ]); - - return chain([ - mergeWith(source), - addPackageToMonorepo(options, path), - ]); -} diff --git a/packages/_/devkit/package/project-files/__path__/README.md b/packages/_/devkit/package/project-files/__path__/README.md deleted file mode 100644 index f4b425475360..000000000000 --- a/packages/_/devkit/package/project-files/__path__/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# <%= displayName %> - -Work in progress diff --git a/packages/_/devkit/package/project-files/__path__/package.json b/packages/_/devkit/package/project-files/__path__/package.json deleted file mode 100644 index 7126e5f40667..000000000000 --- a/packages/_/devkit/package/project-files/__path__/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "<%= name %>", - "version": "0.0.0", - "description": "<%= description %>", - "main": "src/index.js", - "typings": "src/index.d.ts", - "scripts": { - "preinstall": "echo DO NOT INSTALL THIS PROJECT, ONLY THE ROOT PROJECT. && exit 1" - }, - "keywords": [ - ], - "license": "MIT", - "dependencies": { - "@angular-devkit/core": "0.0.0" - } -} diff --git a/packages/_/devkit/package/project-files/__path__/src/index.ts b/packages/_/devkit/package/project-files/__path__/src/index.ts deleted file mode 100644 index 258badcf91cd..000000000000 --- a/packages/_/devkit/package/project-files/__path__/src/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// TODO: Make this useful (and awesome). -export default 1; diff --git a/packages/_/devkit/package/schema.json b/packages/_/devkit/package/schema.json deleted file mode 100644 index 4e8bca4c8627..000000000000 --- a/packages/_/devkit/package/schema.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "http://json-schema.org/schema", - "id": "SchematicsSchematicSchema", - "title": "DevKit Package Schematic Schema", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The package name for the new schematic.", - "$default": { - "$source": "argv", - "index": 0 - } - }, - "description": { - "type": "string", - "description": "The description of the new package" - }, - "displayName": { - "type": "string", - "$default": { - "$source": "interpolation", - "value": "${name}" - }, - "description": "The human readable name." - } - }, - "required": [ - "name", - "displayName" - ] -} diff --git a/packages/angular/build/BUILD.bazel b/packages/angular/build/BUILD.bazel new file mode 100644 index 000000000000..ac02fb717399 --- /dev/null +++ b/packages/angular/build/BUILD.bazel @@ -0,0 +1,404 @@ +load("@devinfra//bazel/api-golden:index.bzl", "api_golden_test_npm_package") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defaults.bzl", "copy_to_bin", "jasmine_test", "npm_package", "ts_project") +load("//tools:ts_json_schema.bzl", "ts_json_schema") + +licenses(["notice"]) + +package(default_visibility = ["//visibility:public"]) + +npm_link_all_packages() + +ts_json_schema( + name = "application_schema", + src = "src/builders/application/schema.json", +) + +ts_json_schema( + name = "dev-server_schema", + src = "src/builders/dev-server/schema.json", +) + +ts_json_schema( + name = "extract_i18n_schema", + src = "src/builders/extract-i18n/schema.json", +) + +ts_json_schema( + name = "library_schema", + src = "src/builders/library/schema.json", +) + +ts_json_schema( + name = "ng_karma_schema", + src = "src/builders/karma/schema.json", +) + +ts_json_schema( + name = "ng_packagr_schema", + src = "src/builders/ng-packagr/schema.json", +) + +ts_json_schema( + name = "unit_test_schema", + src = "src/builders/unit-test/schema.json", +) + +copy_to_bin( + name = "schemas", + srcs = glob(["**/schema.json"]), +) + +RUNTIME_ASSETS = glob( + include = [ + "src/**/schema.json", + "src/**/*.js", + ], +) + [ + "builders.json", + "package.json", +] + +ts_project( + name = "build", + srcs = glob( + include = [ + "src/**/*.ts", + ], + exclude = [ + "src/test-utils.ts", + "src/**/*_spec.ts", + "src/**/tests/**/*.ts", + "src/testing/**/*.ts", + ], + ) + [ + "index.ts", + "//packages/angular/build:src/builders/application/schema.ts", + "//packages/angular/build:src/builders/dev-server/schema.ts", + "//packages/angular/build:src/builders/extract-i18n/schema.ts", + "//packages/angular/build:src/builders/karma/schema.ts", + "//packages/angular/build:src/builders/library/schema.ts", + "//packages/angular/build:src/builders/ng-packagr/schema.ts", + "//packages/angular/build:src/builders/unit-test/schema.ts", + ], + data = RUNTIME_ASSETS, + deps = [ + ":node_modules/@ampproject/remapping", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + ":node_modules/@angular/ssr", + ":node_modules/@babel/core", + ":node_modules/@inquirer/confirm", + ":node_modules/@oxc-project/types", + ":node_modules/@parcel/watcher", + ":node_modules/@vitejs/plugin-basic-ssl", + ":node_modules/beasties", + ":node_modules/browserslist", + ":node_modules/chokidar", + ":node_modules/https-proxy-agent", + ":node_modules/istanbul-lib-instrument", + ":node_modules/jsonc-parser", + ":node_modules/less", + ":node_modules/listr2", + ":node_modules/lmdb", + ":node_modules/magic-string", + ":node_modules/mrmime", + ":node_modules/ng-packagr", + ":node_modules/oxc-parser", + ":node_modules/parse5-html-rewriting-stream", + ":node_modules/picomatch", + ":node_modules/piscina", + ":node_modules/postcss", + ":node_modules/rolldown", + ":node_modules/rolldown-plugin-dts", + ":node_modules/rollup", + ":node_modules/sass", + ":node_modules/sass-embedded", + ":node_modules/source-map-support", + ":node_modules/tinyglobby", + ":node_modules/vite", + ":node_modules/vitest", + ":node_modules/xxhash-wasm", + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/localize", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/platform-server", + "//:node_modules/@angular/service-worker", + "//:node_modules/@types/babel__core", + "//:node_modules/@types/karma", + "//:node_modules/@types/less", + "//:node_modules/@types/node", + "//:node_modules/@types/picomatch", + "//:node_modules/@types/semver", + "//:node_modules/esbuild", + "//:node_modules/esbuild-wasm", + "//:node_modules/karma", + "//:node_modules/semver", + "//:node_modules/tslib", + "//:node_modules/typescript", + ], +) + +ts_project( + name = "unit_test_lib", + testonly = True, + srcs = glob( + include = ["src/**/*_spec.ts"], + exclude = ["src/builders/**/tests/**"], + ), + deps = [ + ":build", + ":node_modules/@angular-devkit/core", + ":node_modules/@babel/core", + ":node_modules/@parcel/watcher", + ":node_modules/oxc-parser", + ":node_modules/vitest", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/router", + "//:node_modules/@types/jasmine", + "//:node_modules/esbuild", + "//:node_modules/prettier", + "//:node_modules/typescript", + "//packages/angular/build/private", + ], +) + +jasmine_test( + name = "test", + data = [":unit_test_lib"], + shard_count = 4, +) + +ts_project( + name = "application_integration_test_lib", + testonly = True, + srcs = glob(include = ["src/builders/application/tests/**/*.ts"]), + deps = [ + ":build", + "//packages/angular/build/private", + "//modules/testing/builder", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + + # Base dependencies for the application in hello-world-app. + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/router", + ":node_modules/rxjs", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + "//:node_modules/buffer", + ], +) + +ts_project( + name = "dev-server_integration_test_lib", + testonly = True, + srcs = glob(include = ["src/builders/dev-server/tests/**/*.ts"]), + deps = [ + ":build", + "//packages/angular/build/private", + "//modules/testing/builder", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + + # dev server only test deps + "//:node_modules/@types/http-proxy", + "//:node_modules/@types/node", + "//:node_modules/http-proxy", + "//:node_modules/puppeteer", + + # Base dependencies for the application in hello-world-app. + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/router", + ":node_modules/ng-packagr", + ":node_modules/rxjs", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + "//:node_modules/buffer", + ], +) + +ts_project( + name = "karma_integration_test_lib", + testonly = True, + srcs = glob(include = ["src/builders/karma/tests/**/*.ts"]), + deps = [ + ":build", + "//packages/angular/build/private", + "//modules/testing/builder", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + "//:node_modules/@types/node", + + # karma specific test deps + "//:node_modules/karma-chrome-launcher", + "//:node_modules/karma-coverage", + "//:node_modules/karma-jasmine", + "//:node_modules/karma-jasmine-html-reporter", + "//:node_modules/puppeteer", + + # Base dependencies for the karma in hello-world-app. + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/router", + ":node_modules/rxjs", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + "//:node_modules/buffer", + ], +) + +ts_project( + name = "unit-test_integration_test_lib", + testonly = True, + srcs = glob(include = ["src/builders/unit-test/tests/**/*.ts"]), + deps = [ + ":build", + "//packages/angular/build/private", + "//modules/testing/builder", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + "//:node_modules/@types/node", + + # unit test specific test deps + ":node_modules/@vitest/coverage-v8", + ":node_modules/vitest", + ":node_modules/jsdom", + + # Base dependencies for the hello-world-app. + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/router", + ":node_modules/rxjs", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + ], +) + +ts_project( + name = "library_integration_test_lib", + testonly = True, + srcs = glob(include = ["src/builders/library/tests/**/*.ts"]), + deps = [ + ":build", + "//packages/angular/build/private", + "//modules/testing/builder", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + "//:node_modules/@types/node", + + # Base dependencies for the library in hello-world-lib. + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/@angular/router", + ":node_modules/rxjs", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + ], +) + +jasmine_test( + name = "application_integration_tests", + size = "medium", + data = [":application_integration_test_lib"], + shard_count = 25, +) + +jasmine_test( + name = "dev-server_integration_tests", + size = "medium", + data = [":dev-server_integration_test_lib"], + env = { + # Force IPv4 to resolve RBE resolution issues + "NODE_OPTIONS": "--dns-result-order=ipv4first", + }, + shard_count = 10, +) + +jasmine_test( + name = "karma_integration_tests", + size = "medium", + data = [":karma_integration_test_lib"], + env = { + # TODO: Replace Puppeteer downloaded browsers with Bazel-managed browsers, + # or standardize to avoid complex configuration like this! + "PUPPETEER_DOWNLOAD_PATH": "../../../node_modules/puppeteer/downloads", + }, + shard_count = 10, +) + +jasmine_test( + name = "unit-test_integration_tests", + size = "medium", + data = [":unit-test_integration_test_lib"], + shard_count = 10, +) + +jasmine_test( + name = "library_integration_tests", + size = "medium", + data = [":library_integration_test_lib"], + shard_count = 6, +) + +genrule( + name = "license", + srcs = ["//:LICENSE"], + outs = ["LICENSE"], + cmd = "cp $(execpath //:LICENSE) $@", +) + +npm_package( + name = "pkg", + pkg_deps = [ + "//packages/angular_devkit/architect:package.json", + ], + stamp_files = [ + "src/utils/version.js", + "src/tools/esbuild/target.js", + "src/utils/normalize-cache.js", + "src/utils/supported-browsers.js", + ], + tags = ["release-package"], + deps = RUNTIME_ASSETS + [ + ":README.md", + ":build", + ":license", + "//packages/angular/build/private", + ], +) + +api_golden_test_npm_package( + name = "api", + data = [ + ":npm_package", + "//goldens:public-api", + ], + golden_dir = "goldens/public-api/angular/build", + npm_package = "packages/angular/build/npm_package", +) diff --git a/packages/angular/build/README.md b/packages/angular/build/README.md new file mode 100644 index 000000000000..62249f7fe422 --- /dev/null +++ b/packages/angular/build/README.md @@ -0,0 +1,5 @@ +# Angular Build System for Applications and Libraries + +The sources for this package are in the [Angular CLI](https://github.com/angular/angular-cli) repository. Please file issues and pull requests against that repository. + +Usage information and reference details can be found in repository [README](https://github.com/angular/angular-cli/blob/main/README.md) file. diff --git a/packages/angular/build/builders.json b/packages/angular/build/builders.json new file mode 100644 index 000000000000..faca69ec8fcc --- /dev/null +++ b/packages/angular/build/builders.json @@ -0,0 +1,39 @@ +{ + "builders": { + "application": { + "implementation": "./src/builders/application/index", + "schema": "./src/builders/application/schema.json", + "description": "Build an application." + }, + "dev-server": { + "implementation": "./src/builders/dev-server/index", + "schema": "./src/builders/dev-server/schema.json", + "description": "Execute a development server for an application." + }, + "extract-i18n": { + "implementation": "./src/builders/extract-i18n/index", + "schema": "./src/builders/extract-i18n/schema.json", + "description": "Extract i18n messages from an application." + }, + "karma": { + "implementation": "./src/builders/karma", + "schema": "./src/builders/karma/schema.json", + "description": "Run Karma unit tests." + }, + "library": { + "implementation": "./src/builders/library/index", + "schema": "./src/builders/library/schema.json", + "description": "Build an Angular library package conforming to the Angular Package Format (APF)." + }, + "ng-packagr": { + "implementation": "./src/builders/ng-packagr/index", + "schema": "./src/builders/ng-packagr/schema.json", + "description": "Build a library with ng-packagr. (Deprecated: Use '@angular/build:library' instead.)" + }, + "unit-test": { + "implementation": "./src/builders/unit-test", + "schema": "./src/builders/unit-test/schema.json", + "description": "Run application unit tests." + } + } +} diff --git a/packages/angular/build/index.ts b/packages/angular/build/index.ts new file mode 100644 index 000000000000..e6da94cc7ded --- /dev/null +++ b/packages/angular/build/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './src/index'; diff --git a/packages/angular/build/package.json b/packages/angular/build/package.json new file mode 100644 index 000000000000..199567cf976b --- /dev/null +++ b/packages/angular/build/package.json @@ -0,0 +1,132 @@ +{ + "name": "@angular/build", + "version": "0.0.0-PLACEHOLDER", + "description": "Official build system for Angular", + "keywords": [ + "angular", + "angular-cli" + ], + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./private": { + "default": "./src/private.js" + }, + "./package.json": "./package.json" + }, + "builders": "builders.json", + "dependencies": { + "@ampproject/remapping": "2.3.0", + "@angular-devkit/architect": "workspace:0.0.0-EXPERIMENTAL-PLACEHOLDER", + "@babel/core": "8.1.2", + "@inquirer/confirm": "6.4.0", + "@parcel/watcher": "2.6.0", + "@vitejs/plugin-basic-ssl": "2.3.0", + "beasties": "0.5.5", + "browserslist": "^4.26.0", + "chokidar": "6.0.0", + "esbuild": "0.28.2", + "https-proxy-agent": "9.1.0", + "jsonc-parser": "3.3.1", + "listr2": "11.4.1", + "magic-string": "1.4.5", + "mrmime": "2.0.1", + "oxc-parser": "0.159.0", + "parse5-html-rewriting-stream": "8.1.1", + "picomatch": "4.0.7", + "piscina": "5.3.2", + "rolldown": "1.3.3", + "rolldown-plugin-dts": "0.30.2", + "sass": "1.108.2", + "sass-embedded": "1.108.2", + "semver": "7.8.6", + "source-map-support": "0.5.21", + "tinyglobby": "0.2.17", + "vite": "8.3.8", + "xxhash-wasm": "1.1.0" + }, + "optionalDependencies": { + "@oxc-parser/binding-wasm32-wasi": "0.159.0", + "lmdb": "3.5.11" + }, + "devDependencies": { + "@angular-devkit/core": "workspace:*", + "@angular/ssr": "workspace:*", + "@oxc-project/types": "0.159.0", + "@vitest/coverage-v8": "5.1.1", + "istanbul-lib-instrument": "6.0.3", + "jsdom": "31.0.1", + "less": "4.9.1", + "ng-packagr": "22.3.0-rc.0", + "postcss": "8.5.33", + "rollup": "4.68.7", + "rxjs": "7.8.2", + "vitest": "5.1.1" + }, + "peerDependencies": { + "@angular/compiler": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/compiler-cli": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/core": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/localize": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/platform-browser": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/platform-server": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/service-worker": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/ssr": "^0.0.0-PLACEHOLDER", + "istanbul-lib-instrument": "^6.0.0", + "karma": "^6.4.0", + "less": "^4.2.0", + "ng-packagr": "0.0.0-NG-PACKAGR-PEER-DEP", + "postcss": "^8.4.0", + "rollup": "^4.0.0", + "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", + "tslib": "^2.3.0", + "typescript": ">=6.0 <6.1", + "vitest": "^4.0.8 || ^5.0.0" + }, + "peerDependenciesMeta": { + "@angular/core": { + "optional": true + }, + "@angular/localize": { + "optional": true + }, + "@angular/platform-browser": { + "optional": true + }, + "@angular/platform-server": { + "optional": true + }, + "@angular/service-worker": { + "optional": true + }, + "@angular/ssr": { + "optional": true + }, + "istanbul-lib-instrument": { + "optional": true + }, + "karma": { + "optional": true + }, + "less": { + "optional": true + }, + "ng-packagr": { + "optional": true + }, + "postcss": { + "optional": true + }, + "rollup": { + "optional": true + }, + "tailwindcss": { + "optional": true + }, + "vitest": { + "optional": true + } + } +} diff --git a/packages/angular/build/private/BUILD.bazel b/packages/angular/build/private/BUILD.bazel new file mode 100644 index 000000000000..c3a100de897f --- /dev/null +++ b/packages/angular/build/private/BUILD.bazel @@ -0,0 +1,11 @@ +load("//tools:defaults.bzl", "ts_project") + +package(default_visibility = ["//visibility:public"]) + +ts_project( + name = "private", + srcs = ["index.ts"], + deps = [ + "//packages/angular/build", + ], +) diff --git a/packages/angular/build/private/index.ts b/packages/angular/build/private/index.ts new file mode 100644 index 000000000000..1c2b76656baf --- /dev/null +++ b/packages/angular/build/private/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from '../src/private'; diff --git a/packages/angular/build/src/builders/application/build-action.ts b/packages/angular/build/src/builders/application/build-action.ts new file mode 100644 index 000000000000..d03d2741b105 --- /dev/null +++ b/packages/angular/build/src/builders/application/build-action.ts @@ -0,0 +1,444 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import { + BuildOutputAsset, + ExecutionResult, + RebuildState, +} from '../../tools/esbuild/bundler-execution-result'; +import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundler-files'; +import { + resetSassWorkerPoolCaches, + shutdownSassWorkerPool, +} from '../../tools/esbuild/stylesheets/sass-language'; +import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/utils'; +import { initializeHash } from '../../utils/hash'; +import { NormalizedCachedOptions } from '../../utils/normalize-cache'; +import { ChangedFiles } from '../../utils/watcher'; +import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options'; +import { + ComponentUpdateResult, + FullResult, + IncrementalResult, + Result, + ResultKind, + ResultMessage, +} from './results'; + +// eslint-disable-next-line max-lines-per-function +export async function* runEsBuildBuildAction( + action: (rebuildState?: RebuildState) => Promise, + options: { + workspaceRoot: string; + projectRoot: string; + outputOptions: NormalizedOutputOptions; + logger: BuilderContext['logger']; + cacheOptions: NormalizedCachedOptions; + watch?: boolean; + verbose?: boolean; + progress?: boolean; + poll?: number; + signal?: AbortSignal; + preserveSymlinks?: boolean; + clearScreen?: boolean; + colors?: boolean; + jsonLogs?: boolean; + incrementalResults?: boolean; + }, +): AsyncIterable { + const { + watch, + poll, + clearScreen, + logger, + cacheOptions, + outputOptions, + verbose, + projectRoot, + workspaceRoot, + progress, + preserveSymlinks, + colors, + jsonLogs, + incrementalResults, + } = options; + + await initializeHash(); + + const withProgress: typeof withSpinner = progress ? withSpinner : withNoProgress; + + // Initial build + let result: ExecutionResult | undefined; + try { + // Perform the build action + result = await withProgress('Building...', () => action()); + + // Log all diagnostic (error/warning/logs) messages + await logMessages(logger, result, colors, jsonLogs); + } finally { + // Ensure Sass workers are shutdown if not watching or if the initial build failed + if (!watch || !result) { + shutdownSassWorkerPool(); + } + } + + let watcher: import('../../utils/watcher').BuildWatcher | undefined; + let watchLoopStarted = false; + try { + // Setup watcher if watch mode enabled + if (watch) { + if (progress) { + logger.info('Watch mode enabled. Watching for file changes...'); + } + + // Setup a watcher + const { setupWatcher } = await import('../../utils/watcher'); + watcher = await setupWatcher({ + workspaceRoot, + projectRoot, + outputPath: outputOptions.base, + cacheOptions, + poll, + preserveSymlinks, + signal: options.signal, + watchFiles: result.watchFiles, + }); + } + + // Output the first build results after setting up the watcher to ensure that any code executed + // higher in the iterator call stack will trigger the watcher. This is particularly relevant for + // unit tests which execute the builder and modify the file system programmatically. + const outputResults = [...emitOutputResults(result, outputOptions)]; + if (!watch) { + await result.dispose(); + // Set to true to prevent double-disposal of the result context in the finally block on generator exit + watchLoopStarted = true; + } + yield* outputResults; + + // Finish if watch mode is not enabled + if (!watcher) { + return; + } + + watchLoopStarted = true; + } finally { + if (!watchLoopStarted && result) { + await result.dispose(); + } + } + + // Used to force a full result on next rebuild if there were initial errors. + // This ensures at least one full result is emitted. + let hasInitialErrors = result.errors.length > 0; + + // Wait for changes and rebuild as needed + const currentWatchFiles = new Set(result.watchFiles); + try { + for await (const changes of watcher) { + if (options.signal?.aborted) { + break; + } + + if (clearScreen) { + // eslint-disable-next-line no-console + console.clear(); + } + + if (verbose) { + logger.info(changes.toDebugString()); + } + + // Clear removed files from current watch files + changes.removed.forEach((removedPath) => currentWatchFiles.delete(removedPath)); + + const hasSassChanges = changes.all.some((f) => /\.(scss|sass|css)$/i.test(f)); + if (hasSassChanges) { + resetSassWorkerPoolCaches(); + } + + const rebuildState = result.createRebuildState(changes); + result = await withProgress('Changes detected. Rebuilding...', () => action(rebuildState)); + + // Log all diagnostic (error/warning/logs) messages + await logMessages(logger, result, colors, jsonLogs); + + // Update watched locations provided by the new build result. + // Keep watching all previous files if there are any errors; otherwise consider all + // files stale until confirmed present in the new result's watch files. + const staleWatchFiles = result.errors.length > 0 ? undefined : new Set(currentWatchFiles); + for (const watchFile of result.watchFiles) { + if (!currentWatchFiles.has(watchFile)) { + // Add new watch location + watcher.add(watchFile); + currentWatchFiles.add(watchFile); + } + + // Present so remove from stale locations + staleWatchFiles?.delete(watchFile); + } + // Remove any stale locations if the build was successful + if (staleWatchFiles?.size) { + watcher.remove([...staleWatchFiles]); + for (const staleFile of staleWatchFiles) { + currentWatchFiles.delete(staleFile); + } + } + + for (const outputResult of emitOutputResults( + result, + outputOptions, + changes, + incrementalResults && !hasInitialErrors ? rebuildState : undefined, + )) { + yield outputResult; + } + + // Clear initial build errors flag if no errors are now present + hasInitialErrors &&= result.errors.length > 0; + } + } finally { + // Stop the watcher and cleanup incremental rebuild state + await Promise.allSettled([watcher.close(), result.dispose()]); + + shutdownSassWorkerPool(); + } +} + +function* emitOutputResults( + { + outputFiles, + assetFiles, + errors, + warnings, + externalMetadata, + htmlIndexPath, + htmlBaseHref, + templateUpdates, + }: ExecutionResult, + outputOptions: NormalizedApplicationBuildOptions['outputOptions'], + changes?: ChangedFiles, + rebuildState?: RebuildState, +): Iterable { + if (errors.length > 0) { + yield { + kind: ResultKind.Failure, + errors: errors as ResultMessage[], + warnings: warnings as ResultMessage[], + detail: { + outputOptions, + }, + }; + + return; + } + + // Use a full result if there is no rebuild state (no prior build result) + if (!rebuildState || !changes) { + yield createFullResult( + outputFiles, + assetFiles, + warnings, + outputOptions, + externalMetadata, + htmlIndexPath, + htmlBaseHref, + ); + + return; + } + + // Template updates only exist if no other JS changes have occurred. + // A full page reload may be required based on the following incremental output change analysis. + const hasTemplateUpdates = !!templateUpdates?.size; + + // Use an incremental result if previous output information is available + const { previousAssetsInfo, previousOutputInfo } = rebuildState; + + const incrementalResult: IncrementalResult = { + kind: ResultKind.Incremental, + warnings: warnings as ResultMessage[], + // Initially attempt to use a background update of files to support component updates. + background: hasTemplateUpdates, + added: [], + removed: [], + modified: [], + files: [], + detail: { + externalMetadata, + htmlIndexPath, + htmlBaseHref, + outputOptions, + }, + }; + + let hasCssUpdates = false; + + // Initially assume all previous output files have been removed + const removedOutputFiles = new Map(previousOutputInfo); + for (const file of outputFiles) { + const key = `${file.type}:${file.path}`; + removedOutputFiles.delete(key); + + const previousHash = previousOutputInfo.get(key)?.hash; + let needFile = false; + if (previousHash === undefined) { + needFile = true; + incrementalResult.added.push(file.path); + } else if (previousHash !== file.hash) { + needFile = true; + incrementalResult.modified.push(file.path); + } + + if (needFile) { + if (file.path.endsWith('.css')) { + hasCssUpdates = true; + } else if (!canBackgroundUpdate(file)) { + incrementalResult.background = false; + } + + incrementalResult.files.push({ + path: file.path, + type: file.type, + contents: file.contents, + origin: 'memory', + hash: file.hash, + }); + } + } + + // Initially assume all previous assets files have been removed + const removedAssetFiles = new Set(previousAssetsInfo); + for (const { source, destination } of assetFiles) { + removedAssetFiles.delete(destination); + + if (!previousAssetsInfo.has(destination)) { + incrementalResult.added.push(destination); + incrementalResult.background = false; + } else if (changes.modified.has(source) || changes.added.has(source)) { + // A file replaced by a rename (e.g. an atomic save) can be reported as added. + incrementalResult.modified.push(destination); + incrementalResult.background = false; + } else { + continue; + } + + hasCssUpdates ||= destination.endsWith('.css'); + + incrementalResult.files.push({ + path: destination, + type: BuildOutputFileType.Browser, + source, + origin: 'disk', + }); + } + + // Do not remove stale files yet if there are template updates. + // Component chunk files may still be referenced in running browser code. + // Module evaluation time component updates will update any of these files. + // This typically occurs when a lazy component is changed that has not yet + // been accessed at runtime. + if (hasTemplateUpdates && incrementalResult.background) { + removedOutputFiles.clear(); + } + + // Include the removed output and asset files + incrementalResult.removed.push( + ...Array.from(removedOutputFiles.values(), ({ type, path }) => ({ + path, + type, + })), + ...Array.from(removedAssetFiles, (path) => ({ + path, + type: BuildOutputFileType.Browser, + })), + ); + + yield incrementalResult; + + // If there are template updates and the incremental update was background only, a component + // update is possible. + if (hasTemplateUpdates && incrementalResult.background) { + // Template changes may be accompanied by stylesheet changes and these should also be updated hot when possible. + if (hasCssUpdates) { + const styleResult: IncrementalResult = { + kind: ResultKind.Incremental, + added: incrementalResult.added.filter(isCssFilePath), + removed: incrementalResult.removed.filter(({ path }) => isCssFilePath(path)), + modified: incrementalResult.modified.filter(isCssFilePath), + files: incrementalResult.files.filter((file) => isCssFilePath(file.path)), + }; + + yield styleResult; + } + + const updateResult: ComponentUpdateResult = { + kind: ResultKind.ComponentUpdate, + updates: Array.from(templateUpdates, ([id, content]) => ({ + type: 'template', + id, + content, + })), + }; + + yield updateResult; + } +} + +function createFullResult( + outputFiles: readonly BuildOutputFile[], + assetFiles: readonly BuildOutputAsset[], + warnings: readonly unknown[], + outputOptions: NormalizedApplicationBuildOptions['outputOptions'], + externalMetadata: unknown, + htmlIndexPath: unknown, + htmlBaseHref: unknown, +): FullResult { + return { + kind: ResultKind.Full, + warnings: warnings as ResultMessage[], + files: [ + ...assetFiles.map(({ source, destination }) => ({ + path: destination, + type: BuildOutputFileType.Browser, + source, + origin: 'disk' as const, + })), + ...outputFiles.map((file) => ({ + path: file.path, + type: file.type, + contents: file.contents, + origin: 'memory' as const, + hash: file.hash, + })), + ], + detail: { + externalMetadata, + htmlIndexPath, + htmlBaseHref, + outputOptions, + }, + }; +} + +function isCssFilePath(filePath: string): boolean { + return /\.css(?:\.map)?$/i.test(filePath); +} + +function canBackgroundUpdate(file: BuildOutputFile): boolean { + // Files in the output root are not served and do not affect the + // application available with the development server. + if (file.type === BuildOutputFileType.Root) { + return true; + } + + // Updates to non-JS files must signal an update with the dev server + // except the service worker configuration which is special cased. + return /(?:\.m?js|\.map)$/.test(file.path) || file.path === 'ngsw.json'; +} diff --git a/packages/angular/build/src/builders/application/chunk-optimizer.ts b/packages/angular/build/src/builders/application/chunk-optimizer.ts new file mode 100644 index 000000000000..a556ae45e7cd --- /dev/null +++ b/packages/angular/build/src/builders/application/chunk-optimizer.ts @@ -0,0 +1,433 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview This file provides a function to optimize JavaScript chunks using rolldown. + * It is designed to be used after an esbuild build to further optimize the output. + * The main function, `optimizeChunks`, takes the result of an esbuild build, + * identifies the main browser entry point, and then uses rolldown to rebundle + * and optimize the chunks. This process can result in smaller and more efficient + * code by combining and restructuring the original chunks. The file also includes + * helper functions to convert rolldown's output into an esbuild-compatible + * metafile, allowing for consistent analysis and reporting of the build output. + */ + +import type { Message, Metafile } from 'esbuild'; +import assert from 'node:assert'; +import type { Plugin } from 'rollup'; +import { BundleMergedContextResult } from '../../tools/esbuild/bundler-context'; +import { + type BuildOutputFile, + BuildOutputFileType, + createOutputFile, + findTransitiveInitialFiles, +} from '../../tools/esbuild/bundler-files'; +import { useRolldownChunks } from '../../utils/environment-options'; +import { assertIsError } from '../../utils/error'; +import { loadRolldown } from '../../utils/load-rolldown'; +import { toPosixPath } from '../../utils/path'; + +/** + * Represents a minimal subset of a Rollup/Rolldown output asset. + * This is manually defined to avoid hard dependencies on both bundlers' types + * and to ensure compatibility since Rolldown and Rollup types have slight differences + * but share these core properties. + */ +interface OutputAsset { + type: 'asset'; + fileName: string; + source: string | Uint8Array; +} + +/** + * Represents a minimal subset of a Rollup/Rolldown output chunk. + * This is manually defined to avoid hard dependencies on both bundlers' types + * and to ensure compatibility since Rolldown and Rollup types have slight differences + * but share these core properties. + */ +interface OutputChunk { + type: 'chunk'; + fileName: string; + code: string; + modules: Record; + imports: string[]; + dynamicImports?: string[]; + exports: string[]; + isEntry: boolean; + facadeModuleId: string | null | undefined; + map?: { toString(): string } | null; + sourcemapFileName?: string | null; +} + +/** + * Converts the output of a bundle build into an esbuild-compatible metafile. + * @param bundleOutput The output of a bundle build. + * @param originalMetafile The original esbuild metafile from the build. + * @returns An esbuild-compatible metafile. + */ +function bundleOutputToEsbuildMetafile( + bundleOutput: (OutputChunk | OutputAsset)[], + originalMetafile: Metafile, +): Metafile { + const newMetafile: Metafile = { + inputs: originalMetafile.inputs, + outputs: {}, + }; + + const intermediateChunkSizes: Record = {}; + for (const [path, output] of Object.entries(originalMetafile.outputs)) { + intermediateChunkSizes[path] = Object.values(output.inputs).reduce( + (s, i) => s + i.bytesInOutput, + 0, + ); + } + + for (const chunk of bundleOutput) { + if (chunk.type === 'asset') { + newMetafile.outputs[chunk.fileName] = { + bytes: + typeof chunk.source === 'string' + ? Buffer.byteLength(chunk.source, 'utf8') + : chunk.source.length, + inputs: {}, + imports: [], + exports: [], + }; + continue; + } + + const newOutputInputs: Record = {}; + if (chunk.modules) { + for (const [moduleId, renderedModule] of Object.entries(chunk.modules)) { + const originalOutputEntry = originalMetafile.outputs[moduleId]; + if (!originalOutputEntry?.inputs) { + continue; + } + + const totalOriginalBytesInModule = intermediateChunkSizes[moduleId]; + if (totalOriginalBytesInModule === 0) { + continue; + } + + // Read once per module: in Rolldown, `renderedLength` is an uncached getter that + // copies the entire module code across the NAPI bridge on each access. + const { renderedLength } = renderedModule; + + for (const [originalInputPath, originalInputInfo] of Object.entries( + originalOutputEntry.inputs, + )) { + const proportion = originalInputInfo.bytesInOutput / totalOriginalBytesInModule; + const newBytesInOutput = Math.floor(renderedLength * proportion); + + const existing = newOutputInputs[originalInputPath]; + if (existing) { + existing.bytesInOutput += newBytesInOutput; + } else { + newOutputInputs[originalInputPath] = { bytesInOutput: newBytesInOutput }; + } + + if (!newMetafile.inputs[originalInputPath]) { + newMetafile.inputs[originalInputPath] = originalMetafile.inputs[originalInputPath]; + } + } + } + } + + const imports = [ + ...chunk.imports.map((path) => ({ path, kind: 'import-statement' as const })), + ...(chunk.dynamicImports?.map((path) => ({ path, kind: 'dynamic-import' as const })) ?? []), + ]; + + let entryPoint: string | undefined; + if (chunk.facadeModuleId) { + const posixFacadeModuleId = toPosixPath(chunk.facadeModuleId); + for (const [outputPath, output] of Object.entries(originalMetafile.outputs)) { + if (posixFacadeModuleId.endsWith(outputPath)) { + entryPoint = output.entryPoint; + break; + } + } + } + + newMetafile.outputs[chunk.fileName] = { + bytes: Buffer.byteLength(chunk.code, 'utf8'), + inputs: newOutputInputs, + imports, + exports: chunk.exports ?? [], + entryPoint, + }; + } + + return newMetafile; +} + +/** + * Creates an esbuild message object for a chunk optimization failure. + * @param message The error message detailing the cause of the failure. + * @returns A partial esbuild message object. + */ +function createChunkOptimizationFailureMessage(message: string): Message { + // Most of these fields are not actually needed for printing the error + return { + id: '', + text: 'Chunk optimization failed', + detail: undefined, + pluginName: '', + location: null, + notes: [ + { + text: message, + location: null, + }, + ], + }; +} + +/** + * Optimizes the chunks of a build result using rolldown. + * + * This function takes the output of an esbuild build, identifies the main browser entry point, + * and uses rolldown to bundle and optimize the JavaScript chunks. The optimized chunks + * replace the original ones in the build result, and the metafile is updated to reflect + * the changes. + * + * @param original The original build result from esbuild. + * @param sourcemap A boolean or 'hidden' to control sourcemap generation. + * @returns A promise that resolves to the updated build result with optimized chunks. + */ +// eslint-disable-next-line max-lines-per-function +export async function optimizeChunks( + original: BundleMergedContextResult, + sourcemap: boolean | 'hidden', +): Promise { + // Failed builds cannot be optimized + if (original.errors) { + return original; + } + + // Find the main browser entrypoint + let mainFile; + for (const [file, record] of original.initialFiles) { + if ( + record.name === 'main' && + record.entrypoint && + !record.serverFile && + record.type === 'script' + ) { + mainFile = file; + break; + } + } + + // No action required if no browser main entrypoint or metafile for stats + if (!mainFile || !original.metafiles.browser) { + return original; + } + + const chunks: Record = {}; + const maps: Record = {}; + for (const originalFile of original.outputFiles) { + if (originalFile.type !== BuildOutputFileType.Browser) { + continue; + } + + if (originalFile.path.endsWith('.js')) { + chunks[originalFile.path] = originalFile; + } else if (originalFile.path.endsWith('.js.map')) { + // Create mapping of JS file to sourcemap content + maps[originalFile.path.slice(0, -4)] = originalFile; + } + } + + const usedChunks = new Set(); + + let bundle; + let optimizedOutput: (OutputChunk | OutputAsset)[]; + try { + const plugins = [ + { + name: 'angular-bundle', + resolveId(source: string) { + // Remove leading `./` if present + const file = source[0] === '.' && source[1] === '/' ? source.slice(2) : source; + + if (chunks[file]) { + return file; + } + + // All other identifiers are considered external to maintain behavior + return { id: source, external: true }; + }, + load(id: string) { + assert( + chunks[id], + `Angular chunk content should always be present in chunk optimizer [${id}].`, + ); + + usedChunks.add(id); + + const result = { + code: chunks[id].text, + map: maps[id]?.text, + }; + + return result; + }, + ...(sourcemap + ? { + augmentChunkHash(chunk: { moduleIds: string[] }) { + let hash = ''; + for (const id of chunk.moduleIds) { + const mapHash = maps[id]?.hash; + if (mapHash) { + hash += mapHash; + } + } + + return hash || undefined; + }, + } + : {}), + }, + ]; + + const chunkFileNames = (chunkInfo: { name: string }) => + `${chunkInfo.name.replace(/-[a-zA-Z0-9_-]{8}$/, '')}-[hash].js`; + + if (useRolldownChunks) { + const { rolldown } = await loadRolldown(); + bundle = await rolldown({ + input: mainFile, + // Allow Rolldown to extend the main entry chunk's exports when merging shared initial + // modules into `main` so that lazy chunks can import those symbols directly from `main`. + preserveEntrySignatures: 'allow-extension', + plugins, + }); + + let result = await bundle.generate({ + minify: { mangle: false, compress: false }, + sourcemap, + codeSplitting: { + // Consolidate all modules statically reachable from the initial entry point (`$initial`) + // back into the `main` chunk. This prevents multi-level initial chunk waterfalls caused + // by esbuild splitting out modules that are shared across `main` and subsets of lazy + // routes, while keeping shared chunks used exclusively by lazy routes separate. + groups: [{ name: 'main', tags: ['$initial'] }], + }, + chunkFileNames, + }); + + // If any module in `$initial` uses top-level `await`, Rolldown cannot fold the manual + // `main` group into the entry chunk and emits an empty entry facade instead. Fall back to + // Rolldown's default TLA-aware chunking in that case. + if ( + result.output.some( + (chunk) => + chunk.type === 'chunk' && chunk.isEntry && Object.keys(chunk.modules).length === 0, + ) + ) { + result = await bundle.generate({ + minify: { mangle: false, compress: false }, + sourcemap, + chunkFileNames, + }); + } + + optimizedOutput = result.output; + } else { + let rollup; + try { + rollup = (await import('rollup')).rollup; + } catch { + throw new Error( + `Rollup is required when 'NG_BUILD_CHUNKS_ROLLDOWN' is set to false. ` + + `Please install 'rollup' manually (e.g. 'npm install rollup --save-dev') to use this fallback.`, + ); + } + bundle = await rollup({ + input: mainFile, + plugins: plugins as Plugin[], + }); + + const result = await bundle.generate({ + compact: true, + sourcemap, + chunkFileNames, + }); + optimizedOutput = result.output; + } + } catch (e) { + assertIsError(e); + + return { + errors: [createChunkOptimizationFailureMessage(e.message)], + warnings: original.warnings, + }; + } finally { + await bundle?.close(); + } + + // Update metafile + const newMetafile = bundleOutputToEsbuildMetafile(optimizedOutput, original.metafiles.browser); + // Add back the outputs that were not part of the optimization + for (const [path, output] of Object.entries(original.metafiles.browser.outputs)) { + if (usedChunks.has(path)) { + continue; + } + + newMetafile.outputs[path] = output; + for (const inputPath of Object.keys(output.inputs)) { + if (!newMetafile.inputs[inputPath]) { + newMetafile.inputs[inputPath] = original.metafiles.browser.inputs[inputPath]; + } + } + } + original.metafiles.browser = newMetafile; + + // Remove used chunks and associated sourcemaps from the original result + original.outputFiles = original.outputFiles.filter( + (file) => + !usedChunks.has(file.path) && + !(file.path.endsWith('.map') && usedChunks.has(file.path.slice(0, -4))), + ); + + // Add new optimized chunks + for (const optimizedFile of optimizedOutput) { + if (optimizedFile.type !== 'chunk') { + continue; + } + + original.outputFiles.push( + createOutputFile(optimizedFile.fileName, optimizedFile.code, BuildOutputFileType.Browser), + ); + if (optimizedFile.map && optimizedFile.sourcemapFileName) { + original.outputFiles.push( + createOutputFile( + optimizedFile.sourcemapFileName, + optimizedFile.map.toString(), + BuildOutputFileType.Browser, + ), + ); + } + } + + // Update initial files to reflect optimized chunks + for (const usedFile of usedChunks) { + // Leave the main file since its information did not change + if (usedFile !== mainFile) { + original.initialFiles.delete(usedFile); + } + } + + // Analyze for transitive initial files + const mainRecord = original.initialFiles.get(mainFile); + assert(mainRecord, `Main file record should always be present in initialFiles [${mainFile}].`); + findTransitiveInitialFiles(newMetafile, original.initialFiles, [[mainFile, mainRecord]]); + + return original; +} diff --git a/packages/angular/build/src/builders/application/execute-build.ts b/packages/angular/build/src/builders/application/execute-build.ts new file mode 100644 index 000000000000..7fc43de92b00 --- /dev/null +++ b/packages/angular/build/src/builders/application/execute-build.ts @@ -0,0 +1,471 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import type { Metafile } from 'esbuild'; +import { createAngularCompilation } from '../../tools/angular/compilation'; +import { + AngularCompilationContext, + PrimaryCompilationContext, +} from '../../tools/esbuild/angular/compilation-state'; +import { SourceFileCache } from '../../tools/esbuild/angular/source-file-cache'; +import { generateBudgetStats } from '../../tools/esbuild/budget-stats'; +import { BundleContextResult, BundlerContext } from '../../tools/esbuild/bundler-context'; +import { ExecutionResult, RebuildState } from '../../tools/esbuild/bundler-execution-result'; +import { BuildOutputFileType } from '../../tools/esbuild/bundler-files'; +import { checkCommonJSModules } from '../../tools/esbuild/commonjs-checker'; +import { LOCALE_DATA_BASE_MODULE } from '../../tools/esbuild/i18n-locale-plugin'; +import { extractLicenses } from '../../tools/esbuild/license-extractor'; +import { transformSupportedBrowsersToTargets } from '../../tools/esbuild/target'; +import { + calculateEstimatedTransferSizes, + isZonelessApp, + logBuildStats, +} from '../../tools/esbuild/utils'; +import { BudgetCalculatorResult, checkBudgets } from '../../utils/bundle-calculator'; +import { optimizeChunksThreshold } from '../../utils/environment-options'; +import { profileAsync } from '../../utils/profiling'; +import { resolveAssets } from '../../utils/resolve-assets'; +import { + SERVER_APP_ENGINE_MANIFEST_FILENAME, + generateAngularServerAppEngineManifest, +} from '../../utils/server-rendering/manifest'; +import { getSupportedBrowsers } from '../../utils/supported-browsers'; +import { executePostBundleSteps } from './execute-post-bundle'; +import { inlineI18n, loadActiveTranslations } from './i18n'; +import { NormalizedApplicationBuildOptions } from './options'; +import { createComponentStyleBundler, setupBundlerContexts } from './setup-bundling'; + +/** The esbuild error text prefix used to detect top-level await errors. */ +const TOP_LEVEL_AWAIT_ERROR_TEXT = + 'Top-level await is not available in the configured target environment'; + +/** Returns a shallow copy of a record with its keys sorted. */ +function sortObjectKeys>(value: T): T { + const sorted: Record = {}; + for (const key of Object.keys(value).sort()) { + sorted[key] = value[key]; + } + + return sorted as T; +} + +/** + * Serializes a metafile with its dynamic path keys sorted so the stats file is identical across + * builds. Only `inputs`, `outputs`, and each output's `inputs` have dynamic keys; the remaining + * fixed-schema objects are left untouched so V8 keeps its native `JSON.stringify` fast path. + */ +function stableStringify(metafile: Metafile): string { + const outputs: Metafile['outputs'] = {}; + for (const key of Object.keys(metafile.outputs).sort()) { + const output = metafile.outputs[key]; + outputs[key] = { + ...output, + inputs: sortObjectKeys(output.inputs), + }; + } + + return JSON.stringify( + { + inputs: sortObjectKeys(metafile.inputs), + outputs, + }, + null, + 2, + ); +} + +// eslint-disable-next-line max-lines-per-function +export async function executeBuild( + options: NormalizedApplicationBuildOptions, + context: BuilderContext, + rebuildState?: RebuildState, +): Promise { + const { + projectRoot, + workspaceRoot, + i18nOptions, + optimizationOptions, + assets, + cacheOptions, + serverEntryPoint, + baseHref, + ssrOptions, + verbose, + colors, + jsonLogs, + security, + } = options; + + // TODO: Consider integrating into watch mode. Would require full rebuild on target changes. + const browsers = getSupportedBrowsers(projectRoot, context.logger); + + // Load active translations if inlining + // TODO: Integrate into watch mode and only load changed translations + if (i18nOptions.shouldInline) { + await loadActiveTranslations(context, i18nOptions); + } + + // Reuse rebuild state or create new bundle contexts for code and global stylesheets + let bundlerContexts; + let componentStyleBundler; + let codeBundleCache; + let bundlingIndividualResults: BundleContextResult[]; + let templateUpdates: Map | undefined; + let angularCompilationContext: AngularCompilationContext | undefined; + let executionResult: ExecutionResult | undefined; + try { + if (rebuildState) { + bundlerContexts = rebuildState.rebuildContexts; + componentStyleBundler = rebuildState.componentStyleBundler; + codeBundleCache = rebuildState.codeBundleCache; + templateUpdates = rebuildState.templateUpdates; + executionResult = new ExecutionResult( + bundlerContexts, + componentStyleBundler, + codeBundleCache, + templateUpdates, + ); + // Reset template updates for new rebuild + templateUpdates?.clear(); + + const allFileChanges = rebuildState.fileChanges.all; + + // Bundle all contexts that do not require TypeScript changed file checks. + // These will automatically use cached results based on the changed files. + bundlingIndividualResults = await BundlerContext.bundleAll( + bundlerContexts.otherContexts, + allFileChanges, + ); + + // Check the TypeScript code bundling cache for changes. If invalid, force a rebundle of + // all TypeScript related contexts. + const forceTypeScriptRebuild = codeBundleCache?.invalidate(allFileChanges); + const typescriptResults: BundleContextResult[] = []; + for (const typescriptContext of bundlerContexts.typescriptContexts) { + typescriptContext.invalidate(allFileChanges); + const result = await typescriptContext.bundle(forceTypeScriptRebuild); + typescriptResults.push(result); + } + + bundlingIndividualResults.push(...typescriptResults); + } else { + const target = transformSupportedBrowsersToTargets(browsers); + codeBundleCache = new SourceFileCache(cacheOptions.enabled ? cacheOptions.path : undefined); + componentStyleBundler = createComponentStyleBundler(options, target); + if (options.templateUpdates) { + templateUpdates = new Map(); + } + const angularCompilation = await createAngularCompilation( + !!options.jit, + !options.serverEntryPoint, + ); + angularCompilationContext = new PrimaryCompilationContext(angularCompilation); + bundlerContexts = setupBundlerContexts( + options, + target, + codeBundleCache, + componentStyleBundler, + angularCompilationContext, + templateUpdates, + ); + executionResult = new ExecutionResult( + bundlerContexts, + componentStyleBundler, + codeBundleCache, + templateUpdates, + ); + + // Bundle everything on initial build + bundlingIndividualResults = await BundlerContext.bundleAll([ + ...bundlerContexts.typescriptContexts, + ...bundlerContexts.otherContexts, + ]); + } + + // Update any external component styles if enabled and rebuilding. + // TODO: Only attempt rebundling of invalidated styles once incremental build results are supported. + if (rebuildState && options.externalRuntimeStyles) { + componentStyleBundler.invalidate(rebuildState.fileChanges.all); + + const componentResults = await componentStyleBundler.bundleAllFiles(true, true); + bundlingIndividualResults.push(...componentResults); + } + + let bundlingResult = BundlerContext.mergeResults(bundlingIndividualResults); + + executionResult.addWarnings(bundlingResult.warnings); + + // Add used external component style referenced files to be watched + if (options.externalRuntimeStyles) { + executionResult.extraWatchFiles.push(...componentStyleBundler.collectReferencedFiles()); + } + + // In non-watch mode, the bundler rebuild contexts and Angular compilation + // are no longer needed once bundling completes. Dispose them early to free + // worker processes, TypeScript ASTs, and caches before post-bundling steps + // execute or before returning bundling errors. + // This is fire-and-forget so worker teardown runs concurrently in the background + // without blocking the critical path of post-bundle optimization steps. + // Any in-flight disposal is awaited in the builder action's finally block. + if (!options.watch) { + void angularCompilationContext?.dispose(); + void executionResult.dispose(); + } + + // Return if the bundling has errors + if (bundlingResult.errors) { + // If Zone.js is used, augment top-level await errors with a more helpful message. + // esbuild's default error mentions "target environment" with browser versions, but + // the actual reason is that async/await is downleveled for Zone.js compatibility. + if (!isZonelessApp(options.polyfills)) { + for (const error of bundlingResult.errors) { + if (error.text?.startsWith(TOP_LEVEL_AWAIT_ERROR_TEXT)) { + error.notes ??= []; + error.notes.push({ + text: + 'Top-level await is not supported in applications that use Zone.js. ' + + 'Consider removing Zone.js or moving this code into an async function. \n' + + 'For more information about zoneless Angular applications, visit: https://angular.dev/guide/zoneless', + location: null, + }); + } + } + } + + executionResult.addErrors(bundlingResult.errors); + + return executionResult; + } + + // Optimize chunks if enabled and threshold is met. + // This pass uses Rollup/Rolldown to further optimize chunks generated by esbuild. + if (options.optimizationOptions.scripts) { + // Count lazy chunks (files not needed for initial load). + // Advanced chunk optimization is most beneficial when there are multiple lazy chunks. + const { metafiles, initialFiles } = bundlingResult; + const lazyChunksCount = Object.keys(metafiles.browser.outputs || {}).filter( + (path) => path.endsWith('.js') && !initialFiles.has(path), + ).length; + + // Only run if the number of lazy chunks meets the configured threshold. + // This avoids overhead for small projects with few chunks. + if (lazyChunksCount >= optimizeChunksThreshold) { + const { optimizeChunks } = await import('./chunk-optimizer'); + const optimizationResult = await profileAsync('OPTIMIZE_CHUNKS', () => + optimizeChunks( + bundlingResult, + options.sourcemapOptions.scripts ? !options.sourcemapOptions.hidden || 'hidden' : false, + ), + ); + + if (optimizationResult.errors) { + executionResult.addErrors(optimizationResult.errors); + + return executionResult; + } + + bundlingResult = optimizationResult; + } + } + + // Analyze external imports if external options are enabled + if (options.externalPackages || bundlingResult.externalConfiguration) { + const { + externalConfiguration = [], + externalImports: { browser = [], server = [] }, + } = bundlingResult; + // Similar to esbuild, --external:@foo/bar automatically implies --external:@foo/bar/*, + // which matches import paths like @foo/bar/baz. + // This means all paths within the @foo/bar package are also marked as external. + const exclusionsPrefixes = externalConfiguration.map((exclusion) => exclusion + '/'); + const exclusions = new Set(externalConfiguration); + const explicitExternal = new Set(); + + const isExplicitExternal = (dep: string): boolean => { + // Locale-data imports are injected by the builder itself (see i18n-locale-plugin) and must stay resolvable + // even when the containing package is externalized by the user. + if (dep.startsWith(`${LOCALE_DATA_BASE_MODULE}/`)) { + return false; + } + + if (exclusions.has(dep)) { + return true; + } + + for (const prefix of exclusionsPrefixes) { + if (dep.startsWith(prefix)) { + return true; + } + } + + return false; + }; + + const implicitBrowser: string[] = []; + for (const dep of browser) { + if (isExplicitExternal(dep)) { + explicitExternal.add(dep); + } else { + implicitBrowser.push(dep); + } + } + + const implicitServer: string[] = []; + for (const dep of server) { + if (isExplicitExternal(dep)) { + explicitExternal.add(dep); + } else { + implicitServer.push(dep); + } + } + + executionResult.setExternalMetadata(implicitBrowser, implicitServer, [...explicitExternal]); + } + + const { + metafiles: { browser: browserMetafile, server: serverMetafile }, + initialFiles, + outputFiles, + } = bundlingResult; + const metafiles = [browserMetafile, serverMetafile]; + + executionResult.outputFiles.push(...outputFiles); + + // Analyze files for bundle budget failures if present + let budgetFailures: BudgetCalculatorResult[] | undefined; + if (options.budgets) { + const compatStats = generateBudgetStats(browserMetafile, outputFiles, initialFiles); + budgetFailures = [...checkBudgets(options.budgets, compatStats, true)]; + for (const { message, severity } of budgetFailures) { + if (severity === 'error') { + executionResult.addError(message); + } else { + executionResult.addWarning(message); + } + } + } + + // Calculate estimated transfer size if scripts are optimized + let estimatedTransferSizes; + if (optimizationOptions.scripts || optimizationOptions.styles.minify) { + estimatedTransferSizes = await calculateEstimatedTransferSizes(executionResult.outputFiles); + } + + // Check metafile for CommonJS module usage if optimizing scripts + if (optimizationOptions.scripts) { + const messages = checkCommonJSModules(browserMetafile, options.allowedCommonJsDependencies); + executionResult.addWarnings(messages); + } + + // Copy assets + if (assets) { + executionResult.addAssets(await resolveAssets(assets, workspaceRoot)); + } + + // Extract and write licenses for used packages + if (options.extractLicenses) { + executionResult.addOutputFile( + '3rdpartylicenses.txt', + await extractLicenses(metafiles, workspaceRoot), + BuildOutputFileType.Root, + ); + } + + // Watch input index HTML file if configured + if (options.indexHtmlOptions) { + executionResult.extraWatchFiles.push(options.indexHtmlOptions.input); + executionResult.htmlIndexPath = options.indexHtmlOptions.output; + executionResult.htmlBaseHref = options.baseHref; + } + + // Create server app engine manifest + if (serverEntryPoint) { + executionResult.addOutputFile( + SERVER_APP_ENGINE_MANIFEST_FILENAME, + generateAngularServerAppEngineManifest(i18nOptions, security.allowedHosts, baseHref), + BuildOutputFileType.ServerRoot, + ); + } + + // Perform i18n translation inlining if enabled + if (i18nOptions.shouldInline) { + const result = await inlineI18n(browserMetafile, options, executionResult, initialFiles); + executionResult.addErrors(result.errors); + executionResult.addWarnings(result.warnings); + executionResult.addPrerenderedRoutes(result.prerenderedRoutes); + } else { + const result = await executePostBundleSteps( + browserMetafile, + options, + executionResult.outputFiles, + executionResult.assetFiles, + initialFiles, + // Set lang attribute to the defined source locale if present + i18nOptions.hasDefinedSourceLocale ? i18nOptions.sourceLocale : undefined, + ); + + // Deduplicate and add errors and warnings + executionResult.addErrors([...new Set(result.errors)]); + executionResult.addWarnings([...new Set(result.warnings)]); + + executionResult.addPrerenderedRoutes(result.prerenderedRoutes); + executionResult.outputFiles.push(...result.additionalOutputFiles); + executionResult.assetFiles.push(...result.additionalAssets); + } + + if (serverEntryPoint) { + executionResult.addOutputFile( + 'prerendered-routes.json', + JSON.stringify({ routes: executionResult.prerenderedRoutes }, null, 2), + BuildOutputFileType.Root, + ); + } + + // Write metafiles if stats option is enabled + if (options.stats) { + executionResult.addOutputFile( + 'browser-stats.json', + stableStringify(browserMetafile), + BuildOutputFileType.Root, + ); + + if (serverEntryPoint) { + executionResult.addOutputFile( + 'server-stats.json', + stableStringify(serverMetafile), + BuildOutputFileType.Root, + ); + } + } + + if (!jsonLogs && !options.quiet) { + const changedFiles = + rebuildState && executionResult.findChangedFiles(rebuildState.previousOutputInfo); + executionResult.addLog( + logBuildStats( + metafiles, + outputFiles, + initialFiles, + budgetFailures, + colors, + changedFiles, + estimatedTransferSizes, + !!ssrOptions, + verbose, + ), + ); + } + + return executionResult; + } catch (error) { + await Promise.allSettled([angularCompilationContext?.dispose(), executionResult?.dispose()]); + + throw error; + } +} diff --git a/packages/angular/build/src/builders/application/execute-post-bundle.ts b/packages/angular/build/src/builders/application/execute-post-bundle.ts new file mode 100644 index 000000000000..99e23bcb30c9 --- /dev/null +++ b/packages/angular/build/src/builders/application/execute-post-bundle.ts @@ -0,0 +1,266 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import assert from 'node:assert'; +import { + type BuildOutputAsset, + type PrerenderedRoutesRecord, +} from '../../tools/esbuild/bundler-execution-result'; +import { + type BuildOutputFile, + BuildOutputFileType, + type InitialFileRecord, + createOutputFile, +} from '../../tools/esbuild/bundler-files'; +import { maxWorkers } from '../../utils/environment-options'; +import { + SERVER_APP_MANIFEST_FILENAME, + generateAngularServerAppManifest, +} from '../../utils/server-rendering/manifest'; +import { WritableSerializableRouteTreeNode } from '../../utils/server-rendering/models'; +import { prerenderPages } from '../../utils/server-rendering/prerender'; +import { augmentAppWithServiceWorkerEsbuild } from '../../utils/service-worker'; +import { generateIndexHtml } from './index-html-generator'; +import { injectDebugIds } from './inject-debug-ids'; +import { INDEX_HTML_CSR, INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options'; +import { OutputMode } from './schema'; + +/** + * Run additional builds steps including SSG, AppShell, Index HTML file and Service worker generation. + * @param browserMetafile An esbuild metafile object. + * @param options The normalized application builder options used to create the build. + * @param outputFiles The output files of an executed build. + * @param assetFiles The assets of an executed build. + * @param initialFiles A map containing initial file information for the executed build. + * @param locale A language locale to insert in the index.html. + */ +// eslint-disable-next-line max-lines-per-function +export async function executePostBundleSteps( + browserMetafile: Metafile, + options: NormalizedApplicationBuildOptions, + outputFiles: BuildOutputFile[], + assetFiles: BuildOutputAsset[], + initialFiles: Map, + locale: string | undefined, +): Promise<{ + errors: string[]; + warnings: string[]; + additionalOutputFiles: BuildOutputFile[]; + additionalAssets: BuildOutputAsset[]; + prerenderedRoutes: PrerenderedRoutesRecord; +}> { + const additionalAssets: BuildOutputAsset[] = []; + const additionalOutputFiles: BuildOutputFile[] = []; + const allErrors: string[] = []; + const allWarnings: string[] = []; + const prerenderedRoutes: PrerenderedRoutesRecord = {}; + + const { + baseHref = '/', + serviceWorker, + ssrOptions, + indexHtmlOptions, + optimizationOptions, + sourcemapOptions, + outputMode, + serverEntryPoint, + prerenderOptions, + appShellOptions, + publicPath, + workspaceRoot, + partialSSRBuild, + } = options; + + // Embed ECMA-426 Debug IDs into JS/source-map pairs before any consumer reads the bytes (in + // particular `generateIndexHtml` below, which computes SRI hashes from the on-disk content). + // Doing this here also covers the i18n path, where this function is invoked once per locale + // with locale-specific output files. Files without a source map sibling are skipped. + if (sourcemapOptions.scripts) { + injectDebugIds(outputFiles); + } + + // Index HTML content without CSS inlining to be used for server rendering (AppShell, SSG and SSR). + // NOTE: Critical CSS inlining is deliberately omitted here, as it will be handled during server rendering. + // Additionally, when using prerendering or AppShell, the index HTML file may be regenerated. + // To prevent generating duplicate files with the same filename, a `Map` is used to store and manage the files. + const additionalHtmlOutputFiles = new Map(); + + // Generate index HTML file + // If localization is enabled, index generation is handled in the inlining process. + if (indexHtmlOptions) { + const { csrContent, ssrContent, errors, warnings } = await generateIndexHtml( + initialFiles, + outputFiles, + options, + locale, + ); + + allErrors.push(...errors); + allWarnings.push(...warnings); + + additionalHtmlOutputFiles.set( + indexHtmlOptions.output, + createOutputFile(indexHtmlOptions.output, csrContent, BuildOutputFileType.Browser), + ); + + if (ssrContent) { + additionalHtmlOutputFiles.set( + INDEX_HTML_SERVER, + createOutputFile(INDEX_HTML_SERVER, ssrContent, BuildOutputFileType.ServerApplication), + ); + } + } + + // Create server manifest + const initialFilesPaths = new Set(initialFiles.keys()); + if (serverEntryPoint && (outputMode || prerenderOptions || appShellOptions || ssrOptions)) { + const { manifestContent, serverAssetsChunks } = await generateAngularServerAppManifest( + additionalHtmlOutputFiles, + outputFiles, + optimizationOptions.styles.inlineCritical ?? false, + undefined, + locale, + baseHref, + initialFilesPaths, + browserMetafile, + publicPath, + ); + + additionalOutputFiles.push( + ...serverAssetsChunks, + createOutputFile( + SERVER_APP_MANIFEST_FILENAME, + manifestContent, + BuildOutputFileType.ServerApplication, + ), + ); + } + + // Pre-render (SSG) and App-shell + // If localization is enabled, prerendering is handled in the inlining process. + if ( + !partialSSRBuild && + (prerenderOptions || appShellOptions || (outputMode && serverEntryPoint)) && + !allErrors.length + ) { + assert( + indexHtmlOptions, + 'The "index" option is required when using the "ssg" or "appShell" options.', + ); + + const { + output, + warnings, + errors, + serializableRouteTreeNode, + prerenderedRoutes: generatedPrerenderedRoutes, + } = await prerenderPages( + workspaceRoot, + baseHref, + appShellOptions, + prerenderOptions, + [...outputFiles, ...additionalOutputFiles], + assetFiles, + outputMode, + sourcemapOptions.scripts, + maxWorkers, + ); + + allErrors.push(...errors); + allWarnings.push(...warnings); + Object.assign(prerenderedRoutes, generatedPrerenderedRoutes); + + const indexHasBeenPrerendered = output[indexHtmlOptions.output]; + for (const [path, { content, appShellRoute }] of Object.entries(output)) { + // Update the index contents with the app shell under these conditions: + // - Replace 'index.html' with the app shell only if it hasn't been prerendered yet. + // - Always replace 'index.csr.html' with the app shell. + let filePath = path; + if (appShellRoute && !indexHasBeenPrerendered) { + if (outputMode !== OutputMode.Server && indexHtmlOptions.output === INDEX_HTML_CSR) { + filePath = 'index.html'; + } else { + filePath = indexHtmlOptions.output; + } + } + + additionalHtmlOutputFiles.set( + filePath, + createOutputFile(filePath, content, BuildOutputFileType.Browser), + ); + } + + const serializableRouteTreeNodeForManifest: WritableSerializableRouteTreeNode = []; + for (const metadata of serializableRouteTreeNode) { + serializableRouteTreeNodeForManifest.push(metadata); + } + + if (outputMode === OutputMode.Server) { + // Regenerate the manifest to append route tree. This is only needed if SSR is enabled. + const manifest = additionalOutputFiles.find((f) => f.path === SERVER_APP_MANIFEST_FILENAME); + assert(manifest, `${SERVER_APP_MANIFEST_FILENAME} was not found in output files.`); + + const { manifestContent, serverAssetsChunks } = await generateAngularServerAppManifest( + additionalHtmlOutputFiles, + outputFiles, + optimizationOptions.styles.inlineCritical ?? false, + serializableRouteTreeNodeForManifest, + locale, + baseHref, + initialFilesPaths, + browserMetafile, + publicPath, + ); + + for (const chunk of serverAssetsChunks) { + const idx = additionalOutputFiles.findIndex(({ path }) => path === chunk.path); + if (idx === -1) { + additionalOutputFiles.push(chunk); + } else { + additionalOutputFiles[idx] = chunk; + } + } + + manifest.contents = new TextEncoder().encode(manifestContent); + } + } + + additionalOutputFiles.push(...additionalHtmlOutputFiles.values()); + + // Augment the application with service worker support + // If localization is enabled, service worker is handled in the inlining process. + if (serviceWorker) { + try { + const serviceWorkerResult = await augmentAppWithServiceWorkerEsbuild( + workspaceRoot, + serviceWorker, + baseHref, + options.indexHtmlOptions?.output, + // Ensure additional files recently added are used + [...outputFiles, ...additionalOutputFiles], + assetFiles, + ); + + additionalOutputFiles.push( + createOutputFile('ngsw.json', serviceWorkerResult.manifest, BuildOutputFileType.Browser), + ); + additionalAssets.push(...serviceWorkerResult.assetFiles); + } catch (error) { + allErrors.push(error instanceof Error ? error.message : `${error}`); + } + } + + return { + errors: allErrors, + warnings: allWarnings, + additionalAssets, + prerenderedRoutes, + additionalOutputFiles, + }; +} diff --git a/packages/angular/build/src/builders/application/i18n.ts b/packages/angular/build/src/builders/application/i18n.ts new file mode 100644 index 000000000000..839384421f1f --- /dev/null +++ b/packages/angular/build/src/builders/application/i18n.ts @@ -0,0 +1,244 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import type { Metafile } from 'esbuild'; +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { + ExecutionResult, + PrerenderedRoutesRecord, +} from '../../tools/esbuild/bundler-execution-result'; +import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-files'; +import { I18nInliner } from '../../tools/i18n'; +import { maxInlinerWorkers } from '../../utils/environment-options'; +import { loadTranslations } from '../../utils/i18n-options'; +import { createTranslationLoader } from '../../utils/load-translations'; +import { createProjectResolver } from '../../utils/resolve-project'; +import type { WorkerPool } from '../../utils/worker-pool'; +import { executePostBundleSteps } from './execute-post-bundle'; +import { NormalizedApplicationBuildOptions, getLocaleBaseHref } from './options'; + +/** + * Inlines all active locales as specified by the application build options into all + * application JavaScript files created during the build. + * @param metafile An esbuild metafile object. + * @param options The normalized application builder options used to create the build. + * @param executionResult The result of an executed build. + * @param initialFiles A map containing initial file information for the executed build. + * @param workerPool An optional worker pool to use for running transformation tasks. + */ +export async function inlineI18n( + metafile: Metafile, + options: NormalizedApplicationBuildOptions, + executionResult: ExecutionResult, + initialFiles: Map, + workerPool?: WorkerPool, +): Promise<{ + errors: string[]; + warnings: string[]; + prerenderedRoutes: PrerenderedRoutesRecord; +}> { + const { i18nOptions, baseHref, cacheOptions } = options; + + // Create the multi-threaded inliner with common options. + const inliner = new I18nInliner( + { + missingTranslation: i18nOptions.missingTranslationBehavior ?? 'warning', + maxConcurrency: workerPool + ? Math.min(workerPool.maxThreads, maxInlinerWorkers) + : maxInlinerWorkers, + persistentCachePath: cacheOptions.enabled ? cacheOptions.path : undefined, + localizeVersion: i18nOptions.localizeVersion, + }, + workerPool, + ); + + const inlineResult: { + errors: string[]; + warnings: string[]; + prerenderedRoutes: PrerenderedRoutesRecord; + } = { + errors: [], + warnings: [], + prerenderedRoutes: {}, + }; + + // For each active locale, use the inliner to process the output files of the build. + const updatedOutputFiles = []; + const updatedAssetFiles = []; + // Root and SSR entry files are not modified. + const unModifiedOutputFiles = executionResult.outputFiles.filter( + ({ type }) => type === BuildOutputFileType.Root || type === BuildOutputFileType.ServerRoot, + ); + + try { + const localesToInline = Array.from(i18nOptions.inlineLocales, (locale) => { + const localeDescription = i18nOptions.locales[locale]; + let translationIntegrity: string | undefined = ''; + for (const file of localeDescription.files) { + if (!file.integrity) { + translationIntegrity = undefined; + break; + } + translationIntegrity += (translationIntegrity ? '|' : '') + file.integrity; + } + + return { + locale, + translation: localeDescription.translation, + translationIntegrity, + }; + }); + + const inlinedLocales = await inliner.inlineAll(executionResult.outputFiles, localesToInline); + + for (const locale of i18nOptions.inlineLocales) { + const localeInlineResult = inlinedLocales.get(locale); + assert(localeInlineResult !== undefined, 'Inlined result must exist for locale: ' + locale); + const localeOutputFiles = localeInlineResult.outputFiles; + inlineResult.errors.push(...localeInlineResult.errors); + inlineResult.warnings.push(...localeInlineResult.warnings); + + const { + errors, + warnings, + additionalAssets, + additionalOutputFiles, + prerenderedRoutes: generatedRoutes, + } = await executePostBundleSteps( + metafile, + { + ...options, + baseHref: getLocaleBaseHref(baseHref, i18nOptions, locale) ?? baseHref, + }, + [...unModifiedOutputFiles, ...localeOutputFiles], + executionResult.assetFiles, + initialFiles, + locale, + ); + + localeOutputFiles.push(...additionalOutputFiles); + inlineResult.errors.push(...errors); + inlineResult.warnings.push(...warnings); + + // Update directory with locale base or subPath + const subPath = i18nOptions.locales[locale].subPath; + if (i18nOptions.flatOutput !== true) { + localeOutputFiles.forEach((file) => { + file.path = join(subPath, file.path); + }); + + for (const assetFile of [...executionResult.assetFiles, ...additionalAssets]) { + updatedAssetFiles.push({ + source: assetFile.source, + destination: join(subPath, assetFile.destination), + }); + } + } else { + executionResult.assetFiles.push(...additionalAssets); + } + + inlineResult.prerenderedRoutes = { ...inlineResult.prerenderedRoutes, ...generatedRoutes }; + updatedOutputFiles.push(...localeOutputFiles); + } + + // Update the result with all localized files. + executionResult.outputFiles = [ + // Root and SSR entry files are not modified. + ...unModifiedOutputFiles, + // Updated files for each locale. + ...updatedOutputFiles, + ]; + + // Assets are only changed if not using the flat output option + if (!i18nOptions.flatOutput) { + executionResult.assetFiles = updatedAssetFiles; + } + + // Inline any template updates if present + if (executionResult.templateUpdates?.size) { + // The development server only allows a single locale but issue a warning if used programmatically (experimental) + // with multiple locales and template HMR. + if (localesToInline.length > 1) { + inlineResult.warnings.push( + `Component HMR updates can only be inlined with a single locale. The first locale will be used.`, + ); + } + const targetLocale = localesToInline[0]; + + for (const [id, content] of executionResult.templateUpdates) { + const templateUpdateResult = await inliner.inlineTemplateUpdate( + targetLocale.locale, + targetLocale.translation, + content, + id, + targetLocale.translationIntegrity, + ); + executionResult.templateUpdates.set(id, templateUpdateResult.code); + inlineResult.errors.push(...templateUpdateResult.errors); + inlineResult.warnings.push(...templateUpdateResult.warnings); + } + } + + return inlineResult; + } finally { + await inliner.close(); + } +} + +/** + * Loads all active translations using the translation loaders from the `@angular/localize` package. + * @param context The architect builder context for the current build. + * @param i18n The normalized i18n options to use. + */ +export async function loadActiveTranslations( + context: BuilderContext, + i18n: NormalizedApplicationBuildOptions['i18nOptions'], +) { + if (!i18n.localizeVersion) { + try { + const projectResolve = createProjectResolver(context.workspaceRoot); + const manifestPath = projectResolve('@angular/localize/package.json'); + const manifest = JSON.parse(await readFile(manifestPath, 'utf-8')) as { version?: string }; + i18n.localizeVersion = manifest.version; + } catch {} + } + + // Load locale data and translations (if present) + let loader; + for (const [locale, desc] of Object.entries(i18n.locales)) { + if (!i18n.inlineLocales.has(locale) && locale !== i18n.sourceLocale) { + continue; + } + + if (!desc.files.length) { + continue; + } + + loader ??= await createTranslationLoader(); + + loadTranslations( + locale, + desc, + context.workspaceRoot, + loader, + { + warn(message) { + context.logger.warn(message); + }, + error(message) { + throw new Error(message); + }, + }, + undefined, + i18n.duplicateTranslationBehavior, + ); + } +} diff --git a/packages/angular/build/src/builders/application/index-html-generator.ts b/packages/angular/build/src/builders/application/index-html-generator.ts new file mode 100644 index 000000000000..a1c9cbcc9b30 --- /dev/null +++ b/packages/angular/build/src/builders/application/index-html-generator.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { createHash } from 'node:crypto'; +import path from 'node:path'; +import { + BuildOutputFile, + BuildOutputFileType, + InitialFileRecord, +} from '../../tools/esbuild/bundler-files'; +import { IndexHtmlGenerator } from '../../utils/index-file/index-html-generator'; +import { NormalizedApplicationBuildOptions } from './options'; + +/** + * The maximum number of module preload link elements that should be added for + * initial scripts. + */ +const MODULE_PRELOAD_MAX = 10; + +export async function generateIndexHtml( + initialFiles: Map, + outputFiles: BuildOutputFile[], + buildOptions: NormalizedApplicationBuildOptions, + lang?: string, +): Promise<{ + csrContent: string; + ssrContent?: string; + warnings: string[]; + errors: string[]; +}> { + // Analyze metafile for initial link-based hints. + // Skip if the internal externalPackages option is enabled since this option requires + // dev server cooperation to properly resolve and fetch imports. + const hints = []; + const { + indexHtmlOptions, + externalPackages, + optimizationOptions, + crossOrigin, + subresourceIntegrity, + baseHref, + } = buildOptions; + + assert(indexHtmlOptions, 'indexHtmlOptions cannot be undefined.'); + + if (!externalPackages && indexHtmlOptions.preloadInitial) { + const modulePreloads = []; + for (const [key, value] of initialFiles) { + if (value.entrypoint || value.serverFile) { + // Entry points are already referenced in the HTML + continue; + } + + if (value.type === 'script') { + modulePreloads.push({ url: key, mode: 'modulepreload' as const, depth: value.depth }); + } else if (value.type === 'style') { + // Provide an "as" value of "style" to ensure external URLs which may not have a + // file extension are treated as stylesheets. + hints.push({ url: key, mode: 'preload' as const, as: 'style' }); + } + } + + // Limit the number of module preloads with smallest depth given priority + modulePreloads.sort((a, b) => a.depth - b.depth); + hints.push(...modulePreloads.slice(0, MODULE_PRELOAD_MAX)); + } + + /** Virtual output path to support reading in-memory files. */ + const browserOutputFiles = outputFiles.filter(({ type }) => type === BuildOutputFileType.Browser); + const virtualOutputPath = '/'; + const readAsset = async function (filePath: string): Promise { + // Remove leading directory separator + const relativefilePath = path.relative(virtualOutputPath, filePath); + const file = browserOutputFiles.find((file) => file.path === relativefilePath); + if (file) { + return file.text; + } + + throw new Error(`Output file does not exist: ${relativefilePath}`); + }; + + // When SRI is enabled, build an integrity map for every browser JavaScript + // chunk so an `', + ); + indexFileContent.toContain(' { + describe('Behavior: "Esbuild for-await"', () => { + it('should properly downlevel for-await loops with optimization enabled', async () => { + // Setup a for-await loop that triggers the esbuild minification bug when async/await is downleveled. + await harness.writeFile( + 'src/main.ts', + ` + async function test() { + const someAsyncIterable = { + [Symbol.asyncIterator]() { + return { + next() { + return Promise.resolve({ done: true, value: undefined }); + } + }; + } + }; + for await(const item of someAsyncIterable) { + console.log(item); + } + } + test(); + `, + ); + + // Ensure target is ES2022 so that optional catch binding is supported natively. + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.compilerOptions.target = 'ES2022'; + return JSON.stringify(tsConfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + polyfills: ['zone.js'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + // We expect the output to contain a catch block that captures the error in a variable, + // even if that variable is mangled. + // The pattern for the downleveled for-await catch block is roughly: + // } catch (temp) { error = [temp]; } + // + // With the bug, esbuild (when minifying) would optimize away the catch binding if it thought it was unused, + // resulting in: } catch { ... } which breaks the logic requiring the error object. + // + // The regex matches: + // catch \s* -> catch keyword and whitespace + // \( [a-zA-Z_$][\w$]* \) -> (variable) + // \s* { \s* -> { and whitespace + // [a-zA-Z_$][\w$]* -> error array variable + // \s* = \s* -> assignment + // \[ [a-zA-Z_$][\w$]* \] -> [variable] + harness + .expectFile('dist/browser/main.js') + .content.toMatch( + /catch\s*\([a-zA-Z_$][\w$]*\)\s*\{\s*[a-zA-Z_$][\w$]*\s*=\s*\[[a-zA-Z_$][\w$]*\]/, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/index-csr_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/index-csr_spec.ts new file mode 100644 index 000000000000..0f87dd78a289 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/index-csr_spec.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "index.csr.html"', () => { + beforeEach(async () => { + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('main.server.ts'); + + return JSON.stringify(tsConfig); + }); + }); + + it(`should generate 'index.csr.html' instead of 'index.html' when ssr is enabled.`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + ssr: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectDirectory('dist/server').toExist(); + harness.expectFile('dist/browser/index.csr.html').toExist(); + harness.expectFile('dist/browser/index.html').toNotExist(); + }); + + it(`should generate 'index.csr.html' instead of 'index.html' when 'output' is 'index.html' and ssr is enabled.`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + index: { + input: 'src/index.html', + output: 'index.html', + }, + server: 'src/main.server.ts', + ssr: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectDirectory('dist/server').toExist(); + harness.expectFile('dist/browser/index.csr.html').toExist(); + harness.expectFile('dist/browser/index.html').toNotExist(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/index-preload-hints_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/index-preload-hints_spec.ts new file mode 100644 index 000000000000..7f6b9711790b --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/index-preload-hints_spec.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Preload hints"', () => { + it('should add preload hints for transitive global style imports', async () => { + await harness.writeFile( + 'src/styles.css', + ` + @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Roboto:wght@300;400;500;700&display=swap'); + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + harness + .expectFile('dist/browser/index.html') + .content.toContain( + '', + ); + }); + + it('should not add preload hints for ssr files', async () => { + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('main.server.ts'); + + return JSON.stringify(tsConfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + ssr: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/server/main.server.mjs').toExist(); + + harness + .expectFile('dist/browser/index.csr.html') + .content.not.toMatch(//); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts new file mode 100644 index 000000000000..91c4cafc571a --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts @@ -0,0 +1,183 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "loader import attribute"', () => { + beforeEach(async () => { + await harness.modifyFile('tsconfig.json', (content) => { + return content.replace('"module": "ES2022"', '"module": "esnext"'); + }); + }); + + it('should inline text content for loader attribute set to "text"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "text" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('ABC'); + }); + + it('should inline binary content for loader attribute set to "binary"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "binary" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + // Should contain the binary encoding used esbuild and not the text content + harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")'); + harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); + }); + + it('should inline base64 content for file extension set to "base64"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "base64" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + // Should contain the base64 encoding used esbuild and not the text content + harness.expectFile('dist/browser/main.js').content.toContain('QUJD'); + harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); + }); + + it('should inline dataurl content for file extension set to "dataurl"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.svg', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.svg" with { loader: "dataurl" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + // Should contain the dataurl encoding used esbuild and not the text content + harness.expectFile('dist/browser/main.js').content.toContain('data:image/svg+xml,ABC'); + }); + + it('should emit an output file for loader attribute set to "file"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); + harness.expectFile('dist/browser/media/a.unknown').toExist(); + }); + + it('should emit an output file with hashing when enabled for loader attribute set to "file"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + outputHashing: 'media' as any, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); + expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue(); + }); + + it('should allow overriding default `.txt` extension behavior', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.txt', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.txt" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.txt'); + harness.expectFile('dist/browser/media/a.txt').toExist(); + }); + + it('should allow overriding default `.js` extension behavior', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.js', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.js" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.js'); + harness.expectFile('dist/browser/media/a.js').toExist(); + }); + + it('should fail with an error if an invalid loader attribute value is used', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "invalid" };\n console.log(contents);', + ); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Unsupported loader import attribute'), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/platform-server-domino_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/platform-server-domino_spec.ts new file mode 100644 index 000000000000..df58f1c833c0 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/platform-server-domino_spec.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { OutputMode, Platform } from '../../schema'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * `@angular/platform-server/init` (bundled into the server polyfills) and + * `@angular/platform-server` (bundled into the main server bundle) both import this file. + */ +const DOMINO_BUNDLE = 'third_party/domino/bundled-domino.mjs'; + +/** The property on globalThis where the Domino instance is stored. */ +const DOMINO_GLOBAL_PROPERTY = /(?:ɵ|\\u0275)domino/; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Domino is bundled once for the server"', () => { + beforeEach(async () => { + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('main.server.ts', 'server.ts'); + + return JSON.stringify(tsConfig); + }); + + await harness.writeFile('src/server.ts', `console.log('Hello!');`); + + // The default template uses i18n which requires `@angular/localize` to prerender. + await harness.writeFile('src/app/app.component.html', `

Hello!

`); + }); + + it('shares the server polyfills copy of Domino with the main server bundle', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + ssr: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/server/polyfills.server.mjs').content.toContain(DOMINO_BUNDLE); + harness + .expectFile('dist/server/polyfills.server.mjs') + .content.toMatch(DOMINO_GLOBAL_PROPERTY); + + harness.expectFile('dist/server/main.server.mjs').content.not.toContain(DOMINO_BUNDLE); + harness.expectFile('dist/server/main.server.mjs').content.toMatch(DOMINO_GLOBAL_PROPERTY); + }); + + it('shares the server polyfills copy of Domino when "outputMode" is "server"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + ssr: { entry: 'src/server.ts' }, + outputMode: OutputMode.Server, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/server/polyfills.server.mjs').content.toContain(DOMINO_BUNDLE); + harness.expectFile('dist/server/main.server.mjs').content.not.toContain(DOMINO_BUNDLE); + harness.expectFile('dist/server/main.server.mjs').content.toMatch(DOMINO_GLOBAL_PROPERTY); + harness.expectFile('dist/server/server.mjs').content.not.toContain(DOMINO_BUNDLE); + }); + + it('shares the server polyfills copy of Domino when "ssr.platform" is "neutral"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + ssr: { entry: 'src/server.ts', platform: Platform.Neutral }, + outputMode: OutputMode.Server, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/server/polyfills.server.mjs').content.toContain(DOMINO_BUNDLE); + harness + .expectFile('dist/server/polyfills.server.mjs') + .content.toMatch(DOMINO_GLOBAL_PROPERTY); + harness.expectFile('dist/server/main.server.mjs').content.not.toContain(DOMINO_BUNDLE); + harness.expectFile('dist/server/main.server.mjs').content.toMatch(DOMINO_GLOBAL_PROPERTY); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-assets_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-assets_spec.ts new file mode 100644 index 000000000000..04610625eb09 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-assets_spec.ts @@ -0,0 +1,148 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { rename } from 'node:fs/promises'; +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when input asset changes"', () => { + beforeEach(async () => { + // Application code is not needed for styles tests + await harness.writeFile('src/main.ts', 'console.log("TEST");'); + await harness.writeFile('public/asset.txt', 'foo'); + }); + + it('emits updated asset', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*', + input: 'public', + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').content.toContain('foo'); + + await harness.writeFile('public/asset.txt', 'bar'); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').content.toContain('bar'); + }, + ]); + }); + + it('emits an asset replaced by renaming another file over it', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*', + input: 'public', + }, + ], + watch: true, + // Polling reports a replaced file as modified, while native watchers can report it as added. + poll: undefined, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').content.toContain('foo'); + + // Editors with atomic save write a temporary file and rename it over the original. + await harness.writeFile('asset.txt.tmp', 'bar'); + await rename( + harness.resolvePath('asset.txt.tmp'), + harness.resolvePath('public/asset.txt'), + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').content.toContain('bar'); + }, + ]); + }); + + it('remove deleted asset from output', async () => { + await Promise.all([ + harness.writeFile('public/asset-two.txt', 'bar'), + harness.writeFile('public/asset-one.txt', 'foo'), + ]); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*', + input: 'public', + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset-one.txt').toExist(); + harness.expectFile('dist/browser/asset-two.txt').toExist(); + + await harness.removeFile('public/asset-two.txt'); + }, + + ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset-one.txt').toExist(); + harness.expectFile('dist/browser/asset-two.txt').toNotExist(); + }, + ]); + }); + + it('remove all outputs of a deleted asset copied to multiple destinations', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*', + input: 'public', + }, + { + glob: '**/*', + input: 'public', + output: 'static', + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').toExist(); + harness.expectFile('dist/browser/static/asset.txt').toExist(); + + await harness.removeFile('public/asset.txt'); + }, + + ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/asset.txt').toNotExist(); + harness.expectFile('dist/browser/static/asset.txt').toNotExist(); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-component_styles_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-component_styles_spec.ts new file mode 100644 index 000000000000..08b683439684 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-component_styles_spec.ts @@ -0,0 +1,142 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * Maximum time in milliseconds for single build/rebuild + * This accounts for CI variability. + */ +export const BUILD_TIMEOUT = 30_000; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when component stylesheets change"', () => { + for (const aot of [true, false]) { + it(`updates component when imported sass changes with ${aot ? 'AOT' : 'JIT'}`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + aot, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('app.component.css', 'app.component.scss'), + ); + await harness.writeFile('src/app/app.component.scss', "@import './a';"); + await harness.writeFile('src/app/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.toContain('color: aqua'); + harness.expectFile('dist/browser/main.js').content.not.toContain('color: blue'); + + await harness.writeFile('src/app/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/main.js').content.toContain('color: blue'); + + await harness.writeFile('src/app/a.scss', '$primary: green;\\nh1 { color: $primary; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/main.js').content.not.toContain('color: blue'); + harness.expectFile('dist/browser/main.js').content.toContain('color: green'); + }, + ]); + }); + } + + it('rebuilds component after error on rebuild from transitive import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('app.component.css', 'app.component.scss'), + ); + await harness.writeFile('src/app/app.component.scss', "@import './a';"); + await harness.writeFile('src/app/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.toContain('color: aqua'); + + // Introduce a syntax error + await harness.writeFile( + 'src/app/a.scss', + 'invalid-invalid-invalid\\nh1 { color: $primary; }', + ); + }, + async ({ result }) => { + expect(result?.success).toBe(false); + + // Fix the syntax error + await harness.writeFile('src/app/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.toContain('color: blue'); + }, + ]); + }); + + it('rebuilds component after error on rebuild from deep transitive import with partials', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('app.component.css', 'app.component.scss'), + ); + await harness.writeFile('src/app/app.component.scss', "@import './intermediary';"); + await harness.writeFile('src/app/_intermediary.scss', "@import './partial';"); + await harness.writeFile('src/app/_partial.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.toContain('color: aqua'); + + // Introduce a syntax error deeply + await harness.writeFile( + 'src/app/_partial.scss', + 'invalid-invalid-invalid\\nh1 { color: $primary; }', + ); + }, + async ({ result }) => { + expect(result?.success).toBe(false); + + // Fix the syntax error deeply + await harness.writeFile( + 'src/app/_partial.scss', + '$primary: blue;\\nh1 { color: $primary; }', + ); + }, + ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/browser/main.js').content.toContain('color: blue'); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts new file mode 100644 index 000000000000..5e7bdeb3fd9c --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts @@ -0,0 +1,470 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuild Error Detection"', () => { + it('detects template errors with no AOT codegen or TS emit differences', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + const goodDirectiveContents = ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir { + @Input() foo!: number; + } + `; + + const typeErrorText = `Type 'number' is not assignable to type 'string'.`; + + // Create a directive and add to application + await harness.writeFile('src/app/dir.ts', goodDirectiveContents); + await harness.writeFile( + 'src/app/app.module.ts', + ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AppComponent } from './app.component'; + import { Dir } from './dir'; + @NgModule({ + declarations: [ + AppComponent, + Dir, + ], + imports: [ + BrowserModule + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + ); + + // Create app component that uses the directive + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core' + @Component({ + selector: 'app-root', + standalone: false, + template: '', + }) + export class AppComponent { } + `, + ); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Update directive to use a different input type for 'foo' (number -> string) + // Should cause a template error + await harness.writeFile( + 'src/app/dir.ts', + ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir { + @Input() foo: string; + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, typeErrorText); + + // Make an unrelated change to verify error cache was updated + // Should persist error in the next rebuild + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, typeErrorText); + + // Revert the directive change that caused the error + // Should remove the error + await harness.writeFile('src/app/dir.ts', goodDirectiveContents); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, typeErrorText); + + // Make an unrelated change to verify error cache was updated + // Should continue showing no error + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, typeErrorText); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('detects template errors across components on watch rebuild when isolatedModules is enabled', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions = { + ...tsconfig.compilerOptions, + isolatedModules: true, + }; + + return JSON.stringify(tsconfig); + }); + + const goodChildComponentContents = ` + import { Component, Input } from '@angular/core'; + @Component({ + selector: 'child', + standalone: true, + template: '

{{ value }}

', + }) + export class ChildComponent { + @Input() value!: number; + } + `; + + const typeErrorText = `Type 'number' is not assignable to type 'string'.`; + + await harness.writeFiles({ + 'src/app/child.component.ts': goodChildComponentContents, + 'src/app/app.module.ts': ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AppComponent } from './app.component'; + @NgModule({ + imports: [ + BrowserModule, + AppComponent, + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + 'src/app/app.component.ts': ` + import { Component } from '@angular/core'; + import { ChildComponent } from './child.component'; + @Component({ + selector: 'app-root', + standalone: true, + imports: [ChildComponent], + template: '', + }) + export class AppComponent {} + `, + }); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Update child component to change input type from number to string + await harness.writeFile( + 'src/app/child.component.ts', + ` + import { Component, Input } from '@angular/core'; + @Component({ + selector: 'child', + standalone: true, + template: '

{{ value }}

', + }) + export class ChildComponent { + @Input() value!: string; + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, typeErrorText); + + // Make an unrelated change to verify error persists + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, typeErrorText); + + // Revert back to number + await harness.writeFile('src/app/child.component.ts', goodChildComponentContents); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, typeErrorText); + + // Make an unrelated change to verify error cache cleared + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, typeErrorText); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('detects template errors when an input becomes required or a selector is renamed on watch rebuild', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions = { + ...tsconfig.compilerOptions, + isolatedModules: true, + }; + + return JSON.stringify(tsconfig); + }); + + const goodChildComponentContents = ` + import { Component, input } from '@angular/core'; + @Component({ + selector: 'app-child', + standalone: true, + template: '

{{ label() }}

', + }) + export class ChildComponent { + label = input(''); + } + `; + + const requiredInputErrorText = `Required input 'label' from component ChildComponent must be specified.`; + const unknownElementErrorText = `'app-child' is not a known element`; + + await harness.writeFiles({ + 'src/app/child.component.ts': goodChildComponentContents, + 'src/app/app.module.ts': ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AppComponent } from './app.component'; + @NgModule({ + imports: [ + BrowserModule, + AppComponent, + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + 'src/app/app.component.ts': ` + import { Component } from '@angular/core'; + import { ChildComponent } from './child.component'; + @Component({ + selector: 'app-root', + standalone: true, + imports: [ChildComponent], + template: '', + }) + export class AppComponent {} + `, + }); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Make input required using signal input.required() (which has the same TS .d.ts type InputSignal) + await harness.writeFile( + 'src/app/child.component.ts', + ` + import { Component, input } from '@angular/core'; + @Component({ + selector: 'app-child', + standalone: true, + template: '

{{ label() }}

', + }) + export class ChildComponent { + label = input.required(); + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, requiredInputErrorText); + + // Revert required input and rename selector instead + await harness.writeFile( + 'src/app/child.component.ts', + ` + import { Component, input } from '@angular/core'; + @Component({ + selector: 'app-child-renamed', + standalone: true, + template: '

{{ label() }}

', + }) + export class ChildComponent { + label = input(''); + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectNoLog(logs, requiredInputErrorText); + expectLog(logs, unknownElementErrorText); + + // Revert back to valid child component + await harness.writeFile('src/app/child.component.ts', goodChildComponentContents); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, requiredInputErrorText); + expectNoLog(logs, unknownElementErrorText); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('detects cumulative block syntax errors', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases( + [ + async () => { + // Add invalid block syntax + await harness.appendToFile('src/app/app.component.html', '@if-one'); + }, + async ({ logs }) => { + expectLog(logs, '@if-one'); + + // Make an unrelated change to verify error cache was updated + // Should persist error in the next rebuild + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ logs }) => { + expectLog(logs, '@if-one'); + + // Add more invalid block syntax + await harness.appendToFile('src/app/app.component.html', '@if-two'); + }, + async ({ logs }) => { + expectLog(logs, '@if-one'); + expectLog(logs, '@if-two'); + + // Add more invalid block syntax + await harness.appendToFile('src/app/app.component.html', '@if-three'); + }, + async ({ logs }) => { + expectLog(logs, '@if-one'); + expectLog(logs, '@if-two'); + expectLog(logs, '@if-three'); + + // Revert the changes that caused the error + // Should remove the error + await harness.writeFile('src/app/app.component.html', '

GOOD

'); + }, + ({ logs }) => { + expectNoLog(logs, '@if-one'); + expectNoLog(logs, '@if-two'); + expectNoLog(logs, '@if-three'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('recovers from component stylesheet error', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + aot: false, + }); + + await harness.executeWithCases( + [ + async () => { + await harness.writeFile('src/app/app.component.css', 'invalid-css-content'); + }, + async ({ logs }) => { + expectLog(logs, 'invalid-css-content'); + + await harness.writeFile('src/app/app.component.css', 'p { color: green }'); + }, + ({ logs }) => { + expectNoLog(logs, 'invalid-css-content'); + + harness + .expectFile('dist/browser/main.js') + .content.toContain('p {\\n color: green;\\n}'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('recovers from component template error', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases( + [ + async () => { + // Missing ending `>` on the div will cause an error + await harness.appendToFile('src/app/app.component.html', '
Hello, world! { + expectLog(logs, 'Unexpected character "EOF"'); + + await harness.appendToFile('src/app/app.component.html', '>'); + }, + async ({ logs }) => { + expectNoLog(logs, 'Unexpected character "EOF"'); + + harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); + + // Make an additional valid change to ensure that rebuilds still trigger + await harness.appendToFile('src/app/app.component.html', '
Guten Tag
'); + }, + ({ logs }) => { + expectNoLog(logs, 'Unexpected character "EOF"'); + + harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); + harness.expectFile('dist/browser/main.js').content.toContain('Guten Tag'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-general_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-general_spec.ts new file mode 100644 index 000000000000..d9ea8870f687 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-general_spec.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * Maximum time in milliseconds for single build/rebuild + * This accounts for CI variability. + */ +export const BUILD_TIMEOUT = 30_000; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuild updates in general cases"', () => { + it('detects changes after a file was deleted and recreated', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + const fileAContent = ` + console.log('FILE-A'); + export {}; + `; + + // Create a file and add to application + await harness.writeFile('src/app/file-a.ts', fileAContent); + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + import './file-a'; + @Component({ + selector: 'app-root', + standalone: false, + template: 'App component', + }) + export class AppComponent { } + `, + ); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/browser/main.js').content.toContain('FILE-A'); + + // Delete the imported file + await harness.removeFile('src/app/file-a.ts'); + }, + async ({ result }) => { + // Should fail from missing import + expect(result?.success).toBeFalse(); + + // Remove the failing import + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace(`import './file-a';`, ''), + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').content.not.toContain('FILE-A'); + + // Recreate the file and the import + await harness.writeFile('src/app/file-a.ts', fileAContent); + await harness.modifyFile( + 'src/app/app.component.ts', + (content) => `import './file-a';\n` + content, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').content.toContain('FILE-A'); + + // Change the imported file + await harness.modifyFile('src/app/file-a.ts', (content) => + content.replace('FILE-A', 'FILE-B'), + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').content.toContain('FILE-B'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-global_styles_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-global_styles_spec.ts new file mode 100644 index 000000000000..2de5c5f229ca --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-global_styles_spec.ts @@ -0,0 +1,250 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when global stylesheets change"', () => { + beforeEach(async () => { + // Application code is not needed for styles tests + await harness.writeFile('src/main.ts', 'console.log("TEST");'); + }); + + it('rebuilds Sass stylesheet after error on rebuild from import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + styles: ['src/styles.scss'], + }); + + await harness.writeFile('src/styles.scss', "@import './a';"); + await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); + + await harness.writeFile( + 'src/a.scss', + 'invalid-invalid-invalid\\nh1 { color: $primary; }', + ); + }, + async ({ result }) => { + expect(result?.success).toBe(false); + + await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('rebuilds Sass stylesheet after error on initial build from import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + styles: ['src/styles.scss'], + }); + + await harness.writeFile('src/styles.scss', "@import './a';"); + await harness.writeFile('src/a.scss', 'invalid-invalid-invalid\\nh1 { color: $primary; }'); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBe(false); + + await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); + + await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('rebuilds dependent Sass stylesheets after error on initial build from import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + styles: [ + { bundleName: 'styles', input: 'src/styles.scss' }, + { bundleName: 'other', input: 'src/other.scss' }, + ], + }); + + await harness.writeFile('src/styles.scss', "@import './a';"); + await harness.writeFile('src/other.scss', "@import './a'; h1 { color: green; }"); + await harness.writeFile('src/a.scss', 'invalid-invalid-invalid\\nh1 { color: $primary; }'); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBe(false); + + await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); + + harness.expectFile('dist/browser/other.css').content.toContain('color: green'); + harness.expectFile('dist/browser/other.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/other.css').content.not.toContain('color: blue'); + + await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); + + harness.expectFile('dist/browser/other.css').content.toContain('color: green'); + harness.expectFile('dist/browser/other.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/other.css').content.toContain('color: blue'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('rebuilds PostCSS stylesheet after error on rebuild from plugin dependency', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + styles: ['src/styles.css'], + }); + + await harness.writeFile( + 'test-plugin.js', + ` + const fs = require('fs'); + const path = require('path'); + module.exports = () => { + return { + postcssPlugin: 'test-plugin', + Once(root, { result }) { + const themePath = path.join(path.dirname(root.source.input.file), 'theme.json'); + result.messages.push({ + type: 'dependency', + file: themePath, + }); + const data = fs.readFileSync(themePath, 'utf-8'); + const json = JSON.parse(data); + root.append('body { color: ' + json.color + '; }'); + }, + }; + }; + module.exports.postcss = true; + `, + ); + await harness.writeFile( + '.postcssrc.json', + JSON.stringify({ + plugins: { + './test-plugin.js': {}, + }, + }), + ); + await harness.writeFile('src/styles.css', '/* base */'); + await harness.writeFile('src/theme.json', '{"color": "aqua"}'); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); + + await harness.writeFile('src/theme.json', 'invalid-json'); + }, + async ({ result }) => { + expect(result?.success).toBe(false); + + await harness.writeFile('src/theme.json', '{"color": "blue"}'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('rebuilds PostCSS stylesheet after CSS syntax error on initial build from import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + styles: ['src/styles.css'], + }); + + await harness.writeFile( + 'noop-plugin.js', + ` + module.exports = () => ({ postcssPlugin: 'noop-plugin' }); + module.exports.postcss = true; + `, + ); + await harness.writeFile( + '.postcssrc.json', + JSON.stringify({ + plugins: { + './noop-plugin.js': {}, + }, + }), + ); + await harness.writeFile('src/styles.css', "@import './a.css';"); + await harness.writeFile('src/a.css', "a { ' }"); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBe(false); + + await harness.writeFile('src/a.css', 'body { color: aqua; }'); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); + + await harness.writeFile('src/a.css', 'body { color: blue; }'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); + harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-index-html_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-index-html_spec.ts new file mode 100644 index 000000000000..99603bc98cee --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-index-html_spec.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * Maximum time in milliseconds for single build/rebuild + * This accounts for CI variability. + */ +export const BUILD_TIMEOUT = 30_000; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when input index HTML changes"', () => { + beforeEach(async () => { + // Application code is not needed for styles tests + await harness.writeFile('src/main.ts', 'console.log("TEST");'); + }); + + it('rebuilds output index HTML', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/index.html').content.toContain('charset="utf-8"'); + + await harness.modifyFile('src/index.html', (content) => + content.replace('charset="utf-8"', 'abc'), + ); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/index.html').content.not.toContain('charset="utf-8"'); + + await harness.modifyFile('src/index.html', (content) => + content.replace('abc', 'charset="utf-8"'), + ); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/index.html').content.toContain('charset="utf-8"'); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts new file mode 100644 index 000000000000..2fdad10f8d8d --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts @@ -0,0 +1,103 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; + +/** + * A regular expression used to check if a built worker is correctly referenced in application code. + */ +const REFERENCED_WORKER_REGEXP = + /new Worker\(new URL\("worker-[A-Z0-9]{8}\.js", import\.meta\.url\)/; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when Web Worker files change"', () => { + it('Recovers from error when directly referenced worker file is changed', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + const workerCodeFile = ` + console.log('WORKER FILE'); + `; + + const errorText = `Expected ";" but found "~"`; + + // Create a worker file + await harness.writeFile('src/app/worker.ts', workerCodeFile); + + // Create app component that uses the directive + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core' + @Component({ + selector: 'app-root', + standalone: false, + template: '

Worker Test

', + }) + export class AppComponent { + worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); + } + `, + ); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Ensure built worker is referenced in the application code + harness.expectFile('dist/browser/main.js').content.toMatch(REFERENCED_WORKER_REGEXP); + + // Update the worker file to be invalid syntax + await harness.writeFile('src/app/worker.ts', `asd;fj$3~kls;kd^(*fjlk;sdj---flk`); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, errorText); + + // Make an unrelated change to verify error cache was updated + // Should persist error in the next rebuild + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ logs }) => { + expectLog(logs, errorText); + + // Revert the change that caused the error + // Should remove the error + await harness.writeFile('src/app/worker.ts', workerCodeFile); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, errorText); + + // Make an unrelated change to verify error cache was updated + // Should continue showing no error + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expectNoLog(logs, errorText); + + // Ensure built worker is referenced in the application code + harness.expectFile('dist/browser/main.js').content.toMatch(REFERENCED_WORKER_REGEXP); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts new file mode 100644 index 000000000000..0adc77b5311a --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts @@ -0,0 +1,458 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { OutputHashing } from '../../schema'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Stylesheet url() Resolution"', () => { + it('should show a note when using tilde prefix in a directly referenced stylesheet', async () => { + await harness.writeFile( + 'src/styles.css', + ` + .a { + background-image: url("~/image.jpg") + } + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('You can remove the tilde and'), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Preprocessor stylesheets may not show the exact'), + }), + ); + }); + + it('should show a note when using tilde prefix in an imported CSS stylesheet', async () => { + await harness.writeFile( + 'src/styles.css', + ` + @import "a.css"; + `, + ); + await harness.writeFile( + 'src/a.css', + ` + .a { + background-image: url("~/image.jpg") + } + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('You can remove the tilde and'), + }), + ); + }); + + it('should show a note when using tilde prefix in an imported Sass stylesheet', async () => { + await harness.writeFile( + 'src/styles.scss', + ` + @import "a"; + `, + ); + await harness.writeFile( + 'src/a.scss', + ` + .a { + background-image: url("~/image.jpg") + } + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.scss'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('You can remove the tilde and'), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Preprocessor stylesheets may not show the exact'), + }), + ); + }); + + it('should show a note when using caret prefix in a directly referenced stylesheet', async () => { + await harness.writeFile( + 'src/styles.css', + ` + .a { + background-image: url("^image.jpg") + } + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('You can remove the caret and'), + }), + ); + }); + + it('should show a note when using caret prefix in an imported Sass stylesheet', async () => { + await harness.writeFile( + 'src/styles.scss', + ` + @import "a"; + `, + ); + await harness.writeFile( + 'src/a.scss', + ` + .a { + background-image: url("^image.jpg") + } + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.scss'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('You can remove the caret and'), + }), + ); + }); + + it('should not rebase a URL with a namespaced Sass variable reference that points to an absolute asset', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @use './b' as named; + .a { + background-image: url(named.$my-var) + } + `, + 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, + 'src/theme/c.scss': `$my-var: "https://example.com/example.png";`, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/styles.css') + .content.toContain('url(https://example.com/example.png)'); + }); + + it('should not rebase a URL with a Sass variable reference that points to an absolute asset', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + .a { + background-image: url($my-var) + } + `, + 'src/theme/b.scss': `$my-var: "https://example.com/example.png";`, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/styles.css') + .content.toContain('url(https://example.com/example.png)'); + }); + + it('should rebase a URL with a namespaced Sass variable referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @use './b' as named; + .a { + background-image: url(named.$my-var) + } + `, + 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, + 'src/theme/c.scss': `$my-var: "./images/logo.svg";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should rebase a URL with a hyphen-namespaced Sass variable referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @use './b' as named-hyphen; + .a { + background-image: url(named-hyphen.$my-var) + } + `, + 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, + 'src/theme/c.scss': `$my-var: "./images/logo.svg";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should rebase a URL with a underscore-namespaced Sass variable referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @use './b' as named_underscore; + .a { + background-image: url(named_underscore.$my-var) + } + `, + 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, + 'src/theme/c.scss': `$my-var: "./images/logo.svg";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should rebase a URL with a Sass variable referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + .a { + background-image: url($my-var) + } + `, + 'src/theme/b.scss': `$my-var: "./images/logo.svg";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should rebase a URL with an leading interpolation referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + .a { + background-image: url(#{$my-var}logo.svg) + } + `, + 'src/theme/b.scss': `$my-var: "./images/";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should rebase a URL with interpolation using concatenation referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + $extra-var: "2"; + $postfix-var: "xyz"; + .a { + background-image: url("#{$my-var}logo#{$extra-var+ "-" + $postfix-var}.svg") + } + `, + 'src/theme/b.scss': `$my-var: "./images/";`, + 'src/theme/images/logo2-xyz.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/styles.css') + .content.toContain(`url("./media/logo2-xyz.svg")`); + harness.expectFile('dist/browser/media/logo2-xyz.svg').toExist(); + }); + + it('should rebase a URL with an non-leading interpolation referencing a local resource', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + .a { + background-image: url(./#{$my-var}logo.svg) + } + `, + 'src/theme/b.scss': `$my-var: "./images/";`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should not rebase Sass function definition with name ending in "url"', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + @import './b'; + .a { + $asset: my-function-url('logo'); + background-image: url($asset) + } + `, + 'src/theme/b.scss': `@function my-function-url($name) { @return "./images/" + $name + ".svg"; }`, + 'src/theme/images/logo.svg': ``, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); + harness.expectFile('dist/browser/media/logo.svg').toExist(); + }); + + it('should not process a URL that has been marked as external', async () => { + await harness.writeFiles({ + 'src/styles.scss': `@use 'theme/a';`, + 'src/theme/a.scss': ` + .a { + background-image: url("assets/logo.svg") + } + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.None, + externalDependencies: ['assets/*'], + styles: ['src/styles.scss'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/styles.css').content.toContain(`url(assets/logo.svg)`); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/stylesheet_autoprefixer_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/stylesheet_autoprefixer_spec.ts new file mode 100644 index 000000000000..41ae225e2d3d --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/stylesheet_autoprefixer_spec.ts @@ -0,0 +1,259 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +const styleBaseContent: Record = Object.freeze({ + 'css': ` + @import url(imported-styles.css); + div { hyphens: none; } + `, +}); + +const styleImportedContent: Record = Object.freeze({ + 'css': 'section { hyphens: none; }', +}); + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Stylesheet autoprefixer"', () => { + for (const ext of ['css'] /* ['css', 'sass', 'scss', 'less'] */) { + it(`should add prefixes for listed browsers in global styles [${ext}]`, async () => { + await harness.writeFile( + '.browserslistrc', + ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + ); + + await harness.writeFiles({ + [`src/styles.${ext}`]: styleBaseContent[ext], + [`src/imported-styles.${ext}`]: styleImportedContent[ext], + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [`src/styles.${ext}`], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/styles.css') + .content.toMatch(/section\s*{\s*-webkit-hyphens:\s*none;\s*hyphens:\s*none;\s*}/); + harness + .expectFile('dist/browser/styles.css') + .content.toMatch(/div\s*{\s*-webkit-hyphens:\s*none;\s*hyphens:\s*none;\s*}/); + }); + + it(`should not add prefixes if not required by browsers in global styles [${ext}]`, async () => { + await harness.writeFile( + '.browserslistrc', + ` + Edge 110 + `, + ); + + await harness.writeFiles({ + [`src/styles.${ext}`]: styleBaseContent[ext], + [`src/imported-styles.${ext}`]: styleImportedContent[ext], + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [`src/styles.${ext}`], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/styles.css') + .content.toMatch(/section\s*{\s*hyphens:\s*none;\s*}/); + harness + .expectFile('dist/browser/styles.css') + .content.toMatch(/div\s*{\s*hyphens:\s*none;\s*}/); + }); + + it(`should add prefixes for listed browsers in external component styles [${ext}]`, async () => { + await harness.writeFile( + '.browserslistrc', + ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + ); + + await harness.writeFiles({ + [`src/app/app.component.${ext}`]: styleBaseContent[ext], + [`src/app/imported-styles.${ext}`]: styleImportedContent[ext], + }); + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('./app.component.css', `./app.component.${ext}`), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/main.js') + .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); + harness + .expectFile('dist/browser/main.js') + .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); + }); + + it(`should not add prefixes if not required by browsers in external component styles [${ext}]`, async () => { + await harness.writeFile( + '.browserslistrc', + ` + Edge 110 + `, + ); + + await harness.writeFiles({ + [`src/app/app.component.${ext}`]: styleBaseContent[ext], + [`src/app/imported-styles.${ext}`]: styleImportedContent[ext], + }); + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('./app.component.css', `./app.component.${ext}`), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/main.js') + .content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); + harness + .expectFile('dist/browser/main.js') + .content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); + }); + } + + it('should add prefixes for listed browsers in inline component styles', async () => { + await harness.writeFile( + '.browserslistrc', + ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + ); + + await harness.modifyFile('src/app/app.component.ts', (content) => { + return content + .replace('styleUrls', 'styles') + .replace('./app.component.css', 'div { hyphens: none; }'); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/main.js') + // div[_ngcontent-%COMP%] {\n -webkit-hyphens: none;\n hyphens: none;\n}\n + .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); + }); + + it('should not add prefixes if not required by browsers in inline component styles', async () => { + await harness.writeFile( + '.browserslistrc', + ` + Edge 110 + `, + ); + + await harness.modifyFile('src/app/app.component.ts', (content) => { + return content + .replace('styleUrls', 'styles') + .replace('./app.component.css', 'div { hyphens: none; }'); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); + }); + + it('should add prefixes for listed browsers in inline template styles', async () => { + await harness.writeFile( + '.browserslistrc', + ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + ); + + await harness.modifyFile('src/app/app.component.ts', (content) => { + return content.replace('styleUrls', 'styles').replace('./app.component.css', ''); + }); + await harness.modifyFile('src/app/app.component.html', (content) => { + return `\n${content}`; + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness + .expectFile('dist/browser/main.js') + // div[_ngcontent-%COMP%] {\n -webkit-hyphens: none;\n hyphens: none;\n}\n + .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); + }); + + it('should not add prefixes if not required by browsers in inline template styles', async () => { + await harness.writeFile( + '.browserslistrc', + ` + Edge 110 + `, + ); + + await harness.modifyFile('src/app/app.component.ts', (content) => { + return content.replace('styleUrls', 'styles').replace('./app.component.css', ''); + }); + await harness.modifyFile('src/app/app.component.html', (content) => { + return `\n${content}`; + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/top-level-await-error_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/top-level-await-error_spec.ts new file mode 100644 index 000000000000..b0220529ee28 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/top-level-await-error_spec.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Top-level await error message"', () => { + it('should show a Zone.js-specific error when top-level await is used with Zone.js', async () => { + await harness.writeFile( + 'src/main.ts', + ` + // The export makes this file a module, which is required for top-level await. + export const value = await Promise.resolve('test'); + console.log(value); + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: ['zone.js'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching( + 'Top-level await is not supported in applications that use Zone.js', + ), + }), + ); + }); + + it('should not show a Zone.js-specific error when top-level await is used without Zone.js', async () => { + await harness.writeFile( + 'src/main.ts', + ` + // The export makes this file a module, which is required for top-level await. + export const value = await Promise.resolve('test'); + console.log(value); + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: [], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringContaining( + 'Top-level await is not supported in applications that use Zone.js', + ), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts new file mode 100644 index 000000000000..cc74b9549e9d --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "TypeScript explicit incremental option usage"', () => { + it('should successfully build with incremental disabled', async () => { + // Disable tsconfig incremental option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.incremental = false; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-isolated-modules_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-isolated-modules_spec.ts new file mode 100644 index 000000000000..bef97e545ad9 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-isolated-modules_spec.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "TypeScript isolated modules direct transpilation"', () => { + it('should successfully build with isolated modules enabled and disabled optimizations', async () => { + // Enable tsconfig isolatedModules option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.isolatedModules = true; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('should successfully build with isolated modules enabled and enabled optimizations', async () => { + // Enable tsconfig isolatedModules option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.isolatedModules = true; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('supports TSX files with isolated modules enabled and enabled optimizations', async () => { + // Enable tsconfig isolatedModules option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.isolatedModules = true; + tsconfig.compilerOptions.jsx = 'react-jsx'; + + // There's an implicit `any`, because we don't include the React typings. + tsconfig.compilerOptions.noImplicitAny = false; + + return JSON.stringify(tsconfig); + }); + + await harness.writeFile('src/types.d.ts', `declare module 'react/jsx-runtime' { jsx: any }`); + await harness.writeFile('src/abc.tsx', `export function hello() { return

Hello

; }`); + await harness.modifyFile( + 'src/main.ts', + (content) => content + `import { hello } from './abc'; console.log(hello());`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + externalDependencies: ['react'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-path-mapping_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-path-mapping_spec.ts new file mode 100644 index 000000000000..416ee9c227bd --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-path-mapping_spec.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "TypeScript Path Mapping"', () => { + it('should resolve TS files when imported with a path mapping', async () => { + // Change main module import to use path mapping + await harness.modifyFile('src/main.ts', (content) => + content.replace(`'./app/app.module'`, `'@root/app.module'`), + ); + + // Add a path mapping for `@root` + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.paths = { + '@root/*': ['./src/app/*'], + }; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('should fail to resolve if no path mapping for an import is present', async () => { + // Change main module import to use path mapping + await harness.modifyFile('src/main.ts', (content) => + content.replace(`'./app/app.module'`, `'@root/app.module'`), + ); + + // Add a path mapping for `@not-root` + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.paths = { + '@not-root/*': ['./src/app/*'], + }; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Could not resolve "@root/app.module"'), + }), + ); + }); + + it('should resolve JS files when imported with a path mapping', async () => { + // Change main module import to use path mapping + await harness.modifyFile('src/main.ts', (content) => + content.replace(`'./app/app.module'`, `'app-module'`), + ); + + await harness.writeFiles({ + 'a.js': `export * from './src/app/app.module';\n\nconsole.log('A');`, + 'a.d.ts': `export * from './src/app/app.module';`, + }); + + // Add a path mapping for `@root` + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.paths = { + 'app-module': ['./a.js'], + }; + tsconfig.compilerOptions.allowJs = true; + + return JSON.stringify(tsconfig); + }); + + // app.module needs to be manually included since it is not referenced via a TS file + // with the test path mapping in place. + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.files.push('app/app.module.ts'); + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain(`console.log("A")`); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts new file mode 100644 index 000000000000..ba01e2a27dce --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { OutputHashing } from '../../schema'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectLog } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + beforeEach(async () => { + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files = ['main.server.ts', 'main.ts']; + + return JSON.stringify(tsConfig); + }); + + await harness.writeFiles({ + 'src/lazy.ts': `export const foo: number = 1;`, + 'src/main.ts': `export async function fn () { + const lazy = await import('./lazy'); + return lazy.foo; + }`, + 'src/main.server.ts': `export { fn as default } from './main';`, + }); + }); + + describe('Behavior: "Rebuild both server and browser bundles when using lazy loading"', () => { + it('detect changes and errors when expected', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + namedChunks: true, + outputHashing: OutputHashing.None, + server: 'src/main.server.ts', + ssr: true, + }); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Add valid code + await harness.appendToFile('src/lazy.ts', `console.log('foo');`); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Update type of 'foo' to invalid (number -> string) + await harness.writeFile('src/lazy.ts', `export const foo: string = 1;`); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expectLog(logs, `Type 'number' is not assignable to type 'string'.`); + + // Fix TS error + await harness.writeFile('src/lazy.ts', `export const foo: string = "1";`); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-touch-file_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-touch-file_spec.ts new file mode 100644 index 000000000000..eeb160ebef47 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-touch-file_spec.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuilds when touching file"', () => { + for (const aot of [true, false]) { + it(`Rebuild correctly when file is touched with ${aot ? 'AOT' : 'JIT'}`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + aot, + }); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + // Touch a file without doing any changes. + await harness.modifyFile('src/app/app.component.ts', (content) => content); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + await harness.removeFile('src/app/app.component.ts'); + }, + ({ result }) => { + expect(result?.success).toBeFalse(); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + } + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts new file mode 100644 index 000000000000..6ad5bbb3a9de --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "TypeScript JSON module resolution"', () => { + it('should resolve JSON files when imported with resolveJsonModule enabled', async () => { + await harness.writeFiles({ + 'src/x.json': `{"a": 1}`, + 'src/main.ts': `import * as x from './x.json'; console.log(x);`, + }); + + // Enable tsconfig resolveJsonModule option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node16'; + tsconfig.compilerOptions.module = 'node16'; + tsconfig.compilerOptions.resolveJsonModule = true; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('should fail to resolve with TS if resolveJsonModule is not present', async () => { + await harness.writeFiles({ + 'src/x.json': `{"a": 1}`, + 'src/main.ts': `import * as x from './x.json'; console.log(x);`, + }); + + // Enable tsconfig resolveJsonModule option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node16'; + tsconfig.compilerOptions.module = 'node16'; + tsconfig.compilerOptions.resolveJsonModule = undefined; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(`Cannot find module './x.json'`), + }), + ); + }); + + it('should fail to resolve with TS if resolveJsonModule is disabled', async () => { + await harness.writeFiles({ + 'src/x.json': `{"a": 1}`, + 'src/main.ts': `import * as x from './x.json'; console.log(x);`, + }); + + // Enable tsconfig resolveJsonModule option in tsconfig + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node16'; + tsconfig.compilerOptions.module = 'node16'; + tsconfig.compilerOptions.resolveJsonModule = false; + + return JSON.stringify(tsconfig); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(`Cannot find module './x.json'`), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts new file mode 100644 index 000000000000..5ae62f020c1c --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts @@ -0,0 +1,275 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * Compiled and base64 encoded WASM file for the following WAT: + * ``` + * (module + * (export "multiply" (func $multiply)) + * (func $multiply (param i32 i32) (result i32) + * local.get 0 + * local.get 1 + * i32.mul + * ) + * ) + * ``` + */ +const exportWasmBase64 = + 'AGFzbQEAAAABBwFgAn9/AX8DAgEABwwBCG11bHRpcGx5AAAKCQEHACAAIAFsCwAXBG5hbWUBCwEACG11bHRpcGx5AgMBAAA='; +const exportWasmBytes = Buffer.from(exportWasmBase64, 'base64'); + +/** + * Compiled and base64 encoded WASM file for the following WAT: + * ``` + * (module + * (import "./values" "getValue" (func $getvalue (result i32))) + * (export "multiply" (func $multiply)) + * (export "subtract1" (func $subtract)) + * (func $multiply (param i32 i32) (result i32) + * local.get 0 + * local.get 1 + * i32.mul + * ) + * (func $subtract (param i32) (result i32) + * call $getvalue + * local.get 0 + * i32.sub + * ) + * ) + * ``` + */ +const importWasmBase64 = + 'AGFzbQEAAAABEANgAAF/YAJ/fwF/YAF/AX8CFQEILi92YWx1ZXMIZ2V0VmFsdWUAAAMDAgECBxgCCG11bHRpcGx5AAEJc3VidHJhY3QxAAIKEQIHACAAIAFsCwcAEAAgAGsLAC8EbmFtZQEfAwAIZ2V0dmFsdWUBCG11bHRpcGx5AghzdWJ0cmFjdAIHAwAAAQACAA=='; +const importWasmBytes = Buffer.from(importWasmBase64, 'base64'); + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Supports WASM/ES module integration"', () => { + it('should inject initialization code and add an export', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/multiply.wasm', exportWasmBytes); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { multiply } from './multiply.wasm'; + + console.log(multiply(4, 5)); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure initialization code and export name is present in output code + harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); + harness.expectFile('dist/browser/main.js').content.toContain('multiply'); + }); + + it('should compile successfully with a provided type definition file', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/multiply.wasm', exportWasmBytes); + await harness.writeFile( + 'src/multiply.wasm.d.ts', + 'export declare function multiply(a: number, b: number): number;', + ); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + import { multiply } from './multiply.wasm'; + + console.log(multiply(4, 5)); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure initialization code and export name is present in output code + harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); + harness.expectFile('dist/browser/main.js').content.toContain('multiply'); + }); + + it('should add WASM defined imports and include resolved TS file for import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/subtract.wasm', importWasmBytes); + + // Create TS file that is expect by WASM file + await harness.writeFile( + 'src/values.ts', + ` + export function getValue(): number { return 100; } + `, + ); + // The file is not imported into any actual TS files so it needs to be manually added to the TypeScript program + await harness.modifyFile('src/tsconfig.app.json', (content) => + content.replace('"main.ts",', '"main.ts","values.ts",'), + ); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { subtract1 } from './subtract.wasm'; + + console.log(subtract1(5)); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure initialization code and export name is present in output code + harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); + harness.expectFile('dist/browser/main.js').content.toContain('subtract1'); + harness.expectFile('dist/browser/main.js').content.toContain('./values'); + harness.expectFile('dist/browser/main.js').content.toContain('getValue'); + }); + + it('should add WASM defined imports and include resolved JS file for import', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/subtract.wasm', importWasmBytes); + + // Create JS file that is expect by WASM file + await harness.writeFile( + 'src/values.js', + ` + export function getValue() { return 100; } + `, + ); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { subtract1 } from './subtract.wasm'; + + console.log(subtract1(5)); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure initialization code and export name is present in output code + harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); + harness.expectFile('dist/browser/main.js').content.toContain('subtract1'); + harness.expectFile('dist/browser/main.js').content.toContain('./values'); + harness.expectFile('dist/browser/main.js').content.toContain('getValue'); + }); + + it('should inline WASM files less than 10kb', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/multiply.wasm', exportWasmBytes); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { multiply } from './multiply.wasm'; + + console.log(multiply(4, 5)); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure WASM is present in output code + harness.expectFile('dist/browser/main.js').content.toContain(exportWasmBase64); + }); + + it('should show an error on invalid WASM file', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // Create WASM file + await harness.writeFile('src/multiply.wasm', 'NOT_WASM'); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { multiply } from './multiply.wasm'; + + console.log(multiply(4, 5)); + `, + ); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Unable to analyze WASM file'), + }), + ); + }); + + it('should show an error if using Zone.js', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: ['zone.js'], + }); + + // Create WASM file + await harness.writeFile('src/multiply.wasm', importWasmBytes); + + // Create main file that uses the WASM file + await harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + import { multiply } from './multiply.wasm'; + + console.log(multiply(4, 5)); + `, + ); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching( + 'WASM/ES module integration imports are not supported with Zone.js applications', + ), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/behavior/web-workers-application_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/web-workers-application_spec.ts new file mode 100644 index 000000000000..10112afd3b6b --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/web-workers-application_spec.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +/** + * A regular expression used to check if a built worker is correctly referenced in application code. + */ +const REFERENCED_WORKER_REGEXP = + /new Worker\(new URL\("worker-[A-Z0-9]{8}\.js", import\.meta\.url\)/; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "Bundles web worker files within application code"', () => { + it('should use the worker entry point when worker lazy chunks are present', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const workerCodeFile = ` + addEventListener('message', () => { + import('./extra').then((m) => console.log(m.default)); + }); + `; + const extraWorkerCodeFile = ` + export default 'WORKER FILE'; + `; + + // Create a worker file + await harness.writeFile('src/app/worker.ts', workerCodeFile); + await harness.writeFile('src/app/extra.ts', extraWorkerCodeFile); + + // Create app component that uses the directive + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core' + @Component({ + selector: 'app-root', + standalone: false, + template: '

Worker Test

', + }) + export class AppComponent { + worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); + } + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // Ensure built worker is referenced in the application code + harness.expectFile('dist/browser/main.js').content.toMatch(REFERENCED_WORKER_REGEXP); + }); + + it('should emit all chunks referenced by a web worker when chunk optimization is enabled', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + }); + + await harness.writeFile( + 'src/app/shared.ts', + `export function sharedHelper(value: string) { return [value, value.toUpperCase(), value.toLowerCase(), value.repeat(3)].join('-'); }`, + ); + await harness.writeFile( + 'src/app/lazy-a.ts', + `import { sharedHelper } from './shared'; export const a = () => sharedHelper('a');`, + ); + await harness.writeFile( + 'src/app/lazy-b.ts', + `import { sharedHelper } from './shared'; export const b = () => sharedHelper('b');`, + ); + await harness.writeFile('src/app/lazy-c.ts', `export const c = () => 'c';`); + + await harness.writeFile( + 'src/app/worker.ts', + ` + addEventListener('message', async () => { + const [{ a }, { b }] = await Promise.all([import('./lazy-a'), import('./lazy-b')]); + postMessage(a() + b()); + }); + `, + ); + + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + @Component({ + selector: 'app-root', + standalone: false, + template: '

Worker Test

', + }) + export class AppComponent { + worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); + constructor() { + Promise.all([import('./lazy-a'), import('./lazy-b'), import('./lazy-c')]).then(console.log); + } + } + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(harness.hasFileMatch('dist/browser', /^worker-chunk-/)).toBeTrue(); + + const mainContent = harness.readFile('dist/browser/main.js'); + const workerMatch = mainContent.match(/(worker-[A-Z0-9]{8}\.js)/); + expect(workerMatch).not.toBeNull(); + + const filesToCheck = new Set(['main.js']); + if (workerMatch) { + filesToCheck.add(workerMatch[1]); + } + + for (const file of filesToCheck) { + expect(harness.hasFile(`dist/browser/${file}`)) + .withContext(`Expected dist/browser/${file} to exist`) + .toBeTrue(); + + const content = harness.readFile(`dist/browser/${file}`); + for (const match of content.matchAll(/(?:from|import)\s*\(?["']\.\/([^"']+\.js)["']\)?/g)) { + filesToCheck.add(match[1]); + } + } + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts b/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts new file mode 100644 index 000000000000..7521b1a1a495 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts @@ -0,0 +1,174 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Option: "allowedCommonJsDependencies"', () => { + describe('given option is not set', () => { + for (const aot of [true, false]) { + it(`should show warning when depending on a Common JS bundle in ${ + aot ? 'AOT' : 'JIT' + } Mode`, async () => { + // Add a Common JS dependency + await harness.appendToFile('src/app/app.component.ts', `import 'buffer';`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + optimization: true, + aot, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectLog(logs, /Module 'buffer' used by 'src\/app\/app\.component\.ts' is not ESM/); + expectLog(logs, /CommonJS or AMD dependencies/); + expectNoLog( + logs, + 'base64-js', + 'Should not warn on transitive CommonJS packages which parent is also CommonJS.', + ); + }); + } + }); + + it('should not show warning when depending on a Common JS bundle which is allowed', async () => { + // Add a Common JS dependency + await harness.appendToFile( + 'src/app/app.component.ts', + ` + import 'buffer'; + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: ['buffer', 'base64-js', 'ieee754'], + optimization: true, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + + it('should not show warning when all dependencies are allowed by wildcard', async () => { + // Add a Common JS dependency + await harness.appendToFile( + 'src/app/app.component.ts', + ` + import 'buffer'; + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: ['*'], + optimization: true, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + + it('should not show warning when depending on zone.js', async () => { + // Add a Common JS dependency + await harness.appendToFile( + 'src/app/app.component.ts', + ` + import 'zone.js'; + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + optimization: true, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + + it(`should not show warning when importing non global local data '@angular/common/locale/fr'`, async () => { + await harness.appendToFile( + 'src/app/app.component.ts', + `import '@angular/common/locales/fr';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + optimization: true, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + + it('should not show warning in JIT for templateUrl and styleUrl when using paths', async () => { + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions ??= {}; + tsconfig.compilerOptions.paths = { + '@app/*': ['./src/app/*'], + }; + + return JSON.stringify(tsconfig, null, 2); + }); + + await harness.modifyFile('src/app/app.module.ts', (content) => + content.replace('./app.component', '@app/app.component'), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + optimization: true, + aot: false, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + + it('should not show warning for relative imports', async () => { + await harness.appendToFile('src/main.ts', `import './abc';`); + await harness.writeFile('src/abc.ts', 'console.log("abc");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + optimization: true, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expectNoLog(logs, /CommonJS or AMD dependencies/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/application/tests/options/app-shell_spec.ts b/packages/angular/build/src/builders/application/tests/options/app-shell_spec.ts new file mode 100644 index 000000000000..16f2a27b634c --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/options/app-shell_spec.ts @@ -0,0 +1,180 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +const appShellRouteFiles: Record = { + 'src/styles.css': `p { color: #000 }`, + 'src/app/app-shell/app-shell.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-app-shell', + standalone: false, + styles: ['div { color: #fff; }'], + template: '

app-shell works!

', + }) + export class AppShellComponent {}`, + 'src/main.server.ts': ` + import { AppServerModule } from './app/app.module.server'; + export default AppServerModule; + `, + 'src/app/app.module.ts': ` + import { BrowserModule } from '@angular/platform-browser'; + import { NgModule } from '@angular/core'; + + import { AppRoutingModule } from './app-routing.module'; + import { AppComponent } from './app.component'; + import { RouterModule } from '@angular/router'; + + @NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + AppRoutingModule, + RouterModule + ], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + 'src/app/app.module.server.ts': ` + import { NgModule } from '@angular/core'; + import { ServerModule } from '@angular/platform-server'; + + import { AppModule } from './app.module'; + import { AppComponent } from './app.component'; + import { Routes, RouterModule } from '@angular/router'; + import { AppShellComponent } from './app-shell/app-shell.component'; + + const routes: Routes = [ { path: 'shell', component: AppShellComponent }]; + + @NgModule({ + imports: [ + AppModule, + ServerModule, + RouterModule.forRoot(routes), + ], + bootstrap: [AppComponent], + declarations: [AppShellComponent], + }) + export class AppServerModule {} + `, + 'src/main.ts': ` + import { platformBrowser } from '@angular/platform-browser'; + import { AppModule } from './app/app.module'; + + platformBrowser().bootstrapModule(AppModule).catch(err => console.log(err)); + `, + 'src/app/app-routing.module.ts': ` + import { NgModule } from '@angular/core'; + import { Routes, RouterModule } from '@angular/router'; + + const routes: Routes = []; + + @NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] + }) + export class AppRoutingModule { } + `, + 'src/app/app.component.html': ``, +}; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + beforeEach(async () => { + await harness.modifyFile('src/tsconfig.app.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('main.server.ts'); + + return JSON.stringify(tsConfig); + }); + + await harness.writeFiles(appShellRouteFiles); + }); + + describe('Option: "appShell"', () => { + it('renders the application shell', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + polyfills: ['zone.js'], + appShell: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/browser/main.js').toExist(); + const indexFileContent = harness.expectFile('dist/browser/index.html').content; + indexFileContent.toContain('app-shell works!'); + }); + + it('critical CSS is inlined', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + server: 'src/main.server.ts', + polyfills: ['zone.js'], + appShell: true, + styles: ['src/styles.css'], + optimization: { + styles: { + minify: true, + inlineCritical: true, + }, + }, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const indexFileContent = harness.expectFile('dist/browser/index.html').content; + indexFileContent.toContain('app-shell works!'); + indexFileContent.toContain('p{color:#000}'); + indexFileContent.toContain( + ``, + ); + }); + + it('applies CSP nonce to critical CSS', async () => { + await harness.modifyFile('src/index.html', (content) => + content.replace(/`, + ); + indexFileContent.toContain('
Styled
', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from "@angular/core"; + + @Component({ + selector: "lib-html-style", + templateUrl: "./lib.component.html", + }) + export class LibComponent {} + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + inlineStyleLanguage: InlineStyleLanguage.Sass, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const fesm = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(fesm).toMatch(/color:\s*#ff5722/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/behavior/watch-cleanup_spec.ts b/packages/angular/build/src/builders/library/tests/behavior/watch-cleanup_spec.ts new file mode 100644 index 000000000000..6518b459b023 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/behavior/watch-cleanup_spec.ts @@ -0,0 +1,216 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Behavior: "Watch Mode Asset and Output Cleanup"', () => { + it('should emit newly created assets, respect ignore patterns, and clean up deleted assets in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/assets-dir/keep.txt': 'keep', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*.txt', + input: 'projects/lib/assets-dir', + output: 'assets', + ignore: ['**/ignored.txt'], + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets/keep.txt')).toBe('keep'); + + // Create an ignored file and a matching nested asset file + await harness.writeFiles({ + 'projects/lib/assets-dir/sub/ignored.txt': 'ignored', + 'projects/lib/assets-dir/sub/added.txt': 'added', + }); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets/sub/added.txt')).toBe('added'); + expect(harness.hasFile('dist/lib/assets/sub/ignored.txt')).toBeFalse(); + + // Remove the added asset file + await harness.removeFile('projects/lib/assets-dir/sub/added.txt'); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets/keep.txt')).toBe('keep'); + expect(harness.hasFile('dist/lib/assets/sub/added.txt')).toBeFalse(); + }, + ]); + }); + + it('should clean up output files when a secondary entry point is removed in watch mode', async () => { + await harness.writeFile( + 'projects/lib/secondary/src/public-api.ts', + `export const secondary = 'secondary-value';`, + ); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './secondary': './secondary/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + declarationMap: true, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib.mjs')).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs')).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs.map')).toBeTrue(); + expect(harness.hasFile('dist/lib/types/lib-secondary.d.ts')).toBeTrue(); + expect(harness.hasFile('dist/lib/types/lib-secondary.d.ts.map')).toBeTrue(); + expect(harness.hasFile('dist/lib/secondary/package.json')).toBeTrue(); + expect(harness.hasFile('dist/lib/.npmignore')).toBeTrue(); + + // Remove the secondary entry point from package.json exports + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib.mjs')).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs')).toBeFalse(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs.map')).toBeFalse(); + expect(harness.hasFile('dist/lib/types/lib-secondary.d.ts')).toBeFalse(); + expect(harness.hasFile('dist/lib/types/lib-secondary.d.ts.map')).toBeFalse(); + expect(harness.hasFile('dist/lib/secondary/package.json')).toBeFalse(); + expect(harness.hasFile('dist/lib/.npmignore')).toBeFalse(); + + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.exports['./secondary']).toBeUndefined(); + }, + ]); + }); + + it('should prune removed nested secondary entry point files and update .npmignore in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/shared/src/public-api.ts': `export const SHARED = 'shared';\n`, + 'projects/lib/testing/sub/src/public-api.ts': `export const SUB = 'sub';\n`, + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './shared': './shared/src/public-api.ts', + './testing/sub': './testing/sub/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/lib/fesm2022/lib-shared.mjs').toExist(); + harness.expectFile('dist/lib/fesm2022/lib-testing-sub.mjs').toExist(); + harness.expectFile('dist/lib/types/lib-testing-sub.d.ts').toExist(); + harness.expectFile('dist/lib/testing/sub/package.json').toExist(); + expect(harness.readFile('dist/lib/.npmignore')).toContain('/testing/sub/package.json'); + + // Remove './testing/sub' while keeping './shared' + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './shared': './shared/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + harness.expectFile('dist/lib/fesm2022/lib-shared.mjs').toExist(); + harness.expectFile('dist/lib/fesm2022/lib-testing-sub.mjs').toNotExist(); + harness.expectFile('dist/lib/fesm2022/lib-testing-sub.mjs.map').toNotExist(); + harness.expectFile('dist/lib/types/lib-testing-sub.d.ts').toNotExist(); + harness.expectFile('dist/lib/testing/sub/package.json').toNotExist(); + + const npmignore = harness.readFile('dist/lib/.npmignore'); + expect(npmignore).toContain('/shared/package.json'); + expect(npmignore).not.toContain('/testing/sub/package.json'); + }, + ]); + }); + + it('should clean up all output destinations when a single asset source matches multiple patterns and is deleted in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/assets-dir/shared.txt': 'shared-content', + 'projects/lib/assets-dir/keep.txt': 'keep-content', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*.txt', + input: 'projects/lib/assets-dir', + output: 'assets-a', + }, + { + glob: '**/*.txt', + input: 'projects/lib/assets-dir', + output: 'assets-b', + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets-a/shared.txt')).toBe('shared-content'); + expect(harness.readFile('dist/lib/assets-b/shared.txt')).toBe('shared-content'); + + await harness.removeFile('projects/lib/assets-dir/shared.txt'); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/assets-a/shared.txt')).toBeFalse(); + expect(harness.hasFile('dist/lib/assets-b/shared.txt')).toBeFalse(); + expect(harness.readFile('dist/lib/assets-a/keep.txt')).toBe('keep-content'); + expect(harness.readFile('dist/lib/assets-b/keep.txt')).toBe('keep-content'); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/behavior/watch_spec.ts b/packages/angular/build/src/builders/library/tests/behavior/watch_spec.ts new file mode 100644 index 000000000000..e117f8efe9f8 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/behavior/watch_spec.ts @@ -0,0 +1,1162 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { rm } from 'node:fs/promises'; +import { executeLibraryBuilder } from '../../builder'; +import { CompilationMode, InlineStyleLanguage } from '../../schema'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Behavior: "Watch Mode Rebuilding"', () => { + it('should rebuild library when a component file is modified', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('LibComponent'); + + // Trigger a change + await harness.writeFile( + 'projects/lib/src/lib/lib.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-rebuilt', + template: 'Rebuilt', + }) + export class LibComponent {} + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('lib-rebuilt'); + }, + ]); + }); + + it('should rebuild when external template or stylesheet file is modified', async () => { + await harness.writeFiles({ + 'projects/lib/src/lib/lib.component.html': '

Initial Template

', + 'projects/lib/src/lib/lib.component.css': 'h1 { color: blue; }', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-resources', + templateUrl: './lib.component.html', + styleUrl: './lib.component.css', + }) + export class LibComponent {} + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('Initial Template'); + expect(content).toMatch(/color:\s*(?:blue|#00f)/); + + // Trigger change to external template + await harness.writeFile( + 'projects/lib/src/lib/lib.component.html', + '

Updated Template

', + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('Updated Template'); + + // Trigger change to external stylesheet + await harness.writeFile('projects/lib/src/lib/lib.component.css', 'h1 { color: green; }'); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toMatch(/color:\s*green/); + }, + ]); + }); + + it('should rebuild intra-dependent secondary entry points when upstream changes', async () => { + await harness.writeFiles({ + 'projects/lib/shared/src/public-api.ts': ` + export const SHARED_VERSION = '1.0.0'; + `, + 'projects/lib/feature/src/public-api.ts': ` + import { SHARED_VERSION } from 'lib/shared'; + export const FEATURE_INFO = \`Feature using \${SHARED_VERSION}\`; + `, + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './shared': './shared/src/public-api.ts', + './feature': './feature/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const featureFesm = harness.readFile('dist/lib/fesm2022/lib-feature.mjs'); + expect(featureFesm).toContain('FEATURE_INFO'); + + // Modify upstream shared entry point + await harness.writeFile( + 'projects/lib/shared/src/public-api.ts', + ` + export const SHARED_VERSION = '2.0.0'; + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const sharedFesm = harness.readFile('dist/lib/fesm2022/lib-shared.mjs'); + expect(sharedFesm).toContain('2.0.0'); + const featureFesm = harness.readFile('dist/lib/fesm2022/lib-feature.mjs'); + expect(featureFesm).toContain('FEATURE_INFO'); + }, + ]); + }); + + it('should re-copy assets when an asset file is modified in watch mode', async () => { + await harness.writeFile('projects/lib/assets/data.json', '{"version": 1}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*', + input: 'projects/lib/assets', + output: 'assets', + }, + ], + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets/data.json')).toBe('{"version": 1}'); + + // Modify asset file + await harness.writeFile('projects/lib/assets/data.json', '{"version": 2}'); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/assets/data.json')).toBe('{"version": 2}'); + }, + ]); + }); + + it('should set a watch version in package.json in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.version).toMatch(/^0\.0\.0-watch\+\d+$/); + }, + ]); + }); + + it('should not update package.json when only source files change in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + let initialVersion: string; + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + initialVersion = pkg.version; + expect(initialVersion).toMatch(/^0\.0\.0-watch\+\d+$/); + + // Wait a brief moment so Date.now() would differ if regenerated + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Modify source file + await harness.writeFile( + 'projects/lib/src/lib/lib.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-rebuilt', + template: 'Rebuilt', + }) + export class LibComponent {} + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('lib-rebuilt'); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.version).toBe(initialVersion); + }, + ]); + }); + + it('should update package.json when package.json is modified in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.description).toBeUndefined(); + + // Modify package.json + const originalPkg = JSON.parse(harness.readFile('projects/lib/package.json')); + originalPkg.description = 'Updated description'; + await harness.writeFile( + 'projects/lib/package.json', + JSON.stringify(originalPkg, null, 2), + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.description).toBe('Updated description'); + }, + ]); + }); + + it('should re-analyze exports and compile new entry point when package.json is modified in watch mode', async () => { + await harness.writeFile( + 'projects/lib/secondary/src/public-api.ts', + `export const secondary = 'secondary-initial';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib.mjs')).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs')).toBeFalse(); + + // Add secondary entry point to package.json exports + const pkg = JSON.parse(harness.readFile('projects/lib/package.json')); + pkg.exports = { + '.': './src/public-api.ts', + './secondary': './secondary/src/public-api.ts', + }; + await harness.writeFile('projects/lib/package.json', JSON.stringify(pkg, null, 2)); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib-secondary.mjs')).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'secondary-initial', + ); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.exports['./secondary']).toBeDefined(); + + // Update secondary entry point source file to ensure it is being watched + await harness.writeFile( + 'projects/lib/secondary/src/public-api.ts', + `export const secondary = 'secondary-updated';`, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'secondary-updated', + ); + }, + ]); + }); + + it('should re-analyze exports and recompile when entry point path is changed in package.json in watch mode', async () => { + await harness.writeFile( + 'projects/lib/src/alternative-api.ts', + `export const value = 'alternative-api-content';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('LibComponent'); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).not.toContain( + 'alternative-api-content', + ); + + // Change primary entry point path in package.json + const pkg = JSON.parse(harness.readFile('projects/lib/package.json')); + pkg.exports = { + '.': './src/alternative-api.ts', + }; + await harness.writeFile('projects/lib/package.json', JSON.stringify(pkg, null, 2)); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain( + 'alternative-api-content', + ); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).not.toContain('LibComponent'); + }, + ]); + }); + + it('should fail with error when name is removed from package.json in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Remove name from package.json + const pkg = JSON.parse(harness.readFile('projects/lib/package.json')); + delete pkg.name; + await harness.writeFile('projects/lib/package.json', JSON.stringify(pkg, null, 2)); + }, + async ({ result }) => { + expect(result?.success).toBeFalse(); + expect(result?.error).toContain("must contain a 'name'"); + + // Restore name in package.json + const pkg = JSON.parse(harness.readFile('projects/lib/package.json')); + pkg.name = 'lib'; + await harness.writeFile('projects/lib/package.json', JSON.stringify(pkg, null, 2)); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + }, + ]); + }); + + it('should recover from compilation errors in watch mode', async () => { + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export const title = 'hello world';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('hello world'); + + // Introduce a compilation error + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export const title: number = 'invalid type';`, + ); + }, + async ({ result }) => { + expect(result?.success).toBeFalse(); + + // Fix the compilation error + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export const title = 'fixed world';`, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('fixed world'); + }, + ]); + }); + + it('should rebuild secondary entry point when its file changes', async () => { + await harness.writeFiles({ + 'projects/lib/secondary/src/public-api.ts': `export const MSG = 'initial secondary';`, + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './secondary': './secondary/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'initial secondary', + ); + + // Modify secondary entry point source + await harness.writeFile( + 'projects/lib/secondary/src/public-api.ts', + `export const MSG = 'updated secondary';`, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'updated secondary', + ); + const messages = logs.map((l) => l.message); + expect(messages.some((m) => m.includes('Compiling lib/secondary...'))).toBeTrue(); + expect(messages.some((m) => m.includes('Compiling lib...'))).toBeFalse(); + }, + ]); + }); + it('should recover when initial build fails with a compilation error', async () => { + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export const title: number = 'invalid type';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeFalse(); + + // Fix the compilation error + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export const title = 'fixed world';`, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('fixed world'); + }, + ]); + }); + + it('should rebuild when a new file is created in projectRoot', async () => { + await harness.writeFile('projects/lib/src/public-api.ts', `export * from './extra';`); + await harness.writeFile('projects/lib/src/extra.ts', `export const INITIAL = true;`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('INITIAL'); + + // Create a brand new file + await harness.writeFile( + 'projects/lib/src/lib/new-feature.ts', + `export const NEW_VAL = 123;`, + ); + await harness.writeFile( + 'projects/lib/src/public-api.ts', + `export * from './extra';\nexport * from './lib/new-feature';`, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('NEW_VAL'); + }, + ]); + }); + + it('should update package.json in watch mode when tslib import is added or removed', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.dependencies).toBeUndefined(); + + // Add a custom decorator that causes tslib to be imported + await harness.writeFile( + 'projects/lib/src/public-api.ts', + ` + function CustomClassDecorator(): ClassDecorator { + return () => {}; + } + + @CustomClassDecorator() + export class DecoratedService {} + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.dependencies).toEqual({ + tslib: jasmine.any(String), + }); + + // Remove the custom decorator so tslib is no longer imported + await harness.writeFile( + 'projects/lib/src/public-api.ts', + ` + export class PlainService {} + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + const pkg = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkg.dependencies).toBeUndefined(); + }, + ]); + }); + + it('should recreate deleted output directories on subsequent watch rebuilds', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.hasFile('dist/lib/fesm2022/lib.mjs')).toBeTrue(); + + // Remove output subdirectory externally between rebuilds + await rm(harness.resolvePath('dist/lib/fesm2022'), { recursive: true, force: true }); + expect(harness.hasFile('dist/lib/fesm2022/lib.mjs')).toBeFalse(); + + // Trigger a rebuild + await harness.writeFile( + 'projects/lib/src/lib/lib.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-recreated', + template: 'Recreated', + }) + export class LibComponent {} + `, + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('lib-recreated'); + }, + ]); + }); + + it('should rebuild when a Sass partial imported by an inline component stylesheet is modified in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/src/lib/_vars.scss': '$primary-color: rgb(10, 20, 30);', + 'projects/lib/src/lib/_spacing.scss': '$pad: 12px;', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-inline-sass', + template: 'Inline Sass', + styles: [ + '@use "./vars"; :host { color: vars.$primary-color; }', + '@use "./spacing"; :host { padding: spacing.$pad; }', + ], + }) + export class LibComponent {} + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + inlineStyleLanguage: InlineStyleLanguage.Scss, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toMatch(/color:\s*(?:#0a141e|rgb\(10,\s*20,\s*30\))/); + expect(content).toMatch(/padding:\s*12px/); + + // Modify the Sass partial referenced by the first inline component style + await harness.writeFile( + 'projects/lib/src/lib/_vars.scss', + '$primary-color: rgb(200, 100, 50);', + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toMatch(/color:\s*(?:#c86432|rgb\(200,\s*100,\s*50\))/); + expect(content).toMatch(/padding:\s*12px/); + }, + ]); + }); + + it('should only rebuild affected entry point when an external template is modified with isolatedModules enabled', async () => { + await harness.writeFiles({ + 'projects/lib/src/lib/lib.component.html': '

Primary Initial

', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-primary', + templateUrl: './lib.component.html', + }) + export class LibComponent {} + `, + 'projects/lib/secondary/src/secondary.component.html': '

Secondary Initial

', + 'projects/lib/secondary/src/secondary.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-secondary', + templateUrl: './secondary.component.html', + }) + export class SecondaryComponent {} + `, + 'projects/lib/secondary/src/public-api.ts': ` + export { SecondaryComponent } from './secondary.component'; + `, + }); + + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.isolatedModules = true; + + return JSON.stringify(tsconfig, null, 2); + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './secondary': './secondary/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'Secondary Initial', + ); + expect(harness.readFile('dist/lib/types/lib.d.ts')).toContain('ɵcmp'); + expect(harness.readFile('dist/lib/types/lib-secondary.d.ts')).toContain('ɵcmp'); + + await harness.writeFile( + 'projects/lib/secondary/src/secondary.component.html', + '

Secondary Updated

', + ); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib-secondary.mjs')).toContain( + 'Secondary Updated', + ); + expect(harness.readFile('dist/lib/types/lib.d.ts')).toContain('ɵcmp'); + expect(harness.readFile('dist/lib/types/lib-secondary.d.ts')).toContain('ɵcmp'); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib/secondary...'), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib...'), + }), + ); + }, + ]); + }); + + it('should rebuild dependent entry point when a shared component input is added in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/shared/src/public-api.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-shared-icon', + template: 'icon', + }) + export class SharedIconComponent {} + `, + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + import { SharedIconComponent } from 'lib/shared'; + + @Component({ + selector: 'lib-primary', + imports: [SharedIconComponent], + template: '', + }) + export class LibComponent {} + `, + }); + + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.isolatedModules = true; + + return JSON.stringify(tsconfig, null, 2); + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './shared': './shared/src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + compilationMode: CompilationMode.Partial, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Trigger a rebuild of `lib` first so `lib/shared` undergoes a `.d.ts`-only check + await harness.writeFile( + 'projects/lib/src/lib/lib.component.ts', + ` + import { Component } from '@angular/core'; + import { SharedIconComponent } from 'lib/shared'; + + @Component({ + selector: 'lib-primary', + imports: [SharedIconComponent], + template: '', + }) + export class LibComponent {} + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib...'), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib/shared...'), + }), + ); + + // Add a new @Input() to SharedIconComponent + await harness.writeFile( + 'projects/lib/shared/src/public-api.ts', + ` + import { Component, Input } from '@angular/core'; + + @Component({ + selector: 'lib-shared-icon', + template: '{{ name }}', + }) + export class SharedIconComponent { + @Input() name = 'default'; + } + `, + ); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib/shared...'), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('Compiling lib...'), + }), + ); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('"name"'); + }, + ]); + }); + + it('should retry reloading broken package.json when another file changes and recover once fixed', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Break package.json with invalid JSON + await harness.writeFile('projects/lib/package.json', '{ invalid json'); + }, + async ({ result }) => { + expect(result?.success).toBeFalse(); + expect(result?.error).toContain("Failed to reload 'package.json'"); + + // Modify a source file while package.json is still broken + await harness.writeFile( + 'projects/lib/src/lib/lib.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-after-pkg-error', + template: 'After Pkg Error', + }) + export class LibComponent {} + `, + ); + }, + async ({ result }) => { + expect(result?.success).toBeFalse(); + expect(result?.error).toContain("Failed to reload 'package.json'"); + + // Fix package.json + await harness.writeFile( + 'projects/lib/package.json', + JSON.stringify( + { + name: 'lib', + version: '0.0.1', + exports: { + '.': './src/public-api.ts', + }, + }, + null, + 2, + ), + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('lib-after-pkg-error'); + }, + ]); + }); + + it('should preserve and recover from TypeScript declaration emit diagnostics in watch mode', async () => { + await harness.writeFiles({ + 'projects/lib/src/lib/internal.ts': ` + interface PrivateData { + value: number; + } + + export const internalData: PrivateData = { value: 42 }; + `, + 'projects/lib/src/lib/feature.ts': ` + import { internalData } from './internal'; + + export const data = internalData; + `, + 'projects/lib/src/public-api.ts': ` + export * from './lib/feature'; + export * from './lib/lib.service'; + export * from './lib/lib.component'; + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases( + [ + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(/TS4023:.*PrivateData/), + }), + ); + + // Modify an unrelated file so feature.ts is not re-emitted + await harness.writeFile( + 'projects/lib/src/lib/lib.service.ts', + ` + import { Injectable } from '@angular/core'; + + @Injectable({ providedIn: 'root' }) + export class LibService { + updated = true; + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(/TS4023:.*PrivateData/), + }), + ); + + // Fix the declaration error in feature.ts by adding an explicit type annotation + await harness.writeFile( + 'projects/lib/src/lib/feature.ts', + ` + import { internalData } from './internal'; + + export const data: { value: number } = internalData; + `, + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + const dtsContent = harness.readFile('dist/lib/types/lib.d.ts'); + expect(dtsContent).toContain('data'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('should rebuild when an external Sass partial or template is modified and recover from template errors', async () => { + await harness.writeFiles({ + 'projects/lib/src/lib/_vars.scss': '$primary-color: rgb(10, 20, 30);', + 'projects/lib/src/lib/lib.component.scss': + '@use "./vars"; :host { color: vars.$primary-color; }', + 'projects/lib/src/lib/lib.component.html': '

{{ title }}

', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-external-resources', + templateUrl: './lib.component.html', + styleUrl: './lib.component.scss', + }) + export class LibComponent { + title = 'Hello'; + } + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + const content = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(content).toContain('h1'); + expect(content).toMatch(/color:\s*(?:#0a141e|rgb\(10,\s*20,\s*30\))/); + expect(harness.readFile('dist/lib/types/lib.d.ts')).toContain('LibComponent'); + + // Modify the imported Sass partial + await harness.writeFile( + 'projects/lib/src/lib/_vars.scss', + '$primary-color: rgb(200, 100, 50);', + ); + }, + async ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toMatch( + /color:\s*(?:#c86432|rgb\(200,\s*100,\s*50\))/, + ); + expect(harness.readFile('dist/lib/types/lib.d.ts')).toContain('LibComponent'); + + // Introduce a template type-checking error in the external HTML template + await harness.writeFile( + 'projects/lib/src/lib/lib.component.html', + '
{{ nonExistentProp }}
', + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining('nonExistentProp'), + }), + ); + + // Fix the external HTML template error + await harness.writeFile( + 'projects/lib/src/lib/lib.component.html', + '
{{ title }}
', + ); + }, + ({ result }) => { + expect(result?.success).toBeTrue(); + expect(harness.readFile('dist/lib/fesm2022/lib.mjs')).toContain('footer'); + expect(harness.readFile('dist/lib/types/lib.d.ts')).toContain('LibComponent'); + }, + ]); + }); + + it('should preserve template diagnostics across watch rebuilds after a stylesheet error', async () => { + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.angularCompilerOptions = { + ...tsconfig.angularCompilerOptions, + strictTemplates: true, + }; + + return JSON.stringify(tsconfig, null, 2); + }); + + await harness.writeFiles({ + 'projects/lib/src/lib/other.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-other', + template: '{{ validProp }}', + }) + export class OtherComponent { + validProp = 'ok'; + } + `, + 'projects/lib/src/lib/lib.component.scss': '.valid { color: blue; }', + 'projects/lib/src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-primary', + template: 'Primary', + styleUrl: './lib.component.scss', + }) + export class LibComponent {} + `, + 'projects/lib/src/public-api.ts': ` + export * from './lib/lib.component'; + export * from './lib/other.component'; + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Introduce both a stylesheet error in LibComponent and a template error in OtherComponent + await harness.writeFiles({ + 'projects/lib/src/lib/lib.component.scss': '.broken { color: $undefined_var; }', + 'projects/lib/src/lib/other.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-other', + template: '{{ unknownProp }}', + }) + export class OtherComponent {} + `, + }); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringContaining('Undefined variable'), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringContaining( + "Property 'unknownProp' does not exist on type 'OtherComponent'", + ), + }), + ); + + // Fix only the stylesheet error in LibComponent while OtherComponent still has the template error + await harness.writeFile( + 'projects/lib/src/lib/lib.component.scss', + '.valid { color: green; }', + ); + }, + ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringContaining( + "Property 'unknownProp' does not exist on type 'OtherComponent'", + ), + }), + ); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/allowed-non-peer-dependencies_spec.ts b/packages/angular/build/src/builders/library/tests/options/allowed-non-peer-dependencies_spec.ts new file mode 100644 index 000000000000..d72923c85ba0 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/allowed-non-peer-dependencies_spec.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "allowedNonPeerDependencies"', () => { + it('should fail build when package.json has unallowed dependencies', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.dependencies = { + 'lodash-es': '^4.17.21', + }; + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching( + /lodash-es.*allowedNonPeerDependencies.*projects\/lib\/package\.json/, + ), + }), + ); + }); + + it('should succeed build when dependency matches allowedNonPeerDependencies pattern', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.dependencies = { + 'lodash-es': '^4.17.21', + }; + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedNonPeerDependencies: ['^lodash-.*'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should allow tslib by default in dependencies without configuration', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.dependencies = { + tslib: '^2.3.0', + }; + return JSON.stringify(pkg, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/assets_spec.ts b/packages/angular/build/src/builders/library/tests/options/assets_spec.ts new file mode 100644 index 000000000000..32d2dc1ab507 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/assets_spec.ts @@ -0,0 +1,128 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "assets"', () => { + it('should copy assets matching glob patterns with input, output, and ignore', async () => { + await harness.writeFiles({ + 'projects/lib/assets-dir/file-a.png': 'PNG_A', + 'projects/lib/assets-dir/file-b.png': 'PNG_B', + 'projects/lib/assets-dir/ignored.png': 'PNG_IGNORED', + 'projects/lib/assets-dir/file-c.svg': 'SVG_C', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { + glob: '**/*.png', + input: 'projects/lib/assets-dir', + output: 'assets', + ignore: ['ignored.png'], + }, + ], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(harness.readFile('dist/lib/assets/file-a.png')).toBe('PNG_A'); + expect(harness.readFile('dist/lib/assets/file-b.png')).toBe('PNG_B'); + expect(harness.hasFile('dist/lib/assets/ignored.png')).toBeFalse(); + expect(harness.hasFile('dist/lib/assets/file-c.svg')).toBeFalse(); + }); + + it('should support string-based asset paths', async () => { + await harness.writeFile('projects/lib/docs/README.md', '# Library Docs'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['projects/lib/docs/README.md'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(harness.readFile('dist/lib/docs/README.md')).toBe('# Library Docs'); + }); + + it('should not copy root README.md into secondary entry point output when secondary entry point is in projectRoot', async () => { + await harness.writeFiles({ + 'projects/lib/README.md': '# Root Library README', + 'projects/lib/testing.ts': 'export const TESTING = true;', + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './testing': './testing.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(harness.readFile('dist/lib/README.md')).toBe('# Root Library README'); + expect(harness.hasFile('dist/lib/testing/README.md')).toBeFalse(); + }); + + it('should not copy README.md into secondary entry point output when sharing directory with primary entry point', async () => { + await harness.writeFiles({ + 'projects/lib/README.md': '# Root Library README', + 'projects/lib/src/README.md': '# Src README', + 'projects/lib/src/testing.ts': 'export const TESTING = true;', + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './testing': './src/testing.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(harness.readFile('dist/lib/README.md')).toBe('# Root Library README'); + expect(harness.hasFile('dist/lib/testing/README.md')).toBeFalse(); + }); + + it('should only copy the root README.md by default and not secondary entry point README.md files', async () => { + await harness.writeFiles({ + 'projects/lib/README.md': '# Root Library README', + 'projects/lib/testing/README.md': '# Testing Entry Point README', + 'projects/lib/testing/public-api.ts': 'export const TESTING = true;', + }); + + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + './testing': './testing/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(harness.readFile('dist/lib/README.md')).toBe('# Root Library README'); + expect(harness.hasFile('dist/lib/testing/README.md')).toBeFalse(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/compilation-mode_spec.ts b/packages/angular/build/src/builders/library/tests/options/compilation-mode_spec.ts new file mode 100644 index 000000000000..0efedef5708f --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/compilation-mode_spec.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { CompilationMode } from '../../schema'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "compilationMode"', () => { + it('should emit partial declarations when compilationMode is "partial"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + compilationMode: CompilationMode.Partial, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const fesm = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(fesm).toContain('ɵɵngDeclareComponent'); + }); + + it('should emit full definitions when compilationMode is "full"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + compilationMode: CompilationMode.Full, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const fesm = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(fesm).toContain('ɵɵdefineComponent'); + }); + + it('should respect angularCompilerOptions.compilationMode from tsconfig when not set in builder options', async () => { + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.angularCompilerOptions = { + ...tsconfig.angularCompilerOptions, + compilationMode: 'full', + }; + + return JSON.stringify(tsconfig, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const fesm = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(fesm).toContain('ɵɵdefineComponent'); + + const pkgJson = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(pkgJson.scripts?.prepublishOnly).toContain('full compilation mode'); + }); + + it('should override angularCompilerOptions.compilationMode from tsconfig when set in builder options', async () => { + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.angularCompilerOptions = { + ...tsconfig.angularCompilerOptions, + compilationMode: 'full', + }; + + return JSON.stringify(tsconfig, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + compilationMode: CompilationMode.Partial, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const fesm = harness.readFile('dist/lib/fesm2022/lib.mjs'); + expect(fesm).toContain('ɵɵngDeclareComponent'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/declaration-map_spec.ts b/packages/angular/build/src/builders/library/tests/options/declaration-map_spec.ts new file mode 100644 index 000000000000..2e30109d6a03 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/declaration-map_spec.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; +import { join } from 'node:path'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "declarationMap"', () => { + it('should not emit declaration sourcemaps by default', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // FESM sourcemaps are always enabled + harness.expectFile('dist/lib/fesm2022/lib.mjs.map').toExist(); + // DTS sourcemaps are disabled by default + harness.expectFile('dist/lib/types/lib.d.ts.map').toNotExist(); + }); + + it('should emit declaration sourcemaps when declarationMap is true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + declarationMap: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // FESM sourcemaps are always enabled + harness.expectFile('dist/lib/fesm2022/lib.mjs.map').toExist(); + + // DTS sourcemaps should be generated + harness.expectFile('dist/lib/types/lib.d.ts.map').toExist(); + const dtsMap = JSON.parse(harness.readFile('dist/lib/types/lib.d.ts.map')); + expect(dtsMap.sources).toContain('../../../projects/lib/src/lib/lib.component.ts'); + harness.expectFile(join('dist/lib/types', dtsMap.sources[0])).toExist(); + }); + + it('should respect declarationMap from tsconfig when not set in builder options', async () => { + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.declarationMap = true; + + return JSON.stringify(tsconfig, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/lib/types/lib.d.ts.map').toExist(); + }); + + it('should override declarationMap from tsconfig when declarationMap is false', async () => { + await harness.modifyFile('projects/lib/tsconfig.lib.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.declarationMap = true; + + return JSON.stringify(tsconfig, null, 2); + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + declarationMap: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + harness.expectFile('dist/lib/fesm2022/lib.mjs.map').toExist(); + harness.expectFile('dist/lib/types/lib.d.ts.map').toNotExist(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/delete-output-path_spec.ts b/packages/angular/build/src/builders/library/tests/options/delete-output-path_spec.ts new file mode 100644 index 000000000000..e8001de35f33 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/delete-output-path_spec.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "deleteOutputPath"', () => { + beforeEach(async () => { + // Add pre-existing files in output directory + await harness.writeFile('dist/lib/extra.txt', 'EXTRA'); + }); + + it('should delete the output files when deleteOutputPath is true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + deleteOutputPath: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('dist/lib/extra.txt').toNotExist(); + harness.expectFile('dist/lib/fesm2022/lib.mjs').toExist(); + }); + + it('should not delete existing output files when deleteOutputPath is false', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + deleteOutputPath: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('dist/lib/extra.txt').toExist(); + harness.expectFile('dist/lib/fesm2022/lib.mjs').toExist(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/entry-points_spec.ts b/packages/angular/build/src/builders/library/tests/options/entry-points_spec.ts new file mode 100644 index 000000000000..cf1bb1b6e7b7 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/entry-points_spec.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Package.json "exports" entry points', () => { + it('should succeed when entry point is a .ts file', async () => { + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should succeed when exports is a string shorthand', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = './src/public-api.ts'; + + return JSON.stringify(pkg, null, 2); + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should succeed when entry point is a .mts file', async () => { + await harness.writeFiles({ + 'projects/lib/src/public-api.mts': 'export const VALUE = 42;\n', + }); + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.mts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should fail when entry point is not a .ts or .mts file', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.cts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result, error } = await harness.executeOnce({ + outputLogsOnException: false, + outputLogsOnFailure: false, + }); + expect(result).toBeUndefined(); + expect(error).toBeDefined(); + expect((error as Error).message).toMatch(/must be a TypeScript file \('\.ts' or '\.mts'\)/); + }); + + it('should fail when entry point is a declaration file', async () => { + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.d.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + + const { result, error } = await harness.executeOnce({ + outputLogsOnException: false, + outputLogsOnFailure: false, + }); + expect(result).toBeUndefined(); + expect(error).toBeDefined(); + expect((error as Error).message).toMatch(/must be a TypeScript file \('\.ts' or '\.mts'\)/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/keep-lifecycle-scripts_spec.ts b/packages/angular/build/src/builders/library/tests/options/keep-lifecycle-scripts_spec.ts new file mode 100644 index 000000000000..4dc3de98cc87 --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/keep-lifecycle-scripts_spec.ts @@ -0,0 +1,69 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "keepLifecycleScripts"', () => { + it('should remove scripts from package.json by default', async () => { + await harness.writeFile( + 'projects/lib/package.json', + JSON.stringify({ + name: 'my-lib', + version: '1.0.0', + exports: { + '.': './src/public-api.ts', + }, + scripts: { + postinstall: 'echo postinstall', + }, + }), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const distPackageJson = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(distPackageJson.scripts).toBeUndefined(); + }); + + it('should preserve scripts in package.json when keepLifecycleScripts is true', async () => { + await harness.writeFile( + 'projects/lib/package.json', + JSON.stringify({ + name: 'my-lib', + version: '1.0.0', + exports: { + '.': './src/public-api.ts', + }, + scripts: { + postinstall: 'echo postinstall', + }, + }), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + keepLifecycleScripts: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const distPackageJson = JSON.parse(harness.readFile('dist/lib/package.json')); + expect(distPackageJson.scripts).toEqual({ + postinstall: 'echo postinstall', + }); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/options/output-path_spec.ts b/packages/angular/build/src/builders/library/tests/options/output-path_spec.ts new file mode 100644 index 000000000000..2969692fa6ac --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/options/output-path_spec.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { executeLibraryBuilder } from '../../builder'; +import { BASE_OPTIONS, LIBRARY_BUILDER_INFO, describeLibraryBuilder } from '../setup'; + +describeLibraryBuilder(executeLibraryBuilder, LIBRARY_BUILDER_INFO, (harness) => { + describe('Option: "outputPath"', () => { + it('should default outputPath to dist/{projectName} when omitted', async () => { + const { outputPath: _, ...optionsWithoutOutputPath } = BASE_OPTIONS; + harness.useTarget('build', optionsWithoutOutputPath); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('dist/lib/fesm2022/lib.mjs').toExist(); + harness.expectFile('dist/lib/package.json').toExist(); + }); + + it('should use custom outputPath when specified', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + outputPath: 'dist/custom-output', + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('dist/custom-output/fesm2022/lib.mjs').toExist(); + harness.expectFile('dist/custom-output/package.json').toExist(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/library/tests/setup.ts b/packages/angular/build/src/builders/library/tests/setup.ts new file mode 100644 index 000000000000..53202094870e --- /dev/null +++ b/packages/angular/build/src/builders/library/tests/setup.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderHandlerFn } from '@angular-devkit/architect'; +import { TestProjectHost } from '@angular-devkit/architect/testing'; +import { json, normalize, join } from '@angular-devkit/core'; +import { readFileSync } from 'node:fs'; +import { JasmineBuilderHarness } from '../../../../../../../modules/testing/builder/src'; +import { Schema } from '../schema'; + +export * from '../../../../../../../modules/testing/builder/src'; + +export const LIBRARY_BUILDER_INFO = Object.freeze({ + name: '@angular/build:library', + schemaPath: __dirname + '/../schema.json', +}); + +export const BASE_OPTIONS = Object.freeze({ + tsConfig: 'projects/lib/tsconfig.lib.json', + outputPath: 'dist/lib', + poll: 100, +}); + +const libWorkspaceRoot = join( + normalize(__dirname), + '../../../../../../../modules/testing/builder/projects/hello-world-lib/', +); +export const libHost = new TestProjectHost(libWorkspaceRoot); + +const optionSchemaCache = new Map(); + +function getCachedSchema(options: { schemaPath: string }): json.schema.JsonSchema { + let optionSchema = optionSchemaCache.get(options.schemaPath); + if (optionSchema === undefined) { + optionSchema = JSON.parse(readFileSync(options.schemaPath, 'utf8')) as json.schema.JsonSchema; + optionSchemaCache.set(options.schemaPath, optionSchema); + } + return optionSchema; +} + +let counter = 0; + +export function describeLibraryBuilder( + builderHandler: BuilderHandlerFn, + options: { name?: string; schemaPath: string }, + specDefinitions: (harness: JasmineBuilderHarness) => void, +): void { + const optionSchema = getCachedSchema(options); + const harness = new JasmineBuilderHarness(builderHandler, libHost, { + builderName: options.name, + optionSchema, + }); + + describe((options.name || builderHandler.name) + ` (Suite: ${counter++})`, () => { + beforeEach(async () => { + harness.resetProjectMetadata(); + harness.useProject('lib', { + root: 'projects/lib', + sourceRoot: 'projects/lib/src', + }); + harness.useTarget('build', BASE_OPTIONS); + + await libHost.initialize().toPromise(); + await harness.modifyFile('projects/lib/package.json', (content) => { + const pkg = JSON.parse(content); + pkg.exports = { + '.': './src/public-api.ts', + }; + + return JSON.stringify(pkg, null, 2); + }); + }); + + afterEach(() => libHost.restore().toPromise()); + + specDefinitions(harness); + }); +} diff --git a/packages/angular/build/src/builders/library/types.ts b/packages/angular/build/src/builders/library/types.ts new file mode 100644 index 000000000000..273f7066cb99 --- /dev/null +++ b/packages/angular/build/src/builders/library/types.ts @@ -0,0 +1,214 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { AngularCompilation } from '../../tools/angular/compilation'; +import type { StylesheetPluginsass } from '../../tools/esbuild/stylesheets/stylesheet-plugin-factory'; +import type { NormalizedAssetsPattern } from '../../utils'; +import type { NormalizedCachedOptions } from '../../utils/normalize-cache'; +import type { PostcssConfiguration } from '../../utils/postcss-configuration'; + +/** + * Normalized representation of an entry point in the library. + */ +export interface NormalizedEntryPoint { + /** The subpath in package.json exports (e.g. '.' or './testing'). */ + subpath: string; + + /** Subpath name without leading './' (e.g. '.' or 'testing'). */ + name: string; + + /** Display name of the entry point (e.g. '@my/lib' or '@my/lib/testing'). */ + displayName: string; + + /** Base name of the output bundle (e.g. 'my-lib' or 'my-lib-testing'). */ + bundleName: string; + + /** Absolute POSIX path to the entry file. */ + entryFilePath: string; + + /** Is this the primary entry point ('.')? */ + isPrimary: boolean; +} + +/** + * Partial package.json data structure for library packaging. + */ +export interface PackageJsonData { + name: string; + version?: string; + type?: string; + main?: string; + module?: string; + typings?: string; + types?: string; + sideEffects?: boolean | string[]; + exports?: string | unknown[] | Record; + scripts?: Record; + workspaces?: unknown; + dependencies?: Record; + optionalDependencies?: Record; + peerDependencies?: Record; + peerDependenciesMeta?: Record; + [key: string]: unknown; +} + +/** + * Normalized options for the library builder. + * All file and directory paths are normalized to POSIX format. + */ +export interface NormalizedLibraryOptions { + /** Absolute POSIX path to the workspace root directory. */ + workspaceRoot: string; + + /** Absolute POSIX path to the library project root directory. */ + projectRoot: string; + + /** Name of the npm package from the library's `package.json`. */ + packageName: string; + + /** Parsed contents of the library's `package.json`. */ + packageJson: PackageJsonData; + + /** Absolute POSIX path to the build output directory. */ + outputPath: string; + + /** Whether to delete the output directory before building. */ + deleteOutputPath: boolean; + + /** Absolute POSIX path to the library's `package.json`. */ + packageJsonPath: string; + + /** Absolute POSIX path to the TypeScript configuration file. */ + tsConfigPath: string; + + /** Map of normalized entry points keyed by entry point name. */ + entryPoints: Map; + + /** Default stylesheet language for inline component styles. */ + inlineStyleLanguage: 'css' | 'less' | 'sass' | 'scss'; + + /** Absolute POSIX paths to style preprocessor include directories. */ + styleIncludePaths: string[]; + + /** Optional Sass preprocessor configuration. */ + sass?: StylesheetPluginsass; + + /** Normalized asset patterns with POSIX `input` and `output` paths. */ + assets: NormalizedAssetsPattern[]; + + /** Angular compilation mode (`'partial'` or `'full'`). */ + compilationMode?: 'partial' | 'full'; + + /** Whether to generate source maps for TypeScript declaration files. */ + declarationMap?: boolean; + + /** Regular expressions matching allowed non-peer dependencies. */ + allowedNonPeerDependencies: RegExp[]; + + /** Whether to preserve lifecycle scripts in the emitted `package.json`. */ + keepLifecycleScripts: boolean; + + /** Whether to run the build in watch mode. */ + watch: boolean; + + /** Optional file watching polling interval in milliseconds. */ + poll?: number; + + /** Whether to preserve symbolic links during resolution and bundling. */ + preserveSymlinks: boolean; + + /** Whether to display build progress in the terminal. */ + progress: boolean; + + /** Whether to clear the terminal screen before watch rebuilds. */ + clearScreen?: boolean; + + /** Normalized build cache configuration. */ + cacheOptions: NormalizedCachedOptions; + + /** Resolved PostCSS configuration, if present in the workspace. */ + postcssConfiguration?: { config: PostcssConfiguration; configPath: string }; + + /** Resolved Tailwind CSS configuration, if applicable. */ + tailwindConfiguration?: { file: string; package: string }; + + /** Whether terminal color output is enabled. */ + colors: boolean; +} + +/** + * Cached module ID and output file sets for a bundled entry point. + */ +export interface BundleResult { + /** Exact set of virtual POSIX ESM module IDs bundled into this entry point. */ + esmModuleIds: ReadonlySet; + + /** Exact set of virtual POSIX DTS module IDs bundled into this entry point. */ + dtsModuleIds: ReadonlySet; + + /** Relative POSIX output paths of ESM bundle files and sourcemaps emitted for this entry point. */ + esmOutputFiles: ReadonlySet; + + /** Relative POSIX output paths of DTS bundle files and sourcemaps emitted for this entry point. */ + dtsOutputFiles: ReadonlySet; + + /** Whether this entry point bundle imports 'tslib'. */ + hasTslibImport: boolean; +} + +/** + * Cached state for the single unified library compilation. + */ +export interface SingleProgramCache { + /** The active Angular compilation instance. */ + readonly compilationInstance: AngularCompilation; + + /** In-memory map of emitted JavaScript files keyed by POSIX path. */ + readonly esmFiles: Map; + + /** In-memory map of emitted TypeScript declaration files keyed by POSIX path. */ + readonly dtsFiles: Map; + + /** Set of POSIX file paths that failed during stylesheet bundling. */ + readonly failedFiles: ReadonlySet; +} + +/** + * Output of the unified library compilation step. + */ +export interface LibraryCompilationOutput { + /** Read-only map of emitted JavaScript files keyed by POSIX path. */ + readonly esmFiles: ReadonlyMap; + + /** Read-only map of emitted TypeScript declaration files keyed by POSIX path. */ + readonly dtsFiles: ReadonlyMap; + + /** Set of POSIX JavaScript file paths that were added, modified, or deleted in this iteration. */ + readonly changedEsmFiles: ReadonlySet; + + /** Set of POSIX declaration file paths that were added, modified, or deleted in this iteration. */ + readonly changedDtsFiles: ReadonlySet; + + /** Set of all POSIX source and dependency file paths referenced during compilation. */ + readonly referencedFiles: ReadonlySet; + + /** Cached compilation state for subsequent incremental builds. */ + readonly cache: SingleProgramCache; + + /** Whether any component stylesheet bundling errors occurred. */ + readonly hasStylesheetErrors: boolean; + + /** Promise that resolves when compilation diagnostics have been formatted and recorded. */ + readonly diagnosePromise: Promise; + + /** Effective declarationMap setting resolved from builder options and tsconfig. */ + readonly declarationMap: boolean; + + /** Effective compilationMode setting resolved from builder options and tsconfig. */ + readonly compilationMode: 'partial' | 'full'; +} diff --git a/packages/angular/build/src/builders/ng-packagr/builder.ts b/packages/angular/build/src/builders/ng-packagr/builder.ts new file mode 100644 index 000000000000..3bbb2680d73c --- /dev/null +++ b/packages/angular/build/src/builders/ng-packagr/builder.ts @@ -0,0 +1,98 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import type { NgPackagrOptions } from 'ng-packagr'; +import { join, resolve } from 'node:path'; +import { assertIsError } from '../../utils/error'; +import { normalizeCacheOptions } from '../../utils/normalize-cache'; +import { purgeStaleBuildCache } from '../../utils/purge-cache'; +import type { Schema as NgPackagrBuilderOptions } from './schema'; + +/** + * A Builder that executes the `ng-packagr` tool to build an Angular library. + * + * @param options The builder options as defined by the JSON schema. + * @param context A BuilderContext instance. + * @returns A BuilderOutput object. + * + * @experimental Direct usage of this function is considered experimental. + * @deprecated Use the `@angular/build:library` builder instead. Deprecated since v22.3. + */ +export async function* execute( + options: NgPackagrBuilderOptions, + context: BuilderContext, +): AsyncIterableIterator { + context.logger.warn( + 'The "@angular/build:ng-packagr" builder is deprecated. ' + + 'Use "@angular/build:library" instead.', + ); + + // Purge old build disk cache. + await purgeStaleBuildCache(context); + + const workspaceRoot = context.workspaceRoot; + let packager; + try { + packager = (await import('ng-packagr')).ngPackagr(); + } catch (error) { + assertIsError(error); + if (error.code === 'MODULE_NOT_FOUND') { + return { + success: false, + error: + 'The "ng-packagr" package was not found. To correct this error, ensure this package is installed in the project.', + }; + } + + throw error; + } + + const projectName = context.target?.project; + if (!projectName) { + throw new Error('The builder requires a target.'); + } + + const metadata = await context.getProjectMetadata(projectName); + const ngPackagrConfig = options.project + ? join(workspaceRoot, options.project) + : join(workspaceRoot, (metadata.root as string | undefined) ?? '', 'ng-package.json'); + + packager.forProject(ngPackagrConfig); + + if (options.tsConfig) { + packager.withTsConfig(resolve(workspaceRoot, options.tsConfig)); + } + + const { enabled: cacheEnabled, path: cacheDirectory } = normalizeCacheOptions( + metadata, + context.workspaceRoot, + projectName, + context.builder.builderName, + ); + + const ngPackagrOptions: NgPackagrOptions = { + cacheEnabled, + poll: options.poll, + cacheDirectory: cacheDirectory, + }; + + try { + if (options.watch) { + await packager.watch(ngPackagrOptions).toPromise(); + } else { + await packager.build(ngPackagrOptions); + } + + yield { success: true }; + } catch (error) { + assertIsError(error); + + yield { success: false, error: error.message }; + } +} diff --git a/packages/angular/build/src/builders/ng-packagr/index.ts b/packages/angular/build/src/builders/ng-packagr/index.ts new file mode 100644 index 000000000000..94824ea5ecd8 --- /dev/null +++ b/packages/angular/build/src/builders/ng-packagr/index.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Builder, createBuilder } from '@angular-devkit/architect'; +import { execute } from './builder'; +import type { Schema as NgPackagrBuilderOptions } from './schema'; + +export { type NgPackagrBuilderOptions, execute }; + +const builder: Builder = createBuilder(execute); + +export default builder; diff --git a/packages/angular/build/src/builders/ng-packagr/schema.json b/packages/angular/build/src/builders/ng-packagr/schema.json new file mode 100644 index 000000000000..94d8774d2af9 --- /dev/null +++ b/packages/angular/build/src/builders/ng-packagr/schema.json @@ -0,0 +1,27 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "ng-packagr Target", + "description": "ng-packagr target options for Build Architect. Use to build library projects.", + "deprecated": true, + "type": "object", + "properties": { + "project": { + "type": "string", + "description": "The file path for the ng-packagr configuration file, relative to the current workspace." + }, + "tsConfig": { + "type": "string", + "description": "The full path for the TypeScript configuration file, relative to the current workspace." + }, + "watch": { + "type": "boolean", + "description": "Run build when files change.", + "default": false + }, + "poll": { + "type": "number", + "description": "Enable and define the file watching poll time period in milliseconds." + } + }, + "additionalProperties": false +} diff --git a/packages/angular/build/src/builders/unit-test/builder.ts b/packages/angular/build/src/builders/unit-test/builder.ts new file mode 100644 index 000000000000..bfb4cae0dcdf --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/builder.ts @@ -0,0 +1,423 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { + type BuilderContext, + type BuilderOutput, + targetStringFromTarget, +} from '@angular-devkit/architect'; +import assert from 'node:assert'; +import { readFile, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin'; +import { assertIsError } from '../../utils/error'; +import { writeTestFiles } from '../../utils/test-files'; +import { buildApplicationInternal } from '../application'; +import type { + ApplicationBuilderExtensions, + ApplicationBuilderInternalOptions, +} from '../application/options'; +import { ResultKind } from '../application/results'; +import { normalizeOptions } from './options'; +import type { TestRunner } from './runners/api'; +import { MissingDependenciesError } from './runners/dependency-checker'; +import type { Schema as UnitTestBuilderOptions } from './schema'; +import { findTests } from './test-discovery'; + +export type { UnitTestBuilderOptions }; + +async function loadTestRunner(runnerName: string): Promise { + // Harden against directory traversal + if (!/^[a-zA-Z0-9-]+$/.test(runnerName)) { + throw new Error( + `Invalid runner name "${runnerName}". Runner names can only contain alphanumeric characters and hyphens.`, + ); + } + + let runnerModule; + try { + runnerModule = await import(`./runners/${runnerName}/index`); + } catch (e) { + assertIsError(e); + if (e.code === 'ERR_MODULE_NOT_FOUND') { + throw new Error(`Unknown test runner "${runnerName}".`, { cause: e }); + } + throw new Error( + `Failed to load the '${runnerName}' test runner. The package may be corrupted or improperly installed.`, + { cause: e }, + ); + } + + const runner = runnerModule.default; + if ( + !runner || + typeof runner.getBuildOptions !== 'function' || + typeof runner.createExecutor !== 'function' + ) { + throw new Error( + `The loaded test runner '${runnerName}' does not appear to be a valid TestRunner implementation.`, + ); + } + + return runner; +} + +function prepareBuildExtensions( + virtualFiles: Record | undefined, + projectSourceRoot: string, + extensions?: ApplicationBuilderExtensions, +): ApplicationBuilderExtensions | undefined { + if (!virtualFiles) { + return extensions; + } + + extensions ??= {}; + extensions.codePlugins ??= []; + for (const [namespace, contents] of Object.entries(virtualFiles)) { + extensions.codePlugins.push( + createVirtualModulePlugin({ + namespace, + loadContent: () => { + return { + contents, + loader: 'js', + resolveDir: projectSourceRoot, + }; + }, + }), + ); + } + + return extensions; +} + +async function* runBuildAndTest( + executor: import('./runners/api').TestExecutor, + applicationBuildOptions: ApplicationBuilderInternalOptions, + context: BuilderContext, + dumpDirectory: string | undefined, + extensions: ApplicationBuilderExtensions | undefined, +): AsyncIterable { + let consecutiveErrorCount = 0; + for await (const buildResult of buildApplicationInternal( + applicationBuildOptions, + context, + extensions, + )) { + if (buildResult.kind === ResultKind.Failure) { + yield { success: false }; + continue; + } else if ( + buildResult.kind !== ResultKind.Full && + buildResult.kind !== ResultKind.Incremental + ) { + assert.fail( + 'A full and/or incremental build result is required from the application builder.', + ); + } + + assert(buildResult.files, 'Builder did not provide result files.'); + + if (dumpDirectory) { + if (buildResult.kind === ResultKind.Full) { + // Full build, so clean the directory + await rm(dumpDirectory, { recursive: true, force: true }); + } else { + // Incremental build, so delete removed files + for (const file of buildResult.removed) { + await rm(path.join(dumpDirectory, file.path), { force: true }); + } + } + await writeTestFiles(buildResult.files, dumpDirectory); + context.logger.info(`Build output files successfully dumped to '${dumpDirectory}'.`); + } + + // Pass the build artifacts to the executor + try { + yield* executor.execute(buildResult); + + // Successful execution resets the failure counter + consecutiveErrorCount = 0; + } catch (e) { + assertIsError(e); + context.logger.error(`An exception occurred during test execution:\n${e.stack ?? e.message}`); + if (e instanceof AggregateError) { + e.errors.forEach((inner) => { + assertIsError(inner); + context.logger.error(inner.stack ?? inner.message); + }); + } + + yield { success: false }; + consecutiveErrorCount++; + } + + if (consecutiveErrorCount >= 3) { + context.logger.error( + 'Test runner process has failed multiple times in a row. Please fix the configuration and restart the process.', + ); + + return; + } + } +} + +/** + * @experimental Direct usage of this function is considered experimental. + */ +export async function* execute( + options: UnitTestBuilderOptions, + context: BuilderContext, + extensions?: ApplicationBuilderExtensions, +): AsyncIterable { + // Determine project name from builder context target + const projectName = context.target?.project; + if (!projectName) { + context.logger.error(`The builder requires a target to be specified.`); + + return; + } + + // Initialize the test runner and normalize options + let runner; + let normalizedOptions; + try { + normalizedOptions = await normalizeOptions(context, projectName, options); + runner = await loadTestRunner(normalizedOptions.runnerName); + await runner.validateDependencies?.(normalizedOptions); + } catch (e) { + assertIsError(e); + if (e instanceof MissingDependenciesError) { + context.logger.error(e.message); + } else { + context.logger.error( + `An exception occurred during initialization of the test runner:\n${e.stack ?? e.message}`, + ); + } + yield { success: false }; + + return; + } + + if (normalizedOptions.listTests) { + const testFiles = await findTests( + normalizedOptions.include, + normalizedOptions.exclude ?? [], + normalizedOptions.workspaceRoot, + normalizedOptions.projectSourceRoot, + ); + + context.logger.info('Discovered test files:'); + for (const file of testFiles) { + context.logger.info(` ${path.relative(normalizedOptions.workspaceRoot, file)}`); + } + + yield { success: true }; + + return; + } + + if (runner.isStandalone) { + try { + await using executor = await runner.createExecutor(context, normalizedOptions, undefined); + yield* executor.execute({ + kind: ResultKind.Full, + files: [], + }); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred during standalone test execution:\n${e.stack ?? e.message}`, + ); + yield { success: false }; + } + + return; + } + + // Get base build options from the buildTarget + let buildTargetOptions: ApplicationBuilderInternalOptions; + try { + const builderName = await context.getBuilderNameForTarget(normalizedOptions.buildTarget); + if (builderName === '@angular/build:application') { + buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + )) as unknown as ApplicationBuilderInternalOptions; + } else if (builderName === '@angular/build:library') { + const libraryOptions = (await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + )) as Record; + + buildTargetOptions = transformLibraryOptions(libraryOptions); + } else if (builderName === '@angular/build:ng-packagr') { + const ngPackagrOptions = await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + ); + + buildTargetOptions = await transformNgPackagrOptions( + context, + ngPackagrOptions, + normalizedOptions.projectRoot, + ); + } else { + context.logger.warn( + `The 'buildTarget' is configured to use '${builderName}', which is not supported. ` + + `The 'unit-test' builder is designed to work with '@angular/build:application', ` + + `'@angular/build:library', or '@angular/build:ng-packagr'. ` + + 'Unexpected behavior or build failures may occur.', + ); + + buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + )) as unknown as ApplicationBuilderInternalOptions; + } + } catch (e) { + assertIsError(e); + context.logger.error( + `Could not load build target options for "${targetStringFromTarget( + normalizedOptions.buildTarget, + )}".\n` + + `Please check your 'angular.json' configuration.\n` + + `Error: ${e.message}`, + ); + yield { success: false }; + + return; + } + + // Get runner-specific build options + let runnerBuildOptions; + let virtualFiles; + let testEntryPointMappings; + try { + ({ + buildOptions: runnerBuildOptions, + virtualFiles, + testEntryPointMappings, + } = await runner.getBuildOptions(normalizedOptions, buildTargetOptions, context.logger)); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred while getting runner-specific build options:\n${e.stack ?? e.message}`, + ); + yield { success: false }; + + return; + } + + try { + await using executor = await runner.createExecutor( + context, + normalizedOptions, + testEntryPointMappings, + ); + + const finalExtensions = prepareBuildExtensions( + virtualFiles, + normalizedOptions.projectSourceRoot, + extensions, + ); + + // Prepare and run the application build + const applicationBuildOptions = { + ...buildTargetOptions, + ...runnerBuildOptions, + polyfills: runnerBuildOptions.polyfills ?? normalizedOptions.polyfills, + watch: normalizedOptions.watch, + progress: normalizedOptions.buildProgress ?? buildTargetOptions.progress, + quiet: normalizedOptions.quiet, + ...(normalizedOptions.tsConfig ? { tsConfig: normalizedOptions.tsConfig } : {}), + preserveSymlinks: normalizedOptions.preserveSymlinks, + } satisfies ApplicationBuilderInternalOptions; + + const dumpDirectory = normalizedOptions.dumpVirtualFiles + ? path.join(normalizedOptions.cacheOptions.path, 'output-files') + : undefined; + + yield* runBuildAndTest( + executor, + applicationBuildOptions, + context, + dumpDirectory, + finalExtensions, + ); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred while creating the test executor:\n${e.stack ?? e.message}`, + ); + yield { success: false }; + } +} + +async function transformNgPackagrOptions( + context: BuilderContext, + options: Record, + projectRoot: string, +): Promise { + const projectPath = options['project']; + + let ngPackagePath: string; + if (projectPath) { + if (typeof projectPath !== 'string') { + throw new Error('ng-packagr builder options "project" property must be a string.'); + } + ngPackagePath = path.join(context.workspaceRoot, projectPath); + } else { + ngPackagePath = path.join(projectRoot, 'ng-package.json'); + } + + let ngPackageJson; + try { + ngPackageJson = JSON.parse(await readFile(ngPackagePath, 'utf-8')); + } catch (e) { + assertIsError(e); + throw new Error(`Could not read ng-package.json at ${ngPackagePath}`, { + cause: e, + }); + } + + const { lib: { styleIncludePaths = [] } = {}, assets = [], inlineStyleLanguage } = ngPackageJson; + + const includePaths = styleIncludePaths.map((includePath: string) => + path.resolve(path.dirname(ngPackagePath), includePath), + ); + + return { + stylePreprocessorOptions: includePaths.length ? { includePaths } : undefined, + assets: assets.length ? assets : undefined, + inlineStyleLanguage, + } as ApplicationBuilderInternalOptions; +} + +/** + * Transforms library builder options into internal application builder options for testing. + * + * @param options The raw validated options from the library build target. + * @returns Application builder options suitable for running tests. + */ +function transformLibraryOptions( + options: Record, +): ApplicationBuilderInternalOptions { + const { stylePreprocessorOptions, assets, inlineStyleLanguage, preserveSymlinks, tsConfig } = + options; + + return { + stylePreprocessorOptions: + stylePreprocessorOptions as ApplicationBuilderInternalOptions['stylePreprocessorOptions'], + assets: Array.isArray(assets) && assets.length ? assets : undefined, + inlineStyleLanguage: + inlineStyleLanguage as ApplicationBuilderInternalOptions['inlineStyleLanguage'], + preserveSymlinks: typeof preserveSymlinks === 'boolean' ? preserveSymlinks : undefined, + tsConfig: typeof tsConfig === 'string' ? tsConfig : undefined, + } as ApplicationBuilderInternalOptions; +} diff --git a/packages/angular/build/src/builders/unit-test/index.ts b/packages/angular/build/src/builders/unit-test/index.ts new file mode 100644 index 000000000000..47666cdc1067 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/index.ts @@ -0,0 +1,16 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type Builder, createBuilder } from '@angular-devkit/architect'; +import { type UnitTestBuilderOptions, execute } from './builder'; + +export { type UnitTestBuilderOptions, execute }; + +const builder: Builder = createBuilder(execute); + +export default builder; diff --git a/packages/angular/build/src/builders/unit-test/options.ts b/packages/angular/build/src/builders/unit-test/options.ts new file mode 100644 index 000000000000..7a70d95ecde2 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/options.ts @@ -0,0 +1,184 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type BuilderContext, targetFromTargetString } from '@angular-devkit/architect'; +import { constants, promises as fs } from 'node:fs'; +import path from 'node:path'; +import { normalizeCacheOptions } from '../../utils/normalize-cache'; +import { canonicalizePath, toPosixPath } from '../../utils/path'; +import { getProjectRootPaths } from '../../utils/project-metadata'; +import { isTTY } from '../../utils/tty'; +import { Runner, type Schema as UnitTestBuilderOptions } from './schema'; + +export type NormalizedUnitTestBuilderOptions = Awaited>; + +async function exists(path: string): Promise { + try { + await fs.access(path, constants.F_OK); + + return true; + } catch { + return false; + } +} + +function normalizeReporterOption( + reporters: unknown[] | undefined, +): [string, Record][] | undefined { + return reporters?.map((entry) => + typeof entry === 'string' + ? ([entry, {}] as [string, Record]) + : (entry as [string, Record]), + ); +} + +export async function normalizeOptions( + context: BuilderContext, + projectName: string, + options: UnitTestBuilderOptions, +) { + // Target specifier defaults to the current project's build target using a development configuration + const buildTargetSpecifier = options.buildTarget ?? `::development`; + const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build'); + + // Load target options to determine preserveSymlinks setting + let buildTargetOptions: Record | undefined; + try { + buildTargetOptions = await context.getTargetOptions(buildTarget); + } catch {} + + const preserveSymlinks = + typeof buildTargetOptions?.preserveSymlinks === 'boolean' + ? buildTargetOptions.preserveSymlinks + : process.execArgv.includes('--preserve-symlinks'); + + // Setup base paths based on workspace root and project information + const workspaceRoot = canonicalizePath(context.workspaceRoot); + + const projectMetadata = await context.getProjectMetadata(projectName); + const { projectRoot, projectSourceRoot } = getProjectRootPaths(workspaceRoot, projectMetadata); + + // Gather persistent caching option and provide a project specific cache location + const cacheOptions = normalizeCacheOptions( + projectMetadata, + workspaceRoot, + projectName, + context.builder.builderName, + ); + + const { + runner, + browsers, + progress, + filter, + browserViewport, + ui, + runnerConfig, + runnerArgs, + isolate, + splitting = true, + polyfills, + } = options; + + if (ui && runner !== Runner.Vitest) { + throw new Error('The "ui" option is only available for the "vitest" runner.'); + } + + if (isolate && runner !== Runner.Vitest) { + throw new Error('The "isolate" option is only available for the "vitest" runner.'); + } + + if (runnerArgs?.length && (runner ?? Runner.Vitest) !== Runner.Vitest) { + throw new Error('The "runnerArgs" option is only available for the "vitest" runner.'); + } + + const [width, height] = browserViewport?.split('x').map(Number) ?? []; + + let tsConfig = options.tsConfig; + if (tsConfig) { + const fullTsConfigPath = path.join(workspaceRoot, tsConfig); + if (!(await exists(fullTsConfigPath))) { + throw new Error(`The specified tsConfig file '${tsConfig}' does not exist.`); + } + } else { + const tsconfigSpecPath = path.join(projectRoot, 'tsconfig.spec.json'); + if (await exists(tsconfigSpecPath)) { + // The application builder expects a path relative to the workspace root. + tsConfig = path.relative(workspaceRoot, tsconfigSpecPath); + } + } + + let watch = options.watch ?? isTTY(); + if (options.ui && options.watch === false) { + context.logger.warn( + `The '--ui' option requires watch mode. The '--no-watch' flag will be ignored.`, + ); + watch = true; + } + + return { + // Project/workspace information + workspaceRoot, + projectRoot, + projectSourceRoot, + cacheOptions, + // Target/configuration specified options + buildTarget, + include: options.include ?? ['**/*.spec.ts'], + exclude: options.exclude, + filter, + runnerName: runner ?? Runner.Vitest, + headless: options.headless, + coverage: { + enabled: options.coverage, + exclude: options.coverageExclude, + include: options.coverageInclude, + reporters: normalizeReporterOption(options.coverageReporters), + thresholds: options.coverageThresholds, + // The schema generation tool doesn't support tuple types for items, but the schema validation + // does ensure that the array has exactly two numbers. + watermarks: options.coverageWatermarks as { + statements?: [number, number]; + branches?: [number, number]; + functions?: [number, number]; + lines?: [number, number]; + }, + }, + tsConfig, + buildProgress: progress, + reporters: normalizeReporterOption(options.reporters), + outputFile: options.outputFile, + browsers: browsers?.length ? browsers : undefined, + browserViewport: width && height ? { width, height } : undefined, + watch, + debug: options.debug ?? false, + ui: process.env['CI'] ? false : ui, + isolate, + splitting, + quiet: options.quiet ?? (process.env['CI'] ? false : true), + providersFile: options.providersFile && path.join(workspaceRoot, options.providersFile), + setupFiles: options.setupFiles + ? options.setupFiles.map((setupFile) => toPosixPath(path.join(workspaceRoot, setupFile))) + : [], + dumpVirtualFiles: options.dumpVirtualFiles, + listTests: options.listTests, + preserveSymlinks, + polyfills, + runnerConfig: + typeof runnerConfig === 'string' + ? runnerConfig.length === 0 + ? true + : path.resolve(workspaceRoot, runnerConfig) + : runnerConfig, + runnerArgs: runnerArgs?.length ? runnerArgs : undefined, + }; +} + +export function injectTestingPolyfills(polyfills: string[] = []): string[] { + return polyfills.includes('zone.js') ? [...polyfills, 'zone.js/testing'] : polyfills; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/api.ts b/packages/angular/build/src/builders/unit-test/runners/api.ts new file mode 100644 index 000000000000..4cd455472bfa --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/api.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import type { ApplicationBuilderInternalOptions } from '../../application/options'; +import type { FullResult, IncrementalResult } from '../../application/results'; +import type { NormalizedUnitTestBuilderOptions } from '../options'; + +/** + * Represents the options for a test runner. + */ +export interface RunnerOptions { + /** + * Partial options for the application builder. + * These will be merged with the options from the build target. + */ + buildOptions: Partial; + + /** + * A record of virtual files to be added to the build. + * The key is the file path and the value is the file content. + */ + virtualFiles?: Record; + + /** + * A map of test entry points to their corresponding test files. + * This is used to avoid re-discovering the test files in the executor. + */ + testEntryPointMappings?: Map; +} + +/** + * Represents a stateful test execution session. + * An instance of this is created for each `ng test` command. + */ +export interface TestExecutor { + /** + * Executes tests using the artifacts from a specific build. + * This method can be called multiple times in watch mode. + * + * @param buildResult The output from the application builder. + * @returns An async iterable builder output stream. + */ + execute(buildResult: FullResult | IncrementalResult): AsyncIterable; + + [Symbol.asyncDispose](): Promise; +} + +/** + * Represents the metadata and hooks for a specific test runner. + */ +export interface TestRunner { + readonly name: string; + readonly isStandalone?: boolean; + + validateDependencies?(options: NormalizedUnitTestBuilderOptions): void | Promise; + + getBuildOptions( + options: NormalizedUnitTestBuilderOptions, + baseBuildOptions: Partial, + logger: BuilderContext['logger'], + ): RunnerOptions | Promise; + + /** + * Creates a stateful executor for a test session. + * This is called once at the start of the `ng test` command. + * + * @param context The Architect builder context. + * @param options The normalized unit test options. + * @param testEntryPointMappings A map of test entry points to their corresponding test files. + * @returns A TestExecutor instance that will handle the test runs. + */ + createExecutor( + context: BuilderContext, + options: NormalizedUnitTestBuilderOptions, + testEntryPointMappings: Map | undefined, + ): Promise; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts b/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts new file mode 100644 index 000000000000..ed774a55476a --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createProjectResolver } from '../../../utils/resolve-project'; + +/** + * A custom error class to represent missing dependency errors. + * This is used to avoid printing a stack trace for this expected error. + */ +export class MissingDependenciesError extends Error { + constructor(message: string) { + super(message); + this.name = 'MissingDependenciesError'; + } +} + +type Resolver = (packageName: string) => string; + +export class DependencyChecker { + private readonly resolver: Resolver; + private readonly missingDependencies = new Set(); + + constructor(projectSourceRoot: string) { + this.resolver = createProjectResolver(projectSourceRoot); + } + + /** + * Checks if a package is installed. + * @param packageName The name of the package to check. + * @returns True if the package is found, false otherwise. + */ + private isInstalled(packageName: string): boolean { + try { + this.resolver(packageName); + + return true; + } catch { + return false; + } + } + + /** + * Verifies that a package is installed and adds it to a list of missing + * dependencies if it is not. + * @param packageName The name of the package to check. + */ + check(packageName: string): void { + if (!this.isInstalled(packageName)) { + this.missingDependencies.add(packageName); + } + } + + /** + * Verifies that at least one of a list of packages is installed. If none are + * installed, a custom error message is added to the list of errors. + * @param packageNames An array of package names to check. + * @param customErrorMessage The error message to use if none of the packages are found. + */ + checkAny(packageNames: string[], customErrorMessage: string): void { + if (packageNames.every((name) => !this.isInstalled(name))) { + // This is a custom error, so we add it directly. + // Using a Set avoids duplicate custom messages. + this.missingDependencies.add(customErrorMessage); + } + } + + /** + * Throws a `MissingDependenciesError` if any dependencies were found to be missing. + * The error message is a formatted list of all missing packages. + */ + report(): void { + if (this.missingDependencies.size === 0) { + return; + } + + let message = 'The following packages are required but were not found:\n'; + for (const name of this.missingDependencies) { + message += ` - ${name}\n`; + } + message += 'Please install the missing packages and rerun the test command.'; + + throw new MissingDependenciesError(message); + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts b/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts new file mode 100644 index 000000000000..8fa7a5fb3632 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts @@ -0,0 +1,178 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import type { ApplicationBuilderInternalOptions } from '../../../application/options'; +import type { KarmaBuilderOptions, KarmaBuilderTransformsOptions } from '../../../karma'; +import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options'; +import type { TestExecutor } from '../api'; + +export class KarmaExecutor implements TestExecutor { + constructor( + private context: BuilderContext, + private options: NormalizedUnitTestBuilderOptions, + ) {} + + async *execute(): AsyncIterable { + const { context, options: unitTestOptions } = this; + + if (unitTestOptions.browserViewport) { + context.logger.warn( + 'The "karma" test runner does not support the "browserViewport" option. The option will be ignored.', + ); + } + + if (unitTestOptions.debug) { + context.logger.warn( + 'The "karma" test runner does not support the "debug" option. The option will be ignored.', + ); + } + + if (unitTestOptions.setupFiles.length) { + context.logger.warn( + 'The "karma" test runner does not support the "setupFiles" option. The option will be ignored.', + ); + } + + if (unitTestOptions.coverage?.include) { + context.logger.warn( + 'The "karma" test runner does not support the "coverageInclude" option. The option will be ignored.', + ); + } + + if (unitTestOptions.headless !== undefined) { + context.logger.warn( + 'The "karma" test runner does not support the "headless" option. The option will be ignored.', + ); + } + + if (unitTestOptions.providersFile) { + context.logger.warn( + 'The "karma" test runner does not support the "providersFile" option. The option will be ignored.', + ); + } + + if (unitTestOptions.outputFile) { + context.logger.warn( + 'The "karma" test runner does not support the "outputFile" option. The option will be ignored.', + ); + } + + if (unitTestOptions.coverage?.reporters) { + context.logger.warn( + 'The "karma" test runner does not support the "coverageReporters" option. The option will be ignored.', + ); + } + + const buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(unitTestOptions.buildTarget), + await context.getBuilderNameForTarget(unitTestOptions.buildTarget), + )) as unknown as ApplicationBuilderInternalOptions; + + let karmaConfig: string | undefined; + if (typeof unitTestOptions.runnerConfig === 'string') { + karmaConfig = unitTestOptions.runnerConfig; + context.logger.info(`Using Karma configuration file: ${karmaConfig}`); + } else if (unitTestOptions.runnerConfig) { + const potentialPath = path.join(unitTestOptions.projectRoot, 'karma.conf.js'); + try { + await fs.access(potentialPath); + karmaConfig = potentialPath; + context.logger.info(`Using Karma configuration file: ${karmaConfig}`); + } catch { + context.logger.info('No Karma configuration file found. Using default configuration.'); + } + } + + const karmaOptions: KarmaBuilderOptions = { + karmaConfig, + tsConfig: unitTestOptions.tsConfig ?? buildTargetOptions.tsConfig, + polyfills: injectTestingPolyfills(unitTestOptions.polyfills ?? buildTargetOptions.polyfills), + assets: buildTargetOptions.assets, + scripts: buildTargetOptions.scripts, + styles: buildTargetOptions.styles, + inlineStyleLanguage: buildTargetOptions.inlineStyleLanguage, + stylePreprocessorOptions: buildTargetOptions.stylePreprocessorOptions, + externalDependencies: buildTargetOptions.externalDependencies, + loader: buildTargetOptions.loader, + define: buildTargetOptions.define, + include: unitTestOptions.include, + exclude: unitTestOptions.exclude, + sourceMap: buildTargetOptions.sourceMap, + progress: unitTestOptions.buildProgress ?? buildTargetOptions.progress, + watch: unitTestOptions.watch, + poll: buildTargetOptions.poll, + preserveSymlinks: unitTestOptions.preserveSymlinks ?? buildTargetOptions.preserveSymlinks, + browsers: unitTestOptions.browsers?.join(','), + codeCoverage: unitTestOptions.coverage.enabled, + codeCoverageExclude: unitTestOptions.coverage.exclude, + fileReplacements: buildTargetOptions.fileReplacements, + reporters: unitTestOptions.reporters?.map((reporter) => { + // Karma only supports string reporters. + if (Object.keys(reporter[1]).length > 0) { + context.logger.warn( + `The "karma" test runner does not support options for the "${reporter[0]}" reporter. The options will be ignored.`, + ); + } + + return reporter[0]; + }), + webWorkerTsConfig: buildTargetOptions.webWorkerTsConfig, + aot: buildTargetOptions.aot, + }; + + const transformOptions = { + karmaOptions: (options) => { + if (unitTestOptions.filter) { + let filter = unitTestOptions.filter; + if (filter[0] === '/' && filter.at(-1) === '/') { + this.context.logger.warn( + 'The `--filter` option is always a regular expression. ' + + 'Leading and trailing `/` are not required and will be ignored.', + ); + } else { + filter = `/${filter}/`; + } + + options.client ??= {}; + options.client.args ??= []; + options.client.args.push('--grep', filter); + } + + // Add coverage options + if (unitTestOptions.coverage.enabled) { + const { thresholds, watermarks } = unitTestOptions.coverage; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const coverageReporter = ((options as any).coverageReporter ??= {}); + + if (thresholds) { + coverageReporter.check = thresholds.perFile + ? { each: thresholds } + : { global: thresholds }; + } + + if (watermarks) { + coverageReporter.watermarks = watermarks; + } + } + + return options; + }, + } satisfies KarmaBuilderTransformsOptions; + + const { execute } = await import('../../../karma'); + + yield* execute(karmaOptions, context, transformOptions); + } + + async [Symbol.asyncDispose](): Promise { + // The Karma builder handles its own teardown + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/karma/index.ts b/packages/angular/build/src/builders/unit-test/runners/karma/index.ts new file mode 100644 index 000000000000..cc9bba0aa1be --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/karma/index.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { TestRunner } from '../api'; +import { DependencyChecker } from '../dependency-checker'; +import { KarmaExecutor } from './executor'; + +/** + * A declarative definition of the Karma test runner. + */ +const KarmaTestRunner: TestRunner = { + name: 'karma', + isStandalone: true, + + validateDependencies(options) { + const checker = new DependencyChecker(options.projectSourceRoot); + checker.check('karma'); + checker.check('karma-jasmine'); + + // A custom configuration loads its own launcher plugins and may define custom launchers. + // The built-in configuration only loads the Chrome launcher, which also provides Chromium. + if (!options.runnerConfig) { + checker.check('karma-chrome-launcher'); + } + + if (options.coverage.enabled) { + checker.check('karma-coverage'); + } + + checker.report(); + }, + + getBuildOptions() { + return { + buildOptions: {}, + }; + }, + + async createExecutor(context, options) { + return new KarmaExecutor(context, options); + }, +}; + +export default KarmaTestRunner; diff --git a/packages/angular/build/src/builders/unit-test/runners/karma/index_spec.ts b/packages/angular/build/src/builders/unit-test/runners/karma/index_spec.ts new file mode 100644 index 000000000000..2e9f5f0876ef --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/karma/index_spec.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { NormalizedUnitTestBuilderOptions } from '../../options'; +import KarmaTestRunner from './index'; + +describe('KarmaTestRunner', () => { + describe('validateDependencies', () => { + function createOptions( + coverageEnabled: boolean, + options: Partial = {}, + ): NormalizedUnitTestBuilderOptions { + return { + projectSourceRoot: '/non-existent', + coverage: { enabled: coverageEnabled }, + ...options, + } as NormalizedUnitTestBuilderOptions; + } + + it('does not require karma-coverage when coverage is disabled', () => { + expect(() => KarmaTestRunner.validateDependencies?.(createOptions(false))).toThrowError( + /^(?!.*karma-coverage)/s, + ); + }); + + it('requires karma-coverage when coverage is enabled', () => { + expect(() => KarmaTestRunner.validateDependencies?.(createOptions(true))).toThrowError( + /karma-coverage/, + ); + }); + + it('requires karma-chrome-launcher for Chromium with the built-in configuration', () => { + const options = createOptions(false, { browsers: ['ChromiumHeadless'] }); + + expect(() => KarmaTestRunner.validateDependencies?.(options)).toThrowError( + /^(?!.*karma-chromium-launcher).*karma-chrome-launcher/s, + ); + }); + + it('does not require launchers for the browsers of a custom configuration', () => { + const options = createOptions(false, { + browsers: ['ChromeNoSandbox'], + runnerConfig: 'karma.conf.js', + }); + + expect(() => KarmaTestRunner.validateDependencies?.(options)).toThrowError( + /^(?!.*-launcher)/s, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts new file mode 100644 index 000000000000..8cc43f93424f --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts @@ -0,0 +1,249 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + BrowserBuiltinProvider, + BrowserConfigOptions, + BrowserProviderOption, +} from 'vitest/node'; +import { assertIsError } from '../../../../utils/error'; +import { createProjectResolver } from '../../../../utils/resolve-project'; + +export interface BrowserConfiguration { + browser?: BrowserConfigOptions; + errors?: string[]; + messages?: string[]; +} + +function findBrowserProvider( + projectResolver: (packageName: string) => string, +): BrowserBuiltinProvider | undefined { + const requiresPreview = !!process.versions.webcontainer; + + // One of these must be installed in the project to use browser testing + const vitestBuiltinProviders = requiresPreview + ? (['preview'] as const) + : (['playwright', 'webdriverio', 'preview'] as const); + + for (const providerName of vitestBuiltinProviders) { + try { + projectResolver(`@vitest/browser-${providerName}`); + + return providerName; + } catch {} + } + + return undefined; +} + +export interface BrowserInstanceConfiguration { + browser: string; + headless: boolean; + provider?: BrowserProviderOption; +} + +export function normalizeBrowserName(browserName: string): BrowserInstanceConfiguration { + // Normalize browser names to match Vitest's expectations for headless but also supports karma's names + // e.g., 'ChromeHeadless' -> 'chrome', 'FirefoxHeadless' -> 'firefox' + // and 'Chrome' -> 'chrome', 'Firefox' -> 'firefox'. + const normalized = browserName.toLowerCase(); + const headless = normalized.endsWith('headless'); + + return { + browser: headless ? normalized.slice(0, -8) : normalized, + headless: headless, + }; +} + +/** + * Mutates the provided browser instances to apply standard headless execution + * constraints based on the chosen provider, user options, and CI environment presence. + * + * @param instances The normalized browser instances to mutate. + * @param providerName The identifier for the chosen Vitest browser provider. + * @param headless The user-provided headless configuration option. + * @param isCI Whether the current environment is running in CI. + * @returns An array of informational messages generated during evaluation. + */ +export function applyHeadlessConfiguration( + instances: BrowserInstanceConfiguration[], + providerName: BrowserBuiltinProvider | undefined, + headless: boolean | undefined, + isCI: boolean, +): string[] { + const messages: string[] = []; + + if (providerName === 'preview') { + instances.forEach((instance) => { + // Preview mode only supports headed execution + instance.headless = false; + }); + + if (headless) { + messages.push('The "headless" option is ignored when using the "preview" provider.'); + } + } else if (headless !== undefined) { + if (headless) { + const allHeadlessByDefault = isCI || instances.every((i) => i.headless); + if (allHeadlessByDefault) { + messages.push( + 'The "headless" option is unnecessary as all browsers are already configured to run in headless mode.', + ); + } + } + + instances.forEach((instance) => { + instance.headless = headless; + }); + } else if (isCI) { + instances.forEach((instance) => { + instance.headless = true; + }); + } + + return messages; +} + +/** + * Resolves and configures the Vitest browser provider for the unit test builder. + * Dynamically discovers and imports the necessary provider (Playwright, WebdriverIO, or Preview), + * maps the requested browser instances, and applies environment-specific execution logic. + * + * @param browsers An array of requested browser names (e.g., 'chrome', 'firefox'). + * @param headless User-provided configuration for headless execution. + * @param debug Whether the builder is running in watch or debug mode. + * @param projectSourceRoot The root directory of the project being tested for resolving installed packages. + * @param viewport Optional viewport dimensions to apply to the launched browser instances. + * @returns A fully resolved Vitest browser configuration object alongside any generated warning or error messages. + */ +export async function setupBrowserConfiguration( + browsers: string[] | undefined, + headless: boolean | undefined, + debug: boolean, + projectSourceRoot: string, + viewport: { width: number; height: number } | undefined, +): Promise { + if (browsers === undefined) { + if (headless !== undefined) { + return { + messages: ['The "headless" option is ignored when no browsers are configured.'], + }; + } + + return {}; + } + + const projectResolver = createProjectResolver(projectSourceRoot); + let errors: string[] | undefined; + + const providerName = findBrowserProvider(projectResolver); + if (!providerName) { + errors ??= []; + errors.push( + 'The "browsers" option requires either "@vitest/browser-playwright", "@vitest/browser-webdriverio", ' + + 'or "@vitest/browser-preview" to be installed within the project.' + + ' Please install one of these packages and rerun the test command.', + ); + } + + const instances = browsers.map(normalizeBrowserName); + + let provider: import('vitest/node').BrowserProviderOption | undefined; + if (providerName) { + const providerPackage = `@vitest/browser-${providerName}`; + try { + const providerModule = await import(projectResolver(providerPackage)); + + // Validate that the imported module has the expected structure + const providerFactory = providerModule[providerName]; + if (typeof providerFactory === 'function') { + const executablePath = process.env['CHROME_BIN']; + + if (providerName === 'playwright') { + const baseOptions = { + contextOptions: { + // Enables `prefer-color-scheme` for Vitest browser instead of `light` + colorScheme: null, + }, + }; + + provider = providerFactory(baseOptions); + + if (executablePath) { + for (const instance of instances) { + if (instance.browser === 'chrome' || instance.browser === 'chromium') { + instance.provider = providerFactory({ + ...baseOptions, + launchOptions: { executablePath }, + }); + } + } + } + } else if (providerName === 'webdriverio') { + provider = providerFactory(); + + if (executablePath) { + for (const instance of instances) { + if (instance.browser === 'chrome' || instance.browser === 'chromium') { + instance.provider = providerFactory({ + capabilities: { + 'goog:chromeOptions': { + binary: executablePath, + args: executablePath.includes('rules_browsers') + ? ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] + : undefined, + }, + }, + }); + } + } + } + } else { + provider = providerFactory(); + } + } else { + errors ??= []; + errors.push( + `The "${providerPackage}" package does not have a valid browser provider export.`, + ); + } + } catch (e) { + assertIsError(e); + errors ??= []; + // Check for a module not found error to provide a more specific message + if (e.code === 'ERR_MODULE_NOT_FOUND') { + errors.push( + `The "browsers" option with "${providerName}" requires the "${providerPackage}" package.` + + ' Please install this package and rerun the test command.', + ); + } else { + // Handle other potential errors during import + errors.push( + `An error occurred while loading the "${providerPackage}" browser provider:\n ${e.message}`, + ); + } + } + } + + if (errors) { + return { errors }; + } + + const isCI = !!process.env['CI']; + const messages = applyHeadlessConfiguration(instances, providerName, headless, isCI); + + const browser = { + enabled: true, + provider, + ui: !isCI && instances.some((instance) => !instance.headless), + viewport, + instances, + } satisfies BrowserConfigOptions; + + return { browser, messages }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts new file mode 100644 index 000000000000..0dd0778420bd --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts @@ -0,0 +1,320 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { applyHeadlessConfiguration, setupBrowserConfiguration } from './browser-provider'; + +describe('setupBrowserConfiguration', () => { + let workspaceRoot: string; + + beforeEach(async () => { + // Create a temporary workspace root + workspaceRoot = await mkdtemp(join(tmpdir(), 'angular-cli-test-')); + await writeFile(join(workspaceRoot, 'package.json'), '{}'); + + // Create a mock @vitest/browser-playwright package + const playwrightPkgPath = join(workspaceRoot, 'node_modules/@vitest/browser-playwright'); + await mkdir(playwrightPkgPath, { recursive: true }); + await writeFile( + join(playwrightPkgPath, 'package.json'), + JSON.stringify({ name: '@vitest/browser-playwright', main: 'index.js' }), + ); + await writeFile( + join(playwrightPkgPath, 'index.js'), + 'module.exports = { playwright: (options) => ({ name: "playwright", options }) };', + ); + }); + + afterEach(async () => { + await rm(workspaceRoot, { recursive: true, force: true }); + }); + + it('should configure headless mode for specific browsers based on name', async () => { + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless', 'Firefox'], + undefined, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.enabled).toBeTrue(); + expect(browser?.instances).toEqual([ + jasmine.objectContaining({ browser: 'chrome', headless: true }), + jasmine.objectContaining({ browser: 'firefox', headless: false }), + ]); + }); + + it('should force headless mode in CI environment', async () => { + const originalCI = process.env['CI']; + process.env['CI'] = 'true'; + + try { + const { browser } = await setupBrowserConfiguration( + ['Chrome', 'FirefoxHeadless'], + undefined, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.instances).toEqual([ + jasmine.objectContaining({ browser: 'chrome', headless: true }), + jasmine.objectContaining({ browser: 'firefox', headless: true }), + ]); + } finally { + if (originalCI === undefined) { + delete process.env['CI']; + } else { + process.env['CI'] = originalCI; + } + } + }); + + it('should set ui property based on headless instances (local)', async () => { + // Local run (not CI) + const originalCI = process.env['CI']; + delete process.env['CI']; + + try { + // Case 1: All headless -> UI false + let result = await setupBrowserConfiguration( + ['ChromeHeadless'], + undefined, + false, + workspaceRoot, + undefined, + ); + expect(result.browser?.ui).toBeFalse(); + + // Case 2: Mixed -> UI true + result = await setupBrowserConfiguration( + ['ChromeHeadless', 'Firefox'], + undefined, + false, + workspaceRoot, + undefined, + ); + expect(result.browser?.ui).toBeTrue(); + } finally { + if (originalCI !== undefined) { + process.env['CI'] = originalCI; + } + } + }); + + it('should disable UI in CI even if headed browsers are requested', async () => { + const originalCI = process.env['CI']; + process.env['CI'] = 'true'; + + try { + const { browser } = await setupBrowserConfiguration( + ['Chrome'], + undefined, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.ui).toBeFalse(); + // And verify instances are forced to headless + expect(browser?.instances?.[0].headless).toBeTrue(); + } finally { + if (originalCI === undefined) { + delete process.env['CI']; + } else { + process.env['CI'] = originalCI; + } + } + }); + + // See: https://github.com/angular/angular-cli/issues/32469 + it('should pass colorScheme=null to Playwright provider', async () => { + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless'], + undefined, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.provider?.options).toEqual( + jasmine.objectContaining({ + contextOptions: jasmine.objectContaining({ + colorScheme: null, + }), + }), + ); + }); + + it('should support Preview provider forcing headless false', async () => { + // Create mock preview package + const previewPkgPath = join(workspaceRoot, 'node_modules/@vitest/browser-preview'); + await mkdir(previewPkgPath, { recursive: true }); + await writeFile( + join(previewPkgPath, 'package.json'), + JSON.stringify({ name: '@vitest/browser-preview', main: 'index.js' }), + ); + await writeFile( + join(previewPkgPath, 'index.js'), + 'module.exports = { preview: () => ({ name: "preview" }) };', + ); + + // Remove playwright mock for this test to force usage of preview + await rm(join(workspaceRoot, 'node_modules/@vitest/browser-playwright'), { + recursive: true, + force: true, + }); + + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless'], + undefined, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.provider).toBeDefined(); + // Preview forces headless false + expect(browser?.instances?.[0].headless).toBeFalse(); + }); + + it('should force headless mode when headless option is true', async () => { + const { browser, messages } = await setupBrowserConfiguration( + ['Chrome', 'Firefox'], + true, + false, + workspaceRoot, + undefined, + ); + + expect(browser?.instances).toEqual([ + jasmine.objectContaining({ browser: 'chrome', headless: true }), + jasmine.objectContaining({ browser: 'firefox', headless: true }), + ]); + expect(messages).toEqual([]); + }); + + it('should return information message when headless option is redundant', async () => { + const { messages } = await setupBrowserConfiguration( + ['ChromeHeadless'], + true, + false, + workspaceRoot, + undefined, + ); + + expect(messages).toEqual([ + 'The "headless" option is unnecessary as all browsers are already configured to run in headless mode.', + ]); + }); + + describe('CHROME_BIN usage', () => { + let originalChromeBin: string | undefined; + + beforeEach(() => { + originalChromeBin = process.env['CHROME_BIN']; + process.env['CHROME_BIN'] = '/custom/path/to/chrome'; + }); + + afterEach(() => { + if (originalChromeBin === undefined) { + delete process.env['CHROME_BIN']; + } else { + process.env['CHROME_BIN'] = originalChromeBin; + } + }); + + it('should set executablePath on the individual chrome instance', async () => { + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless', 'Chromium'], + undefined, + false, + workspaceRoot, + undefined, + ); + + // Verify the global provider does NOT have executablePath + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((browser?.provider as any)?.options?.launchOptions?.executablePath).toBeUndefined(); + + // Verify the individual instances have executablePath + expect( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (browser?.instances?.[0]?.provider as any)?.options?.launchOptions?.executablePath, + ).toBe('/custom/path/to/chrome'); + expect( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (browser?.instances?.[1]?.provider as any)?.options?.launchOptions?.executablePath, + ).toBe('/custom/path/to/chrome'); + }); + + it('should set executablePath for chrome instances but not for others when mixed browsers are requested', async () => { + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless', 'Firefox'], + undefined, + false, + workspaceRoot, + undefined, + ); + + // Verify the global provider does NOT have executablePath + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect((browser?.provider as any)?.options?.launchOptions?.executablePath).toBeUndefined(); + + // Verify chrome gets it + expect( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (browser?.instances?.[0]?.provider as any)?.options?.launchOptions?.executablePath, + ).toBe('/custom/path/to/chrome'); + + // Verify firefox does not + expect(browser?.instances?.[1]?.provider).toBeUndefined(); + }); + }); + + describe('applyHeadlessConfiguration', () => { + it('should set headless false and issue warning when using preview provider with headless true', () => { + const instances = [{ browser: 'chrome', headless: true }]; + const messages = applyHeadlessConfiguration(instances, 'preview', true, false); + + expect(instances[0].headless).toBeFalse(); + expect(messages).toEqual([ + 'The "headless" option is ignored when using the "preview" provider.', + ]); + }); + + it('should force headless mode when headless option is true', () => { + const instances = [{ browser: 'chrome', headless: false }]; + const messages = applyHeadlessConfiguration(instances, 'playwright', true, false); + + expect(instances[0].headless).toBeTrue(); + expect(messages).toEqual([]); + }); + + it('should return information message when headless option is redundant', () => { + const instances = [{ browser: 'chrome', headless: true }]; + const messages = applyHeadlessConfiguration(instances, 'playwright', true, false); + + expect(instances[0].headless).toBeTrue(); + expect(messages).toEqual([ + 'The "headless" option is unnecessary as all browsers are already configured to run in headless mode.', + ]); + }); + + it('should force headless mode in CI environment when headless is undefined', () => { + const instances = [{ browser: 'chrome', headless: false }]; + const messages = applyHeadlessConfiguration(instances, 'playwright', undefined, true); + + expect(instances[0].headless).toBeTrue(); + expect(messages).toEqual([]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts new file mode 100644 index 000000000000..efff72e5d8bb --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts @@ -0,0 +1,339 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * Provides Vitest-specific build options and virtual file contents for Angular unit testing. + */ + +import type { BuilderContext } from '@angular-devkit/architect'; +import path from 'node:path'; +import { toPosixPath } from '../../../../utils/path'; +import { createProjectResolver } from '../../../../utils/resolve-project'; +import type { ApplicationBuilderInternalOptions } from '../../../application/options'; +import { OutputHashing } from '../../../application/schema'; +import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options'; +import { findTests, getTestEntrypoints } from '../../test-discovery'; +import { RunnerOptions } from '../api'; + +/** + * Creates the virtual file contents to initialize the Angular testing environment (TestBed). + * + * @param providersFile Optional path to a file that exports default providers. + * @param projectSourceRoot The root directory of the project source. + * @param teardown Whether to configure TestBed to destroy after each test. + * @returns The string content of the virtual initialization file. + */ +function createTestBedInitVirtualFile( + providersFile: string | undefined, + projectSourceRoot: string, + teardown: boolean, + hasLocalize: boolean, +): string { + let providersImport = 'const providers = [];'; + if (providersFile) { + const relativePath = path.relative(projectSourceRoot, providersFile); + const { dir, name } = path.parse(relativePath); + const importPath = toPosixPath(path.join(dir, name)); + providersImport = `import providers from './${importPath}';`; + } + + // The DynamicDOMTestComponentRenderer is used to avoid stale document references + // when running Vitest in non-isolated mode with JSDOM. It looks up the + // document dynamically on every operation instead of caching it. + return ` + ${hasLocalize ? "import '@angular/localize/init';" : ''} + // Initialize the Angular testing environment + import { NgModule, provideZoneChangeDetection } from '@angular/core'; + import { getTestBed, ɵgetCleanupHook as getCleanupHook, TestComponentRenderer } from '@angular/core/testing'; + import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; + import { ɵgetDOM } from '@angular/common'; + import { afterEach, beforeEach } from 'vitest'; + ${providersImport} + + // The beforeEach and afterEach hooks are registered outside the globalThis guard. + // This ensures that the hooks are always applied, even in non-isolated browser environments. + // Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29 + beforeEach(getCleanupHook(false)); + afterEach(getCleanupHook(true)); + + class DynamicDOMTestComponentRenderer extends TestComponentRenderer { + insertRootElement(rootElId, tagName = 'div') { + this.removeAllRootElements(); + + const dom = ɵgetDOM(); + const doc = dom.getDefaultDocument(); + if (doc && doc.body) { + const rootElement = doc.createElement(tagName); + rootElement.setAttribute('id', rootElId); + doc.body.appendChild(rootElement); + } + } + + removeAllRootElements() { + const dom = ɵgetDOM(); + const doc = dom.getDefaultDocument(); + if (doc && typeof doc.querySelectorAll === 'function') { + const oldRoots = doc.querySelectorAll('[id^=root]'); + for (let i = 0; i < oldRoots.length; i++) { + dom.remove(oldRoots[i]); + } + } + } + } + + const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup'); + if (!globalThis[ANGULAR_TESTBED_SETUP]) { + globalThis[ANGULAR_TESTBED_SETUP] = true; + + // The Angular TestBed needs to be initialized before any tests are run. + // In a non-isolated environment, this setup file can be executed multiple times. + // The guard condition above ensures that the setup is only performed once. + + @NgModule({ + providers: [ + ...(typeof Zone !== 'undefined' ? [provideZoneChangeDetection()] : []), + ...providers, + { provide: TestComponentRenderer, useClass: DynamicDOMTestComponentRenderer }, + ], + }) + class TestModule {} + + getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), { + errorOnUnknownElements: true, + errorOnUnknownProperties: true, + ${teardown === false ? 'teardown: { destroyAfterEach: false },' : ''} + }); + } + `; +} + +/** + * Adjusts output hashing settings for testing purposes. For example, ensuring media + * is continued to be hashed to avoid overwriting assets, but turning off JavaScript hashing. + * + * @param hashing The original OutputHashing configuration. + * @returns The adjusted OutputHashing configuration. + */ +function adjustOutputHashing(hashing?: OutputHashing): OutputHashing { + switch (hashing) { + case OutputHashing.All: + case OutputHashing.Media: + // Ensure media is continued to be hashed to avoid overwriting of output media files + return OutputHashing.Media; + default: + return OutputHashing.None; + } +} + +/** + * Injects Zone.js and Zone.js testing polyfills into the build options based on the + * project configuration and `polyfills` option. + * + * @param polyfills The configured polyfills from the test or build target. + * @param projectSourceRoot The root directory of the project source. + * @param logger The logger instance for reporting deprecation warnings. + * @returns An array of polyfill specifiers to use for testing. + */ +function injectZoneJsTestingPolyfills( + polyfills: string[] | undefined, + projectSourceRoot: string, + logger: BuilderContext['logger'], +): string[] { + if (polyfills) { + return injectTestingPolyfills(polyfills); + } + + // If polyfills is undefined (e.g. library build target), attempt to load zone.js if installed. + try { + const projectResolve = createProjectResolver(projectSourceRoot); + projectResolve('zone.js'); + + logger.warn( + 'Zone.js polyfills are being automatically injected because "zone.js" was detected in the project dependencies. ' + + 'This behavior is deprecated. If your project is zoneless, set the "polyfills" option to an empty array ("[]") in the ' + + 'test configuration. Otherwise, explicitly add "zone.js" to the "polyfills" option.', + ); + + return ['zone.js', 'zone.js/testing']; + } catch { + return []; + } +} + +/** + * Generates options and virtual files for the Vitest test runner. + * + * Discovers specs matchers, creates entry points, decides polyfills strategy, and orchestrates + * internal ApplicationBuilder options. + * + * @param options The normalized unit test builder options. + * @param baseBuildOptions The base build config to derive testing config from. + * @param logger The logger instance for reporting deprecation warnings. + * @returns An async RunnerOptions configuration. + */ +export async function getVitestBuildOptions( + options: NormalizedUnitTestBuilderOptions, + baseBuildOptions: Partial, + logger: BuilderContext['logger'], +): Promise { + const { + workspaceRoot, + projectSourceRoot, + include, + polyfills, + exclude = [], + watch, + providersFile, + setupFiles, + } = options; + + // Find test files + const testFiles = await findTests(include, exclude, workspaceRoot, projectSourceRoot); + if (testFiles.length === 0) { + throw new Error( + 'No tests found matching the following patterns:\n' + + `- Included: ${include.join(', ')}\n` + + (exclude.length ? `- Excluded: ${exclude.join(', ')}\n` : '') + + `\nPlease check the 'test' target configuration in your project's 'angular.json' file.`, + ); + } + + const entryPoints = getTestEntrypoints(testFiles, { + projectSourceRoot, + workspaceRoot, + removeTestExtension: true, + }); + + const rootFiles = [...testFiles]; + if (providersFile) { + rootFiles.push(providersFile); + } + + if (setupFiles?.length) { + rootFiles.push(...setupFiles); + + const setupEntryPoints = getTestEntrypoints(setupFiles, { + projectSourceRoot, + workspaceRoot, + removeTestExtension: false, + prefix: 'setup', + }); + + for (const [entryPoint, setupFile] of setupEntryPoints) { + entryPoints.set(entryPoint, setupFile); + } + } + + // The Angular compiler facade must be loaded in a dedicated setup file before TestBed initialization. + // This ensures the compiler facade is published before 'init-testbed' or any shared code-split chunks + // (such as those from a configured 'providersFile') are evaluated. + entryPoints.set('init-compiler', 'angular:compiler-init'); + entryPoints.set('init-testbed', 'angular:test-bed-init'); + entryPoints.set('vitest-mock-patch', 'angular:vitest-mock-patch'); + + // The 'vitest' package is always external for testing purposes + const externalDependencies = ['vitest']; + if (baseBuildOptions.externalDependencies) { + externalDependencies.push(...baseBuildOptions.externalDependencies); + } + + const buildOptions: Partial = { + ...baseBuildOptions, + polyfills: injectZoneJsTestingPolyfills( + polyfills ?? baseBuildOptions.polyfills, + projectSourceRoot, + logger, + ), + watch, + incrementalResults: watch, + index: false, + browser: undefined, + server: undefined, + outputMode: undefined, + localize: false, + budgets: [], + serviceWorker: false, + appShell: false, + ssr: false, + prerender: false, + sourceMap: { scripts: true, vendor: false, styles: false }, + outputHashing: adjustOutputHashing(baseBuildOptions.outputHashing), + optimization: false, + namedChunks: false, + entryPoints, + rootFiles, + // Vitest's Node-based module loading emulation (vite-node) is not fully spec compliant and lacks + // live ESM bindings across chunk boundaries. This can cause uninitialized exports or break mocking. + // Disabling code splitting avoids shared chunks, but increases build and coverage memory/time. + disableCodeSplitting: !options.splitting, + // Enable support for vitest browser prebundling. Excludes can be controlled with a runnerConfig + // and the `optimizeDeps.exclude` option. + externalPackages: true, + externalDependencies, + }; + + let hasLocalize = false; + try { + const projectResolve = createProjectResolver(projectSourceRoot); + projectResolve('@angular/localize'); + hasLocalize = true; + } catch {} + + const testBedInitContents = createTestBedInitVirtualFile( + providersFile, + projectSourceRoot, + !options.debug, + hasLocalize, + ); + + const mockPatchContents = ` + import { vi } from 'vitest'; + + const ANGULAR_VITEST_MOCK_PATCH = Symbol.for('@angular/cli/vitest-mock-patch'); + if (!globalThis[ANGULAR_VITEST_MOCK_PATCH]) { + globalThis[ANGULAR_VITEST_MOCK_PATCH] = true; + + const error = new Error( + 'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' + + 'Please use Angular TestBed for mocking dependencies.' + ); + + // Store original implementations + const { mock, doMock, importMock, unmock, doUnmock } = vi; + + function patch(original) { + return (path, ...args) => { + // Check if the path is a string and starts with a character that indicates a relative path. + if (typeof path === 'string' && /^[./]/.test(path)) { + throw error; + } + + // Call the original function for non-relative paths. + return original(path, ...args); + }; + } + + vi.mock = patch(mock); + vi.doMock = patch(doMock); + vi.importMock = patch(importMock); + vi.unmock = patch(unmock); + vi.doUnmock = patch(doUnmock); + } + `; + + return { + buildOptions, + virtualFiles: { + 'angular:compiler-init': "import '@angular/compiler';", + 'angular:test-bed-init': testBedInitContents, + 'angular:vitest-mock-patch': mockPatchContents, + }, + testEntryPointMappings: entryPoints, + }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options.ts new file mode 100644 index 000000000000..ce428f36515a --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { CliOptions } from 'vitest/node'; +import type { NormalizedUnitTestBuilderOptions } from '../../options'; + +/** + * The subset of the normalized builder options that are used to create the Vitest CLI options. + */ +export interface VitestCliOptionsSource extends Pick< + NormalizedUnitTestBuilderOptions, + 'workspaceRoot' | 'watch' | 'outputFile' | 'filter' | 'ui' | 'debug' +> { + cacheOptions: Pick; +} + +/** + * Creates the Vitest CLI level options from the normalized builder options. + * These are the options that Vitest would otherwise receive from its own command line. + * + * @param options The normalized builder options to convert. + * @param project The name of the Vitest project to execute. + * @param configPath The path to an external Vitest configuration file, if any. + * @param runnerArgOptions The Vitest CLI options from the `runnerArgs` builder option, if any. + * The options created from the other builder options take precedence over these. + * @returns The Vitest CLI options. + */ +export function createVitestCliOptions( + options: VitestCliOptionsSource, + project: string, + configPath: string | false | undefined, + runnerArgOptions?: CliOptions, +): CliOptions { + const { workspaceRoot, watch, outputFile, cacheOptions, filter, ui, debug } = options; + + return { + ...runnerArgOptions, + config: configPath, + root: workspaceRoot, + project, + watch, + ...(outputFile !== undefined ? { outputFile } : {}), + ...(cacheOptions.enabled ? {} : { cache: false as const }), + ...(filter !== undefined ? { testNamePattern: filter } : {}), + ...(typeof ui === 'boolean' ? { ui } : {}), + ...(debug ? { inspectBrk: true, isolate: false, fileParallelism: false } : {}), + }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options_spec.ts new file mode 100644 index 000000000000..c940e7695138 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/cli-options_spec.ts @@ -0,0 +1,101 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type VitestCliOptionsSource, createVitestCliOptions } from './cli-options'; + +describe('createVitestCliOptions', () => { + const baseOptions: VitestCliOptionsSource = { + workspaceRoot: '/workspace', + watch: false, + outputFile: undefined, + cacheOptions: { enabled: true }, + filter: undefined, + ui: undefined, + debug: false, + }; + + it('should provide the root, project, watch mode, and configuration file', () => { + expect(createVitestCliOptions(baseOptions, 'app', '/workspace/vitest-base.config.mts')).toEqual( + { + config: '/workspace/vitest-base.config.mts', + root: '/workspace', + project: 'app', + watch: false, + }, + ); + }); + + it('should disable configuration file lookup when no configuration file is used', () => { + expect(createVitestCliOptions(baseOptions, 'app', false).config).toBeFalse(); + }); + + it('should only include the output file when it is defined', () => { + expect('outputFile' in createVitestCliOptions(baseOptions, 'app', false)).toBeFalse(); + expect( + createVitestCliOptions({ ...baseOptions, outputFile: 'results.json' }, 'app', false) + .outputFile, + ).toBe('results.json'); + }); + + it('should disable the Vitest cache when the Angular CLI cache is disabled', () => { + expect('cache' in createVitestCliOptions(baseOptions, 'app', false)).toBeFalse(); + expect( + createVitestCliOptions({ ...baseOptions, cacheOptions: { enabled: false } }, 'app', false) + .cache, + ).toBeFalse(); + }); + + it('should map the filter option to the test name pattern', () => { + expect('testNamePattern' in createVitestCliOptions(baseOptions, 'app', false)).toBeFalse(); + expect( + createVitestCliOptions({ ...baseOptions, filter: 'should work' }, 'app', false) + .testNamePattern, + ).toBe('should work'); + }); + + it('should only include the UI option when it is a boolean', () => { + expect('ui' in createVitestCliOptions(baseOptions, 'app', false)).toBeFalse(); + expect(createVitestCliOptions({ ...baseOptions, ui: false }, 'app', false).ui).toBeFalse(); + expect(createVitestCliOptions({ ...baseOptions, ui: true }, 'app', false).ui).toBeTrue(); + }); + + it('should configure the inspector and disable parallelism when debugging', () => { + const options = createVitestCliOptions({ ...baseOptions, debug: true }, 'app', false); + + expect(options.inspectBrk).toBeTrue(); + expect(options.isolate).toBeFalse(); + expect(options.fileParallelism).toBeFalse(); + }); + + it('should include the options from the runner arguments', () => { + const options = createVitestCliOptions(baseOptions, 'app', false, { update: true, bail: 1 }); + + expect(options.update).toBeTrue(); + expect(options.bail).toBe(1); + }); + + it('should prefer the builder options over the options from the runner arguments', () => { + const options = createVitestCliOptions({ ...baseOptions, filter: 'builder' }, 'app', false, { + root: '/other', + watch: true, + testNamePattern: 'runner', + }); + + expect(options.root).toBe('/workspace'); + expect(options.watch).toBeFalse(); + expect(options.testNamePattern).toBe('builder'); + }); + + it('should not configure the inspector when not debugging', () => { + const options = createVitestCliOptions(baseOptions, 'app', false); + + expect('inspectBrk' in options).toBeFalse(); + expect('isolate' in options).toBeFalse(); + expect('fileParallelism' in options).toBeFalse(); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts new file mode 100644 index 000000000000..6df583350e07 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * This file contains utility functions for finding the Vitest base configuration file. + */ + +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; + +/** + * A list of potential Vitest configuration filenames. + * The order of the files is important as the first one found will be used. + */ +const POTENTIAL_CONFIGS = [ + 'vitest-base.config.ts', + 'vitest-base.config.mts', + 'vitest-base.config.cts', + 'vitest-base.config.js', + 'vitest-base.config.mjs', + 'vitest-base.config.cjs', +]; + +/** + * Finds the Vitest configuration file in the given search directories. + * + * @param searchDirs An array of directories to search for the configuration file. + * @returns The path to the configuration file, or `false` if no file is found. + * Returning `false` is used to disable Vitest's default configuration file search. + */ +export async function findVitestBaseConfig(searchDirs: string[]): Promise { + const uniqueDirs = new Set(searchDirs); + for (const dir of uniqueDirs) { + try { + const entries = await readdir(dir, { withFileTypes: true }); + const files = new Set(entries.filter((e) => e.isFile()).map((e) => e.name)); + + for (const potential of POTENTIAL_CONFIGS) { + if (files.has(potential)) { + return path.join(dir, potential); + } + } + } catch { + // Ignore directories that cannot be read + } + } + + return false; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts new file mode 100644 index 000000000000..c67d6feab31b --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts @@ -0,0 +1,426 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import assert from 'node:assert'; +import path from 'node:path'; +import { setTimeout } from 'node:timers/promises'; +import type * as Vite from 'vite' with { + 'resolution-mode': 'import', +}; +import type { Vitest } from 'vitest/node'; +import { + DevServerExternalResultMetadata, + updateExternalMetadata, +} from '../../../../tools/vite/utils'; +import { assertIsError } from '../../../../utils/error'; +import { toPosixPath } from '../../../../utils/path'; +import { + type FullResult, + type IncrementalResult, + type ResultFile, + ResultKind, +} from '../../../application/results'; +import { NormalizedUnitTestBuilderOptions } from '../../options'; +import type { TestExecutor } from '../api'; +import { setupBrowserConfiguration } from './browser-provider'; +import { createVitestCliOptions } from './cli-options'; +import { findVitestBaseConfig } from './configuration'; +import { createVitestConfigPlugin, createVitestPlugins, rebasePath } from './plugins'; +import type { RunnerArgOptions } from './runner-args'; + +enum DebugLogLevel { + Info = 1, + Verbose = 2, +} + +export class VitestExecutor implements TestExecutor { + private vitest: Vitest | undefined; + private normalizePath: ((id: string) => string) | undefined; + private readonly projectName: string; + private readonly options: NormalizedUnitTestBuilderOptions; + private readonly logger: BuilderContext['logger']; + private readonly runnerArgOptions: RunnerArgOptions | undefined; + private readonly buildResultFiles = new Map(); + private readonly externalMetadata: DevServerExternalResultMetadata = { + implicitBrowser: [], + implicitServer: [], + explicitBrowser: [], + explicitServer: [], + }; + private readonly debugLevel: number; + + // This is a reverse map of the entry points created in `build-options.ts`. + // It is used by the in-memory provider plugin to map the requested test file + // path back to its bundled output path. + // Example: `Map<'/path/to/src/app.spec.ts', 'spec-src-app-spec'>` + private readonly testFileToEntryPoint = new Map(); + private readonly entryPointToTestFile = new Map(); + + constructor( + projectName: string, + options: NormalizedUnitTestBuilderOptions, + testEntryPointMappings: Map | undefined, + logger: BuilderContext['logger'], + runnerArgOptions?: RunnerArgOptions, + ) { + const level = parseInt(process.env['NG_TEST_LOG'] ?? '0', 10); + this.debugLevel = isNaN(level) ? 0 : level; + + this.projectName = projectName; + this.options = options; + this.logger = logger; + this.runnerArgOptions = runnerArgOptions; + + this.debugLog(DebugLogLevel.Info, 'VitestExecutor instantiated.'); + this.debugLog(DebugLogLevel.Verbose, 'NormalizedUnitTestBuilderOptions:', options); + + if (testEntryPointMappings) { + for (const [entryPoint, testFile] of testEntryPointMappings) { + this.testFileToEntryPoint.set(testFile, entryPoint); + this.entryPointToTestFile.set(entryPoint + '.js', testFile); + } + this.debugLog( + DebugLogLevel.Verbose, + 'Test entry point mappings:', + Object.fromEntries(testEntryPointMappings), + ); + } + } + + private debugLog(level: DebugLogLevel, message: string, data?: object) { + if (this.debugLevel < level) { + return; + } + + const formattedMessage = `[VitestExecutor:${DebugLogLevel[level]}] ${message}`; + // Custom formatting for data object to ensure it's readable + const logData = data ? JSON.stringify(data, null, 2) : ''; + this.logger.info(`${formattedMessage}${logData ? `\n${logData}` : ''}`); + } + + async *execute(buildResult: FullResult | IncrementalResult): AsyncIterable { + this.debugLog(DebugLogLevel.Info, `Executing test run (kind: ${buildResult.kind}).`); + this.normalizePath ??= ((await import('vite' as string)) as typeof Vite).normalizePath; + + if (buildResult.kind === ResultKind.Full) { + this.buildResultFiles.clear(); + for (const file of buildResult.files) { + this.buildResultFiles.set(this.normalizePath(file.path), file); + } + this.debugLog( + DebugLogLevel.Info, + `Full build results received. Total files: ${this.buildResultFiles.size}.`, + ); + } else { + this.debugLog( + DebugLogLevel.Info, + `Incremental build results received.` + + `Added: ${buildResult.added.length}, Modified: ${buildResult.modified.length}, Removed: ${buildResult.removed.length}.`, + ); + this.debugLog(DebugLogLevel.Verbose, 'Added files:', buildResult.added); + this.debugLog(DebugLogLevel.Verbose, 'Modified files:', buildResult.modified); + this.debugLog(DebugLogLevel.Verbose, 'Removed files:', buildResult.removed); + + for (const file of buildResult.removed) { + this.buildResultFiles.delete(this.normalizePath(file.path)); + } + for (const file of buildResult.files) { + this.buildResultFiles.set(this.normalizePath(file.path), file); + } + } + + updateExternalMetadata(buildResult, this.externalMetadata, undefined, true); + this.debugLog(DebugLogLevel.Verbose, 'Updated external metadata:', this.externalMetadata); + + // Reset the exit code to allow for a clean state. + // This is necessary because Vitest may set the exit code on failure, which can + // affect subsequent runs in watch mode or when running multiple builders. + process.exitCode = 0; + + // Initialize Vitest if not already present. + this.vitest ??= await this.initializeVitest(); + const vitest = this.vitest; + + let testResults; + if (buildResult.kind === ResultKind.Incremental) { + const vitestRoot = vitest.config.root; + const workspaceRoot = this.options.workspaceRoot; + const isAliasedRoot = Boolean(vitestRoot && vitestRoot !== toPosixPath(workspaceRoot)); + const activeRoot = isAliasedRoot ? vitestRoot : workspaceRoot; + + // To rerun tests, Vitest needs the original test file paths, not the output paths. + const modifiedSourceFiles = new Set(); + for (const modifiedFile of [...buildResult.modified, ...buildResult.added]) { + // The `modified` files in the build result are the output paths. + // We need to find the original source file path to pass to Vitest. + const source = this.entryPointToTestFile.get(modifiedFile); + if (source) { + this.debugLog( + DebugLogLevel.Verbose, + `Mapped output file '${modifiedFile}' to source file '${source}' for re-run.`, + ); + modifiedSourceFiles.add(source); + } else { + this.debugLog( + DebugLogLevel.Verbose, + `Could not map output file '${modifiedFile}' to a source file. It may not be a test file.`, + ); + } + vitest.invalidateFile(this.normalizePath(path.join(activeRoot, modifiedFile))); + } + + const specsToRerun = []; + for (const file of modifiedSourceFiles) { + const targetFile = isAliasedRoot ? rebasePath(file, workspaceRoot, vitestRoot) : file; + vitest.invalidateFile(targetFile); + const specs = vitest.getModuleSpecifications(targetFile); + if (specs) { + specsToRerun.push(...specs); + } + } + + if (specsToRerun.length > 0) { + this.debugLog(DebugLogLevel.Info, `Re-running ${specsToRerun.length} test specifications.`); + this.debugLog(DebugLogLevel.Verbose, 'Specs to rerun:', specsToRerun); + testResults = await vitest.rerunTestSpecifications(specsToRerun); + } else { + this.debugLog(DebugLogLevel.Info, 'No test specifications to rerun.'); + } + } + + // Check if all the tests pass to calculate the result + const testModules = testResults?.testModules ?? this.vitest.state.getTestModules(); + + let success = testModules.every((testModule) => testModule.ok()); + let finalResultReason = 'All tests passed.'; + + // Vitest does not return a failure result when coverage thresholds are not met. + // Instead, it sets the process exit code to 1. + // We check this exit code to determine if the test run should be considered a failure. + if (success && process.exitCode === 1) { + success = false; + finalResultReason = 'Test run failed due to unmet coverage thresholds.'; + // Reset the exit code to prevent it from carrying over to subsequent runs/builds + process.exitCode = 0; + } + + this.debugLog( + DebugLogLevel.Info, + `Test run finished with success: ${success}. Reason: ${finalResultReason}`, + ); + yield { success }; + } + + async [Symbol.asyncDispose](): Promise { + if (!this.vitest) { + return; + } + + this.debugLog(DebugLogLevel.Info, 'Disposing VitestExecutor: Closing Vitest instance.'); + + const controller = new AbortController(); + const timeoutMs = 10_000; + + try { + await Promise.race([ + this.vitest.close(), + setTimeout(timeoutMs, undefined, { signal: controller.signal, ref: false }) + .then(() => { + this.logger.warn( + `Vitest instance failed to close cleanly within ${timeoutMs}ms. Continuing teardown...`, + ); + }) + .catch(() => { + // Suppress AbortError triggered by controller.abort() when close() resolves first + }), + ]); + } catch (error: unknown) { + assertIsError(error); + this.logger.error(`An error occurred while closing Vitest instance: ${error.message}`); + } finally { + controller.abort(); + } + + this.debugLog(DebugLogLevel.Info, 'Vitest instance closed.'); + } + + private prepareSetupFiles(): string[] { + const { setupFiles } = this.options; + // Add setup file entries for TestBed initialization and project polyfills + const testSetupFiles = [ + 'init-compiler.js', + 'init-testbed.js', + 'vitest-mock-patch.js', + ...setupFiles, + ]; + + // TODO: Provide additional result metadata to avoid needing to extract based on filename + if (this.buildResultFiles.has('polyfills.js')) { + testSetupFiles.unshift('polyfills.js'); + } + + this.debugLog(DebugLogLevel.Info, 'Prepared setup files:', testSetupFiles); + + return testSetupFiles; + } + + private async initializeVitest(): Promise { + this.debugLog(DebugLogLevel.Info, 'Initializing Vitest.'); + const { + coverage, + reporters, + workspaceRoot, + browsers, + debug, + watch, + browserViewport, + projectRoot, + runnerConfig, + projectSourceRoot, + cacheOptions, + } = this.options; + const projectName = this.projectName; + + let vitestNodeModule; + try { + vitestNodeModule = await import('vitest/node'); + } catch (error: unknown) { + assertIsError(error); + this.debugLog( + DebugLogLevel.Info, + `Failed to import 'vitest/node'. Error code: ${error.code}`, + ); + if (error.code !== 'ERR_MODULE_NOT_FOUND') { + throw error; + } + throw new Error( + 'The `vitest` package was not found. Please install the package and rerun the test command.', + { cause: error }, + ); + } + const { startVitest } = vitestNodeModule; + + // Setup vitest browser options if configured + const browserOptions = await setupBrowserConfiguration( + browsers, + this.options.headless, + debug, + projectSourceRoot, + browserViewport, + ); + if (browserOptions.errors?.length) { + this.debugLog(DebugLogLevel.Info, 'Browser configuration errors found.', { + errors: browserOptions.errors, + }); + throw new Error(browserOptions.errors.join('\n')); + } + + if (browserOptions.messages?.length) { + for (const message of browserOptions.messages) { + this.logger.info(message); + } + } + this.debugLog(DebugLogLevel.Info, 'Browser configuration complete.', { + config: browserOptions.browser, + }); + + this.debugLog( + DebugLogLevel.Info, + `Verifying build results. File count: ${this.buildResultFiles.size}.`, + ); + assert( + this.buildResultFiles.size > 0, + 'buildResult must be available before initializing vitest', + ); + + const testSetupFiles = this.prepareSetupFiles(); + const projectPlugins = createVitestPlugins({ + workspaceRoot, + projectSourceRoot, + projectName, + buildResultFiles: this.buildResultFiles, + testFileToEntryPoint: this.testFileToEntryPoint, + setupFiles: testSetupFiles, + }); + + const externalConfigPath = + runnerConfig === true + ? await findVitestBaseConfig([projectRoot, workspaceRoot]) + : runnerConfig; + + this.debugLog(DebugLogLevel.Info, 'External Vitest configuration path:', { + externalConfigPath, + }); + + let project = projectName; + if (debug && browserOptions.browser?.instances) { + if (browserOptions.browser.instances.length > 1) { + this.logger.warn( + 'Multiple browsers are configured, but only the first browser will be used for debugging.', + ); + } + + // When running browser tests, Vitest appends the browser name to the project identifier. + // The project name must match this augmented name to ensure the correct project is targeted. + project = `${projectName} (${browserOptions.browser.instances[0].browser})`; + this.debugLog(DebugLogLevel.Info, 'Adjusted project name for debugging with browser:', { + project, + }); + } + + // Filter internal entries and setup files from the include list + const internalEntries = ['angular:']; + const setupFileSet = new Set(testSetupFiles); + const include: string[] = []; + for (const entry of this.testFileToEntryPoint.keys()) { + if ( + !internalEntries.some((internal) => entry.startsWith(internal)) && + !setupFileSet.has(entry) + ) { + include.push(toPosixPath(path.relative(workspaceRoot, entry))); + } + } + this.debugLog(DebugLogLevel.Verbose, 'Included test files (after filtering):', include); + + const vitestConfig = createVitestCliOptions( + this.options, + project, + externalConfigPath, + this.runnerArgOptions?.cli, + ); + const vitestServerConfig = { + // Note `.vitest` is auto appended to the path. + cacheDir: cacheOptions.path, + plugins: [ + await createVitestConfigPlugin({ + browser: browserOptions.browser, + cacheOptions, + coverage, + projectName, + projectSourceRoot, + optimizeDepsInclude: this.externalMetadata.implicitBrowser, + reporters, + setupFiles: testSetupFiles, + projectPlugins, + include, + watch, + isolate: this.options.isolate, + preserveSymlinks: this.options.preserveSymlinks, + runnerArgOptions: this.runnerArgOptions?.project, + }), + ], + }; + + this.debugLog(DebugLogLevel.Info, 'Calling startVitest with final configuration.'); + this.debugLog(DebugLogLevel.Verbose, 'Vitest config:', vitestConfig); + this.debugLog(DebugLogLevel.Verbose, 'Vitest server config:', vitestServerConfig); + + return startVitest('test', undefined, vitestConfig, vitestServerConfig); + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/executor_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/executor_spec.ts new file mode 100644 index 000000000000..8ff3ed6fa486 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/executor_spec.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext } from '@angular-devkit/architect'; +import path from 'node:path'; +import type { Vitest } from 'vitest/node'; +import { toPosixPath } from '../../../../utils/path'; +import { type IncrementalResult, ResultKind } from '../../../application/results'; +import type { NormalizedUnitTestBuilderOptions } from '../../options'; +import { VitestExecutor } from './executor'; + +describe('VitestExecutor', () => { + describe('incremental rebuilds', () => { + const workspaceRoot = path.resolve('/logical-workspace/test-project'); + const specFile = toPosixPath(path.join(workspaceRoot, 'src/app/app.spec.ts')); + const incrementalResult: IncrementalResult = { + kind: ResultKind.Incremental, + added: [], + removed: [], + modified: ['spec-src-app-app-spec.js', 'chunk-ABCDEF.js'], + files: [], + }; + + let originalExitCode: typeof process.exitCode; + + beforeEach(() => { + // The executor resets the process exit code when executing. + originalExitCode = process.exitCode; + }); + + afterEach(() => { + process.exitCode = originalExitCode; + }); + + /** + * Executes an incremental rebuild with a stand-in Vitest instance that uses the provided root. + * The stand-in only has test specifications for the module ids in `knownModuleIds`. + */ + async function executeIncremental(vitestRoot: string, knownModuleIds: string[]) { + const executor = new VitestExecutor( + 'test-project', + { workspaceRoot } as NormalizedUnitTestBuilderOptions, + new Map([['spec-src-app-app-spec', specFile]]), + { info: () => {} } as unknown as BuilderContext['logger'], + ); + + const invalidateFile = jasmine.createSpy('invalidateFile'); + const getModuleSpecifications = jasmine + .createSpy('getModuleSpecifications') + .and.callFake((moduleId: string) => + knownModuleIds.includes(moduleId) ? [{ moduleId }] : [], + ); + const rerunTestSpecifications = jasmine + .createSpy('rerunTestSpecifications') + .and.resolveTo({ testModules: [{ ok: () => true }] }); + + // Provide an already initialized Vitest instance to avoid starting Vitest. + executor['vitest'] = { + config: { root: vitestRoot }, + state: { getTestModules: () => [] }, + invalidateFile, + getModuleSpecifications, + rerunTestSpecifications, + } as unknown as Vitest; + + const outputs = []; + for await (const output of executor.execute(incrementalResult)) { + outputs.push(output); + } + + return { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications }; + } + + it('uses workspace root based paths when the Vitest root is not aliased', async () => { + const root = toPosixPath(workspaceRoot); + const { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications } = + await executeIncremental(root, [specFile]); + + expect(invalidateFile.calls.allArgs()).toEqual([ + [`${root}/spec-src-app-app-spec.js`], + [`${root}/chunk-ABCDEF.js`], + [specFile], + ]); + expect(getModuleSpecifications.calls.allArgs()).toEqual([[specFile]]); + expect(rerunTestSpecifications).toHaveBeenCalledOnceWith([{ moduleId: specFile }]); + expect(outputs).toEqual([{ success: true }]); + }); + + it('rebases paths onto the Vitest root when the root is aliased', async () => { + const physicalRoot = toPosixPath(path.resolve('/physical-disk/tmp/test-project')); + const physicalSpecFile = `${physicalRoot}/src/app/app.spec.ts`; + const { outputs, invalidateFile, getModuleSpecifications, rerunTestSpecifications } = + await executeIncremental(physicalRoot, [physicalSpecFile]); + + expect(invalidateFile.calls.allArgs()).toEqual([ + [`${physicalRoot}/spec-src-app-app-spec.js`], + [`${physicalRoot}/chunk-ABCDEF.js`], + [physicalSpecFile], + ]); + expect(getModuleSpecifications.calls.allArgs()).toEqual([[physicalSpecFile]]); + expect(rerunTestSpecifications).toHaveBeenCalledOnceWith([{ moduleId: physicalSpecFile }]); + expect(outputs).toEqual([{ success: true }]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts new file mode 100644 index 000000000000..2823072d6dbc --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import type { TestRunner } from '../api'; +import { DependencyChecker } from '../dependency-checker'; +import { getVitestBuildOptions } from './build-options'; +import { VitestExecutor } from './executor'; +import { type RunnerArgOptions, parseRunnerArgs } from './runner-args'; + +/** + * A declarative definition of the Vitest test runner. + */ +const VitestTestRunner: TestRunner = { + name: 'vitest', + + validateDependencies(options) { + const checker = new DependencyChecker(options.projectSourceRoot); + checker.check('vitest'); + + // If a runnerConfig is present, only check for 'vitest' itself. + // Custom configuration may include unknown browsers or other setup + // that doesn't follow the default dependency requirements. + if (options.runnerConfig) { + checker.report(); + + return; + } + + if (options.browsers?.length) { + if (process.versions.webcontainer) { + checker.check('@vitest/browser-preview'); + } else { + checker.checkAny( + ['@vitest/browser-playwright', '@vitest/browser-webdriverio', '@vitest/browser-preview'], + 'The "browsers" option requires either ' + + '"@vitest/browser-playwright", "@vitest/browser-webdriverio", or "@vitest/browser-preview" to be installed.', + ); + } + } else { + // DOM emulation is used when no browsers are specified + checker.checkAny( + ['jsdom', 'happy-dom'], + 'A DOM environment is required for non-browser tests. Please install either "jsdom" or "happy-dom".', + ); + } + + if (options.coverage.enabled) { + checker.checkAny( + ['@vitest/coverage-v8', '@vitest/coverage-istanbul'], + 'Code coverage requires either "@vitest/coverage-v8" or "@vitest/coverage-istanbul" to be installed.', + ); + } + + checker.report(); + }, + + getBuildOptions(options, baseBuildOptions, logger) { + return getVitestBuildOptions(options, baseBuildOptions, logger); + }, + + async createExecutor(context, options, testEntryPointMappings) { + const projectName = context.target?.project; + assert(projectName, 'The builder requires a target.'); + + if (!!process.versions.webcontainer && options.browsers?.length) { + context.logger.info( + `Webcontainer environment detected. Using '@vitest/browser-preview' for browser-based tests.`, + ); + } + + if (typeof options.runnerConfig === 'string') { + context.logger.info(`Using Vitest configuration file: ${options.runnerConfig}`); + } else if (options.runnerConfig) { + context.logger.info('Automatically searching for and using Vitest configuration file.'); + } + + // Parse and validate any additional Vitest arguments prior to the build to fail fast. + let runnerArgOptions: RunnerArgOptions | undefined; + if (options.runnerArgs) { + const { parseCLI } = await import('vitest/node'); + runnerArgOptions = parseRunnerArgs(options.runnerArgs, parseCLI); + } + + return new VitestExecutor( + projectName, + options, + testEntryPointMappings, + context.logger, + runnerArgOptions, + ); + }, +}; + +export default VitestTestRunner; diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts new file mode 100644 index 000000000000..3af89f0311ab --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts @@ -0,0 +1,713 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import { platform } from 'node:os'; +import path, { type PlatformPath } from 'node:path'; +import type { + BrowserConfigOptions, + InlineConfig, + ResolvedConfig, + UserWorkspaceConfig, + Vite, + VitestPluginContext, +} from 'vitest/node'; +import { createBuildAssetsMiddleware } from '../../../../tools/vite/middlewares/assets-middleware'; +import type { NormalizedCachedOptions } from '../../../../utils/normalize-cache'; +import { toPosixPath } from '../../../../utils/path'; +import { createProjectResolver } from '../../../../utils/resolve-project'; +import type { ResultFile } from '../../../application/results'; +import type { NormalizedUnitTestBuilderOptions } from '../../options'; +import { normalizeBrowserName } from './browser-provider'; + +interface ExistingRawSourceMap { + sources?: string[]; + sourcesContent?: string[]; + mappings?: string; +} + +interface PluginOptions { + workspaceRoot: string; + projectSourceRoot: string; + projectName: string; + buildResultFiles: ReadonlyMap; + testFileToEntryPoint: ReadonlyMap; + setupFiles: readonly string[]; +} + +type VitestCoverageOption = Exclude; + +interface VitestConfigPluginOptions { + browser: BrowserConfigOptions | undefined; + cacheOptions: NormalizedCachedOptions; + coverage: NormalizedUnitTestBuilderOptions['coverage']; + projectName: string; + projectSourceRoot: string; + reporters?: string[] | [string, object][]; + setupFiles: string[]; + projectPlugins: Vite.PluginOption[]; + include: string[]; + optimizeDepsInclude: string[]; + watch: boolean; + isolate: boolean | undefined; + preserveSymlinks?: boolean; + + /** Vitest project options from the `runnerArgs` builder option. */ + runnerArgOptions?: Record; +} + +async function findTestEnvironment( + projectResolver: (packageName: string) => string, +): Promise<'jsdom' | 'happy-dom'> { + try { + projectResolver('happy-dom'); + + return 'happy-dom'; + } catch { + // happy-dom is not installed, fallback to jsdom + return 'jsdom'; + } +} + +function determineCoverageProvider( + browser: BrowserConfigOptions | undefined, + testConfig: InlineConfig | undefined, + optionsCoverageEnabled: boolean | undefined, + projectSourceRoot: string, +): 'istanbul' | 'v8' | 'custom' | undefined { + let determinedProvider = testConfig?.coverage?.provider; + if (!determinedProvider && (optionsCoverageEnabled || testConfig?.coverage?.enabled)) { + const browsersToCheck = getBrowsersToCheck(browser, testConfig?.browser); + + const hasNonChromium = browsersToCheck.some( + (b) => !['chrome', 'chromium', 'edge'].includes(normalizeBrowserName(b).browser), + ); + + if (hasNonChromium) { + determinedProvider = 'istanbul'; + } else { + const projectResolve = createProjectResolver(projectSourceRoot); + const checkInstalled = (pkg: string) => { + try { + projectResolve(pkg); + + return true; + } catch { + return false; + } + }; + const hasIstanbul = checkInstalled('@vitest/coverage-istanbul'); + const hasV8 = checkInstalled('@vitest/coverage-v8'); + + // Favor istanbul when browser testing is enabled (to avoid slow CDP V8 HTTP sourcemap remapping) + // or when only istanbul is installed. + if (hasIstanbul && (browsersToCheck.length > 0 || !hasV8)) { + determinedProvider = 'istanbul'; + } else { + determinedProvider = 'v8'; + } + } + } + + return determinedProvider; +} + +function getBrowsersToCheck( + browser: BrowserConfigOptions | undefined, + testConfigBrowser: BrowserConfigOptions | undefined, +): string[] { + const browsersToCheck: string[] = []; + + const cliBrowser = browser as CustomBrowserConfigOptions | undefined; + const userBrowser = testConfigBrowser as CustomBrowserConfigOptions | undefined; + + // 1. CLI options override the Vitest configuration completely. + if (cliBrowser) { + if (cliBrowser.instances) { + browsersToCheck.push(...cliBrowser.instances.map((i) => i.browser)); + } + if (cliBrowser.name) { + browsersToCheck.push(cliBrowser.name); + } + + return browsersToCheck; + } + + // 2. Fall back to Vitest configuration ONLY if browser testing is enabled. + if (userBrowser && userBrowser.enabled !== false) { + if (userBrowser.instances) { + browsersToCheck.push(...userBrowser.instances.map((i) => i.browser)); + } + if (userBrowser.name) { + browsersToCheck.push(userBrowser.name); + } + } + + return browsersToCheck; +} + +export async function createVitestConfigPlugin( + options: VitestConfigPluginOptions, +): Promise { + const { + include, + browser, + projectName, + reporters, + setupFiles, + projectPlugins, + projectSourceRoot, + } = options; + + const { mergeConfig } = await import('vitest/config'); + + return { + name: 'angular:vitest-configuration', + enforce: 'post', + configResolved: { + order: 'post', + handler(config: Vite.ResolvedConfig) { + // Vitest's internal post-configResolved hook resets `server.watch` to `{}` when + // `watch` is enabled (`server.watch ??= {}`). Force it back to `null` so Vite uses + // a no-op watcher and relies solely on the Angular CLI build watcher. + config.server.watch = null; + }, + }, + async config(config: UserWorkspaceConfig & Vite.UserConfig) { + const testConfig = config.test; + + const determinedProvider = determineCoverageProvider( + browser, + testConfig, + options.coverage.enabled, + projectSourceRoot, + ); + + if (reporters !== undefined) { + delete testConfig?.reporters; + } + + if ( + options.coverage.reporters !== undefined && + testConfig?.coverage && + 'reporter' in testConfig.coverage + ) { + delete testConfig.coverage.reporter; + } + + if (testConfig?.projects?.length) { + this.warn( + 'The "test.projects" option in the Vitest configuration file is not supported. ' + + 'The Angular CLI Test system will construct its own project configuration.', + ); + delete testConfig.projects; + } + + if (testConfig?.include) { + this.warn( + 'The "test.include" option in the Vitest configuration file is not supported. ' + + 'The Angular CLI Test system will manage test file discovery.', + ); + delete testConfig.include; + } + + if (testConfig?.watch !== undefined && testConfig.watch !== options.watch) { + this.warn( + `The "test.watch" option in the Vitest configuration file is overridden by the builder's ` + + `watch option. Please use the Angular CLI "--watch" option to enable or disable watch mode.`, + ); + delete testConfig.watch; + } + + if (testConfig?.exclude) { + this.warn( + 'The "test.exclude" option in the Vitest configuration file is evaluated after ' + + 'tests are compiled. For better build performance, please use the Angular CLI ' + + '"exclude" option instead.', + ); + } + + // Merge user-defined plugins from the Vitest config with the CLI's internal plugins. + if (config.plugins) { + const userPlugins = config.plugins.filter( + (plugin: Vite.PluginOption) => + // Only inspect objects with a `name` property as these would be the internal injected plugins + !plugin || + typeof plugin !== 'object' || + !('name' in plugin) || + (!plugin.name.startsWith('angular:') && !plugin.name.startsWith('vitest')), + ); + + if (userPlugins.length > 0) { + projectPlugins.push(...userPlugins); + } + delete config.plugins; + } + + // Validate browser coverage support if coverage is enabled + if ( + (browser || testConfig?.browser?.enabled) && + (options.coverage.enabled || testConfig?.coverage?.enabled) + ) { + validateBrowserCoverage(browser, testConfig?.browser, determinedProvider); + } + + const projectResolver = createProjectResolver(projectSourceRoot); + + // Vitest enables its file system module cache by default and stores it in `node_modules`, + // regardless of `cache` and `cacheDir`. Follow the Angular CLI cache settings instead, + // unless the Vitest configuration file sets them. + const fsModuleCache = testConfig?.fsModuleCache ?? options.cacheOptions.enabled; + const fsModuleCachePath = + testConfig?.fsModuleCachePath ?? + path.join(options.cacheOptions.path, 'vitest-module-cache'); + + const projectDefaults: Vite.UserConfig & UserWorkspaceConfig = { + extends: false, + test: { + setupFiles, + globals: true, + // Default to `false` to align with the Karma/Jasmine experience. + isolate: false, + sequence: { setupFiles: 'list' }, + fsModuleCache, + fsModuleCachePath, + }, + optimizeDeps: { + noDiscovery: true, + include: options.optimizeDepsInclude, + }, + resolve: { + mainFields: ['es2020', 'module', 'main'], + conditions: ['es2015', 'es2020', 'module', ...(browser ? ['browser'] : [])], + preserveSymlinks: options.preserveSymlinks, + }, + }; + + const { optimizeDeps, resolve } = config; + const projectOverrides: Vite.UserConfig & UserWorkspaceConfig = { + extends: false, + test: { + name: projectName, + include, + // CLI provider browser options override, if present + ...(browser ? { browser } : {}), + // Only override if the user explicitly set it via CLI + ...(options.isolate !== undefined ? { isolate: options.isolate } : {}), + // If the user has not specified an environment, use a smart default. + ...(!testConfig?.environment + ? { environment: await findTestEnvironment(projectResolver) } + : {}), + }, + plugins: projectPlugins, + optimizeDeps, + resolve, + }; + + // The order of precedence from lowest to highest is the builder defaults, the Vitest + // configuration file, the `runnerArgs` builder option, and then the other builder options. + const projectBase = mergeConfig(projectDefaults, testConfig ? { test: testConfig } : {}); + const projectWithRunnerArgs = options.runnerArgOptions + ? mergeConfig(projectBase, { test: options.runnerArgOptions }) + : projectBase; + const projectConfig = mergeConfig(projectWithRunnerArgs, projectOverrides); + + return { + test: { + // The cache metadata is always read from the root configuration. + fsModuleCache, + fsModuleCachePath, + coverage: await generateCoverageOption( + options.coverage, + testConfig?.coverage, + projectName, + determinedProvider, + ), + ...(reporters ? { reporters } : {}), + projects: [projectConfig], + }, + }; + }, + }; +} + +const textDecoder = new TextDecoder('utf-8'); +async function loadResultFile(file: ResultFile): Promise { + if (file.origin === 'memory') { + return textDecoder.decode(file.contents); + } + + return readFile(file.source, 'utf-8'); +} + +/** + * Rebases a file path from `fromRoot` to `toRoot` in POSIX format. + * + * The path is rebased using its location relative to `fromRoot`. This includes a path outside of + * `fromRoot` (reached through `..` segments), which matches how Vitest resolves the root relative + * test `include` entries. Only a path that cannot be expressed relative to `fromRoot`, such as a + * file on a different Windows drive, is left unchanged (as POSIX). + * + * @param filePath The absolute file path to rebase. + * @param fromRoot The root that `filePath` is currently based on. + * @param toRoot The root to rebase `filePath` onto. + * @param pathImpl The path implementation to use. Defaults to that of the host platform. + * @returns The rebased file path in POSIX format. + */ +export function rebasePath( + filePath: string, + fromRoot: string, + toRoot: string, + pathImpl: PlatformPath = path, +): string { + const relative = pathImpl.relative(fromRoot, filePath); + const rebased = pathImpl.isAbsolute(relative) ? filePath : pathImpl.join(toRoot, relative); + + // Equivalent to `toPosixPath` but follows `pathImpl` instead of the host platform. + return pathImpl.sep === '\\' ? rebased.replace(/\\/g, '/') : rebased; +} + +export function createVitestPlugins(pluginOptions: PluginOptions): Vite.Plugin[] { + const { buildResultFiles, setupFiles } = pluginOptions; + let { workspaceRoot, testFileToEntryPoint } = pluginOptions; + const isWindows = platform() === 'win32'; + let setupFileSet = new Set( + setupFiles.map((file) => + toPosixPath(path.isAbsolute(file) ? file : path.join(workspaceRoot, file)), + ), + ); + let vitestConfig: ResolvedConfig; + + /** The build output path served for a module, whether it is a test entry point or a built artifact. */ + const getOutputPath = (id: string): string => { + const entryPoint = testFileToEntryPoint.get(id); + + return entryPoint ? entryPoint + '.js' : toPosixPath(path.relative(workspaceRoot, id)); + }; + + // Setup files must not be wrapped in a virtual import stub because Vitest only invalidates + // the setup file itself between test files; wrapping it would cause the underlying bundle + // to be cached, preventing per-test hooks from running on subsequent test files. + const isCoverageRedirect = (id: string): boolean => + !!vitestConfig?.coverage?.enabled && testFileToEntryPoint.has(id) && !setupFileSet.has(id); + + return [ + { + name: 'angular:test-in-memory-provider', + enforce: 'pre', + configureVitest(context: VitestPluginContext) { + vitestConfig = context.vitest.config; + + if (vitestConfig.root && vitestConfig.root !== toPosixPath(workspaceRoot)) { + const originalRoot = pluginOptions.workspaceRoot; + workspaceRoot = vitestConfig.root; + testFileToEntryPoint = new Map( + Array.from(pluginOptions.testFileToEntryPoint, ([file, entryPoint]) => [ + file.startsWith('angular:') ? file : rebasePath(file, originalRoot, workspaceRoot), + entryPoint, + ]), + ); + setupFileSet = new Set( + setupFiles.map((file) => + path.isAbsolute(file) + ? rebasePath(file, originalRoot, workspaceRoot) + : toPosixPath(path.join(workspaceRoot, file)), + ), + ); + } + + // Vitest keys its file system module cache on the file found on disk. A test entry point is + // served from its bundle instead, which also holds the application code it imports, so the + // key must follow the served build output, or the cache would return a stale bundle. + // Vitest 4.1 only has the experimental name, and 4.0 has no file system module cache at all. + const pluginContext: Partial = context; + const defineCacheKeyGenerator = + pluginContext.defineCacheKeyGenerator ?? + pluginContext.experimental_defineCacheKeyGenerator; + defineCacheKeyGenerator?.(({ id }) => { + const outputPath = getOutputPath(id); + // With coverage, `load` serves a redirect stub instead of the bundle, see below. + if (isCoverageRedirect(id)) { + return `coverage-redirect:${outputPath}`; + } + + const outputFile = buildResultFiles.get(outputPath); + if (!outputFile) { + return undefined; + } + if (outputFile.origin !== 'memory') { + return false; + } + + const sourceMapFile = buildResultFiles.get(outputPath + '.map'); + + return `${outputFile.hash}:${sourceMapFile?.origin === 'memory' ? sourceMapFile.hash : ''}`; + }); + }, + resolveId: (id: string, importer: string | undefined) => { + // Fast path for test entry points. + if (testFileToEntryPoint.has(id)) { + return id; + } + + // Workaround for Vitest in Windows when a fully qualified absolute path is provided with + // a superfluous leading slash. This can currently occur with the `@vitest/coverage-v8` provider + // when it uses `removeStartsWith(url, FILE_PROTOCOL)` to convert a file URL resulting in + // `/D:/tmp_dir/...` instead of `D:/tmp_dir/...`. + if (id[0] === '/' && isWindows) { + const slicedId = id.slice(1); + if (path.isAbsolute(slicedId)) { + return slicedId; + } + } + + // Determine the base directory for resolution. + let baseDir: string; + if (importer) { + // If the importer is a test entry point, resolve relative to the workspace root. + // Otherwise, resolve relative to the importer's directory. + baseDir = testFileToEntryPoint.has(importer) ? workspaceRoot : path.dirname(importer); + } else { + // If there's no importer, assume the id is relative to the workspace root. + baseDir = workspaceRoot; + } + + // Construct the full, absolute path and normalize it to POSIX format. + let fullPath: string; + if (path.isAbsolute(id)) { + const relativeId = path.relative(baseDir, id); + fullPath = + !relativeId.startsWith('..') && !path.isAbsolute(relativeId) + ? id + : path.join(baseDir, id); + } else { + fullPath = path.join(baseDir, id); + } + fullPath = toPosixPath(fullPath); + + if (testFileToEntryPoint.has(fullPath)) { + return fullPath; + } + + // Check if the resolved path corresponds to a known build artifact. + const relativePath = path.relative(workspaceRoot, fullPath); + if (buildResultFiles.has(toPosixPath(relativePath))) { + return fullPath; + } + + // If the module cannot be resolved from the build artifacts, let other plugins handle it. + return undefined; + }, + async load(id: string) { + assert(buildResultFiles.size > 0, 'buildResult must be available for in-memory loading.'); + + // Attempt to load as a source test file, or else as a built artifact. + const outputPath = getOutputPath(id); + if (isCoverageRedirect(id)) { + // To support coverage exclusion of the actual test file, the virtual + // test entry point only references the built and bundled intermediate file. + // If vitest supported an "excludeOnlyAfterRemap" option, this could be removed completely. + return { + code: `import "./${outputPath}";`, + }; + } + + const outputFile = buildResultFiles.get(outputPath); + if (outputFile) { + const code = await loadResultFile(outputFile); + const sourceMapPath = outputPath + '.map'; + const sourceMapFile = buildResultFiles.get(sourceMapPath); + const sourceMapText = sourceMapFile ? await loadResultFile(sourceMapFile) : undefined; + + const map = sourceMapText ? JSON.parse(sourceMapText) : undefined; + if (map) { + adjustSourcemapSources(map, true, workspaceRoot, id); + } + + return { + code, + map, + }; + } + }, + configureServer: (server: Vite.ViteDevServer) => { + server.middlewares.use(createBuildAssetsMiddleware(server.config.base, buildResultFiles)); + }, + }, + { + name: 'angular:html-index', + transformIndexHtml: () => { + // Add all global stylesheets + if (buildResultFiles.has('styles.css')) { + return [ + { + tag: 'link', + attrs: { href: 'styles.css', rel: 'stylesheet' }, + injectTo: 'head', + }, + ]; + } + + return []; + }, + }, + ]; +} + +/** + * Adjusts the sources field in a sourcemap to ensure correct source mapping and coverage reporting. + * + * @param map The raw sourcemap to adjust. + * @param rebaseSources Whether to rebase the source paths relative to the test file. + * @param workspaceRoot The root directory of the workspace. + * @param id The ID (path) of the file being loaded. + */ +function adjustSourcemapSources( + map: ExistingRawSourceMap, + rebaseSources: boolean, + workspaceRoot: string, + id: string, +): void { + if (!map.sources?.length && !map.sourcesContent?.length && !map.mappings) { + // Vitest will include files in the coverage report if the sourcemap contains no sources. + // For builder-internal generated code chunks, which are typically helper functions, + // a virtual source is added to the sourcemap to prevent them from being incorrectly + // included in the final coverage report. + map.sources = ['virtual:builder']; + } else if (rebaseSources && map.sources) { + map.sources = map.sources.map((source) => { + if (!source || source.startsWith('angular:')) { + return source; + } + + // source is relative to the workspace root because the output file is at the root of the output. + const absoluteSource = path.join(workspaceRoot, source); + + return toPosixPath(path.relative(path.dirname(id), absoluteSource)); + }); + } +} + +interface CustomBrowserConfigOptions { + enabled?: boolean; + instances?: { browser: string }[]; + name?: string; +} + +/** + * Validates that all enabled browsers support V8 coverage when coverage is enabled. + * Throws an error if an unsupported browser is detected. + */ +function validateBrowserCoverage( + browser: BrowserConfigOptions | undefined, + testConfigBrowser: BrowserConfigOptions | undefined, + provider?: string, +): void { + if (provider === 'istanbul') { + return; + } + const browsersToCheck = getBrowsersToCheck(browser, testConfigBrowser); + + // Normalize and filter unsupported browsers + const unsupportedBrowsers = browsersToCheck + .map((b) => normalizeBrowserName(b).browser) + .filter((b) => !['chrome', 'chromium', 'edge'].includes(b)); + + if (unsupportedBrowsers.length > 0) { + throw new Error( + `Code coverage is enabled, but the following configured browsers do not support the V8 coverage provider: ` + + `${unsupportedBrowsers.join(', ')}. ` + + `V8 coverage is only supported on Chromium-based browsers (e.g., Chrome, Chromium, Edge). ` + + `Please use the "istanbul" coverage provider (requires "@vitest/coverage-istanbul"), ` + + `remove the unsupported browsers, or disable coverage.`, + ); + } +} + +async function generateCoverageOption( + optionsCoverage: NormalizedUnitTestBuilderOptions['coverage'], + configCoverage: VitestCoverageOption | undefined, + projectName: string, + provider?: 'istanbul' | 'v8' | 'custom', +): Promise { + let defaultExcludes: string[] = []; + // When a coverage exclude option is provided, Vitest's default coverage excludes + // will be overridden. To retain them, we manually fetch the defaults to append to the + // user's provided exclusions. + if (optionsCoverage.exclude) { + try { + const vitestConfig = await import('vitest/config'); + defaultExcludes = vitestConfig.coverageConfigDefaults.exclude; + } catch {} + } + + return { + provider, + excludeAfterRemap: true, + reportsDirectory: + configCoverage?.reportsDirectory ?? toPosixPath(path.join('coverage', projectName)), + ...(optionsCoverage.enabled !== undefined ? { enabled: optionsCoverage.enabled } : {}), + // Vitest performs a pre-check and a post-check for sourcemaps. + // The pre-check uses the bundled files, so specific bundled entry points and chunks need to be included. + // The post-check uses the original source files, so the user's include is used. + ...(optionsCoverage.include + ? { include: ['spec-*.js', 'chunk-*.js', ...optionsCoverage.include] } + : {}), + // The 'in' operator is used here because 'configCoverage' is a union type and + // not all coverage providers support thresholds or watermarks. + thresholds: mergeCoverageObjects( + configCoverage && 'thresholds' in configCoverage ? configCoverage.thresholds : undefined, + optionsCoverage.thresholds, + ), + watermarks: mergeCoverageObjects( + configCoverage && 'watermarks' in configCoverage ? configCoverage.watermarks : undefined, + optionsCoverage.watermarks, + ), + // Special handling for `exclude`/`reporters` due to an undefined value causing upstream failures + ...(optionsCoverage.exclude + ? { + exclude: Array.from( + new Set([ + // Augment the default exclude https://vitest.dev/config/#coverage-exclude + // with the user defined exclusions + ...(configCoverage?.exclude || []), + ...optionsCoverage.exclude, + ...defaultExcludes, + ]), + ), + } + : {}), + ...(optionsCoverage.reporters + ? ({ reporter: optionsCoverage.reporters } satisfies VitestCoverageOption) + : {}), + }; +} + +/** + * Merges coverage related objects while ignoring any `undefined` values. + * This ensures that Angular CLI options correctly override Vitest configuration + * only when explicitly provided. + */ +function mergeCoverageObjects( + configValue: T | undefined, + optionsValue: T | undefined, +): T | undefined { + if (optionsValue === undefined) { + return configValue; + } + + const result: Record = { ...(configValue ?? {}) }; + for (const [key, value] of Object.entries(optionsValue)) { + if (value !== undefined) { + result[key] = value; + } + } + + return Object.keys(result).length > 0 ? (result as T) : undefined; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/plugins_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins_spec.ts new file mode 100644 index 000000000000..637862bcbf1a --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins_spec.ts @@ -0,0 +1,214 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 'node:path'; +import { BuildOutputFileType } from '../../../../tools/esbuild/bundler-files'; +import { toPosixPath } from '../../../../utils/path'; +import type { ResultFile } from '../../../application/results'; +import { createVitestPlugins, rebasePath } from './plugins'; + +describe('rebasePath', () => { + it('rebases a path from fromRoot to toRoot in POSIX format', () => { + const fromRoot = path.resolve('/logical-workspace/test-project'); + const toRoot = toPosixPath(path.resolve('/physical-disk/tmp/test-project')); + const filePath = path.join(fromRoot, 'src/app/app.spec.ts'); + + expect(rebasePath(filePath, fromRoot, toRoot)).toBe(`${toRoot}/src/app/app.spec.ts`); + }); + + it('rebases a path outside of fromRoot using its relative location', () => { + expect( + rebasePath( + '/logical/shared/setup.ts', + '/logical/test-project', + '/physical/test-project', + path.posix, + ), + ).toBe('/physical/shared/setup.ts'); + }); + + it('rebases a Windows path onto a different drive in POSIX format', () => { + expect( + rebasePath( + 'X:\\test-project\\src\\app\\app.spec.ts', + 'X:\\test-project', + 'D:/tmp/test-project', + path.win32, + ), + ).toBe('D:/tmp/test-project/src/app/app.spec.ts'); + }); + + it('leaves a path on a different Windows drive than fromRoot unchanged', () => { + expect( + rebasePath('C:\\shared\\setup.ts', 'X:\\test-project', 'D:/tmp/test-project', path.win32), + ).toBe('C:/shared/setup.ts'); + }); +}); + +describe('createVitestPlugins', () => { + it('resolves and loads setup and spec files when vitestConfig.root differs from workspaceRoot', async () => { + const workspaceRoot = path.resolve('/logical-workspace/test-project'); + const physicalRoot = toPosixPath(path.resolve('/physical-disk/tmp/test-project')); + const specFile = toPosixPath(path.join(workspaceRoot, 'src/app/app.spec.ts')); + + const buildResultFiles = new Map([ + [ + 'init-compiler.js', + { + origin: 'memory', + path: 'init-compiler.js', + type: BuildOutputFileType.Root, + contents: new TextEncoder().encode('console.log("init-compiler");'), + hash: 'hash-init-compiler', + }, + ], + [ + 'spec-src-app-app-spec.js', + { + origin: 'memory', + path: 'spec-src-app-app-spec.js', + type: BuildOutputFileType.Root, + contents: new TextEncoder().encode('console.log("spec");'), + hash: 'hash-spec', + }, + ], + ]); + + const testFileToEntryPoint = new Map([ + [specFile, 'spec-src-app-app-spec'], + ['angular:compiler-init', 'init-compiler'], + ]); + + const plugins = createVitestPlugins({ + workspaceRoot, + projectSourceRoot: path.join(workspaceRoot, 'src'), + projectName: 'test-project', + buildResultFiles, + testFileToEntryPoint, + setupFiles: ['init-compiler.js'], + }); + + const inMemoryPlugin = plugins.find((p) => p.name === 'angular:test-in-memory-provider'); + expect(inMemoryPlugin).toBeDefined(); + + const configureVitest = inMemoryPlugin?.configureVitest as + | ((context: { + vitest: { config: { root: string; coverage?: { enabled: boolean } } }; + }) => void) + | undefined; + configureVitest?.({ + vitest: { + config: { + root: physicalRoot, + }, + }, + }); + + const resolveId = inMemoryPlugin?.resolveId as ( + id: string, + importer: string | undefined, + ) => string | undefined; + const load = inMemoryPlugin?.load as ( + id: string, + ) => Promise<{ code: string; map?: unknown } | undefined>; + + expect(resolveId('angular:compiler-init', undefined)).toBe('angular:compiler-init'); + + const expectedSetupId = `${physicalRoot}/init-compiler.js`; + const resolvedSetupId = resolveId(expectedSetupId, undefined); + expect(resolvedSetupId).toBe(expectedSetupId); + + const loadedSetup = await load(expectedSetupId); + expect(loadedSetup?.code).toBe('console.log("init-compiler");'); + + const expectedSpecId = `${physicalRoot}/src/app/app.spec.ts`; + const resolvedSpecId = resolveId(expectedSpecId, undefined); + expect(resolvedSpecId).toBe(expectedSpecId); + + const loadedSpec = await load(expectedSpecId); + expect(loadedSpec?.code).toBe('console.log("spec");'); + }); + + it('rebases absolute setupFiles for coverage exclusion and handles repeated configureVitest calls', async () => { + const workspaceRoot = path.resolve('/logical-workspace/test-project'); + const firstPhysicalRoot = toPosixPath(path.resolve('/physical-disk/first/test-project')); + const secondPhysicalRoot = toPosixPath(path.resolve('/physical-disk/second/test-project')); + const userSetupFile = toPosixPath(path.join(workspaceRoot, 'src/test-setup.ts')); + const specFile = toPosixPath(path.join(workspaceRoot, 'src/app/app.spec.ts')); + + const buildResultFiles = new Map([ + [ + 'setup-src-test-setup.js', + { + origin: 'memory', + path: 'setup-src-test-setup.js', + type: BuildOutputFileType.Root, + contents: new TextEncoder().encode('console.log("user-setup");'), + hash: 'hash-user-setup', + }, + ], + [ + 'spec-src-app-app-spec.js', + { + origin: 'memory', + path: 'spec-src-app-app-spec.js', + type: BuildOutputFileType.Root, + contents: new TextEncoder().encode('console.log("spec");'), + hash: 'hash-spec', + }, + ], + ]); + + const testFileToEntryPoint = new Map([ + [userSetupFile, 'setup-src-test-setup'], + [specFile, 'spec-src-app-app-spec'], + ]); + + const plugins = createVitestPlugins({ + workspaceRoot, + projectSourceRoot: path.join(workspaceRoot, 'src'), + projectName: 'test-project', + buildResultFiles, + testFileToEntryPoint, + setupFiles: [userSetupFile], + }); + + const inMemoryPlugin = plugins.find((p) => p.name === 'angular:test-in-memory-provider'); + const configureVitest = inMemoryPlugin?.configureVitest as + | ((context: { + vitest: { config: { root: string; coverage?: { enabled: boolean } } }; + }) => void) + | undefined; + const load = inMemoryPlugin?.load as ( + id: string, + ) => Promise<{ code: string; map?: unknown } | undefined>; + + configureVitest?.({ + vitest: { + config: { + root: firstPhysicalRoot, + coverage: { enabled: true }, + }, + }, + }); + configureVitest?.({ + vitest: { + config: { + root: secondPhysicalRoot, + coverage: { enabled: true }, + }, + }, + }); + + const loadedSetup = await load(`${secondPhysicalRoot}/src/test-setup.ts`); + expect(loadedSetup?.code).toBe('console.log("user-setup");'); + + const loadedSpec = await load(`${secondPhysicalRoot}/src/app/app.spec.ts`); + expect(loadedSpec?.code).toBe('import "./spec-src-app-app-spec.js";'); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args.ts new file mode 100644 index 000000000000..306e480bb6e1 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args.ts @@ -0,0 +1,289 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * Parses and validates the Vitest command line arguments provided via the builder's + * `runnerArgs` option. + * + * Vitest's own command line parser is used to parse the arguments so that the value coercion and + * dot-notation behavior matches the Vitest documentation. However, that parser accepts unknown + * options, command names, and test file filters without error. The parsed result is therefore + * validated against an explicit list of supported options. + */ + +import type { CliOptions } from 'vitest/node'; + +/** + * The portion of the `parseCLI` function from `vitest/node` used to parse the arguments. + */ +export type VitestCliParser = (argv: string[]) => { filter: string[]; options: object }; + +/** + * The Vitest options created from the builder's `runnerArgs` option. + */ +export interface RunnerArgOptions { + /** Options for the Vitest CLI level configuration. */ + cli: CliOptions; + + /** + * Options for the Vitest project configuration. + * Vitest only forwards a version specific subset of CLI options to a configured project. + * The project applicable options are provided directly to the project to avoid relying + * on that subset. + */ + project: Record; +} + +interface SupportedOption { + /** A description of the accepted values for use in error messages. */ + readonly expects: string; + + /** Determines if the parsed value is valid for the option. */ + readonly isValid: (value: unknown) => boolean; + + /** Indicates the option only applies to the root Vitest configuration. */ + readonly rootOnly?: boolean; +} + +const isBoolean = (value: unknown): boolean => typeof value === 'boolean'; +const isCount = (value: unknown): boolean => + typeof value === 'number' && Number.isInteger(value) && value >= 0; + +const BOOLEAN_OPTION: SupportedOption = { expects: 'a boolean', isValid: isBoolean }; +const COUNT_OPTION: SupportedOption = { expects: 'a non-negative integer', isValid: isCount }; + +const SUPPORTED_SEQUENCE_OPTIONS: ReadonlyMap = new Map([ + ['shuffle', BOOLEAN_OPTION], + ['seed', COUNT_OPTION], +]); + +/** + * The Vitest CLI options that can be provided via the `runnerArgs` option. + * The keys are the camel case option names as provided by the Vitest command line parser. + */ +const SUPPORTED_OPTIONS: ReadonlyMap = new Map([ + ['allowOnly', BOOLEAN_OPTION], + ['bail', COUNT_OPTION], + ['disableConsoleIntercept', BOOLEAN_OPTION], + ['expandSnapshotDiff', BOOLEAN_OPTION], + [ + 'maxWorkers', + { + expects: 'a positive integer or a percentage', + isValid: (value) => + (typeof value === 'number' && Number.isInteger(value) && value > 0) || + (typeof value === 'string' && /^\d+%$/.test(value)), + }, + ], + ['printConsoleTrace', BOOLEAN_OPTION], + ['retry', COUNT_OPTION], + [ + 'sequence', + { + expects: `only the following options: ${[...SUPPORTED_SEQUENCE_OPTIONS.keys()] + .map((name) => `"--sequence.${name}"`) + .join(', ')}`, + isValid: (value) => + typeof value === 'object' && + value !== null && + Object.entries(value).every( + ([name, nestedValue]) => + SUPPORTED_SEQUENCE_OPTIONS.get(name)?.isValid(nestedValue) === true, + ), + }, + ], + [ + 'shard', + { + expects: 'a value in the form of /', + isValid: (value) => typeof value === 'string' && /^\d+\/\d+$/.test(value), + rootOnly: true, + }, + ], + ['testTimeout', COUNT_OPTION], + [ + 'update', + { + expects: 'a boolean, "all", "new", or "none"', + isValid: (value) => + typeof value === 'boolean' || value === 'all' || value === 'new' || value === 'none', + }, + ], +]); + +/** + * Vitest CLI options that are intentionally not supported along with the reason or alternative. + */ +const UNSUPPORTED_OPTIONS: ReadonlyMap = new Map([ + ['browser', 'Use the "browsers" and "headless" options instead.'], + [ + 'changed', + 'Tests are executed from bundled output which prevents Vitest from determining the affected tests.', + ], + ['config', 'Use the "runnerConfig" option instead.'], + ['coverage', 'Use the "coverage" options instead.'], + [ + 'dir', + 'Test discovery is managed by the builder. Use the "include" and "exclude" options instead.', + ], + ['exclude', 'Use the "exclude" option instead.'], + ['globals', 'The option is managed by the builder.'], + ['inspect', 'Use the "debug" option instead.'], + ['inspectBrk', 'Use the "debug" option instead.'], + ['isolate', 'Use the "isolate" option instead.'], + ['mode', 'The option is managed by the builder.'], + ['outputFile', 'Use the "outputFile" option instead.'], + ['passWithNoTests', 'The builder requires at least one test file.'], + ['project', 'The option is managed by the builder.'], + [ + 'related', + 'Tests are executed from bundled output which prevents Vitest from determining the affected tests.', + ], + ['reporter', 'Use the "reporters" option instead.'], + ['root', 'The option is managed by the builder.'], + ['run', 'Use the "watch" option instead.'], + ['testNamePattern', 'Use the "filter" option instead.'], + ['ui', 'Use the "ui" option instead.'], + ['watch', 'Use the "watch" option instead.'], +]); + +/** + * The single character aliases of the Vitest CLI options and their full option names. + * The Vitest command line parser provides both the alias and the full name within its result. + */ +const OPTION_ALIASES: ReadonlyMap = new Map([ + ['c', 'config'], + ['p', 'project'], + ['r', 'root'], + ['t', 'testNamePattern'], + ['u', 'update'], + ['w', 'watch'], +]); + +/** + * The names of the Vitest CLI commands. The Vitest command line parser consumes + * a command name without including it in the parsed result. + */ +const VITEST_COMMANDS: ReadonlySet = new Set([ + 'bench', + 'dev', + 'init', + 'list', + 'related', + 'run', + 'watch', +]); + +function toFlag(name: string): string { + return `--${name}`; +} + +/** + * Parses and validates the Vitest command line arguments provided via the `runnerArgs` option. + * + * @param runnerArgs The Vitest command line arguments. + * @param parseCLI The `parseCLI` function from the project's `vitest/node` package. + * @returns The validated Vitest options. + * @throws An error describing each argument that is not supported. + */ +export function parseRunnerArgs( + runnerArgs: readonly string[], + parseCLI: VitestCliParser, +): RunnerArgOptions { + const errors: string[] = []; + + // Arguments following a `--` separator are not interpreted by the parser and cannot be a command. + const separatorIndex = runnerArgs.indexOf('--'); + const interpretedArgs = separatorIndex === -1 ? runnerArgs : runnerArgs.slice(0, separatorIndex); + const commands = new Set(interpretedArgs.filter((arg) => VITEST_COMMANDS.has(arg))); + for (const command of commands) { + errors.push(`The Vitest "${command}" command is not supported.`); + } + + let parsed: ReturnType; + try { + // The parser requires the executable name as the first element and modifies the provided array. + parsed = parseCLI(['vitest', ...runnerArgs]); + } catch (e) { + throw new Error( + `Vitest was unable to parse the "runnerArgs" option: ${e instanceof Error ? e.message : String(e)}`, + { cause: e }, + ); + } + const { filter, options } = parsed; + + if (filter.length > 0) { + errors.push( + `Test file filters are not supported (${filter.map((value) => `"${value}"`).join(', ')}). ` + + 'Use the "include" option instead.', + ); + } + + const cli: Record = {}; + const project: Record = {}; + const parsedOptions = options as Record; + + for (const [name, value] of Object.entries(parsedOptions)) { + if (name === '--') { + if (Array.isArray(value) && value.length > 0) { + errors.push( + `Arguments following "--" are not supported (${value.map((arg) => `"${String(arg)}"`).join(', ')}).`, + ); + } + + continue; + } + + // `color` is always present with a default value of `true`. + if (name === 'color' && value === true) { + continue; + } + + // Some commands are also represented as an option. The command has already been reported. + if (commands.has(name) && value === true) { + continue; + } + + // Skip an alias when the full option name is also present. + const aliasedName = OPTION_ALIASES.get(name); + if (aliasedName !== undefined && aliasedName in parsedOptions) { + continue; + } + + const supported = SUPPORTED_OPTIONS.get(name); + if (supported) { + if (supported.isValid(value)) { + cli[name] = value; + if (!supported.rootOnly) { + project[name] = value; + } + } else { + errors.push(`The Vitest "${toFlag(name)}" option requires ${supported.expects}.`); + } + + continue; + } + + const unsupportedReason = UNSUPPORTED_OPTIONS.get(name); + errors.push( + `The Vitest "${toFlag(name)}" option is not supported.` + + (unsupportedReason ? ` ${unsupportedReason}` : ''), + ); + } + + if (errors.length > 0) { + throw new Error( + 'The "runnerArgs" option contains unsupported values:\n' + + errors.map((error) => ` - ${error}`).join('\n') + + `\nSupported Vitest options: ${[...SUPPORTED_OPTIONS.keys()].map(toFlag).join(', ')}`, + ); + } + + return { cli: cli as unknown as CliOptions, project }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args_spec.ts new file mode 100644 index 000000000000..480e5006ccf2 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/runner-args_spec.ts @@ -0,0 +1,235 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type VitestCliParser, parseRunnerArgs } from './runner-args'; + +describe('parseRunnerArgs', () => { + let parseCLI: VitestCliParser; + + beforeAll(async () => { + // Use the actual Vitest parser to ensure the validation matches its behavior. + ({ parseCLI } = await import('vitest/node')); + }); + + function parse(...runnerArgs: string[]) { + return parseRunnerArgs(runnerArgs, parseCLI); + } + + describe('supported options', () => { + it('should return no options when no arguments are provided', () => { + expect(parse()).toEqual({ cli: {}, project: {} }); + }); + + it('should support a boolean option', () => { + expect(parse('--update')).toEqual({ cli: { update: true }, project: { update: true } }); + }); + + it('should support a negated boolean option', () => { + expect(parse('--no-update').cli).toEqual({ update: false }); + }); + + it('should support the alias of an option', () => { + expect(parse('-u')).toEqual({ cli: { update: true }, project: { update: true } }); + }); + + it('should support a kebab case option name', () => { + expect(parse('--disable-console-intercept').cli).toEqual({ disableConsoleIntercept: true }); + }); + + it('should support the named update modes', () => { + expect(parse('--update=all').cli).toEqual({ update: 'all' }); + expect(parse('--update=new').cli).toEqual({ update: 'new' }); + expect(parse('--update=none').cli).toEqual({ update: 'none' }); + }); + + it('should support a numeric value provided with an equals sign', () => { + expect(parse('--bail=1').cli).toEqual({ bail: 1 }); + }); + + it('should support a numeric value provided as a separate argument', () => { + expect(parse('--bail', '1').cli).toEqual({ bail: 1 }); + }); + + it('should support the bail option without a value', () => { + expect(parse('--bail').cli).toEqual({ bail: 1 }); + }); + + it('should support multiple options', () => { + expect(parse('--retry=2', '--testTimeout=10000', '--allowOnly').cli).toEqual({ + retry: 2, + testTimeout: 10000, + allowOnly: true, + }); + }); + + it('should support a worker count or percentage', () => { + expect(parse('--maxWorkers=2').cli).toEqual({ maxWorkers: 2 }); + expect(parse('--maxWorkers=50%').cli).toEqual({ maxWorkers: '50%' }); + }); + + it('should support the sequence shuffle and seed options', () => { + const expected = { sequence: { shuffle: true, seed: 42 } }; + + expect(parse('--sequence.shuffle', '--sequence.seed=42')).toEqual({ + cli: expected, + project: expected, + }); + }); + + it('should only provide the shard option to the CLI options', () => { + expect(parse('--shard=1/3')).toEqual({ cli: { shard: '1/3' }, project: {} }); + }); + + it('should not modify the provided arguments', () => { + const runnerArgs = Object.freeze(['--update', '--bail=1']); + + expect(parseRunnerArgs(runnerArgs, parseCLI).cli).toEqual({ update: true, bail: 1 }); + expect(runnerArgs).toEqual(['--update', '--bail=1']); + }); + }); + + describe('unsupported values', () => { + it('should reject an unknown option', () => { + expect(() => parse('--updat')).toThrowError(/The Vitest "--updat" option is not supported\./); + }); + + it('should list the supported options', () => { + expect(() => parse('--unknown')).toThrowError(/Supported Vitest options: .*--update/); + }); + + it('should reject an option name that is an inherited object property', () => { + expect(() => parse('--toString')).toThrowError(/"runnerArgs" option/); + }); + + it('should reject an invalid value for a supported option', () => { + expect(() => parse('--bail=abc')).toThrowError( + /Vitest was unable to parse the "runnerArgs" option:.*--bail=abc/, + ); + expect(() => parse('--bail=-1')).toThrowError( + /The Vitest "--bail" option requires a non-negative integer\./, + ); + expect(() => parse('--retry=abc')).toThrowError( + /The Vitest "--retry" option requires a non-negative integer\./, + ); + expect(() => parse('--retry')).toThrowError( + /The Vitest "--retry" option requires a non-negative integer\./, + ); + expect(() => parse('--update=other')).toThrowError( + /The Vitest "--update" option requires a boolean, "all", "new", or "none"\./, + ); + expect(() => parse('--maxWorkers=0')).toThrowError( + /The Vitest "--maxWorkers" option requires a positive integer or a percentage\./, + ); + expect(() => parse('--shard=1')).toThrowError( + /The Vitest "--shard" option requires a value in the form of \/\./, + ); + }); + + it('should reject an unsupported nested sequence option', () => { + expect(() => parse('--sequence.concurrent')).toThrowError( + /The Vitest "--sequence" option requires only the following options: "--sequence.shuffle", "--sequence.seed"\./, + ); + }); + + it('should direct options with a builder equivalent to the builder option', () => { + expect(() => parse('--reporter=dot')).toThrowError( + /The Vitest "--reporter" option is not supported\. Use the "reporters" option instead\./, + ); + expect(() => parse('--coverage.enabled')).toThrowError( + /The Vitest "--coverage" option is not supported\. Use the "coverage" options instead\./, + ); + expect(() => parse('--ui')).toThrowError(/Use the "ui" option instead\./); + expect(() => parse('--isolate')).toThrowError(/Use the "isolate" option instead\./); + expect(() => parse('--watch')).toThrowError(/Use the "watch" option instead\./); + expect(() => parse('--config=vitest.config.ts')).toThrowError( + /Use the "runnerConfig" option instead\./, + ); + }); + + it('should report the full option name when an unsupported alias is used', () => { + expect(() => parse('-t', 'should work')).toThrowError( + /The Vitest "--testNamePattern" option is not supported\. Use the "filter" option instead\./, + ); + }); + + it('should reject options that are managed by the builder', () => { + expect(() => parse('--root=/other')).toThrowError( + /The Vitest "--root" option is not supported\. The option is managed by the builder\./, + ); + expect(() => parse('--project=other')).toThrowError( + /The Vitest "--project" option is not supported\. The option is managed by the builder\./, + ); + }); + + it('should reject options that select tests based on changed files', () => { + expect(() => parse('--changed')).toThrowError( + /The Vitest "--changed" option is not supported\. Tests are executed from bundled output/, + ); + expect(() => parse('--related=src/app/app.ts')).toThrowError( + /The Vitest "--related" option is not supported\. Tests are executed from bundled output/, + ); + }); + + it('should reject test file filters', () => { + expect(() => parse('src/app/app.spec.ts')).toThrowError( + /Test file filters are not supported \("src\/app\/app\.spec\.ts"\)\. Use the "include" option instead\./, + ); + }); + + it('should reject arguments following a "--" separator', () => { + expect(() => parse('--update', '--', 'src/app/app.spec.ts')).toThrowError( + /Arguments following "--" are not supported \("src\/app\/app\.spec\.ts"\)\./, + ); + }); + + it('should reject Vitest commands', () => { + expect(() => parse('bench')).toThrowError(/The Vitest "bench" command is not supported\./); + expect(() => parse('--update', 'list')).toThrowError( + /The Vitest "list" command is not supported\./, + ); + }); + + it('should not report a command name that follows a "--" separator as a command', () => { + let message = ''; + try { + parse('--update', '--', 'run'); + } catch (e) { + message = (e as Error).message; + } + + expect(message).toContain('Arguments following "--" are not supported ("run").'); + expect(message).not.toContain('command is not supported'); + }); + + it('should only report a command once when it is also represented as an option', () => { + let message = ''; + try { + parse('run'); + } catch (e) { + message = (e as Error).message; + } + + expect(message).toContain('The Vitest "run" command is not supported.'); + expect(message).not.toContain('"--run"'); + }); + + it('should report all unsupported values together', () => { + let message = ''; + try { + parse('--unknown', '--reporter=dot', 'src/app/app.spec.ts'); + } catch (e) { + message = (e as Error).message; + } + + expect(message).toContain('The "runnerArgs" option contains unsupported values:'); + expect(message).toContain('The Vitest "--unknown" option is not supported.'); + expect(message).toContain('The Vitest "--reporter" option is not supported.'); + expect(message).toContain('Test file filters are not supported'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/schema.json b/packages/angular/build/src/builders/unit-test/schema.json new file mode 100644 index 000000000000..c08df9a38ecb --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/schema.json @@ -0,0 +1,309 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "Unit testing", + "description": "Unit testing options for Angular applications.", + "type": "object", + "properties": { + "buildTarget": { + "type": "string", + "description": "Specifies the build target to use for the unit test build in the format `project:target[:configuration]`. This defaults to the `build` target of the current project with the `development` configuration. You can also pass a comma-separated list of configurations. Example: `project:target:production,staging`.", + "pattern": "^[^:\\s]*:[^:\\s]*(:[^\\s]+)?$" + }, + "tsConfig": { + "type": "string", + "description": "The path to the TypeScript configuration file, relative to the workspace root. Defaults to `tsconfig.spec.json` in the project root if it exists. If not specified and the default does not exist, the `tsConfig` from the specified `buildTarget` will be used." + }, + "runner": { + "type": "string", + "description": "Specifies the test runner to use for test execution.", + "default": "vitest", + "enum": ["karma", "vitest"] + }, + "runnerConfig": { + "type": ["string", "boolean"], + "description": "Specifies the configuration file for the selected test runner. If a string is provided, it will be used as the path to the configuration file. If `true`, the builder will search for a default configuration file (e.g., `vitest-base.config.mts` or `karma.conf.js`). If `false`, no external configuration file will be used.\\nFor Vitest, this enables advanced options and the use of custom plugins. Please note that while the file is loaded, the Angular team does not provide direct support for its specific contents or any third-party plugins used within it.", + "default": false + }, + "runnerArgs": { + "type": "array", + "description": "Additional command line arguments to provide to the test runner. Each argument must be a separate value, for example `--runner-args=--update --runner-args=--bail=1`. This option is only available for the Vitest runner and only a subset of the Vitest command line options is supported. Options that have an equivalent builder option, such as `--reporter` or `--coverage`, must be configured with the builder option.", + "items": { + "type": "string" + }, + "x-passthrough": true + }, + "browsers": { + "description": "Specifies the browsers to use for test execution. When not specified, the Vitest runner runs tests in a Node.js environment using `happy-dom` if it is installed, otherwise `jsdom`, and the Karma runner uses the browsers of its configuration. Browser names ending with `Headless` enable headless mode (e.g., `ChromiumHeadless` for Vitest with the Playwright provider, or `ChromeHeadless` for Karma).", + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1 + }, + "browserViewport": { + "description": "Specifies the browser viewport dimensions for browser-based tests in the format `widthxheight`.", + "type": "string", + "pattern": "^\\d+x\\d+$" + }, + "include": { + "type": "array", + "items": { + "type": "string" + }, + "default": ["**/*.spec.ts", "**/*.test.ts"], + "description": "Specifies glob patterns of files to include for testing, relative to the project source root. This option also has special handling for directory paths (includes all test files within) and file paths (includes the corresponding test file if one exists)." + }, + "exclude": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Specifies glob patterns of files to exclude from testing, relative to the project source root." + }, + "filter": { + "type": "string", + "description": "Specifies a regular expression pattern to match against test suite and test names. Only tests with a name matching the pattern will be executed. For example, `^App` will run only tests in suites beginning with 'App'." + }, + "watch": { + "type": "boolean", + "description": "Enables watch mode, which re-runs tests when source files change. Defaults to `true` in TTY environments and `false` otherwise." + }, + "headless": { + "type": "boolean", + "description": "Forces all configured browsers to run in headless mode. When using the Vitest runner, this option is ignored if no browsers are configured. The Karma runner does not support this option." + }, + "debug": { + "type": "boolean", + "description": "Enables debugging mode for tests, allowing the use of the Node Inspector.", + "default": false + }, + "ui": { + "type": "boolean", + "description": "Enables the Vitest UI for interactive test execution. This option is only available for the Vitest runner." + }, + "isolate": { + "type": "boolean", + "description": "Enables isolation for test execution. When true, Vitest runs tests in separate threads or processes. This option is only available for the Vitest runner. Defaults to false to align with the Karma/Jasmine experience." + }, + "splitting": { + "type": "boolean", + "description": "Enables code splitting for test execution. When enabled, shared code between test files is split into separate chunks. Issues with live ESM bindings in Node.js environments (such as uninitialized exports or mocking failures) can be resolved by disabling splitting. This option is only available for the Vitest runner.", + "default": true, + "x-deprecated": "No longer needed with Vitest 5." + }, + "quiet": { + "type": "boolean", + "description": "Suppresses the verbose build summary and stats table on each rebuild. Defaults to `true` locally and `false` in CI environments." + }, + "coverage": { + "type": "boolean", + "description": "Enables coverage reporting for tests. If not specified, the coverage configuration from a runner configuration file will be used if present. Otherwise, coverage is disabled by default." + }, + "coverageInclude": { + "type": "array", + "description": "Specifies glob patterns of files to include in the coverage report.", + "items": { + "type": "string" + } + }, + "coverageExclude": { + "type": "array", + "description": "Specifies glob patterns of files to exclude from the coverage report.", + "items": { + "type": "string" + } + }, + "coverageReporters": { + "type": "array", + "description": "Specifies the reporters to use for coverage results. Each reporter can be a string representing its name, or a tuple containing the name and an options object. Built-in reporters include 'html', 'lcov', 'lcovonly', 'text', 'text-summary', 'cobertura', 'json', and 'json-summary'.", + "items": { + "oneOf": [ + { + "enum": [ + "html", + "lcov", + "lcovonly", + "text", + "text-summary", + "cobertura", + "json", + "json-summary" + ] + }, + { + "type": "array", + "minItems": 1, + "maxItems": 2, + "items": [ + { + "enum": [ + "html", + "lcov", + "lcovonly", + "text", + "text-summary", + "cobertura", + "json", + "json-summary" + ] + }, + { + "type": "object" + } + ] + } + ] + } + }, + "coverageThresholds": { + "type": "object", + "description": "Specifies minimum coverage thresholds that must be met. If thresholds are not met, the builder will exit with an error.", + "properties": { + "perFile": { + "type": "boolean", + "description": "When true, thresholds are enforced for each file individually." + }, + "statements": { + "type": "number", + "description": "Minimum percentage of statements covered." + }, + "branches": { + "type": "number", + "description": "Minimum percentage of branches covered." + }, + "functions": { + "type": "number", + "description": "Minimum percentage of functions covered." + }, + "lines": { + "type": "number", + "description": "Minimum percentage of lines covered." + } + }, + "additionalProperties": false + }, + "coverageWatermarks": { + "type": "object", + "description": "Specifies coverage watermarks for the HTML reporter. These determine the color coding for high, medium, and low coverage.", + "properties": { + "statements": { + "type": "array", + "description": "The high and low watermarks for statements coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "branches": { + "type": "array", + "description": "The high and low watermarks for branches coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "functions": { + "type": "array", + "description": "The high and low watermarks for functions coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "lines": { + "type": "array", + "description": "The high and low watermarks for lines coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + } + }, + "additionalProperties": false + }, + "reporters": { + "type": "array", + "description": "Specifies the reporters to use during test execution. Each reporter can be a string representing its name, or a tuple containing the name and an options object. Built-in reporters include 'default', 'verbose', 'dots', 'json', 'junit', 'tap', 'tap-flat', and 'html'. You can also provide a path to a custom reporter.", + "items": { + "oneOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "enum": ["default", "verbose", "dots", "json", "junit", "tap", "tap-flat", "html"] + } + ] + }, + { + "type": "array", + "minItems": 1, + "maxItems": 2, + "items": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "enum": [ + "default", + "verbose", + "dots", + "json", + "junit", + "tap", + "tap-flat", + "html" + ] + } + ] + }, + { + "type": "object" + } + ] + } + ] + } + }, + "outputFile": { + "type": "string", + "description": "Specifies a file path for the test report. This path is used by every configured reporter that writes to a file. To write a separate file for each reporter, use the tuple format `['reporter-name', { outputFile: '...' }]` within the `reporters` option. When not provided, output is written to the console." + }, + "providersFile": { + "type": "string", + "description": "Specifies the path to a TypeScript file that provides an array of Angular providers for the test environment. The file must contain a default export of the provider array.", + "minLength": 1 + }, + "polyfills": { + "description": "A list of polyfills to include in the build. Can be a full path for a file, relative to the current workspace or module specifier. Example: 'zone.js'. If not specified, polyfills will be inherited from the build target.", + "type": "array", + "items": { + "type": "string", + "uniqueItems": true + } + }, + "setupFiles": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A list of paths to global setup files that are executed before the test files. The application's polyfills and the Angular TestBed are always initialized before these files." + }, + "progress": { + "type": "boolean", + "description": "Shows build progress information in the console. Defaults to the `progress` setting of the specified `buildTarget`." + }, + "listTests": { + "type": "boolean", + "description": "Lists all discovered test files and exits the process without building or executing the tests.", + "default": false + }, + "dumpVirtualFiles": { + "type": "boolean", + "description": "Dumps build output files to the `.angular/cache` directory for debugging purposes.", + "default": false, + "visible": false + } + }, + "additionalProperties": false, + "required": [] +} diff --git a/packages/angular/build/src/builders/unit-test/test-discovery.ts b/packages/angular/build/src/builders/unit-test/test-discovery.ts new file mode 100644 index 000000000000..2452675a9abf --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/test-discovery.ts @@ -0,0 +1,342 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type PathLike, constants, promises as fs } from 'node:fs'; +import os from 'node:os'; +import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'; +import { glob, isDynamicPattern } from 'tinyglobby'; +import { calculateHash, initializeHash } from '../../utils/hash'; +import { toPosixPath } from '../../utils/path'; + +/** + * An array of file infix notations that identify a file as a test file. + * For example, `.spec` in `app.component.spec.ts`. + */ +const TEST_FILE_INFIXES = ['.spec', '.test']; + +/** Maximum length for a generated test entrypoint name. */ +const MAX_FILENAME_LENGTH = 128; + +/** + * Finds all test files in the project. This function implements a special handling + * for static paths (non-globs) to improve developer experience. For example, if a + * user provides a path to a component, this function will find the corresponding + * test file. If a user provides a path to a directory, it will find all test + * files within that directory. + * + * @param include Glob patterns of files to include. + * @param exclude Glob patterns of files to exclude. + * @param workspaceRoot The absolute path to the workspace root. + * @param projectSourceRoot The absolute path to the project's source root. + * @returns A unique set of absolute paths to all test files. + */ +export async function findTests( + include: string[], + exclude: string[], + workspaceRoot: string, + projectSourceRoot: string, +): Promise { + await initializeHash(); + const resolvedTestFiles = new Set(); + const dynamicPatterns: string[] = []; + + const projectRootPrefix = toPosixPath(relative(workspaceRoot, projectSourceRoot) + '/'); + const normalizedExcludes = exclude.map((p) => normalizePattern(p, projectRootPrefix)); + + // 1. Separate static and dynamic patterns + for (const pattern of include) { + const normalized = normalizePattern(pattern, projectRootPrefix); + if (isDynamicPattern(pattern)) { + dynamicPatterns.push(normalized); + } else { + const { resolved, unresolved } = await resolveStaticPattern(normalized, projectSourceRoot); + resolved.forEach((file) => resolvedTestFiles.add(file)); + unresolved.forEach((p) => dynamicPatterns.push(p)); + } + } + + // 2. Execute a single glob for all dynamic patterns + if (dynamicPatterns.length > 0) { + const globMatches = await glob(dynamicPatterns, { + cwd: projectSourceRoot, + absolute: true, + expandDirectories: false, + ignore: ['**/node_modules/**', ...normalizedExcludes], + }); + + for (const match of globMatches) { + resolvedTestFiles.add(toPosixPath(match)); + } + } + + // 3. Combine, de-duplicate and sort the results. The glob crawls directories asynchronously and + // returns matches in a varying order; the order feeds the build entry points, so an unsorted list + // makes the output (chunk contents and names) differ between two builds of the same sources. + return [...resolvedTestFiles].sort(); +} + +interface TestEntrypointsOptions { + projectSourceRoot: string; + workspaceRoot: string; + removeTestExtension?: boolean; + prefix?: string; +} + +/** + * Generates unique, dash-delimited bundle names for a set of test files. + * This is used to create distinct output files for each test. + * + * @param testFiles An array of absolute paths to test files. + * @param options Configuration options for generating entry points. + * @returns A map where keys are the generated unique bundle names and values are the original file paths. + */ +export function getTestEntrypoints( + testFiles: string[], + { + projectSourceRoot, + workspaceRoot, + removeTestExtension, + prefix = 'spec', + }: TestEntrypointsOptions, +): Map { + const seen = new Set(); + const counters = new Map(); + const roots = [projectSourceRoot, workspaceRoot]; + const infixes = TEST_FILE_INFIXES.map((i) => i.slice(1)); + if (!infixes.includes(prefix)) { + infixes.push(prefix); + } + const infixesPattern = infixes.join('|'); + + return new Map( + Array.from(testFiles, (testFile) => { + const fileName = generateNameFromPath(testFile, roots, !!removeTestExtension); + const baseName = fileName === prefix ? prefix : `${prefix}-${fileName}`; + let uniqueName = baseName; + // Start at 2 for collisions as the first instance remains suffix-less. + let suffix = counters.get(baseName) ?? 2; + + while (seen.has(uniqueName)) { + uniqueName = `${baseName}-${suffix}`.replace( + new RegExp(`([^\\w](?:${infixesPattern}))-([\\d]+)$`), + '-$2$1', + ); + ++suffix; + } + seen.add(uniqueName); + counters.set(baseName, suffix); + + return [uniqueName, testFile]; + }), + ); +} + +/** + * Generates a unique, dash-delimited name from a file path. This is used to + * create a consistent and readable bundle name for a given test file. + * + * @param testFile The absolute path to the test file. + * @param roots An array of root paths to remove from the beginning of the test file path. + * @param removeTestExtension Whether to remove the test file infix and extension from the result. + * @returns A dash-cased name derived from the relative path of the test file. + */ +export function generateNameFromPath( + testFile: string, + roots: string[], + removeTestExtension: boolean, +): string { + const relativePath = removeRoots(testFile, roots.map(toPosixPath)); + + let startIndex = 0; + // Skip leading dots and slashes + while (startIndex < relativePath.length && /^[./\\]$/.test(relativePath[startIndex])) { + startIndex++; + } + + let endIndex = relativePath.length; + if (removeTestExtension) { + const infixes = TEST_FILE_INFIXES.map((p) => p.substring(1)).join('|'); + const match = relativePath.match(new RegExp(`\\.(${infixes})\\.[^.]+$`)); + + if (match?.index) { + endIndex = match.index; + } + } else { + const extIndex = relativePath.lastIndexOf('.'); + if (extIndex > startIndex) { + endIndex = extIndex; + } + } + + // Build the final string in a single pass + let result = ''; + for (let i = startIndex; i < endIndex; i++) { + const char = relativePath[i]; + result += char === '/' || char === '\\' ? '-' : char; + } + + return truncateName(result, relativePath); +} + +/** + * Truncates a generated name if it exceeds the maximum allowed filename length. + * If truncation occurs, the name will be shortened by replacing a middle segment + * with an 8-character SHA256 hash of the original full path to maintain uniqueness. + * + * @param name The generated name to potentially truncate. + * @param originalPath The original full path from which the name was derived. Used for hashing. + * @returns The original name if within limits, or a truncated name with a hash. + */ +function truncateName(name: string, originalPath: string): string { + if (name.length <= MAX_FILENAME_LENGTH) { + return name; + } + + const hash = calculateHash(originalPath).substring(0, 8); + const availableLength = MAX_FILENAME_LENGTH - hash.length - 2; // 2 for '-' separators + const prefixLength = Math.floor(availableLength / 2); + const suffixLength = availableLength - prefixLength; + + return `${name.substring(0, prefixLength)}-${hash}-${name.substring(name.length - suffixLength)}`; +} + +/** + * Whether the current operating system's filesystem is case-insensitive. + */ +const isCaseInsensitiveFilesystem = os.platform() === 'win32' || os.platform() === 'darwin'; + +/** + * Removes a prefix from the beginning of a string, with conditional case-insensitivity + * based on the operating system's filesystem characteristics. + * + * @param text The string to remove the prefix from. + * @param prefix The prefix to remove. + * @returns The string with the prefix removed, or the original string if the prefix was not found. + */ +function removePrefix(text: string, prefix: string): string { + if (isCaseInsensitiveFilesystem) { + if (text.toLowerCase().startsWith(prefix.toLowerCase())) { + return text.substring(prefix.length); + } + } else { + if (text.startsWith(prefix)) { + return text.substring(prefix.length); + } + } + + return text; +} + +/** + * Removes potential root paths from a file path, returning a relative path. + * If no root path matches, it returns the file's basename. + * + * @param path The file path to process. + * @param roots An array of root paths to attempt to remove. + * @returns A relative path. + */ +function removeRoots(path: string, roots: string[]): string { + for (const root of roots) { + const result = removePrefix(path, root); + // If the prefix was removed, the result will be a different string. + if (result !== path) { + return result; + } + } + + return basename(path); +} + +/** + * Normalizes a glob pattern by converting it to a POSIX path, removing leading + * slashes, and making it relative to the project source root. + * + * @param pattern The glob pattern to normalize. + * @param projectRootPrefix The POSIX-formatted prefix of the project's source root relative to the workspace root. + * @returns A normalized glob pattern. + */ +function normalizePattern(pattern: string, projectRootPrefix: string): string { + const posixPattern = toPosixPath(pattern); + + // Do not modify absolute paths. The globber will handle them correctly. + if (isAbsolute(posixPattern)) { + return posixPattern; + } + + // For relative paths, ensure they are correctly relative to the project source root. + // This involves removing the project root prefix if the user provided a workspace-relative path. + const normalizedRelative = removePrefix(posixPattern, projectRootPrefix); + + return normalizedRelative; +} + +/** + * Resolves a static (non-glob) path. + * + * If the path is a directory, it returns a glob pattern to find all test files + * within that directory. + * + * If the path is a file, it attempts to find a corresponding test file by + * checking for files with the same name and a test infix (e.g., `.spec.ts`). + * + * If no corresponding test file is found, the original path is returned as an + * unresolved pattern. + * + * @param pattern The static path pattern. + * @param projectSourceRoot The absolute path to the project's source root. + * @returns A promise that resolves to an object containing resolved spec files and unresolved patterns. + */ +async function resolveStaticPattern( + pattern: string, + projectSourceRoot: string, +): Promise<{ resolved: string[]; unresolved: string[] }> { + const fullPath = isAbsolute(pattern) ? pattern : join(projectSourceRoot, pattern); + if (await isDirectory(fullPath)) { + const infixes = TEST_FILE_INFIXES.map((p) => p.substring(1)).join('|'); + + return { resolved: [], unresolved: [`${pattern}/**/*.@(${infixes}).@(ts|tsx)`] }; + } + + const fileExt = extname(fullPath); + const baseName = basename(fullPath, fileExt); + + for (const infix of TEST_FILE_INFIXES) { + const potentialSpec = join(dirname(fullPath), `${baseName}${infix}${fileExt}`); + if (await exists(potentialSpec)) { + return { resolved: [toPosixPath(potentialSpec)], unresolved: [] }; + } + } + + if (await exists(fullPath)) { + return { resolved: [toPosixPath(fullPath)], unresolved: [] }; + } + + return { resolved: [], unresolved: [toPosixPath(pattern)] }; +} + +/** Checks if a path exists and is a directory. */ +async function isDirectory(path: PathLike): Promise { + try { + const stats = await fs.stat(path); + + return stats.isDirectory(); + } catch { + return false; + } +} + +/** Checks if a path exists on the file system. */ +async function exists(path: PathLike): Promise { + try { + await fs.access(path, constants.F_OK); + + return true; + } catch { + return false; + } +} diff --git a/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts b/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts new file mode 100644 index 000000000000..91c33fd0120a --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts @@ -0,0 +1,204 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { promises as fs } from 'node:fs'; +import { join } from 'node:path'; +import { initializeHash } from '../../utils/hash'; +import { toPosixPath } from '../../utils/path'; +import { findTests, generateNameFromPath, getTestEntrypoints } from './test-discovery'; + +describe('findTests', () => { + let projectSourceRoot: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + projectSourceRoot = await fs.mkdtemp(join(baseTmpDir, 'angular-find-tests-')); + }); + + afterEach(async () => { + await fs.rm(projectSourceRoot, { recursive: true, force: true }); + }); + + it('should return the test files sorted, regardless of the crawl order', async () => { + const files = ['z/z.spec.ts', 'a/b/c.spec.ts', 'm.spec.ts', 'a/a.spec.ts', 'b/x/y.spec.ts']; + for (const file of files) { + const path = join(projectSourceRoot, file); + await fs.mkdir(join(path, '..'), { recursive: true }); + await fs.writeFile(path, ''); + } + + const result = await findTests(['**/*.spec.ts'], [], projectSourceRoot, projectSourceRoot); + + const expected = files.map((file) => toPosixPath(join(projectSourceRoot, file))).sort(); + expect(result).toEqual(expected); + }); +}); + +describe('getTestEntrypoints', () => { + beforeAll(async () => { + await initializeHash(); + }); + + const workspaceRoot = '/project'; + const projectSourceRoot = '/project/src'; + const options = { workspaceRoot, projectSourceRoot }; + + it('should generate entry points for unique files', () => { + const files = ['/project/src/a.spec.ts', '/project/src/b.spec.ts']; + const result = getTestEntrypoints(files, { ...options, removeTestExtension: true }); + + expect(result.size).toBe(2); + expect(result.get('spec-a')).toBe(files[0]); + expect(result.get('spec-b')).toBe(files[1]); + }); + + it('should handle collisions with numeric suffixes correctly positioned', () => { + // To trigger the regex replacement, the name must end in 'spec', 'test', or the prefix. + const files = ['/project/src/sub-test.spec.ts', '/project/src/sub/test.spec.ts']; + + const result = getTestEntrypoints(files, { ...options, removeTestExtension: true }); + // Both map to 'sub-test' (relative to src root). + // baseName = 'spec-sub-test'. + // 1st: 'spec-sub-test'. + // 2nd: 'spec-sub-test-2'. Regex matches '-test-2'. -> 'spec-sub-2-test'. + expect(result.get('spec-sub-test')).toBe(files[0]); + expect(result.get('spec-sub-2-test')).toBe(files[1]); + }); + + it('should handle setup file naming with prefix setup', () => { + const files = ['/project/src/setup.ts']; + const result = getTestEntrypoints(files, { + ...options, + removeTestExtension: false, + prefix: 'setup', + }); + + // 'setup.ts' -> 'setup' (via generateNameFromPath). + // prefix='setup'. + // baseName = 'setup' === 'setup' ? 'setup' : 'setup-setup' -> 'setup'. + expect(result.get('setup')).toBe(files[0]); + }); + + it('should handle setup file collisions', () => { + const files = ['/project/src/sub-setup.ts', '/project/src/sub/setup.ts']; + const result = getTestEntrypoints(files, { + ...options, + removeTestExtension: false, + prefix: 'setup', + }); + + // Both map to 'sub-setup' (baseName: 'setup-sub-setup'). + // 1st: 'setup-sub-setup'. + // 2nd: 'setup-sub-setup-2'. Regex matches '-setup-2'. -> 'setup-sub-2-setup'. + expect(result.get('setup-sub-setup')).toBe(files[0]); + expect(result.get('setup-sub-2-setup')).toBe(files[1]); + }); + + it('should handle custom prefixes', () => { + const files = ['/project/src/sub-my-file.ts', '/project/src/sub/my-file.ts']; + const result = getTestEntrypoints(files, { + ...options, + removeTestExtension: false, + prefix: 'custom', + }); + + // 'sub-my-file.ts' -> 'sub-my-file'. + // baseName: 'custom-sub-my-file'. + expect(result.get('custom-sub-my-file')).toBe(files[0]); + // 'custom-sub-my-file-2'. Does not match regex (no 'spec'/'test'/'custom' at end). + expect(result.get('custom-sub-my-file-2')).toBe(files[1]); + }); +}); + +describe('generateNameFromPath', () => { + beforeAll(async () => { + await initializeHash(); + }); + + const roots = ['/project/src/', '/project/']; + + it('should generate a dash-cased name from a simple path', () => { + const testFile = '/project/src/app/components/my-component.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-components-my-component'); + }); + + it('should handle Windows-style paths', () => { + const testFile = 'C:\\project\\src\\app\\components\\my-component.spec.ts'; + const result = generateNameFromPath(testFile, ['C:\\project\\src\\'], true); + expect(result).toBe('app-components-my-component'); + }); + + it('should remove test extensions when removeTestExtension is true', () => { + const testFile = '/project/src/app/utils/helpers.test.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-utils-helpers'); + }); + + it('should not remove test extensions when removeTestExtension is false', () => { + const testFile = '/project/src/app/utils/helpers.test.ts'; + const result = generateNameFromPath(testFile, roots, false); + expect(result).toBe('app-utils-helpers.test'); + }); + + it('should handle paths with leading dots and slashes', () => { + const testFile = '/project/src/./app/services/api.service.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-services-api.service'); + }); + + it('should return the basename if no root matches', () => { + const testFile = '/unrelated/path/to/some/file.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('file'); + }); + + it('should truncate a long file name', () => { + const longPath = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/in/the/function.spec.ts'; // eslint-disable-line max-len + const testFile = `/project/src/${longPath}`; + const result = generateNameFromPath(testFile, roots, true); + + expect(result.length).toBeLessThanOrEqual(128); + expect(result).toBe( + 'a-very-long-path-that-definitely-exceeds-the-maximum-allowe-4af8113d-me-in-order-to-trigger-the-truncation-logic-in-the-function', + ); // eslint-disable-line max-len + }); + + it('should generate different hashes for different paths with similar truncated names', () => { + const longPath1 = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/variant-a.spec.ts'; // eslint-disable-line max-len + const longPath2 = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/variant-b.spec.ts'; // eslint-disable-line max-len + + const testFile1 = `/project/src/${longPath1}`; + const testFile2 = `/project/src/${longPath2}`; + + const result1 = generateNameFromPath(testFile1, roots, true); + const result2 = generateNameFromPath(testFile2, roots, true); + + expect(result1).not.toBe(result2); + // The hash is always 8 characters long and is surrounded by hyphens. + const hashRegex = /-[a-f0-9]{8}-/; + const hash1 = result1.match(hashRegex)?.[0]; + const hash2 = result2.match(hashRegex)?.[0]; + + expect(hash1).toBeDefined(); + expect(hash2).toBeDefined(); + expect(hash1).not.toBe(hash2); + }); + + it('should not truncate a filename that is exactly the max length', () => { + const name = 'a'.repeat(128); + const testFile = `/project/src/${name}.spec.ts`; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe(name); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/coverage-ignore-comments_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/coverage-ignore-comments_spec.ts new file mode 100644 index 000000000000..2c680ac08cf0 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/coverage-ignore-comments_spec.ts @@ -0,0 +1,237 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + UNIT_TEST_BUILDER_INFO, + describeBuilder, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "coverage ignore comments"', () => { + beforeEach(async () => { + setupApplicationTarget(harness, { extractLicenses: false, optimization: false }); + }); + + function getSpecContent(extraTest = '') { + return ` +import { TestBed } from '@angular/core/testing'; +import { AppComponent } from './app.component'; + +describe('AppComponent', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [AppComponent], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); + + it('should render title', async () => { + const fixture = TestBed.createComponent(AppComponent); + await fixture.whenStable(); + const compiled = fixture.nativeElement as HTMLElement; + expect(compiled.querySelector('h1')?.textContent).toContain('hello'); + }); + + ${extraTest} +}); +`; + } + + async function assertNoUncoveredStatements(contextMessage: string) { + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').toExist(); + + const coverageMap = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const appComponentPath = Object.keys(coverageMap).find((p) => p.includes('app.component.ts')); + expect(appComponentPath).toBeDefined(); + + const appComponentCoverage = coverageMap[appComponentPath as string]; + + const statementCounts = Object.values(appComponentCoverage.s); + const hasUncoveredStatements = statementCounts.some((count) => count === 0); + expect(hasUncoveredStatements).withContext(contextMessage).toBeFalse(); + } + + for (const type of ['istanbul', 'v8']) { + it(`should respect ${type} ignore next comments when computing coverage`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coverageReporters: ['json'] as any, + }); + + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

hello

', + standalone: true, + }) + export class AppComponent { + title = 'app'; + + /* ${type} ignore next */ + untestedFunction() { + return false; + } + } + `, + ); + + await harness.writeFile('src/app/app.component.spec.ts', getSpecContent()); + + await assertNoUncoveredStatements( + 'There should be no uncovered statements as the uncalled function was ignored', + ); + }); + + it(`should respect ${type} ignore if comments when computing coverage`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coverageReporters: ['json'] as any, + }); + + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

hello

', + standalone: true, + }) + export class AppComponent { + checkValue(val: boolean) { + /* ${type} ignore if -- @preserve */ + if (val) { + return true; + } + return false; + } + } + `, + ); + + await harness.writeFile( + 'src/app/app.component.spec.ts', + getSpecContent(` + it('should exercise the function but not the if block', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + app.checkValue(false); + }); + `), + ); + + await assertNoUncoveredStatements( + 'There should be no uncovered statements as the uncalled branch was ignored', + ); + }); + + it(`should respect ${type} ignore else comments when computing coverage`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coverageReporters: ['json'] as any, + }); + + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

hello

', + standalone: true, + }) + export class AppComponent { + checkValue(val: boolean) { + /* ${type} ignore else -- @preserve */ + if (val) { + return true; + } else { + return false; + } + } + } + `, + ); + + await harness.writeFile( + 'src/app/app.component.spec.ts', + getSpecContent(` + it('should exercise the function but not the else block', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + app.checkValue(true); + }); + `), + ); + + await assertNoUncoveredStatements( + 'There should be no uncovered statements as the uncalled else branch was ignored', + ); + }); + } + + it('should respect v8 ignore start/stop comments when computing coverage', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coverageReporters: ['json'] as any, + }); + + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

hello

', + standalone: true, + }) + export class AppComponent { + title = 'app'; + + /* v8 ignore start */ + untestedFunction() { + return false; + } + /* v8 ignore stop */ + } + `, + ); + + await harness.writeFile('src/app/app.component.spec.ts', getSpecContent()); + + await assertNoUncoveredStatements( + 'There should be no uncovered statements as the uncalled function was ignored', + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/library-target_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/library-target_spec.ts new file mode 100644 index 000000000000..d6d604d9f311 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/library-target_spec.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { BASE_OPTIONS, describeBuilder, UNIT_TEST_BUILDER_INFO } from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "@angular/build:library buildTarget"', () => { + it('should support library buildTarget with stylePreprocessorOptions and inlineStyleLanguage', async () => { + harness.withBuilderTarget( + 'build', + async () => ({ success: true }), + { + tsConfig: 'src/tsconfig.lib.json', + inlineStyleLanguage: 'scss', + stylePreprocessorOptions: { + includePaths: ['src/styles'], + }, + }, + { + builderName: '@angular/build:library', + }, + ); + + await harness.writeFiles({ + 'src/styles/_vars.scss': '$primary-color: #123456;', + 'src/public-api.ts': `export * from './lib/lib.component';`, + 'src/lib/lib.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-comp', + standalone: true, + template: '

lib

', + styles: [\` + @use 'vars'; + p { color: vars.$primary-color; } + \`], + }) + export class LibComponent {} + `, + 'src/lib/lib.component.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { describe, it, expect } from 'vitest'; + import { LibComponent } from './lib.component'; + + describe('LibComponent', () => { + it('creates component with scss styles', () => { + TestBed.configureTestingModule({ + imports: [LibComponent], + }); + const fixture = TestBed.createComponent(LibComponent); + expect(fixture).toBeTruthy(); + }); + }); + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/lib/**/*.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts new file mode 100644 index 000000000000..0893660a251e --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts @@ -0,0 +1,750 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { readdirSync } from 'node:fs'; +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +const VITEST_CONFIG_CONTENT = ` +import { defineConfig } from 'vitest/config'; +export default defineConfig({ + test: { + reporters: [['junit', { outputFile: './vitest-results.xml' }]], + }, +}); +`; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "runnerConfig with Vitest runner"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + it('should use custom reporters defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile('vitest.config.mts', VITEST_CONFIG_CONTENT); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should use custom reporters and outputFile defined as an object in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + reporters: ['junit'], + outputFile: { + junit: './vitest-results-outputfile.xml', + }, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results-outputfile.xml').toExist(); + }); + + it('should preserve custom coverage options (e.g. clean: false) from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + coverage: true, + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + clean: false, + }, + }, + }); + `, + ); + + // Create a placeholder file in the coverage directory before running the test + harness.writeFile('coverage/test/placeholder-file.txt', 'do-not-delete'); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // The builder outputs to coverage/test by default. + // If clean: false is preserved, the placeholder-file.txt should still exist. + harness.expectFile('coverage/test/placeholder-file.txt').toExist(); + }); + + it('should override reporters defined in runnerConfig file when CLI option is present', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + reporters: ['default'], + }); + + harness.writeFile('vitest.config.mts', VITEST_CONFIG_CONTENT); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // The CLI option 'default' should override the 'junit' reporter in VITEST_CONFIG_CONTENT + harness.expectFile('vitest-results.xml').toNotExist(); + }); + + it('should use custom reportsDirectory defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + coverage: true, + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + reportsDirectory: './custom-coverage-reports', + }, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('custom-coverage-reports/coverage-final.json').toExist(); + }); + + it('should use default reportsDirectory when not defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: {}, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').toExist(); + }); + + it('should enable coverage when set in runnerConfig file without builder option', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + enabled: true, + }, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').toExist(); + }); + + it('should exclude test files based on runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + exclude: ['src/app/app.component.spec.ts'], + reporters: ['default', ['json', { outputFile: 'vitest-results.json' }]], + }, + }); + `, + ); + + // Create a second test file that should be executed + harness.writeFile( + 'src/app/app-second.spec.ts', + ` + import { TestBed } from '@angular/core/testing'; + import { AppComponent } from './app.component'; + + describe('AppComponent', () => { + beforeEach(() => TestBed.configureTestingModule({ + declarations: [AppComponent], + })); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const results = JSON.parse(harness.readFile('vitest-results.json')); + expect(results.numPassedTests).toBe(1); + }); + + it('should correctly merge coverage.exclude arrays from builder and runner options', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + runnerConfig: 'vitest.config.mts', + coverageExclude: ['src/app/cli-excluded.ts'], + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + exclude: ['src/app/config-excluded.ts'], + }, + }, + }); + `, + ); + + // Create two files that would normally be covered + harness.writeFile('src/app/cli-excluded.ts', 'export const cliExcluded = true;'); + harness.writeFile('src/app/config-excluded.ts', 'export const configExcluded = true;'); + + // Update the test file to import them so they're picked up by coverage + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + import './cli-excluded'; + import './config-excluded'; + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').toExist(); + + const coverageMap = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const coveredFiles = Object.keys(coverageMap); + + const hasCliExcluded = coveredFiles.some((f) => f.includes('cli-excluded.ts')); + const hasConfigExcluded = coveredFiles.some((f) => f.includes('config-excluded.ts')); + + expect(hasCliExcluded).withContext('CLI target should be excluded').toBeFalse(); + expect(hasConfigExcluded).withContext('Config file target should be excluded').toBeFalse(); + }); + + it('should allow overriding globals to false via runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + globals: false, + }, + }); + `, + ); + + // This test will fail if globals are enabled, because `test` will not be defined. + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { expect } from 'vitest'; + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should initialize environment even when globals are disabled in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + globals: false, + }, + }); + `, + ); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should fail when a DOM-dependent test is run in a node environment', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + environment: 'node', + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should warn and ignore "test.projects" option from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + projects: ['./foo.config.ts'], + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.projects" option in the Vitest configuration file is not supported.', + // ), + // }), + // ); + }); + + it('should warn and ignore "test.include" option from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + include: ['src/app/non-existent.spec.ts'], + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.include" option in the Vitest configuration file is not supported.', + // ), + // }), + // ); + }); + + it('should warn and ignore "test.watch" option from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: false, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + watch: true, + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.watch" option in the Vitest configuration file is overridden by the builder\\'s watch option.', + // ), + // }), + // ); + }); + + it('should warn about performance when "test.exclude" option is in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + exclude: ['src/app/non-existent.spec.ts'], + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.exclude" option in the Vitest configuration file is evaluated after', + // ), + // }), + // ); + }); + + it(`should append "test.setupFiles" (string) from runnerConfig to the CLI's setup`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + setupFiles: './src/app/custom-setup.ts', + }, + }); + `, + ); + + harness.writeFile('src/app/custom-setup.ts', `(globalThis as any).customSetupLoaded = true;`); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have custom setup loaded', () => { + expect((globalThis as any).customSetupLoaded).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should append "test.setupFiles" (array) from runnerConfig to the CLI's setup`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + setupFiles: ['./src/app/custom-setup-1.ts', './src/app/custom-setup-2.ts'], + }, + }); + `, + ); + + harness.writeFile('src/app/custom-setup-1.ts', `(globalThis as any).customSetup1 = true;`); + harness.writeFile('src/app/custom-setup-2.ts', `(globalThis as any).customSetup2 = true;`); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have custom setups loaded', () => { + expect((globalThis as any).customSetup1).toBe(true); + expect((globalThis as any).customSetup2).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should merge and apply custom Vite plugins from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + plugins: [ + { + name: 'my-custom-transform-plugin', + transform(code, id) { + if (code.includes('__PLACEHOLDER__')) { + return code.replace('__PLACEHOLDER__', 'transformed by custom plugin'); + } + }, + }, + ], + }); + `, + ); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have been transformed by custom plugin', () => { + const placeholder = '__PLACEHOLDER__'; + expect(placeholder).toBe('transformed by custom plugin'); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should not serve stale cached modules across runs when an imported file changes', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + await harness.writeFiles({ + 'vitest.config.mts': ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + fsModuleCache: true, + fsModuleCachePath: './.vitest-cache', + }, + }); + `, + 'src/app/value.ts': `export const VALUE = 'initial';`, + 'src/app/app.component.spec.ts': ` + import { test, expect } from 'vitest'; + import { VALUE } from './value'; + + test('should use the latest value from imported module', () => { + expect(VALUE).toBe('updated'); + }); + `, + }); + + const firstRun = await harness.executeOnce(); + expect(firstRun.result?.success).toBeFalse(); + + // Update the imported application file without modifying the .spec.ts file on disk + await harness.writeFile('src/app/value.ts', `export const VALUE = 'updated';`); + + const secondRun = await harness.executeOnce(); + expect(secondRun.result?.success).toBeTrue(); + harness.expectDirectory('.vitest-cache').toExist(); + }); + + it('should reuse the cached modules across runs when nothing changes', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + + await harness.writeFiles({ + 'vitest.config.mts': ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + fsModuleCache: true, + fsModuleCachePath: './.vitest-cache', + }, + }); + `, + 'src/app/value.ts': `export const VALUE = 'initial';`, + 'src/app/app.component.spec.ts': ` + import { test, expect } from 'vitest'; + import { VALUE } from './value'; + + test('should use the value from imported module', () => { + expect(VALUE).toBe('initial'); + }); + `, + }); + const cacheEntries = () => + readdirSync(harness.resolvePath('.vitest-cache'), { recursive: true }).sort(); + + const firstRun = await harness.executeOnce(); + expect(firstRun.result?.success).toBeTrue(); + const entriesAfterFirstRun = cacheEntries(); + expect(entriesAfterFirstRun.length).toBeGreaterThan(0); + + // An unchanged build produces the same bundles, so no new cache entry is written. + const secondRun = await harness.executeOnce(); + expect(secondRun.result?.success).toBeTrue(); + expect(cacheEntries()).toEqual(entriesAfterFirstRun); + }); + + it('should not write the module cache when the Angular CLI cache is disabled', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectDirectory('node_modules/.vitest-cache').toNotExist(); + }); + + it('should not serve the cached bundle of a test entry point once coverage is enabled', async () => { + await harness.writeFiles({ + 'vitest.config.mts': ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + fsModuleCache: true, + fsModuleCachePath: './.vitest-cache', + }, + }); + `, + 'src/app/value.ts': `export const VALUE = 'initial';`, + 'src/app/app.component.spec.ts': ` + import { test, expect } from 'vitest'; + import { VALUE } from './value'; + + test('should use the value from imported module', () => { + expect(VALUE).toBe('initial'); + }); + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + }); + const firstRun = await harness.executeOnce(); + expect(firstRun.result?.success).toBeTrue(); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.mts', + coverage: true, + coverageReporters: ['json'] as any, + }); + const secondRun = await harness.executeOnce(); + expect(secondRun.result?.success).toBeTrue(); + + // The application code is only reported when the spec is served as the coverage redirect stub. + const coverageMap = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + expect(Object.keys(coverageMap).some((file) => file.endsWith('value.ts'))).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-barrel-side-effects_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-barrel-side-effects_spec.ts new file mode 100644 index 000000000000..7a59f09eeaa0 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-barrel-side-effects_spec.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { BASE_OPTIONS, describeBuilder, UNIT_TEST_BUILDER_INFO } from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "Vitest barrel sideEffects"', () => { + // Regression test for https://github.com/angular/angular-cli/issues/33910. + it('should retain barrel-exported components when package.json has sideEffects: false', async () => { + harness.withBuilderTarget( + 'build', + async () => ({ success: true }), + { + project: 'src/lib/ng-package.json', + }, + { + builderName: '@angular/build:ng-packagr', + }, + ); + + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions ??= {}; + tsconfig.compilerOptions.paths = { + '@lib': ['./src/lib/public-api.ts'], + '@lib/sub': ['./src/lib/sub/public-api.ts'], + }; + + return JSON.stringify(tsconfig); + }); + + await harness.writeFiles({ + 'src/lib/package.json': JSON.stringify({ + name: '@lib', + version: '0.0.1', + sideEffects: false, + }), + 'src/lib/ng-package.json': JSON.stringify({ + lib: { + entryFile: 'public-api.ts', + }, + }), + 'src/lib/public-api.ts': ` + export * from './components/public-api-components'; + export * from './other/other.component'; + `, + 'src/lib/components/public-api-components.ts': `export * from './foo/foo.component';`, + 'src/lib/components/foo/foo.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-foo', + standalone: true, + template: '

foo

', + }) + export class FooComponent {} + `, + 'src/lib/other/other.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-other', + standalone: true, + template: '

other

', + }) + export class OtherComponent {} + `, + 'src/lib/other/other.component.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { describe, it, expect } from 'vitest'; + import { OtherComponent } from '@lib'; + + describe('OtherComponent', () => { + it('creates', () => { + TestBed.configureTestingModule({ + imports: [OtherComponent], + }); + const fixture = TestBed.createComponent(OtherComponent); + expect(fixture).toBeTruthy(); + }); + }); + `, + 'src/lib/sub/ng-package.json': JSON.stringify({ + lib: { + entryFile: 'public-api.ts', + }, + }), + 'src/lib/sub/public-api.ts': `export * from './bar/bar.component';`, + 'src/lib/sub/bar/bar.component.ts': ` + import { Component } from '@angular/core'; + import { FooComponent } from '@lib'; + + @Component({ + selector: 'lib-bar', + standalone: true, + imports: [FooComponent], + template: '', + }) + export class BarComponent {} + `, + 'src/lib/sub/bar/bar.component.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { describe, it, expect } from 'vitest'; + import { BarComponent } from './bar.component'; + + describe('BarComponent', () => { + it('creates', () => { + TestBed.configureTestingModule({ + imports: [BarComponent], + }); + const fixture = TestBed.createComponent(BarComponent); + expect(fixture).toBeTruthy(); + }); + }); + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['lib/**/*.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-mock-unsupported_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-mock-unsupported_spec.ts new file mode 100644 index 000000000000..547d6528d86d --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-mock-unsupported_spec.ts @@ -0,0 +1,68 @@ +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "Vitest mocking unsupported"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + it('should fail when vi.mock is used', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + harness.writeFile( + 'src/app/mock-throw.spec.ts', + ` + import { vi } from 'vitest'; + vi.mock('./something', () => ({})); + `, + ); + + // Overwrite default to avoid noise + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + describe('Ignored', () => { it('pass', () => expect(true).toBe(true)); }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should not fail when vi.mock is used with a non-relative path', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + harness.writeFile( + 'src/app/mock-non-relative.spec.ts', + ` + import { vi } from 'vitest'; + vi.mock('@angular/cdk', () => ({})); + describe('Ignored', () => { it('pass', () => expect(true).toBe(true)); }); + `, + ); + + // Overwrite default to avoid noise + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + describe('Ignored', () => { it('pass', () => expect(true).toBe(true)); }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-shared-chunk-init_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-shared-chunk-init_spec.ts new file mode 100644 index 000000000000..1cddec79a14d --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-shared-chunk-init_spec.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "Vitest shared chunk initialization"', () => { + it('should provide shared-module exports to class-field initializers in async specs', async () => { + setupApplicationTarget(harness); + + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + // Keep the default project's spec deterministic; a third spec entry that does not touch + // the shared module does not affect the reproduction (verified in a fresh workspace). + await harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('AppComponent placeholder', () => { + it('runs', () => { + expect(1 + 1).toBe(2); + }); + }); + `, + ); + + // The shared `const`. Reached from both spec entry points, so it is hoisted into a chunk + // shared between them. + await harness.writeFile( + 'src/environments/env-config.ts', + ` + export interface DealerConfig { + dealerId: string; + clientKey: string; + } + + export const DEALERS: DealerConfig[] = [ + { dealerId: 'dealer-one', clientKey: 'KEY-ONE' }, + { dealerId: 'dealer-two', clientKey: 'KEY-TWO' }, + { dealerId: 'dealer-three', clientKey: 'KEY-THREE' }, + { dealerId: 'dealer-four', clientKey: 'KEY-FOUR' }, + ]; + `, + ); + + // Reached by both spec entries, so it and env-config.ts land in the shared chunk. Reads the + // const inside a method — after module initialization — and is the passing control. + await harness.writeFile( + 'src/app/features/lead-generator/services/lead.service.ts', + ` + import { Injectable } from '@angular/core'; + + import { DEALERS } from '../../../../environments/env-config'; + + @Injectable({ providedIn: 'root' }) + export class LeadService { + resolveClientKey(dealerId: string, clientKey?: string): string { + return clientKey ?? DEALERS.find((d) => d.dealerId === dealerId)?.clientKey ?? ''; + } + } + `, + ); + + await harness.writeFile( + 'src/app/features/lead-generator/services/index.ts', + `export * from './lead.service';\n`, + ); + + // Spec entry point 1 — the second importer that causes the chunk to be shared at all. + await harness.writeFile( + 'src/app/features/lead-generator/services/lead.service.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + import { TestBed } from '@angular/core/testing'; + + import { LeadService } from './lead.service'; + + describe('LeadService', () => { + it('reads DEALERS inside a method', () => { + TestBed.configureTestingModule({ providers: [LeadService] }); + + expect(TestBed.inject(LeadService).resolveClientKey('dealer-one')).toBe('KEY-ONE'); + }); + }); + `, + ); + + // In the other chunk; reads the shared export eagerly during class-field initialization. + await harness.writeFile( + 'src/app/features/lead-generator/lead-generator.container.ts', + ` + import { Component, inject } from '@angular/core'; + + import { LeadService } from './services'; + import { DEALERS, DealerConfig } from '../../../environments/env-config'; + + @Component({ + selector: 'app-lead-generator', + standalone: true, + template: '', + }) + export class LeadGeneratorContainer { + private readonly leadService = inject(LeadService); + + readonly dealers: DealerConfig[] = DEALERS; + readonly dealerOptions = this.dealers.map((d) => d.dealerId); + + hasService(): boolean { + return this.leadService != null; + } + } + `, + ); + + // Spec entry point 2 — the failing case without the fix. The `async` is load-bearing: + // zone.js makes the builder downlevel it, the spec then imports the `__async` helper, and + // esbuild emits this entry CommonJS-wrapped with the component module behind a lazy + // `__esm` initializer. No `await` is needed; a synchronous callback hides the defect. + await harness.writeFile( + 'src/app/features/lead-generator/lead-generator.container.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + import { TestBed } from '@angular/core/testing'; + + import { LeadGeneratorContainer } from './lead-generator.container'; + + describe('LeadGeneratorContainer', () => { + it('reads DEALERS in a class-field initialiser', async () => { + const fixture = TestBed.createComponent(LeadGeneratorContainer); + + expect(fixture.componentInstance.dealers.length).toBe(4); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-zone-init_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-zone-init_spec.ts new file mode 100644 index 000000000000..e19ef884aef5 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/vitest-zone-init_spec.ts @@ -0,0 +1,250 @@ +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "Vitest Zone initialization"', () => { + // Zone.js does not current provide fakAsync support for Vitest + xit('should load Zone and Zone testing support by default', async () => { + setupApplicationTarget(harness); // Defaults include zone.js + + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + import { fakeAsync, tick } from '@angular/core/testing'; + + describe('Zone Test', () => { + it('should have Zone defined', () => { + expect((globalThis as any).Zone).toBeDefined(); + }); + + it('should support fakeAsync', fakeAsync(() => { + let val = false; + setTimeout(() => { val = true; }, 100); + tick(100); + expect(val).toBeTrue(); + })); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should NOT load Zone when zoneless (no zone.js in polyfills)', async () => { + // Setup application target WITHOUT zone.js in polyfills + setupApplicationTarget(harness, { + polyfills: [], + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Zoneless Test', () => { + it('should NOT have Zone defined', () => { + expect((globalThis as any).Zone).toBeUndefined(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + }); + + it('should NOT load Zone when test polyfills is empty even if zone.js is in build polyfills', async () => { + setupApplicationTarget(harness, { + polyfills: ['zone.js'], + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: [], + }); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Zoneless Override Test', () => { + it('should NOT have Zone defined', () => { + expect((globalThis as any).Zone).toBeUndefined(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should load Zone when test polyfills includes zone.js even if build polyfills is empty', async () => { + setupApplicationTarget(harness, { + polyfills: [], + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: ['zone.js'], + }); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Zone Forced Test', () => { + it('should have Zone defined', () => { + expect((globalThis as any).Zone).toBeDefined(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should load Zone and emit a deprecation warning when testing a library and zone.js is installed', async () => { + harness.withBuilderTarget( + 'build', + async () => ({ success: true }), + { + project: 'ng-package.json', + }, + { + builderName: '@angular/build:ng-packagr', + }, + ); + + await harness.writeFile( + 'ng-package.json', + JSON.stringify({ + lib: { + entryFile: 'src/public-api.ts', + }, + }), + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app.component.spec.ts'], + }); + + await harness.writeFile( + 'src/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Library Zone Test', () => { + it('should have Zone defined', () => { + expect((globalThis as any).Zone).toBeDefined(); + }); + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectLog(logs, /Zone\.js polyfills are being automatically injected/); + }); + + it('should NOT load Zone and not emit warning when testing a library with polyfills: []', async () => { + harness.withBuilderTarget( + 'build', + async () => ({ success: true }), + { + project: 'ng-package.json', + }, + { + builderName: '@angular/build:ng-packagr', + }, + ); + + await harness.writeFile( + 'ng-package.json', + JSON.stringify({ + lib: { + entryFile: 'src/public-api.ts', + }, + }), + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: [], + include: ['src/app.component.spec.ts'], + }); + + await harness.writeFile( + 'src/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Library Zoneless Test', () => { + it('should NOT have Zone defined', () => { + expect((globalThis as any).Zone).toBeUndefined(); + }); + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectNoLog(logs, /Zone\.js polyfills are being automatically injected/); + }); + + it('should load Zone and Zone testing support when testing a library using @angular/build:library and zone.js is installed', async () => { + harness.withBuilderTarget( + 'build', + async () => ({ success: true }), + { + tsConfig: 'src/tsconfig.lib.json', + }, + { + builderName: '@angular/build:library', + }, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app.component.spec.ts'], + }); + + await harness.writeFile( + 'src/app.component.spec.ts', + ` + import { describe, it, expect } from 'vitest'; + + describe('Library Zone Test', () => { + it('should have Zone defined', () => { + expect((globalThis as any).Zone).toBeDefined(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts new file mode 100644 index 000000000000..cab5afd48a2c --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Watch Mode Behavior', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should run tests when a compilation error is fixed and a test failure is introduced simultaneously', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + // 1. Initial success + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // 2. Introduce compilation error + await harness.writeFiles({ + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should create the app', () => { + expect(true).toBe(true); // Syntax error incoming + const x: string = 1; // Type error + }); + });`, + }); + }, + // 3. Expect compilation error + async ({ result }) => { + expect(result?.success).toBeFalse(); + + // 4. Fix compilation error BUT introduce test failure + await harness.writeFiles({ + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should create the app', () => { + expect(true).toBe(false); // Logic failure + }); + });`, + }); + }, + // 5. Expect test failure (NOT success, which would happen if the test was skipped) + ({ result }) => { + expect(result?.success).toBeFalse(); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts new file mode 100644 index 000000000000..abd0a8d54e38 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "browsers"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should use DOM emulation when browsers is not provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + browsers: undefined, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should fail when a browser is requested but no provider is installed', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + browsers: ['chrome'], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + expectLog( + logs, + `The "browsers" option requires either "@vitest/browser-playwright", "@vitest/browser-webdriverio", or "@vitest/browser-preview" to be installed`, + ); + }); + + it('should name the provider packages when a runner config skips the dependency check', async () => { + await harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({}); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest-base.config.mts', + browsers: ['chrome'], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + expectLog( + logs, + `The "browsers" option requires either "@vitest/browser-playwright", "@vitest/browser-webdriverio", or "@vitest/browser-preview" to be installed within the project`, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/build-target_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/build-target_spec.ts new file mode 100644 index 000000000000..1af56e060e3d --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/build-target_spec.ts @@ -0,0 +1,63 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + xdescribe('Option: "buildTarget"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when buildTarget is not provided', async () => { + const { buildTarget, ...rest } = BASE_OPTIONS; + harness.useTarget('test', rest as any); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError(/"buildTarget" is required/); + }); + + it('should fail when buildTarget is empty', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + buildTarget: '', + }); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError( + /must match "\^\S+:\S+(:\S+)?\$"/, + ); + }); + + it('should fail when buildTarget does not have a project name', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + buildTarget: ':build', + }); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError( + /must match "\^\S+:\S+(:\S+)?\$"/, + ); + }); + + it('should fail when buildTarget does not have a target name', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + buildTarget: 'app:', + }); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError( + /must match "\^\S+:\S+(:\S+)?\$"/, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts new file mode 100644 index 000000000000..b92e709d2f12 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "coverageExclude"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + await harness.writeFiles({ + 'src/app/error.ts': `export const a = 1;`, + }); + }); + + it('should not exclude any files from coverage when not provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageInclude: ['**/*.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const summary = harness.readFile('coverage/test/coverage-final.json'); + expect(summary).toContain('src/app/error.ts"'); + }); + + it('should exclude files from coverage that match the glob pattern', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageInclude: ['**/*.ts'], + coverageExclude: ['**/error.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const summary = harness.readFile('coverage/test/coverage-final.json'); + expect(summary).not.toContain('src/app/error.ts"'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts new file mode 100644 index 000000000000..6cdbc8bfa23b --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "coverageInclude"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + await harness.writeFiles({ + 'src/app/included.ts': `export const a = 1;`, + 'src/app/included.spec.ts': ` + import { a } from './included'; + describe('included', () => { + it('should work', () => { + expect(a).toBe(1); + }); + }); + `, + 'src/app/excluded.ts': `export const b = 2;`, + }); + }); + + it('should only include and report coverage for files that match the glob pattern', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageInclude: ['**/included.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const summary = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const summaryKeys = Object.keys(summary); + + const includedKey = summaryKeys.find((key) => key.endsWith('src/app/included.ts')); + const excludedKey = summaryKeys.find((key) => key.endsWith('src/app/excluded.ts')); + + // Check that the included file is in the report and the excluded one is not. + expect(includedKey).toBeDefined(); + expect(excludedKey).toBeUndefined(); + + // Check that the coverage data for the included file is valid. + const includedCoverage = summary[includedKey!]; + // The file has one statement, and it should have been executed once. + expect(includedCoverage.s['0']).toBe(1); + }); + + it('should only include referenced files when no include pattern is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // coverageInclude is not provided, so only referenced files should be included. + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const summary = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const summaryKeys = Object.keys(summary); + + const includedKey = summaryKeys.find((key) => key.endsWith('src/app/included.ts')); + const excludedKey = summaryKeys.find((key) => key.endsWith('src/app/excluded.ts')); + + // The included file is referenced by its spec and should be in the report. + expect(includedKey).toBeDefined(); + // The excluded file is not referenced and should NOT be in the report. + expect(excludedKey).toBeUndefined(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts new file mode 100644 index 000000000000..edebb9e28167 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "coverageReporters"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should generate a json summary report when specified', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageReporters: ['json-summary'] as any, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(harness.hasFile('coverage/test/coverage-summary.json')).toBeTrue(); + }); + + it('should generate multiple reports when specified', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageReporters: ['json-summary', 'lcov'] as any, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(harness.hasFile('coverage/test/coverage-summary.json')).toBeTrue(); + expect(harness.hasFile('coverage/test/lcov.info')).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts new file mode 100644 index 000000000000..d0f51e731de9 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "coverage"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should not generate a code coverage report when coverage is false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/index.html').toNotExist(); + }); + + it('should generate a code coverage report when coverage is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/index.html').toExist(); + }); + + it('should generate a code coverage report when coverage is true and coverageReporters is set to json', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageReporters: ['json'] as any, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').content.toContain('app.component.ts'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts new file mode 100644 index 000000000000..9028ee0eb5fd --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + xdescribe('Option: "debug"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should not enter debug mode when debug is false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + debug: false, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectNoLog(logs, /Node.js inspector/); + }); + + it('should enter debug mode when debug is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + debug: true, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectLog(logs, /Node.js inspector is active/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts new file mode 100644 index 000000000000..2c21f7680716 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts @@ -0,0 +1,63 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "exclude"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + beforeEach(async () => { + await harness.writeFiles({ + 'src/app/error.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('Error spec', () => { + test('should error', () => { + expect(false).toBe(true); + }); + });`, + }); + }); + + it(`should not exclude any spec when exclude is not supplied`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it(`should exclude spec that matches the 'exclude' glob pattern`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + exclude: ['**/error.spec.ts'], + }); + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should exclude spec that matches the 'exclude' pattern with a relative project root`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + exclude: ['src/app/error.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts new file mode 100644 index 000000000000..abcfe5976f94 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../builder'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "filter"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + + await harness.writeFiles({ + 'src/app/pass.spec.ts': ` + describe('Passing Suite', () => { + it('should pass', () => { + expect(true).toBe(true); + }); + }); + `, + 'src/app/fail.spec.ts': ` + describe('Failing Suite', () => { + it('should fail', () => { + expect(true).toBe(false); + }); + }); + `, + }); + }); + + it('should only run tests that match the filter regex', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + // This filter should only match the 'should pass' test + filter: 'pass$', + }); + + const { result } = await harness.executeOnce(); + // The overall result should be success because the failing test was filtered out. + expect(result?.success).toBe(true); + }); + + it('should run all tests when no filter is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + // The overall result should be failure because the failing test was included. + expect(result?.success).toBe(false); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts new file mode 100644 index 000000000000..4ba7c9eaa051 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts @@ -0,0 +1,281 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "include"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it(`should fail when includes doesn't match any files`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['abc.spec.ts', 'def.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + [ + { + test: 'relative path from workspace to spec', + input: ['src/app/app.component.spec.ts'], + }, + { + test: 'relative path from project root to spec', + input: ['app/services/test.service.spec.ts'], + }, + { + test: 'relative path from workspace to directory', + input: ['src/app/services'], + }, + { + test: 'relative path from project root to directory', + input: ['app/services'], + }, + { + test: 'glob with spec suffix', + input: ['**/*.pipe.spec.ts', '**/*.pipe.spec.ts', '**/*test.service.spec.ts'], + }, + ].forEach((options, index) => { + it(`should work with ${options.test} (${index})`, async () => { + await harness.writeFiles({ + 'src/app/services/test.service.spec.ts': ` + describe('TestService', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + 'src/app/failing.service.spec.ts': ` + describe('FailingService', () => { + it('should be ignored', () => { + expect(true).toBe(false); + }); + });`, + 'src/app/property.pipe.spec.ts': ` + describe('PropertyPipe', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: options.input, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); + + it('should ignore TypeScript compilation errors in non-included test files', async () => { + await harness.writeFiles({ + 'src/app/services/test.service.spec.ts': ` + describe('TestService', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + 'src/app/broken.service.spec.ts': ` + // This test has a TypeScript type error that would fail compilation if compiled + const invalidNumber: number = 'not a number'; + describe('BrokenService', () => { + it('should fail compilation', () => { + expect(invalidNumber).toBe(1); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app/services/test.service.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should not compile unimported application files when testing standalone code', async () => { + await harness.writeFiles({ + 'src/tsconfig.spec.json': JSON.stringify({ + extends: '../tsconfig.json', + compilerOptions: { + outDir: '../out-tsc/spec', + types: ['jasmine', '@angular/localize'], + }, + files: ['polyfills.ts'], + include: ['**/*.ts', '**/*.d.ts'], + }), + 'src/app/services/test.service.spec.ts': ` + describe('TestService', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + 'src/app/unused-broken.ts': ` + // This unimported file has a TypeScript error and should not be compiled for standalone tests + export const invalidNumber: number = 'not a number'; + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app/services/test.service.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should resolve NgModule scope when testing a non-standalone component without importing the NgModule', async () => { + await harness.writeFiles({ + 'src/tsconfig.spec.json': JSON.stringify({ + extends: '../tsconfig.json', + compilerOptions: { + outDir: '../out-tsc/spec', + types: ['jasmine', '@angular/localize'], + }, + files: ['polyfills.ts'], + include: ['**/*.ts', '**/*.d.ts'], + }), + 'src/app/app.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

Hello, {{ title }}

', + standalone: false, + }) + export class App { + title = 'test'; + } + `, + 'src/app/app-module.ts': ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { RouterModule } from '@angular/router'; + import { App } from './app'; + + @NgModule({ + declarations: [App], + imports: [BrowserModule, RouterModule.forRoot([])], + bootstrap: [App], + }) + export class AppModule {} + `, + 'src/app/app.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { RouterModule } from '@angular/router'; + import { App } from './app'; + + describe('App', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [RouterModule.forRoot([])], + declarations: [App], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(App); + expect(fixture.componentInstance).toBeTruthy(); + }); + }); + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app/app.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should not compile unimported files when a non-standalone component NgModule is imported by the test', async () => { + await harness.writeFiles({ + 'src/tsconfig.spec.json': JSON.stringify({ + extends: '../tsconfig.json', + compilerOptions: { + outDir: '../out-tsc/spec', + types: ['jasmine', '@angular/localize'], + }, + files: ['polyfills.ts'], + include: ['**/*.ts', '**/*.d.ts'], + }), + 'src/app/app.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + template: '

Hello, {{ title }}

', + standalone: false, + }) + export class App { + title = 'test'; + } + `, + 'src/app/app-module.ts': ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { RouterModule } from '@angular/router'; + import { App } from './app'; + + @NgModule({ + declarations: [App], + imports: [BrowserModule, RouterModule.forRoot([])], + bootstrap: [App], + }) + export class AppModule {} + `, + 'src/app/app.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { App } from './app'; + import { AppModule } from './app-module'; + + describe('App', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [AppModule], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(App); + expect(fixture.componentInstance).toBeTruthy(); + }); + }); + `, + 'src/app/unused-broken.ts': ` + // This unimported file has a TypeScript error and should not be compiled when AppModule is already imported + export const invalidNumber: number = 'not a number'; + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + include: ['src/app/app.spec.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/isolate_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/isolate_spec.ts new file mode 100644 index 000000000000..28fbb855a91f --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/isolate_spec.ts @@ -0,0 +1,112 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "isolate"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when isolate is true and runner is karma', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'karma' as any, + isolate: true, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + expectLog(logs, /The "isolate" option is only available for the "vitest" runner/); + }); + + it('should run tests successfully when isolate is true and runner is vitest', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'vitest' as any, + isolate: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should run tests successfully when isolate is false and runner is vitest', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'vitest' as any, + isolate: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should override isolate from the Vitest config file when set to false', async () => { + harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + + export default defineConfig({ + test: { + fileParallelism: false, + isolate: true, + setupFiles: ['./src/setup.ts'], + }, + }); + `, + ); + + harness.writeFile( + 'src/setup.ts', + ` + const global = globalThis as typeof globalThis & { setupCount?: number }; + global.setupCount = (global.setupCount ?? 0) + 1; + `, + ); + + harness.writeFile( + 'src/app/first.spec.ts', + ` + it('runs first', () => { + expect(true).toBe(true); + }); + `, + ); + + harness.writeFile( + 'src/app/second.spec.ts', + ` + it('shares the test environment with the first spec file', () => { + const global = globalThis as typeof globalThis & { setupCount?: number }; + expect(global.setupCount).toBeGreaterThan(1); + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'vitest' as any, + runnerConfig: true, + isolate: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts new file mode 100644 index 000000000000..ade399d1936f --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "listTests"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + + await harness.writeFiles({ + 'src/app/app.component.spec.ts': + 'describe("AppComponent", () => { it("should...", () => {}); });', + 'src/app/other.spec.ts': 'describe("Other", () => { it("should...", () => {}); });', + 'src/app/ignored.ts': 'export const a = 1;', + }); + }); + + it('should list all discovered tests and exit when true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + listTests: true, + }); + + const { result, logs } = await harness.executeOnce(); + + // Should succeed and exit without running tests + expect(result?.success).toBe(true); + + // Should log the discovered test files + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/Discovered test files:/) }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/.*app\.component\.spec\.ts/), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/.*other\.spec\.ts/) }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/.*ignore\.ts/) }), + ); + + // Should NOT log output from the test runner (since it shouldn't run) + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/Application bundle generation complete/), + }), + ); + }); + + it('should not list tests and should run them as normal when false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + listTests: false, + }); + + const { result, logs } = await harness.executeOnce(); + + // Should succeed because the tests pass + expect(result?.success).toBe(true); + + // Should NOT log the discovered test files + expect(logs).not.toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/Discovered test files:/) }), + ); + + // Should log output from the test runner + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/Application bundle generation complete/), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/polyfills_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/polyfills_spec.ts new file mode 100644 index 000000000000..06bc3bd8fc98 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/polyfills_spec.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "polyfills"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should include polyfills specified on test target', async () => { + await harness.writeFiles({ + 'src/custom-polyfill.js': `globalThis['CUSTOM_POLYFILL_RAN'] = true;`, + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest'; + describe('Polyfill Test', () => { + test('should have run test polyfill', () => { + expect((globalThis as any)['CUSTOM_POLYFILL_RAN']).toBe(true); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: ['src/custom-polyfill.js'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should override buildTarget polyfills when polyfills is specified on test target', async () => { + setupApplicationTarget(harness, { + polyfills: ['src/app-polyfill.js'], + }); + + await harness.writeFiles({ + 'src/app-polyfill.js': `globalThis['APP_POLYFILL_RAN'] = true;`, + 'src/test-polyfill.js': `globalThis['TEST_POLYFILL_RAN'] = true;`, + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest'; + describe('Polyfill Override Test', () => { + test('should have run test polyfill and not app polyfill', () => { + expect((globalThis as any)['TEST_POLYFILL_RAN']).toBe(true); + expect((globalThis as any)['APP_POLYFILL_RAN']).toBeUndefined(); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: ['src/test-polyfill.js'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should allow overriding buildTarget polyfills with an empty array', async () => { + setupApplicationTarget(harness, { + polyfills: ['src/app-polyfill.js'], + }); + + await harness.writeFiles({ + 'src/app-polyfill.js': `globalThis['APP_POLYFILL_RAN'] = true;`, + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest'; + describe('Empty Polyfill Override Test', () => { + test('should not have run app polyfill', () => { + expect((globalThis as any)['APP_POLYFILL_RAN']).toBeUndefined(); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + polyfills: [], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts new file mode 100644 index 000000000000..6485975270e8 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts @@ -0,0 +1,118 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "providersFile"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when providersFile does not exist', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + providersFile: 'src/my.providers.ts', + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Could not resolve "./my.providers"'), + }), + ); + }); + + it('should use providers from the specified file', async () => { + await harness.writeFiles({ + 'src/my.providers.ts': ` + import { importProvidersFrom } from '@angular/core'; + import { CommonModule } from '@angular/common'; + export default [importProvidersFrom(CommonModule)]; + `, + }); + + await harness.modifyFile('src/tsconfig.spec.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('my.providers.ts'); + + return JSON.stringify(tsConfig); + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + providersFile: 'src/my.providers.ts', + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should work with providers that inject services requiring JIT compilation', async () => { + await harness.writeFiles({ + 'src/test.service.ts': ` + import { Injectable, inject } from '@angular/core'; + import { Router } from '@angular/router'; + + @Injectable({ providedIn: 'root' }) + export class TestService { + router = inject(Router); + } + `, + 'src/test.providers.ts': ` + import { TestService } from './test.service'; + export default [TestService]; + `, + 'src/app/app.component.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { AppComponent } from './app.component'; + import { TestService } from '../test.service'; + import { describe, expect, it } from 'vitest'; + + describe('AppComponent', () => { + it('should create the app and inject TestService', () => { + TestBed.configureTestingModule({ + declarations: [AppComponent], + }); + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + const testService = TestBed.inject(TestService); + expect(app).toBeTruthy(); + expect(testService).toBeTruthy(); + expect(testService.router).toBeTruthy(); + }); + }); + `, + }); + + await harness.modifyFile('src/tsconfig.spec.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('test.service.ts', 'test.providers.ts'); + + return JSON.stringify(tsConfig); + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + providersFile: 'src/test.providers.ts', + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/quiet_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/quiet_spec.ts new file mode 100644 index 000000000000..1ca8281db8b1 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/quiet_spec.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "quiet"', () => { + let originalCI: string | undefined; + + beforeEach(async () => { + setupApplicationTarget(harness); + originalCI = process.env['CI']; + }); + + afterEach(() => { + if (originalCI !== undefined) { + process.env['CI'] = originalCI; + } else { + delete process.env['CI']; + } + }); + + it('should default to true (quiet) when CI is not set', async () => { + delete process.env['CI']; + + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // Should not contain the stats table headers + expectNoLog(logs, /Initial chunk files/); + }); + + it('should default to false (verbose) when CI is set', async () => { + process.env['CI'] = 'true'; + + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // Should contain the stats table headers or file listing + expectLog(logs, /Application bundle generation complete/); + }); + + it('should respect quiet: true explicitly', async () => { + process.env['CI'] = 'false'; // Ensure CI doesn't interfere if it defaults to false + + harness.useTarget('test', { + ...BASE_OPTIONS, + quiet: true, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectNoLog(logs, /Initial chunk files/); + }); + + it('should respect quiet: false explicitly', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + quiet: false, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // On initial build, it should print the file list + expectLog(logs, /Initial/); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts new file mode 100644 index 000000000000..31fc1a7bfe95 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Options: "reporter" and "outputFile"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it(`should output a JSON report`, async () => { + await harness.removeFile('src/app/app.component.spec.ts'); + await harness.writeFiles({ + 'src/app/services/test.service.spec.ts': ` + describe('TestService', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: ['json'], + outputFile: 'test-report.json', + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const reportContent = await harness.readFile('test-report.json'); + expect(reportContent).toContain('TestService'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts new file mode 100644 index 000000000000..89ac5804e37e --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "reporters"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + it(`should support a single reporter`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: ['json'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should support multiple reporters`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: ['json', 'verbose'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should support a single reporter with options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [['json', { outputFile: 'a.json' }]], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('a.json').toExist(); + }); + + it(`should support multiple reporters with options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [ + ['json', { outputFile: 'a.json' }], + ['junit', { outputFile: 'a.xml' }], + ], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('a.json').toExist(); + harness.expectFile('a.xml').toExist(); + }); + + it(`should support multiple reporters with and without options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [['json', { outputFile: 'a.json' }], 'verbose', 'default'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('a.json').toExist(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/runner-args_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/runner-args_spec.ts new file mode 100644 index 000000000000..d4adf9f3096c --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/runner-args_spec.ts @@ -0,0 +1,154 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + UNIT_TEST_BUILDER_INFO, + describeBuilder, + expectLog, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "runnerArgs"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when used with the karma runner', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'karma' as any, + runnerArgs: ['--update'], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + expectLog(logs, /The "runnerArgs" option is only available for the "vitest" runner/); + }); + + it('should fail when an unsupported Vitest option is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerArgs: ['--reporter=dot'], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + expectLog( + logs, + /The Vitest "--reporter" option is not supported\. Use the "reporters" option instead\./, + ); + }); + + describe('with a test that passes on the second attempt', () => { + beforeEach(async () => { + await harness.writeFile( + 'src/app/retry.spec.ts', + ` + let attempts = 0; + + it('passes on the second attempt', () => { + attempts++; + expect(attempts).toBe(2); + }); + `, + ); + }); + + it('should fail when the test is not retried', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should provide a supported Vitest option to the test project', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerArgs: ['--retry=1'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should take precedence over a Vitest configuration file', async () => { + await harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + + export default defineConfig({ + test: { + retry: 0, + }, + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + runnerArgs: ['--retry=1'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); + + describe('with an outdated snapshot', () => { + const snapshotFile = 'src/app/__snapshots__/snapshot.spec.ts.snap'; + + beforeEach(async () => { + await harness.writeFile( + 'src/app/snapshot.spec.ts', + ` + import { expect, it } from 'vitest'; + + it('matches the snapshot', () => { + expect('current value').toMatchSnapshot(); + }); + `, + ); + + await harness.writeFile( + snapshotFile, + '// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html\n\n' + + 'exports[`matches the snapshot 1`] = `"outdated value"`;\n', + ); + }); + + it('should fail when the snapshot is not updated', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + harness.expectFile(snapshotFile).content.toContain('"outdated value"'); + }); + + it('should update the snapshot when the Vitest update option is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerArgs: ['--update'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile(snapshotFile).content.toContain('"current value"'); + harness.expectFile(snapshotFile).content.not.toContain('"outdated value"'); + }); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/runner-config-coverage_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/runner-config-coverage_spec.ts new file mode 100644 index 000000000000..9998caea72e3 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/runner-config-coverage_spec.ts @@ -0,0 +1,120 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "runnerConfig" Coverage Merging', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + describe('Vitest Runner', () => { + it('should preserve thresholds from Vitest config when not overridden by CLI', async () => { + harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + thresholds: { + branches: 100 + } + } + } + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + coverage: true, + }); + + const { result } = await harness.executeOnce(); + + // Should fail because branches are not 100% + expect(result?.success).toBeFalse(); + }); + + it('should override Vitest config thresholds with CLI thresholds', async () => { + harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + thresholds: { + branches: 100 + } + } + } + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + coverage: true, + coverageThresholds: { + branches: 0, + }, + }); + + const { result } = await harness.executeOnce(); + + // Should pass because CLI overrides threshold to 0 + expect(result?.success).toBeTrue(); + }); + + it('should merge partial CLI thresholds with Vitest config thresholds', async () => { + harness.writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + thresholds: { + statements: 100, + branches: 100 + } + } + } + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + coverage: true, + coverageThresholds: { + statements: 0, + // branches is undefined here, should remain 100 from config + }, + }); + + const { result } = await harness.executeOnce(); + + // Should still fail because branches threshold (100) is not met + expect(result?.success).toBeFalse(); + }); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts new file mode 100644 index 000000000000..57ec6be0f25d --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +const VITEST_CONFIG_CONTENT = ` +import { defineConfig } from 'vitest/config'; +export default defineConfig({ + test: { + reporters: [['junit', { outputFile: './vitest-results.xml' }]], + }, +}); +`; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "runnerConfig"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + describe('Vitest Runner', () => { + it('should use a specified config file path', async () => { + harness.writeFile('custom-vitest.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'custom-vitest.config.mts', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should search for a config file when `true`', async () => { + harness.writeFile('vitest-base.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should ignore config file when `false`', async () => { + harness.writeFile('vitest-base.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + + it('should ignore config file by default', async () => { + harness.writeFile('vitest-base.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + + it('should find and use a `vitest-base.config.mts` in the project root', async () => { + harness.writeFile('vitest-base.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should find and use a `vitest-base.config.mjs` in the workspace root', async () => { + // This file should be ignored because the new logic looks for `vitest-base.config.*`. + harness.writeFile('vitest.config.ts', VITEST_CONFIG_CONTENT); + // The workspace root is the directory containing the project root in the test harness. + harness.writeFile('vitest-base.config.mjs', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should fallback to in-memory config when no base config is found', async () => { + // This file should be ignored because the new logic looks for `vitest-base.config.*` + // and when `runnerConfig` is true, it should not fall back to the default search. + harness.writeFile('vitest.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/runner_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/runner_spec.ts new file mode 100644 index 000000000000..77479149784c --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/runner_spec.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + xdescribe('Option: "runner"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when runner is not provided', async () => { + const { runner, ...rest } = BASE_OPTIONS; + harness.useTarget('test', rest as any); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError(/"runner" is required/); + }); + + it('should fail when runner is invalid', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runner: 'invalid' as any, + }); + + await expectAsync(harness.executeOnce()).toBeRejectedWithError( + /must be one of the following values: "karma", "vitest"/, + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts new file mode 100644 index 000000000000..44241bbcfd8a --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "setupFiles"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should fail when a setup file does not exist', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + setupFiles: ['src/setup.ts'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + // Verify that the build failed due to resolution error (esbuild error) + expectLog(logs, /Could not resolve/); + expectLog(logs, /src\/setup\.ts/); + }); + + it('should include the setup files', async () => { + await harness.writeFiles({ + 'src/setup.ts': `(globalThis as any)['TEST_SETUP_RAN'] = true;`, + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should have run setup file', () => { + expect((globalThis as any)['TEST_SETUP_RAN']).toBe(true); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + setupFiles: ['src/setup.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should run setup file hooks for each spec file when coverage is enabled', async () => { + await harness.writeFiles({ + 'custom-vitest.config.mts': ` + import { defineConfig } from 'vitest/config'; + + export default defineConfig({ + test: { + fileParallelism: false, + }, + }); + `, + 'src/setup.ts': ` + import { afterEach, beforeEach, expect } from 'vitest'; + const global = globalThis as typeof globalThis & { + setupHookCalls?: string[]; + }; + const setupHookCalls = (global.setupHookCalls ??= []); + beforeEach(() => { + const testName = expect.getState().currentTestName ?? ''; + setupHookCalls.push('beforeEach:' + testName); + }); + afterEach(() => { + const testName = expect.getState().currentTestName ?? ''; + setupHookCalls.push('afterEach:' + testName); + }); + `, + 'src/app/app.component.spec.ts': ` + import { expect, it } from 'vitest'; + it('runs setup hooks for first test in app.component.spec', () => { + const global = globalThis as typeof globalThis & { setupHookCalls?: string[] }; + expect(global.setupHookCalls).toContain('beforeEach:runs setup hooks for first test in app.component.spec'); + }); + it('runs setup hooks for second test in app.component.spec', () => { + const global = globalThis as typeof globalThis & { setupHookCalls?: string[] }; + expect(global.setupHookCalls).toContain('beforeEach:runs setup hooks for second test in app.component.spec'); + expect(global.setupHookCalls).toContain('afterEach:runs setup hooks for first test in app.component.spec'); + }); + `, + 'src/app/second.spec.ts': ` + import { expect, it } from 'vitest'; + it('runs setup hooks for first test in second.spec', () => { + const global = globalThis as typeof globalThis & { setupHookCalls?: string[] }; + expect(global.setupHookCalls).toContain('beforeEach:runs setup hooks for first test in second.spec'); + }); + it('runs setup hooks for second test in second.spec', () => { + const global = globalThis as typeof globalThis & { setupHookCalls?: string[] }; + expect(global.setupHookCalls).toContain('beforeEach:runs setup hooks for second test in second.spec'); + expect(global.setupHookCalls).toContain('afterEach:runs setup hooks for first test in second.spec'); + }); + `, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + runnerConfig: 'custom-vitest.config.mts', + setupFiles: ['src/setup.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/splitting_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/splitting_spec.ts new file mode 100644 index 000000000000..133c54ca21e9 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/splitting_spec.ts @@ -0,0 +1,132 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, + expectNoLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "splitting"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should default to true and run tests successfully', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should run tests successfully when splitting is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + splitting: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should run tests successfully when splitting is false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + splitting: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should split shared code into a separate chunk when splitting is true', async () => { + await harness.writeFile( + 'src/app/shared.ts', + `export const SHARED_DATA = 'shared-data-value';`, + ); + + await harness.writeFile( + 'src/app/first.spec.ts', + ` + import { SHARED_DATA } from './shared'; + + it('tests first', () => { + expect(SHARED_DATA).toBe('shared-data-value'); + }); + `, + ); + + await harness.writeFile( + 'src/app/second.spec.ts', + ` + import { SHARED_DATA } from './shared'; + + it('tests second', () => { + expect(SHARED_DATA).toBe('shared-data-value'); + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + splitting: true, + quiet: false, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectLog(logs, /chunk-[a-z0-9]+\.js/i); + }); + + it('should not split shared code into a separate chunk when splitting is false', async () => { + await harness.writeFile( + 'src/app/shared.ts', + `export const SHARED_DATA = 'shared-data-value';`, + ); + + await harness.writeFile( + 'src/app/first.spec.ts', + ` + import { SHARED_DATA } from './shared'; + + it('tests first', () => { + expect(SHARED_DATA).toBe('shared-data-value'); + }); + `, + ); + + await harness.writeFile( + 'src/app/second.spec.ts', + ` + import { SHARED_DATA } from './shared'; + + it('tests second', () => { + expect(SHARED_DATA).toBe('shared-data-value'); + }); + `, + ); + + harness.useTarget('test', { + ...BASE_OPTIONS, + splitting: false, + quiet: false, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expectNoLog(logs, /chunk-[a-z0-9]+\.js/i); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts new file mode 100644 index 000000000000..101f07c1d12e --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, + expectLog, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "tsConfig"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should use "tsconfig.spec.json" by default when it exists', async () => { + const { tsConfig, ...rest } = BASE_OPTIONS; + harness.useTarget('test', rest); + + // Create tsconfig.spec.json + await harness.writeFile( + 'tsconfig.spec.json', + `{ "extends": "./tsconfig.json", "compilerOptions": { "types": ["jasmine"] }, "include": ["src/**/*.ts"] }`, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // TODO: Add expectation that the file was used. + }); + + it('should use build target tsConfig when "tsconfig.spec.json" does not exist', async () => { + const { tsConfig, ...rest } = BASE_OPTIONS; + harness.useTarget('test', rest); + + // The build target tsconfig is not setup to build the tests and should fail + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should fail when user specified tsConfig does not exist', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + tsConfig: 'random/tsconfig.spec.json', + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expectLog(logs, `The specified tsConfig file 'random/tsconfig.spec.json' does not exist.`); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts new file mode 100644 index 000000000000..79e25ca84b27 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "watch"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should run tests once when watch is false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should re-run tests when a file changes when watch is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + await harness.writeFiles({ + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should create the app', () => { + expect(true).toBe(false); + }); + });`, + }); + }, + ({ result }) => { + expect(result?.success).toBeFalse(); + }, + ]); + }); + + it('should disable the Vite server file watcher when watch is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: true, + runnerConfig: 'vitest.config.mts', + }); + + await harness.writeFile( + 'vitest.config.mts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + plugins: [ + { + name: 'assert-watch-disabled', + configureVitest({ vitest, project }) { + if (vitest.vite.config.server.watch !== null || project.vite.config.server.watch !== null) { + throw new Error('Expected Vite server.watch to be null'); + } + }, + }, + ], + }); + `, + ); + + await harness.executeWithCases([ + ({ result }) => { + expect(result?.success).toBeTrue(); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/setup.ts b/packages/angular/build/src/builders/unit-test/tests/setup.ts new file mode 100644 index 000000000000..e6770e115789 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/setup.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { json } from '@angular-devkit/core'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { BuilderHarness } from '../../../../../../../modules/testing/builder/src'; +import { + ApplicationBuilderOptions as ApplicationSchema, + buildApplication, +} from '../../../builders/application'; +import { Runner, Schema } from '../schema'; + +// TODO: Consider using package.json imports field instead of relative path +// after the switch to rules_js. +export * from '../../../../../../../modules/testing/builder/src'; + +// TODO: Remove and use import after Vite-based dev server is moved to new package +export const APPLICATION_BUILDER_INFO = Object.freeze({ + name: '@angular/build:application', + schemaPath: path.join( + path.dirname(require.resolve('@angular/build/package.json')), + 'src/builders/application/schema.json', + ), +}); + +/** + * Contains all required application builder fields. + * Also disables progress reporting to minimize logging output. + */ +export const APPLICATION_BASE_OPTIONS = Object.freeze({ + index: 'src/index.html', + browser: 'src/main.ts', + outputPath: 'dist', + tsConfig: 'src/tsconfig.app.json', + progress: false, + + // Disable optimizations + optimization: false, + + // Enable polling (if a test enables watch mode). + // This is a workaround for bazel isolation file watch not triggering in tests. + poll: 100, +}); + +export const UNIT_TEST_BUILDER_INFO = Object.freeze({ + name: '@angular/build:unit-test', + schemaPath: __dirname + '/../schema.json', +}); + +/** + * Contains all required dev-server builder fields. + * The port is also set to zero to ensure a free port is used for each test which + * supports parallel test execution. + */ +export const BASE_OPTIONS = Object.freeze({ + buildTarget: 'test:build', + tsConfig: 'src/tsconfig.spec.json', + runner: Runner.Vitest, +}); + +/** + * Maximum time for single build/rebuild + * This accounts for CI variability. + */ +export const BUILD_TIMEOUT = 25_000; + +/** + * Cached application builder option schema + */ +let applicationSchema: json.schema.JsonSchema | undefined; + +/** + * Adds a `build` target to a builder test harness for the application builder with the base options + * used by the application builder tests. + * + * @param harness The builder harness to use when setting up the application builder target + * @param extraOptions The additional options that should be used when executing the target. + */ +export function setupApplicationTarget( + harness: BuilderHarness, + extraOptions?: Partial, +): void { + applicationSchema ??= JSON.parse( + readFileSync(APPLICATION_BUILDER_INFO.schemaPath, 'utf8'), + ) as json.schema.JsonSchema; + + harness.withBuilderTarget( + 'build', + buildApplication, + { + ...APPLICATION_BASE_OPTIONS, + polyfills: ['zone.js', '@angular/localize/init'], + ...extraOptions, + }, + { + builderName: APPLICATION_BUILDER_INFO.name, + optionSchema: applicationSchema, + }, + ); +} diff --git a/packages/angular/build/src/index.ts b/packages/angular/build/src/index.ts new file mode 100644 index 000000000000..b6a547921db8 --- /dev/null +++ b/packages/angular/build/src/index.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export { buildApplication, type ApplicationBuilderOptions } from './builders/application'; +export type { ApplicationBuilderExtensions } from './builders/application/options'; +export { type BuildOutputFile, BuildOutputFileType } from './tools/esbuild/bundler-files'; +export type { BuildOutputAsset } from './tools/esbuild/bundler-execution-result'; + +export { + executeDevServerBuilder, + type DevServerBuilderOptions, + type DevServerBuilderOutput, +} from './builders/dev-server'; + +export { + execute as executeExtractI18nBuilder, + type ExtractI18nBuilderOptions, +} from './builders/extract-i18n'; + +export { + execute as executeNgPackagrBuilder, + type NgPackagrBuilderOptions, +} from './builders/ng-packagr'; +export { + execute as executeUnitTestBuilder, + type UnitTestBuilderOptions, +} from './builders/unit-test'; + +export { execute as executeKarmaBuilder, type KarmaBuilderOptions } from './builders/karma'; diff --git a/packages/angular/build/src/private.ts b/packages/angular/build/src/private.ts new file mode 100644 index 000000000000..e95ad26af3fc --- /dev/null +++ b/packages/angular/build/src/private.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * Private exports intended only for use with the @angular-devkit/build-angular package. + * All exports are not supported for external use, do not provide SemVer guarantees, and + * their existence may change in any future version. + */ + +import { createAngularCompilation } from './tools/angular/compilation'; +import { SecondaryCompilationContext } from './tools/esbuild/angular/compilation-state'; +import { + CompilerPluginOptions, + createCompilerPlugin as internalCreateCompilerPlugin, +} from './tools/esbuild/angular/compiler-plugin'; +import { ComponentStylesheetBundler } from './tools/esbuild/angular/component-stylesheets'; +import { BundleStylesheetOptions } from './tools/esbuild/stylesheets/bundle-options'; + +// Builders +export { buildApplicationInternal } from './builders/application'; +export type { ApplicationBuilderInternalOptions } from './builders/application/options'; +export { type Result, type ResultFile, ResultKind } from './builders/application/results'; +export { serveWithVite } from './builders/dev-server/vite'; +export { + normalizeOptions as normalizeDevServerOptions, + type NormalizedDevServerOptions, +} from './builders/dev-server/options'; + +// Tools +export type { ExternalResultMetadata } from './tools/esbuild/bundler-execution-result'; +export { transformSupportedBrowsersToTargets } from './tools/esbuild/target'; +export { SassCompiler } from './tools/sass/sass-service'; + +export { SourceFileCache } from './tools/esbuild/angular/source-file-cache'; +export { Cache } from './utils/cache'; +export { createJitResourceTransformer } from './tools/angular/transformers/jit-resource-transformer'; +export { JavaScriptTransformer } from './tools/javascript-transformer'; + +export function createCompilerPlugin( + pluginOptions: CompilerPluginOptions & { + browserOnlyBuild?: boolean; + noopTypeScriptCompilation?: boolean; + }, + styleOptions: BundleStylesheetOptions & { inlineStyleLanguage: string }, +): import('esbuild').Plugin { + return internalCreateCompilerPlugin( + pluginOptions, + pluginOptions.noopTypeScriptCompilation + ? new SecondaryCompilationContext() + : () => createAngularCompilation(!!pluginOptions.jit, !!pluginOptions.browserOnlyBuild), + new ComponentStylesheetBundler( + styleOptions, + styleOptions.inlineStyleLanguage, + pluginOptions.incremental, + ), + ); +} + +export type { CompilerPluginOptions, BundleStylesheetOptions }; +export type { AngularCompilation } from './tools/angular/compilation'; +export { DiagnosticModes } from './tools/angular/compilation'; +export { createAngularCompilation }; +export { ComponentStylesheetBundler } from './tools/esbuild/angular/component-stylesheets'; + +// Utilities +export * from './utils/bundle-calculator'; +export { checkPort } from './utils/check-port'; +export { deleteOutputDir } from './utils/delete-output-dir'; +export { emitFilesToDisk } from './utils/disk-files'; +export { type I18nOptions, createI18nOptions, loadTranslations } from './utils/i18n-options'; +export { + IndexHtmlGenerator, + type IndexHtmlGeneratorOptions, + type IndexHtmlGeneratorProcessOptions, + type IndexHtmlTransform, +} from './utils/index-file/index-html-generator'; +export type { FileInfo } from './utils/index-file/augment-index-html'; +export { loadProxyConfiguration } from './utils/load-proxy-config'; +export { type TranslationLoader, createTranslationLoader } from './utils/load-translations'; +export { purgeStaleBuildCache } from './utils/purge-cache'; +export { augmentAppWithServiceWorker } from './utils/service-worker'; +export { type BundleStats, generateBuildStatsTable } from './utils/stats-table'; +export { getSupportedBrowsers } from './utils/supported-browsers'; +export { assertCompatibleAngularVersion } from './utils/version'; +export { findTests, getTestEntrypoints } from './builders/karma/find-tests'; +export { + findTailwindConfiguration, + generateSearchDirectories, + loadPostcssConfiguration, +} from './utils/postcss-configuration'; diff --git a/packages/angular/build/src/tools/angular/angular-host.ts b/packages/angular/build/src/tools/angular/angular-host.ts new file mode 100644 index 000000000000..214666908ddf --- /dev/null +++ b/packages/angular/build/src/tools/angular/angular-host.ts @@ -0,0 +1,286 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import assert from 'node:assert'; +import nodePath from 'node:path'; +import type ts from 'typescript'; +import { calculateHash } from '../../utils/hash'; + +export type AngularCompilerOptions = ng.CompilerOptions; +export type AngularCompilerHost = ng.CompilerHost; + +export interface AngularHostOptions { + fileReplacements?: Record; + modifiedFiles?: Set; + externalStylesheets?: Map; + transformStylesheet( + data: string, + containingFile: string, + stylesheetFile?: string, + order?: number, + className?: string, + ): Promise; + processWebWorker(workerFile: string, containingFile: string): string; +} + +/** + * Patches in-place the `getSourceFiles` function on an instance of a TypeScript + * `Program` to ensure that all returned SourceFile instances have a `version` + * field. The `version` field is required when used with a TypeScript BuilderProgram. + * @param program The TypeScript Program instance to patch. + */ +export function ensureSourceFileVersions( + program: ts.Program, + previousProgram?: ts.BuilderProgram, +): void { + const baseGetSourceFiles = program.getSourceFiles; + // TODO: Update Angular compiler to add versions to all internal files and remove this + program.getSourceFiles = function (...parameters) { + const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles( + ...parameters, + ); + + for (const file of files) { + if (file.version === undefined) { + const previousFile: (ts.SourceFile & { version?: string }) | undefined = + previousProgram && !file.fileName.endsWith('.ngtypecheck.ts') + ? previousProgram.getSourceFile(file.fileName) + : undefined; + file.version = previousFile?.version ?? calculateHash(file.text); + } + } + + return files; + }; +} + +function augmentHostWithCaching(host: ts.CompilerHost, cache: Map): void { + const baseGetSourceFile = host.getSourceFile; + host.getSourceFile = function ( + fileName, + languageVersion, + onError, + shouldCreateNewSourceFile, + ...parameters + ) { + if (!shouldCreateNewSourceFile && cache.has(fileName)) { + return cache.get(fileName); + } + + const file = baseGetSourceFile.call( + host, + fileName, + languageVersion, + onError, + true, + ...parameters, + ); + + if (file) { + cache.set(fileName, file); + } + + return file; + }; +} + +function augmentResolveModuleNames( + typescript: typeof ts, + host: ts.CompilerHost, + resolvedModuleModifier: ( + resolvedModule: ts.ResolvedModule | undefined, + moduleName: string, + ) => ts.ResolvedModule | undefined, + moduleResolutionCache?: ts.ModuleResolutionCache, +): void { + if (host.resolveModuleNames) { + const baseResolveModuleNames = host.resolveModuleNames; + host.resolveModuleNames = function (moduleNames: string[], ...parameters) { + return moduleNames.map((name) => { + const result = baseResolveModuleNames.call(host, [name], ...parameters); + + return resolvedModuleModifier(result[0], name); + }); + }; + } else { + host.resolveModuleNames = function ( + moduleNames: string[], + containingFile: string, + _reusedNames: string[] | undefined, + redirectedReference: ts.ResolvedProjectReference | undefined, + options: ts.CompilerOptions, + ) { + return moduleNames.map((name) => { + const result = typescript.resolveModuleName( + name, + containingFile, + options, + host, + moduleResolutionCache, + redirectedReference, + ).resolvedModule; + + return resolvedModuleModifier(result, name); + }); + }; + } +} + +function normalizePath(path: string): string { + return nodePath.win32.normalize(path).replace(/\\/g, nodePath.posix.sep); +} + +function augmentHostWithReplacements( + typescript: typeof ts, + host: ts.CompilerHost, + replacements: Record, + moduleResolutionCache?: ts.ModuleResolutionCache, +): void { + if (Object.keys(replacements).length === 0) { + return; + } + + const normalizedReplacements: Record = {}; + for (const [key, value] of Object.entries(replacements)) { + normalizedReplacements[normalizePath(key)] = normalizePath(value); + } + + const tryReplace = (resolvedModule: ts.ResolvedModule | undefined) => { + const replacement = resolvedModule && normalizedReplacements[resolvedModule.resolvedFileName]; + if (replacement) { + return { + resolvedFileName: replacement, + isExternalLibraryImport: /[/\\]node_modules[/\\]/.test(replacement), + }; + } else { + return resolvedModule; + } + }; + + augmentResolveModuleNames(typescript, host, tryReplace, moduleResolutionCache); +} + +export function createAngularCompilerHost( + typescript: typeof ts, + compilerOptions: AngularCompilerOptions, + hostOptions: AngularHostOptions, + packageJsonCache: ts.PackageJsonInfoCache | undefined, + sourceFileCache?: Map, +): AngularCompilerHost { + // Create TypeScript compiler host + const host: AngularCompilerHost = typescript.createIncrementalCompilerHost(compilerOptions); + // Set the parsing mode to the same as TS 5.3+ default for tsc. This provides a parse + // performance improvement by skipping non-type related JSDoc parsing. + host.jsDocParsingMode = typescript.JSDocParsingMode.ParseForTypeErrors; + + // The AOT compiler currently requires this hook to allow for a transformResource hook. + // Once the AOT compiler allows only a transformResource hook, this can be reevaluated. + host.readResource = async function (filename) { + // Only template resources need to be read by the compiler host. + // External stylesheets are read and bundled by the stylesheet bundler during `transformResource`. + if (!hasTemplateExtension(filename)) { + return ''; + } + + return this.readFile(filename) ?? ''; + }; + + // Add an AOT compiler resource transform hook + host.transformResource = async function (data, context) { + // Only style resources are transformed currently + if (context.type !== 'style') { + return null; + } + + assert( + !context.resourceFile || !hostOptions.externalStylesheets?.has(context.resourceFile), + 'External runtime stylesheets should not be transformed: ' + context.resourceFile, + ); + + // No transformation required if an inline resource is empty + if (!context.resourceFile && data.trim().length === 0) { + return { content: '' }; + } + + const result = await hostOptions.transformStylesheet( + data, + context.containingFile, + context.resourceFile ?? undefined, + context.order, + context.className, + ); + + return typeof result === 'string' ? { content: result } : null; + }; + + host.resourceNameToFileName = function (resourceName, containingFile) { + const resolvedPath = nodePath.join(nodePath.dirname(containingFile), resourceName); + if (!this.fileExists(resolvedPath)) { + return null; + } + + // Reject TypeScript files used as component resources (e.g., styleUrl pointing to a .ts file). + // Processing a TypeScript file as a stylesheet or template causes confusing downstream errors. + if (hasTypeScriptExtension(resolvedPath)) { + return null; + } + + // All resource names that have template file extensions are assumed to be templates + // TODO: Update compiler to provide the resource type to avoid extension matching here. + if (!hostOptions.externalStylesheets || hasTemplateExtension(resolvedPath)) { + return resolvedPath; + } + + // For external stylesheets, create a unique identifier and store the mapping + let externalId = hostOptions.externalStylesheets.get(resolvedPath); + if (externalId === undefined) { + externalId = calculateHash(resolvedPath); + hostOptions.externalStylesheets.set(resolvedPath, externalId); + } + + return externalId + '.css'; + }; + + // Allow the AOT compiler to request the set of changed templates and styles + host.getModifiedResourceFiles = function () { + return hostOptions.modifiedFiles; + }; + + // Provide a resolution cache to ensure package.json lookups are cached + const resolutionCache = typescript.createModuleResolutionCache( + host.getCurrentDirectory(), + host.getCanonicalFileName.bind(host), + compilerOptions, + packageJsonCache, + ); + host.getModuleResolutionCache = () => resolutionCache; + + // Augment TypeScript Host for file replacements option + if (hostOptions.fileReplacements) { + augmentHostWithReplacements(typescript, host, hostOptions.fileReplacements, resolutionCache); + } + + // Augment TypeScript Host with source file caching if provided + if (sourceFileCache) { + augmentHostWithCaching(host, sourceFileCache); + } + + return host; +} + +const TEMPLATE_EXTENSIONS: ReadonlySet = new Set(['.htm', '.html', '.svg']); +const TYPESCRIPT_EXTENSIONS: ReadonlySet = new Set(['.ts', '.tsx', '.mts', '.cts']); + +function hasTemplateExtension(file: string): boolean { + return TEMPLATE_EXTENSIONS.has(nodePath.extname(file).toLowerCase()); +} + +function hasTypeScriptExtension(file: string): boolean { + return TYPESCRIPT_EXTENSIONS.has(nodePath.extname(file).toLowerCase()); +} diff --git a/packages/angular/build/src/tools/angular/angular-host_spec.ts b/packages/angular/build/src/tools/angular/angular-host_spec.ts new file mode 100644 index 000000000000..ab2b6151aed0 --- /dev/null +++ b/packages/angular/build/src/tools/angular/angular-host_spec.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; +import { type AngularHostOptions, createAngularCompilerHost } from './angular-host'; + +describe('createAngularCompilerHost', () => { + function createHost() { + const transformStylesheet = jasmine + .createSpy('transformStylesheet') + .and.resolveTo('.compiled {}'); + const processWebWorker = jasmine + .createSpy('processWebWorker') + .and.returnValue('worker.js'); + + const host = createAngularCompilerHost( + ts, + {}, + { + transformStylesheet, + processWebWorker, + }, + undefined, + ); + + return { host, transformStylesheet }; + } + + describe('readResource', () => { + it('should not call readFile for .css and .scss stylesheet files', async () => { + const { host } = createHost(); + const readFileSpy = spyOn(host, 'readFile').and.returnValue('.btn { color: red; }'); + + expect(await host.readResource?.('/app/src/app.component.css')).toBe(''); + expect(await host.readResource?.('/app/src/app.component.scss')).toBe(''); + expect(readFileSpy).not.toHaveBeenCalled(); + }); + + it('should call readFile for .html and .svg template files', async () => { + const { host } = createHost(); + const readFileSpy = spyOn(host, 'readFile').and.callFake( + (fileName) => ``, + ); + + expect(await host.readResource?.('/app/src/app.component.html')).toBe( + '', + ); + expect(await host.readResource?.('/app/src/icon.component.svg')).toBe( + '', + ); + expect(readFileSpy).toHaveBeenCalledTimes(2); + }); + }); + + describe('transformResource', () => { + it('should invoke transformStylesheet when context.resourceFile is set even if data is empty', async () => { + const { host, transformStylesheet } = createHost(); + + const result = await host.transformResource?.('', { + type: 'style', + containingFile: '/app/src/app.component.ts', + resourceFile: '/app/src/app.component.scss', + order: 0, + className: 'AppComponent', + }); + + expect(result).toEqual({ content: '.compiled {}' }); + expect(transformStylesheet).toHaveBeenCalledOnceWith( + '', + '/app/src/app.component.ts', + '/app/src/app.component.scss', + 0, + 'AppComponent', + ); + }); + + it('should short-circuit empty inline styles without calling transformStylesheet', async () => { + const { host, transformStylesheet } = createHost(); + + const result = await host.transformResource?.(' ', { + type: 'style', + containingFile: '/app/src/app.component.ts', + resourceFile: null, + order: 0, + className: 'AppComponent', + }); + + expect(result).toEqual({ content: '' }); + expect(transformStylesheet).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts b/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts new file mode 100644 index 000000000000..3da78cdf0275 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { PartialMessage } from 'esbuild'; +import type { AngularHostOptions } from '../angular-host'; +import type { CompilerOptionOverrides } from './compiler-options'; + +export interface EmitFileResult { + filename: string; + contents: string; + dependencies?: readonly string[]; +} + +export interface FileTransformResult { + contents: string; + watchFiles?: readonly string[]; +} + +export interface AngularCompilationOptions { + allowJs?: boolean; + compilationMode?: 'full' | 'partial' | 'experimental-local'; + declarationMap?: boolean; + isolatedModules?: boolean; + sourceMap?: boolean; + inlineSourceMap?: boolean; + _useTypeScriptTranspilation?: boolean; + [key: string]: unknown; +} + +export interface AngularCompilationResult { + compilerOptions: AngularCompilationOptions; + referencedFiles: readonly string[]; + externalStylesheets?: ReadonlyMap; + templateUpdates?: ReadonlyMap; + componentResourcesDependencies?: ReadonlyMap; + warnings?: readonly PartialMessage[]; +} + +export enum DiagnosticModes { + None = 0, + Option = 1 << 0, + Syntactic = 1 << 1, + Semantic = 1 << 2, + All = Option | Syntactic | Semantic, +} + +export abstract class AngularCompilation { + abstract initialize( + tsconfig: string, + hostOptions: AngularHostOptions, + compilerOptionOverrides?: CompilerOptionOverrides, + buildType?: 'application' | 'library', + ): Promise; + + emitAffectedFiles(): Iterable | Promise> { + return []; + } + + transformFile?(filename: string, content: string): Promise; + + async diagnoseFiles( + modes?: DiagnosticModes, + ): Promise<{ errors?: PartialMessage[]; warnings?: PartialMessage[] }> { + return {}; + } + + update?(files: Set): Promise; + + close?(): Promise; +} diff --git a/packages/angular/build/src/tools/angular/compilation/angular-compilation_spec.ts b/packages/angular/build/src/tools/angular/compilation/angular-compilation_spec.ts new file mode 100644 index 000000000000..e0aad6a77db4 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/angular-compilation_spec.ts @@ -0,0 +1,650 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 'node:path'; +import ts from 'typescript'; +import type { AngularHostOptions } from '../angular-host'; +import { ensurePreDeclarationTransformers } from './aot-compilation'; +import { CompilerOptionOverrides, transformCompilerOptions } from './compiler-options'; +import { TypeScriptCompilation } from './typescript-compilation'; +import { + AngularCompilation, + AngularCompilationResult, + DiagnosticModes, + createAngularCompilation, +} from './index'; + +describe('AngularCompilation', () => { + class CustomTransformCompilation extends AngularCompilation { + override async initialize(): Promise { + return { + compilerOptions: { allowJs: false }, + referencedFiles: ['/src/main.ts'], + }; + } + + override async transformFile(filename: string, content: string) { + if (filename.endsWith('.ts')) { + return { + contents: content + '\n// transformed', + watchFiles: ['/src/dep.ts'], + }; + } + + return null; + } + } + + it('allows implementing on-demand transformFile without collectDiagnostics', async () => { + const compilation = new CustomTransformCompilation(); + const initResult = await compilation.initialize(); + + expect(initResult.referencedFiles).toEqual(['/src/main.ts']); + expect(initResult.compilerOptions.allowJs).toBe(false); + + const transformResult = await compilation.transformFile?.( + '/src/main.ts', + 'console.log("hello");', + ); + expect(transformResult).toEqual({ + contents: 'console.log("hello");\n// transformed', + watchFiles: ['/src/dep.ts'], + }); + + const diagnostics = await compilation.diagnoseFiles(); + expect(diagnostics).toEqual({}); + }); + + describe('TypeScriptCompilation', () => { + class MockTypeScriptCompilation extends TypeScriptCompilation { + async initialize(): Promise { + return { compilerOptions: {}, referencedFiles: [] }; + } + + protected override *collectDiagnostics(modes: DiagnosticModes): Iterable { + if (modes & DiagnosticModes.Option) { + yield { + category: ts.DiagnosticCategory.Error, + code: 1234, + messageText: 'Mock option error', + file: undefined, + start: undefined, + length: undefined, + }; + } + if (modes & DiagnosticModes.Semantic) { + yield { + category: ts.DiagnosticCategory.Warning, + code: 5678, + messageText: 'Mock semantic warning', + file: undefined, + start: undefined, + length: undefined, + }; + } + } + + public getCachedSourceFiles(): Map { + return this.sourceFiles; + } + + public async testLoadConfiguration( + tsconfig: string, + overrides?: CompilerOptionOverrides, + buildType?: 'application' | 'library', + ) { + return this.loadConfiguration(tsconfig, overrides, buildType); + } + } + + it('collects and converts diagnostics categorized by error and warning', async () => { + const compilation = new MockTypeScriptCompilation(); + const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.All); + + expect(diagnostics.errors?.length).toBe(1); + expect(diagnostics.errors?.[0].text).toContain('Mock option error'); + expect(diagnostics.warnings?.length).toBe(1); + expect(diagnostics.warnings?.[0].text).toContain('Mock semantic warning'); + }); + + it('filters diagnostics according to requested DiagnosticModes', async () => { + const compilation = new MockTypeScriptCompilation(); + const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.Option); + + expect(diagnostics.errors?.length).toBe(1); + expect(diagnostics.errors?.[0].text).toContain('Mock option error'); + expect(diagnostics.warnings).toBeUndefined(); + }); + + it('returns empty diagnostics immediately when mode is DiagnosticModes.None', async () => { + const compilation = new MockTypeScriptCompilation(); + const diagnostics = await compilation.diagnoseFiles(DiagnosticModes.None); + + expect(diagnostics).toEqual({}); + }); + + it('evicts files from AST cache on update and invalidateFiles', async () => { + const compilation = new MockTypeScriptCompilation(); + const mockSourceFile = ts.createSourceFile('test.ts', '', ts.ScriptTarget.Latest); + compilation.getCachedSourceFiles().set('/src/test.ts', mockSourceFile); + + expect(compilation.getCachedSourceFiles().has('/src/test.ts')).toBeTrue(); + + await compilation.update?.(new Set(['/src/test.ts'])); + expect(compilation.getCachedSourceFiles().has('/src/test.ts')).toBeFalse(); + }); + + it('dynamically loads the @angular/compiler-cli module', async () => { + const compilerCli = await TypeScriptCompilation.loadCompilerCli(); + expect(compilerCli).toBeDefined(); + expect(typeof compilerCli.readConfiguration).toBe('function'); + }); + + it('loads configuration and applies compiler option transformations', async () => { + const compilation = new MockTypeScriptCompilation(); + const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({ + options: { target: ts.ScriptTarget.ES2020 }, + rootNames: ['/src/main.ts'], + errors: [], + }); + spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({ + readConfiguration: mockReadConfig, + } as unknown as typeof import('@angular/compiler-cli')); + + const result = await compilation.testLoadConfiguration('tsconfig.json', { sourcemap: true }); + + expect(mockReadConfig).toHaveBeenCalledWith( + 'tsconfig.json', + jasmine.objectContaining({ + suppressOutputPathCheck: true, + outDir: undefined, + }), + undefined, + jasmine.any(Map), + ); + expect(result.rootNames).toEqual(['/src/main.ts']); + expect(result.fallbackRootNames).toBeUndefined(); + expect(result.compilerOptions.target).toBe(ts.ScriptTarget.ES2022); + expect(result.compilerOptions.inlineSources).toBe(true); + expect(result.warnings.length).toBeGreaterThan(0); + expect(result.tsConfigFiles).toEqual(['tsconfig.json']); + }); + + it('filters rootNames to rootFiles while retaining ambient declaration files and setting fallbackRootNames', async () => { + const compilation = new MockTypeScriptCompilation(); + const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({ + options: { target: ts.ScriptTarget.ES2022 }, + rootNames: [ + '/src/app/included.spec.ts', + '/src/app/excluded.spec.ts', + '/src/app/app-module.ts', + '/src/env.d.ts', + '/src/types.d.mts', + '/src/legacy.d.cts', + ], + errors: [], + }); + spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({ + readConfiguration: mockReadConfig, + } as unknown as typeof import('@angular/compiler-cli')); + + const result = await compilation.testLoadConfiguration('tsconfig.spec.json', { + rootFiles: ['/src/app/included.spec.ts'], + }); + + expect(result.rootNames).toEqual([ + '/src/app/included.spec.ts', + '/src/env.d.ts', + '/src/types.d.mts', + '/src/legacy.d.cts', + ]); + expect(result.fallbackRootNames).toEqual([ + '/src/app/included.spec.ts', + '/src/app/excluded.spec.ts', + '/src/app/app-module.ts', + '/src/env.d.ts', + '/src/types.d.mts', + '/src/legacy.d.cts', + ]); + }); + + it('omits fallbackRootNames when buildType is "library" or when rootFiles covers all tsconfig files', async () => { + const compilation = new MockTypeScriptCompilation(); + const mockReadConfig = jasmine.createSpy('readConfiguration').and.returnValue({ + options: { target: ts.ScriptTarget.ES2022 }, + rootNames: ['/src/public-api.ts', '/src/internal.ts', '/src/env.d.ts'], + errors: [], + }); + spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({ + readConfiguration: mockReadConfig, + } as unknown as typeof import('@angular/compiler-cli')); + + const libraryResult = await compilation.testLoadConfiguration( + 'tsconfig.lib.json', + { rootFiles: ['/src/public-api.ts'] }, + 'library', + ); + expect(libraryResult.rootNames).toEqual(['/src/public-api.ts', '/src/env.d.ts']); + expect(libraryResult.fallbackRootNames).toBeUndefined(); + + const fullSetResult = await compilation.testLoadConfiguration( + 'tsconfig.app.json', + { rootFiles: ['/src/public-api.ts', '/src/internal.ts'] }, + 'application', + ); + expect(fullSetResult.rootNames).toEqual([ + '/src/public-api.ts', + '/src/internal.ts', + '/src/env.d.ts', + ]); + expect(fullSetResult.fallbackRootNames).toBeUndefined(); + }); + + it('passes extendedConfigCache to readConfiguration and invalidates entries on config change', async () => { + const compilation = new MockTypeScriptCompilation(); + let passedCache: Map | undefined; + const mockReadConfig = jasmine + .createSpy('readConfiguration') + .and.callFake((_project, _options, _host, extendedConfigCache) => { + passedCache = extendedConfigCache; + extendedConfigCache?.set( + '/path/to/tsconfig.base.json', + {} as ts.ExtendedConfigCacheEntry, + ); + + return { + options: { target: ts.ScriptTarget.ES2020 }, + rootNames: ['/src/main.ts'], + errors: [], + }; + }); + spyOn(TypeScriptCompilation, 'loadCompilerCli').and.resolveTo({ + readConfiguration: mockReadConfig, + } as unknown as typeof import('@angular/compiler-cli')); + + const result1 = await compilation.testLoadConfiguration('tsconfig.json'); + expect(mockReadConfig).toHaveBeenCalledTimes(1); + expect(passedCache).toBeDefined(); + expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeTrue(); + expect(result1.tsConfigFiles).toEqual(['tsconfig.json', '/path/to/tsconfig.base.json']); + + // Invalidation of non-config file should keep extended config cache intact + await compilation.update?.(new Set(['/src/main.ts'])); + expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeTrue(); + + // Invalidation of extended tsconfig file should remove it from cache + await compilation.update?.(new Set(['/path/to/tsconfig.base.json'])); + expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeFalse(); + + // Invalidation with different casing should also remove it from cache + passedCache?.set('/path/to/tsconfig.base.json', {} as ts.ExtendedConfigCacheEntry); + await compilation.update?.(new Set(['/PATH/TO/TSCONFIG.BASE.JSON'])); + expect(passedCache?.has('/path/to/tsconfig.base.json')).toBeFalse(); + + // Subsequent configuration load re-uses the same cache instance + await compilation.testLoadConfiguration('tsconfig.json'); + expect(mockReadConfig).toHaveBeenCalledTimes(2); + expect(mockReadConfig.calls.argsFor(1)[3]).toBe(passedCache); + }); + }); + + describe('createAngularCompilation', () => { + it('creates JitCompilation when mode is "jit"', async () => { + const compilation = await createAngularCompilation('jit', true, false); + expect(compilation.constructor.name).toBe('JitCompilation'); + }); + + it('creates AotCompilation when mode is "aot"', async () => { + const compilation = await createAngularCompilation('aot', true, false); + expect(compilation.constructor.name).toBe('AotCompilation'); + }); + + it('creates JitCompilation when mode is boolean true (legacy)', async () => { + const compilation = await createAngularCompilation(true, true, false); + expect(compilation.constructor.name).toBe('JitCompilation'); + }); + + it('creates AotCompilation when mode is boolean false (legacy)', async () => { + const compilation = await createAngularCompilation(false, true, false); + expect(compilation.constructor.name).toBe('AotCompilation'); + }); + + it('throws when mode is "transform"', async () => { + await expectAsync(createAngularCompilation('transform', true, false)).toBeRejectedWithError( + 'Transform compilation mode is not supported.', + ); + }); + }); + + describe('transformCompilerOptions', () => { + it('does not mutate the input compiler options object', () => { + const originalOptions: ts.CompilerOptions = { + target: ts.ScriptTarget.ES2020, + module: ts.ModuleKind.CommonJS, + }; + const originalCopy = { ...originalOptions }; + + transformCompilerOptions(ts, originalOptions); + + expect(originalOptions).toEqual(originalCopy); + }); + + it('sets target to ES2022 and useDefineForClassFields to false when target is undefined', () => { + const { compilerOptions, warnings } = transformCompilerOptions( + ts, + { module: ts.ModuleKind.ES2022 }, + undefined, + 'tsconfig.json', + ); + + expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022); + expect(compilerOptions.useDefineForClassFields).toBe(false); + expect(warnings.length).toBe(1); + expect(warnings[0].text).toContain( + "TypeScript compiler options 'target' and 'useDefineForClassFields'", + ); + expect(warnings[0].location?.file).toBe('tsconfig.json'); + }); + + it('preserves existing useDefineForClassFields if target < ES2022', () => { + const { compilerOptions, warnings } = transformCompilerOptions( + ts, + { + target: ts.ScriptTarget.ES2020, + useDefineForClassFields: true, + module: ts.ModuleKind.ES2022, + }, + undefined, + 'tsconfig.json', + ); + + expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022); + expect(compilerOptions.useDefineForClassFields).toBe(true); + expect(warnings.length).toBe(1); + }); + + it('sets compilationMode to full and warns when compilationMode is partial', () => { + const { compilerOptions, warnings } = transformCompilerOptions(ts, { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ES2022, + compilationMode: 'partial', + }); + + expect(compilerOptions.compilationMode).toBe('full'); + expect(warnings.length).toBe(1); + expect(warnings[0].text).toContain('Angular partial compilation mode is not supported'); + }); + + it('configures incremental and tsBuildInfoFile when cachePath is provided', () => { + const { compilerOptions } = transformCompilerOptions( + ts, + { target: ts.ScriptTarget.ES2022 }, + { cachePath: '/tmp/cache' }, + ); + + expect(compilerOptions.incremental).toBe(true); + expect(compilerOptions.tsBuildInfoFile).toContain('.tsbuildinfo'); + }); + + it('sets incremental to false when cachePath is not provided or incremental is false', () => { + const { compilerOptions: opt1 } = transformCompilerOptions( + ts, + { target: ts.ScriptTarget.ES2022 }, + undefined, + ); + expect(opt1.incremental).toBe(false); + + const { compilerOptions: opt2 } = transformCompilerOptions( + ts, + { target: ts.ScriptTarget.ES2022, incremental: false }, + { cachePath: '/tmp/cache' }, + ); + expect(opt2.incremental).toBe(false); + }); + + it('sets module to ES2022 and warns when module < ES2015', () => { + const { compilerOptions, warnings } = transformCompilerOptions(ts, { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.CommonJS, + }); + + expect(compilerOptions.module).toBe(ts.ModuleKind.ES2022); + expect(warnings.length).toBe(1); + expect(warnings[0].text).toContain( + "TypeScript compiler options 'module' values 'CommonJS', 'UMD'", + ); + }); + + it('warns when isolatedModules is enabled with emitDecoratorMetadata', () => { + const { warnings } = transformCompilerOptions(ts, { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ES2022, + isolatedModules: true, + emitDecoratorMetadata: true, + }); + + expect(warnings.length).toBe(1); + expect(warnings[0].text).toContain( + "TypeScript compiler option 'isolatedModules' may prevent", + ); + }); + + it('synchronizes customConditions when moduleResolution is Bundler or module is Preserve', () => { + const { compilerOptions: bundlerOptions } = transformCompilerOptions( + ts, + { target: ts.ScriptTarget.ES2022, moduleResolution: ts.ModuleResolutionKind.Bundler }, + { customConditions: ['development'] }, + ); + expect(bundlerOptions.customConditions).toEqual(['development']); + + const { compilerOptions: preserveOptions } = transformCompilerOptions( + ts, + { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.Preserve }, + { customConditions: ['development'] }, + ); + expect(preserveOptions.customConditions).toEqual(['development']); + }); + + it('applies override options correctly', () => { + const { compilerOptions } = transformCompilerOptions( + ts, + { + target: ts.ScriptTarget.ES2022, + isolatedModules: true, + basePath: '/workspace/projects/app', + }, + { + sourcemap: true, + preserveSymlinks: true, + externalRuntimeStyles: true, + enableHmr: true, + instrumentForCoverage: true, + includeTestMetadata: true, + basePath: '/workspace', + }, + ); + + expect(compilerOptions.basePath).toBe('/workspace'); + expect(compilerOptions.inlineSources).toBe(true); + expect(compilerOptions.inlineSourceMap).toBe(true); + expect(compilerOptions.preserveSymlinks).toBe(true); + expect(compilerOptions.externalRuntimeStyles).toBe(true); + expect(compilerOptions['_enableHmr']).toBe(true); + expect(compilerOptions['_useTypeScriptTranspilation']).toBe(true); + expect(compilerOptions.supportTestBed).toBe(true); + expect(compilerOptions.supportJitMode).toBe(true); + expect(compilerOptions.noEmit).toBe(false); + expect(compilerOptions.noEmitOnError).toBe(false); + expect(compilerOptions.emitDeclarationOnly).toBe(false); + expect(compilerOptions.composite).toBe(false); + }); + + it('enforces library compiler options and skips app-only target warning', () => { + const { compilerOptions, warnings } = transformCompilerOptions( + ts, + { + target: ts.ScriptTarget.ES2020, + noEmit: true, + emitDeclarationOnly: true, + isolatedModules: true, + }, + { + cachePath: '/tmp/cache', + }, + 'tsconfig.lib.json', + 'library', + ); + + expect(compilerOptions.target).toBe(ts.ScriptTarget.ES2022); + expect(compilerOptions.module).toBe(ts.ModuleKind.Preserve); + expect(compilerOptions.useDefineForClassFields).toBeUndefined(); + expect(compilerOptions.noEmit).toBe(false); + expect(compilerOptions.emitDeclarationOnly).toBe(false); + expect(compilerOptions.incremental).toBe(true); + expect(compilerOptions.tsBuildInfoFile).toBe(path.join('/tmp/cache', '.tsbuildinfo')); + expect(warnings).toEqual([]); + }); + }); + + describe('ensurePreDeclarationTransformers', () => { + function createTestProgram( + fileName: string, + content: string, + ): { + program: ts.Program; + sourceFile: ts.SourceFile; + } { + const options: ts.CompilerOptions = { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ES2022, + declaration: true, + noLib: true, + }; + const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES2022, true); + const host = ts.createCompilerHost(options); + host.getSourceFile = (name) => (name === fileName ? sourceFile : undefined); + host.fileExists = (name) => name === fileName; + host.readFile = (name) => (name === fileName ? content : undefined); + host.writeFile = () => {}; + + const program = ts.createProgram([fileName], options, host); + + return { program, sourceFile }; + } + + it('transforms each SourceFile only once when emitting .d.ts followed by .js and reuses the cached SourceFile', () => { + const { program, sourceFile } = createTestProgram('/index.ts', 'export const value = 1;'); + + let preDeclStatePopulated = false; + const beforeSpy1 = jasmine + .createSpy('beforeTransformer1') + .and.callFake((sf: ts.SourceFile) => { + preDeclStatePopulated = true; + const addedStmt = ts.factory.createVariableStatement( + [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], + ts.factory.createVariableDeclarationList( + [ + ts.factory.createVariableDeclaration( + 'fromBefore1', + undefined, + undefined, + ts.factory.createNumericLiteral(2), + ), + ], + ts.NodeFlags.Const, + ), + ); + + return ts.factory.updateSourceFile(sf, [...sf.statements, addedStmt]); + }); + + const beforeSpy2 = jasmine + .createSpy('beforeTransformer2') + .and.callFake((sf: ts.SourceFile) => { + const addedStmt = ts.factory.createVariableStatement( + [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], + ts.factory.createVariableDeclarationList( + [ + ts.factory.createVariableDeclaration( + 'fromBefore2', + undefined, + undefined, + ts.factory.createNumericLiteral(3), + ), + ], + ts.NodeFlags.Const, + ), + ); + + return ts.factory.updateSourceFile(sf, [...sf.statements, addedStmt]); + }); + + let sawPopulatedPreDeclState = false; + const afterDeclSpy = jasmine + .createSpy('afterDeclarationsTransformer') + .and.callFake((sf: ts.SourceFile) => { + sawPopulatedPreDeclState = preDeclStatePopulated; + + return sf; + }); + + const transformers: ts.CustomTransformers = { + before: [() => beforeSpy1, () => beforeSpy2], + afterDeclarations: [() => afterDeclSpy], + }; + + ensurePreDeclarationTransformers(transformers); + + const emittedFiles = new Map(); + const writeFile: ts.WriteFileCallback = (fileName, text) => { + emittedFiles.set(fileName, text); + }; + + // Emit .d.ts first (emitOnlyDtsFiles = true) + program.emit(sourceFile, writeFile, undefined, true, transformers); + + expect(sawPopulatedPreDeclState).toBeTrue(); + expect(beforeSpy1).toHaveBeenCalledTimes(1); + expect(beforeSpy2).toHaveBeenCalledTimes(1); + expect(afterDeclSpy).toHaveBeenCalledTimes(1); + expect(emittedFiles.has('/index.d.ts')).toBeTrue(); + expect(emittedFiles.has('/index.js')).toBeFalse(); + + // Emit .js second; before transformers must not execute again and cached AST must be emitted + program.emit(sourceFile, writeFile, undefined, 0 as unknown as boolean, transformers); + + expect(beforeSpy1).toHaveBeenCalledTimes(1); + expect(beforeSpy2).toHaveBeenCalledTimes(1); + expect(emittedFiles.get('/index.js')).toContain('export const fromBefore1 = 2;'); + expect(emittedFiles.get('/index.js')).toContain('export const fromBefore2 = 3;'); + }); + + it('transforms each SourceFile only once when emitting .js and .d.ts together', () => { + const { program, sourceFile } = createTestProgram('/index.ts', 'export const value = 1;'); + + const beforeSpy = jasmine + .createSpy('beforeTransformer') + .and.callFake((sf: ts.SourceFile) => sf); + const afterDeclSpy = jasmine + .createSpy('afterDeclarationsTransformer') + .and.callFake((sf: ts.SourceFile) => sf); + + const transformers: ts.CustomTransformers = { + before: [() => beforeSpy], + afterDeclarations: [() => afterDeclSpy], + }; + + ensurePreDeclarationTransformers(transformers); + + program.emit(sourceFile, () => {}, undefined, false, transformers); + + expect(beforeSpy).toHaveBeenCalledTimes(1); + expect(afterDeclSpy).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts b/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts new file mode 100644 index 000000000000..8a3e559c9c69 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts @@ -0,0 +1,1051 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import assert from 'node:assert'; +import { relative } from 'node:path'; +import ts from 'typescript'; +import { useTypeChecking } from '../../../utils/environment-options'; +import { profileAsync, profileSync } from '../../../utils/profiling'; +import { + AngularHostOptions, + createAngularCompilerHost, + ensureSourceFileVersions, +} from '../angular-host'; +import { replaceBootstrap } from '../transformers/jit-bootstrap-transformer'; +import { lazyRoutesTransformer } from '../transformers/lazy-routes-transformer'; +import { createWorkerTransformer } from '../transformers/web-worker-transformer'; +import { + type AngularCompilationResult, + DiagnosticModes, + type EmitFileResult, +} from './angular-compilation'; +import type { CompilerOptionOverrides } from './compiler-options'; +import { collectHmrCandidates } from './hmr-candidates'; +import { TypeScriptCompilation } from './typescript-compilation'; +import { printSourceFileWithMap } from './typescript-printer'; + +/** + * The modified files count limit for performing component HMR analysis. + * Performing content analysis for a large amount of files can result in longer rebuild times + * than a full rebuild would entail. + */ +const HMR_MODIFIED_FILE_LIMIT = 32; + +/** + * Extension for Angular type-checking files. + */ +const TTC_EXTENSION = '.ngtypecheck.ts'; + +/** + * Length of the `.ngtypecheck.ts` extension. + */ +const TTC_EXTENSION_LENGTH = TTC_EXTENSION.length; + +/** + * Internal TypeScript `ts.EmitOnly` enum values used by `Program.emit`. + */ +enum EmitOnly { + Js = 0, + Dts = 1, + BuilderSignature = 2, +} + +/** + * Checks if a file is an Angular type-checking shim file. + */ +function isNgTypeCheckFile(fileName: string): boolean { + return fileName.endsWith(TTC_EXTENSION); +} + +/** + * Returns the original filename for a type-checking shim file. + */ +function getOriginalFilename(fileName: string): string { + return fileName.slice(0, -TTC_EXTENSION_LENGTH) + '.ts'; +} + +class AngularCompilationState { + constructor( + public readonly angularProgram: ng.NgtscProgram, + public readonly compilerHost: ng.CompilerHost, + public typeScriptProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram, + public readonly affectedFiles: ReadonlySet, + public readonly templateDiagnosticsOptimization: ng.OptimizeFor, + public readonly webWorkerTransform: ts.TransformerFactory, + public readonly useTypeScriptTranspilation: boolean, + public readonly diagnosticCache = new WeakMap(), + public readonly declarationDiagnostics = new WeakMap(), + public readonly filesWithoutDtsSignature = new Set(), + public readonly useFallbackRootNames = false, + public readonly emittedDtsSourceFiles = new WeakSet(), + ) {} + + get angularCompiler() { + return this.angularProgram.compiler; + } +} + +export class AotCompilation extends TypeScriptCompilation { + #state?: AngularCompilationState; + + constructor(private readonly browserOnlyBuild: boolean) { + super(); + } + + // eslint-disable-next-line max-lines-per-function + async initialize( + tsconfig: string, + hostOptions: AngularHostOptions, + compilerOptionOverrides?: CompilerOptionOverrides, + buildType: 'application' | 'library' = 'application', + ): Promise { + // Dynamically load the Angular compiler CLI package + const { NgtscProgram, OptimizeFor } = await TypeScriptCompilation.loadCompilerCli(); + + // Load the compiler configuration and transform as needed + const { + compilerOptions, + rootNames, + fallbackRootNames, + errors: configurationDiagnostics, + warnings, + tsConfigFiles, + } = await this.loadConfiguration(tsconfig, compilerOptionOverrides, buildType); + + const useTypeScriptTranspilation = + (compilerOptions['_useTypeScriptTranspilation'] as boolean | undefined) ?? + !compilerOptions.isolatedModules; + + if (compilerOptions.externalRuntimeStyles) { + hostOptions.externalStylesheets ??= new Map(); + } + + // Reuse the package.json cache from the previous compilation + const packageJsonCache = this.#state?.compilerHost + .getModuleResolutionCache?.() + ?.getPackageJsonInfoCache(); + + const useHmr = + compilerOptions['_enableHmr'] && + hostOptions.modifiedFiles && + hostOptions.modifiedFiles.size <= HMR_MODIFIED_FILE_LIMIT; + + let staleSourceFiles; + let clearPackageJsonCache = false; + if (hostOptions.modifiedFiles) { + this.invalidateFiles(hostOptions.modifiedFiles); + + if (this.#state && hostOptions.modifiedFiles.size > 0) { + for (const modifiedFile of hostOptions.modifiedFiles) { + // Clear package.json cache if a node modules file was modified + if (!clearPackageJsonCache && modifiedFile.includes('node_modules')) { + clearPackageJsonCache = true; + packageJsonCache?.clear(); + } + + // Collect stale source files for HMR analysis of inline component resources + if (useHmr) { + const sourceFile = this.#state.typeScriptProgram.getSourceFile(modifiedFile); + if (sourceFile) { + staleSourceFiles ??= new Map(); + staleSourceFiles.set(modifiedFile, sourceFile); + } + } + } + + if (useTypeChecking || useTypeScriptTranspilation) { + populatePreviousDtsSignatures( + this.#state.typeScriptProgram, + hostOptions.modifiedFiles, + this.#state.filesWithoutDtsSignature, + ); + } + } + } + + // Create Angular compiler host + const host = createAngularCompilerHost( + ts, + compilerOptions, + hostOptions, + packageJsonCache, + this.sourceFiles, + ); + + // If a previous watch rebuild already fell back to the full tsconfig root file set, + // start directly with fallbackRootNames to avoid repeating the two-step check. + let useFallbackRootNames = this.#state?.useFallbackRootNames ?? false; + + // Create the Angular specific program that contains the Angular compiler + let angularProgram = profileSync( + 'NG_CREATE_PROGRAM', + () => + new NgtscProgram( + (useFallbackRootNames && fallbackRootNames) || rootNames, + compilerOptions, + host, + this.#state?.angularProgram, + ), + ); + let angularCompiler = angularProgram.compiler; + + await profileAsync('NG_ANALYZE_PROGRAM', () => angularCompiler.analyzeAsync()); + + let angularTypeScriptProgram = angularProgram.getTsProgram(); + + // When rootFiles filtering is active and a non-standalone component without a resolved + // NgModule scope is encountered, its declaring NgModule may not be directly imported by + // the test entry points. Fall back to the full tsconfig root file set if it contains + // additional uncompiled files so the Angular compiler can discover all NgModules and + // resolve component compilation scopes. + if ( + !useFallbackRootNames && + fallbackRootNames?.some((file) => !angularTypeScriptProgram.getSourceFile(file)) && + hasUnscopedComponent(angularCompiler) + ) { + useFallbackRootNames = true; + angularProgram = profileSync( + 'NG_CREATE_PROGRAM_FALLBACK', + () => new NgtscProgram(fallbackRootNames, compilerOptions, host, angularProgram), + ); + angularCompiler = angularProgram.compiler; + + await profileAsync('NG_ANALYZE_PROGRAM_FALLBACK', () => angularCompiler.analyzeAsync()); + angularTypeScriptProgram = angularProgram.getTsProgram(); + } + + ensureSourceFileVersions(angularTypeScriptProgram); + + let oldProgram = this.#state?.typeScriptProgram; + let usingBuildInfo = false; + if (!oldProgram) { + oldProgram = ts.readBuilderProgram(compilerOptions, host); + usingBuildInfo = !!oldProgram; + } + + const typeScriptProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram( + angularTypeScriptProgram, + host, + oldProgram, + configurationDiagnostics, + ); + + const filesWithoutDtsSignature = this.#state?.filesWithoutDtsSignature ?? new Set(); + if (!this.#state && !usingBuildInfo && (useTypeChecking || useTypeScriptTranspilation)) { + for (const sourceFile of typeScriptProgram.getSourceFiles()) { + if ( + !sourceFile.isDeclarationFile && + !angularCompiler.ignoreForDiagnostics.has(sourceFile) + ) { + filesWithoutDtsSignature.add(sourceFile.fileName); + } + } + } + + let templateUpdates; + if (useHmr && hostOptions.modifiedFiles && this.#state) { + const componentNodes = collectHmrCandidates( + hostOptions.modifiedFiles, + angularProgram, + staleSourceFiles, + ); + + for (const node of componentNodes) { + if (!ts.isClassDeclaration(node)) { + continue; + } + const componentFilename = node.getSourceFile().fileName; + let relativePath = relative( + compilerOptions.rootDir ?? host.getCurrentDirectory(), + componentFilename, + ); + if (relativePath.startsWith('..')) { + relativePath = componentFilename; + } + relativePath = relativePath.replaceAll('\\', '/'); + const updateId = encodeURIComponent( + `${host.getCanonicalFileName(relativePath)}@${node.name?.text}`, + ); + const updateText = angularCompiler.emitHmrUpdateModule(node); + // If compiler cannot generate an update for the component, prevent template updates. + if (updateText === null) { + // Build is needed if a template cannot be updated + templateUpdates = undefined; + break; + } + templateUpdates ??= new Map(); + templateUpdates.set(updateId, updateText); + } + } + + // The affected files walk runs a full semantic type-check as a side effect + // (via `getSemanticDiagnosticsOfNextAffectedFile`). Its result is only consumed to + // scope Angular template diagnostics and to force re-emit of TS-affected files in the + // slow TypeScript emit path. When type-checking is disabled, template/semantic + // diagnostics are already suppressed at the consumption layer (see the compiler-plugin + // `diagnoseFiles` mask), and in the isolatedModules fast path emit is per-file, so the + // set is never read. Skip the walk in that case to avoid a discarded semantic pass. + const affectedFiles = + useTypeChecking || useTypeScriptTranspilation + ? profileSync('NG_FIND_AFFECTED', () => + findAffectedFiles( + typeScriptProgram, + angularCompiler, + usingBuildInfo, + this.#state?.typeScriptProgram, + filesWithoutDtsSignature, + ), + ) + : new Set(); + + const componentResourcesDependencies = new Map(); + + // Get all files referenced in the TypeScript/Angular program including component resources + const referencedFiles = [...tsConfigFiles]; + for (const sourceFile of typeScriptProgram.getSourceFiles()) { + if (angularCompiler.ignoreForEmit.has(sourceFile)) { + continue; + } + + referencedFiles.push(sourceFile.fileName); + if (sourceFile.isDeclarationFile) { + continue; + } + + const resourceDependencies = angularCompiler.getResourceDependencies(sourceFile); + componentResourcesDependencies.set(sourceFile.fileName, resourceDependencies); + + if (resourceDependencies.length === 0) { + continue; + } + + referencedFiles.push(...resourceDependencies); + + // Also invalidate Angular diagnostics for a source file if component resources are modified + if (this.#state && hostOptions.modifiedFiles?.size) { + for (const resourceDependency of resourceDependencies) { + if ( + !hostOptions.modifiedFiles.has(resourceDependency) || + /\.(?:css|scss|sass|less)$/i.test(resourceDependency) + ) { + continue; + } + + this.#state.diagnosticCache.delete(sourceFile); + + const oldSourceFile = this.#state.typeScriptProgram.getSourceFile(sourceFile.fileName); + if (oldSourceFile) { + this.#state.diagnosticCache.delete(oldSourceFile); + } + + // Also mark as affected in case changed template affects diagnostics + affectedFiles.add(sourceFile); + break; + } + } + } + + this.#state = new AngularCompilationState( + angularProgram, + host, + typeScriptProgram, + affectedFiles, + affectedFiles.size === 1 ? OptimizeFor.SingleFile : OptimizeFor.WholeProgram, + createWorkerTransformer(hostOptions.processWebWorker.bind(hostOptions)), + useTypeScriptTranspilation, + this.#state?.diagnosticCache, + this.#state?.declarationDiagnostics, + filesWithoutDtsSignature, + useFallbackRootNames, + this.#state?.emittedDtsSourceFiles, + ); + + return { + compilerOptions, + referencedFiles, + externalStylesheets: hostOptions.externalStylesheets, + templateUpdates, + componentResourcesDependencies, + warnings, + }; + } + + protected override *collectDiagnostics(modes: DiagnosticModes): Iterable { + assert(this.#state, 'Angular compilation must be initialized prior to collecting diagnostics.'); + const { + affectedFiles, + angularCompiler, + declarationDiagnostics, + diagnosticCache, + templateDiagnosticsOptimization, + typeScriptProgram, + } = this.#state; + + const syntactic = modes & DiagnosticModes.Syntactic; + const semantic = modes & DiagnosticModes.Semantic; + + try { + // Collect program level diagnostics + if (modes & DiagnosticModes.Option) { + yield* typeScriptProgram.getConfigFileParsingDiagnostics(); + yield* angularCompiler.getOptionDiagnostics(); + yield* typeScriptProgram.getOptionsDiagnostics(); + } + if (syntactic) { + yield* typeScriptProgram.getGlobalDiagnostics(); + } + + // Collect source file specific diagnostics + for (const sourceFile of typeScriptProgram.getSourceFiles()) { + if (angularCompiler.ignoreForDiagnostics.has(sourceFile)) { + continue; + } + + if (syntactic) { + // TypeScript will use cached diagnostics for files that have not been + // changed or affected for this build when using incremental building. + yield* profileSync( + 'NG_DIAGNOSTICS_SYNTACTIC', + () => typeScriptProgram.getSyntacticDiagnostics(sourceFile), + true, + ); + } + + if (!semantic) { + continue; + } + + yield* profileSync( + 'NG_DIAGNOSTICS_SEMANTIC', + () => typeScriptProgram.getSemanticDiagnostics(sourceFile), + true, + ); + + // Declaration files cannot have template or declaration emit diagnostics + if (sourceFile.isDeclarationFile) { + continue; + } + + const fileDeclarationDiagnostics = declarationDiagnostics.get(sourceFile); + if (fileDeclarationDiagnostics) { + yield* fileDeclarationDiagnostics; + } + + // Only request Angular template diagnostics for affected files to avoid + // overhead of template diagnostics for unchanged files. + if (affectedFiles.has(sourceFile)) { + const angularDiagnostics = profileSync( + 'NG_DIAGNOSTICS_TEMPLATE', + () => + angularCompiler.getDiagnosticsForFile(sourceFile, templateDiagnosticsOptimization), + true, + ); + diagnosticCache.set(sourceFile, angularDiagnostics); + yield* angularDiagnostics; + } else { + const angularDiagnostics = diagnosticCache.get(sourceFile); + if (angularDiagnostics) { + yield* angularDiagnostics; + } + } + } + } finally { + // Angular's template typechecker lazily creates `.ngtypecheck.ts` shims in a new `ts.Program` + // during `getDiagnosticsForFile`. Sync the builder program with `angularCompiler.getCurrentProgram()` + // so the next incremental build does not treat all `.ngtypecheck.ts` files as newly added files. + const currentTsProgram = angularCompiler.getCurrentProgram(); + if (currentTsProgram !== typeScriptProgram.getProgram()) { + ensureSourceFileVersions(currentTsProgram, typeScriptProgram); + this.#state.typeScriptProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram( + currentTsProgram, + this.#state.compilerHost, + typeScriptProgram, + ); + + // Temporarily enable `isolatedModules` and `assumeChangesOnlyAffectDirectDependencies` while + // draining the newly created `.ngtypecheck.ts` files. Because each component `.ts` file + // references its `.ngtypecheck.ts` shim via `sourceFile.referencedFiles`, TypeScript's + // `referencedMap` treats the component `.ts` file as depending on its `.ngtypecheck.ts` shim. + // Without both flags (whether `isolatedModules` is enabled or disabled in `tsconfig`), + // TypeScript would walk from `.ngtypecheck.ts` to the component `.ts` file and its transitive + // importers, resetting their `.d.ts` shape signatures and queueing them into + // `affectedFilesPendingEmit` for the next incremental rebuild. + const compilerOptions = currentTsProgram.getCompilerOptions(); + const prevIsolatedModules = compilerOptions.isolatedModules; + const prevAssumeDirect = compilerOptions.assumeChangesOnlyAffectDirectDependencies; + compilerOptions.isolatedModules = true; + compilerOptions.assumeChangesOnlyAffectDirectDependencies = true; + + const baseEmit = currentTsProgram.emit; + currentTsProgram.emit = () => ({ emitSkipped: true, diagnostics: [] }); + try { + while (this.#state.typeScriptProgram.emitNextAffectedFile(() => {})) { + /* empty */ + } + } finally { + currentTsProgram.emit = baseEmit; + compilerOptions.isolatedModules = prevIsolatedModules; + compilerOptions.assumeChangesOnlyAffectDirectDependencies = prevAssumeDirect; + } + } + } + } + + override emitAffectedFiles(): Iterable { + assert(this.#state, 'Angular compilation must be initialized prior to emitting files.'); + const { + angularCompiler, + compilerHost, + declarationDiagnostics, + emittedDtsSourceFiles, + typeScriptProgram, + webWorkerTransform, + useTypeScriptTranspilation, + } = this.#state; + const compilerOptions = typeScriptProgram.getCompilerOptions(); + const emitDeclarations = !!compilerOptions.declaration; + const buildInfoFilename = compilerOptions.tsBuildInfoFile ?? '.tsbuildinfo'; + + const emittedFiles = new Map(); + const emittedSourceFiles = new Set(); + const writeFileCallback: ts.WriteFileCallback = (filename, contents, _a, _b, sourceFiles) => { + if (!sourceFiles?.length && filename.endsWith(buildInfoFilename)) { + // Save builder info contents to specified location + compilerHost.writeFile(filename, contents, false); + + return; + } + + assert(sourceFiles?.length === 1, 'Invalid TypeScript program emit for ' + filename); + const sourceFile = ts.getOriginalNode(sourceFiles[0], ts.isSourceFile); + if (angularCompiler.ignoreForEmit.has(sourceFile)) { + return; + } + + const isMap = filename.endsWith('.map'); + const isDts = !isMap && /\.d\.[cm]?ts$/i.test(filename); + if (!emitDeclarations || (!isMap && !isDts)) { + angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile); + emittedSourceFiles.add(sourceFile); + } else if (isDts) { + emittedDtsSourceFiles.add(sourceFile); + } + + const targetFilename = emitDeclarations ? filename : sourceFile.fileName; + emittedFiles.set(targetFilename, { filename: targetFilename, contents }); + }; + const transformers = angularCompiler.prepareEmit().transformers; + if (!emitDeclarations) { + transformers.before ??= []; + transformers.before.push( + replaceBootstrap(() => typeScriptProgram.getProgram().getTypeChecker()), + webWorkerTransform, + ); + + if (!this.browserOnlyBuild) { + transformers.before.push(lazyRoutesTransformer(compilerOptions, compilerHost)); + } + } else if (transformers.before?.length && transformers.afterDeclarations?.length) { + ensurePreDeclarationTransformers(transformers); + } + + // Emit is handled in write file callback when using TypeScript + if (useTypeScriptTranspilation) { + // TypeScript will loop until there are no more affected files in the program + while (true) { + const affectedEmitResult = typeScriptProgram.emitNextAffectedFile( + writeFileCallback, + undefined, + undefined, + transformers, + ); + if (!affectedEmitResult) { + break; + } + if ('kind' in affectedEmitResult.affected) { + declarationDiagnostics.set( + affectedEmitResult.affected, + affectedEmitResult.result.diagnostics, + ); + } + } + } else if (compilerOptions.tsBuildInfoFile) { + // Manually get the builder state for the persistent cache + // The TypeScript API currently embeds this behavior inside the program emit + // via emitNextAffectedFile but that also applies all internal transforms. + const programWithGetState = typeScriptProgram.getProgram() as ts.Program & { + emitBuildInfo(writeFileCallback?: ts.WriteFileCallback): void; + }; + + assert( + typeof programWithGetState.emitBuildInfo === 'function', + 'TypeScript program emitBuildInfo is missing.', + ); + + programWithGetState.emitBuildInfo(); + } + + // Angular may have files that must be emitted but TypeScript does not consider affected + for (const sourceFile of typeScriptProgram.getSourceFiles()) { + if (emittedSourceFiles.has(sourceFile) || angularCompiler.ignoreForEmit.has(sourceFile)) { + continue; + } + + if (sourceFile.isDeclarationFile) { + continue; + } + + if (angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile)) { + continue; + } + + if (useTypeScriptTranspilation) { + const hasEmittedDts = emittedDtsSourceFiles.has(sourceFile); + const emitOnly = hasEmittedDts ? (EmitOnly.Js as unknown as boolean) : undefined; + const emitResult = typeScriptProgram.emit( + sourceFile, + writeFileCallback, + undefined, + emitOnly, + transformers, + ); + if (!hasEmittedDts) { + declarationDiagnostics.set(sourceFile, emitResult.diagnostics); + } + continue; + } + + // When not using TypeScript transpilation, directly apply only Angular specific transformations + const transformResult = ts.transform( + sourceFile, + [ + ...(transformers.before ?? []), + ...(transformers.after ?? []), + ] as ts.TransformerFactory[], + compilerOptions, + ); + + assert( + transformResult.transformed.length === 1, + 'TypeScript transforms should not produce multiple outputs for ' + sourceFile.fileName, + ); + + let contents: string; + if (sourceFile === transformResult.transformed[0]) { + // Use original content if no changes were made + contents = sourceFile.text; + } else { + // Otherwise, print the transformed source file with map if needed + const printer = ts.createPrinter(compilerOptions, transformResult); + const printResult = printSourceFileWithMap( + transformResult.transformed[0], + printer, + compilerHost, + compilerOptions, + ); + + contents = printResult.code; + + if (printResult.map) { + if (compilerOptions.inlineSourceMap) { + const base64Map = Buffer.from(printResult.map).toString('base64'); + contents += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`; + } else if (compilerOptions.sourceMap) { + const mapFilename = sourceFile.fileName + '.map'; + emittedFiles.set(mapFilename, { filename: mapFilename, contents: printResult.map }); + } + } + } + + angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile); + emittedSourceFiles.add(sourceFile); + emittedFiles.set(sourceFile.fileName, { filename: sourceFile.fileName, contents }); + } + + return emittedFiles.values(); + } +} + +/** + * When TypeScript's `BuilderProgram.emitNextAffectedFile` emits `.d.ts`-only (`emitOnly = Dts`) + * for a transitive importer, TypeScript skips `transformers.before`. However, Angular's + * `declarationTransformFactory` in `afterDeclarations` relies on `ivyTransformFactory` in + * `before` having compiled the file's classes to populate `dtsTransforms`. + * + * This helper ensures `before` transformers have executed on the original `SourceFile` prior to + * `afterDeclarations`, and caches the transformed `SourceFile` so a subsequent `.js` emit for the + * same file does not re-execute `before` transformers. + */ +export function ensurePreDeclarationTransformers(transformers: ts.CustomTransformers): void { + if (!transformers.before?.length || !transformers.afterDeclarations?.length) { + return; + } + + const beforeTransformers = transformers.before as ts.TransformerFactory[]; + const seenSourceFiles = new Set(); + const preTransformedSourceFiles = new Map(); + const runBefore = ( + beforeTransforms: ts.Transformer[], + sourceFile: ts.SourceFile, + originalSourceFile: ts.SourceFile, + ): ts.SourceFile => { + seenSourceFiles.add(originalSourceFile); + let current = sourceFile; + for (const transform of beforeTransforms) { + current = transform(current); + } + + return current; + }; + + transformers.before = [ + (context) => { + let beforeTransforms: ts.Transformer[] | undefined; + + return (sourceFile) => { + const originalSourceFile = ts.getOriginalNode(sourceFile, ts.isSourceFile); + const preTransformed = preTransformedSourceFiles.get(originalSourceFile); + if (preTransformed !== undefined) { + preTransformedSourceFiles.delete(originalSourceFile); + + return preTransformed; + } + + beforeTransforms ??= beforeTransformers.map((factory) => factory(context)); + + return runBefore(beforeTransforms, sourceFile, originalSourceFile); + }; + }, + ]; + transformers.afterDeclarations = [ + (context) => { + let beforeTransforms: ts.Transformer[] | undefined; + + return (fileOrBundle) => { + if (!ts.isBundle(fileOrBundle)) { + const originalSourceFile = ts.getOriginalNode(fileOrBundle, ts.isSourceFile); + if (!seenSourceFiles.has(originalSourceFile)) { + beforeTransforms ??= beforeTransformers.map((factory) => factory(context)); + preTransformedSourceFiles.set( + originalSourceFile, + runBefore(beforeTransforms, originalSourceFile, originalSourceFile), + ); + } + } + + return fileOrBundle; + }; + }, + ...transformers.afterDeclarations, + ]; +} + +function findAffectedFiles( + builder: ts.EmitAndSemanticDiagnosticsBuilderProgram, + { ignoreForDiagnostics, incrementalCompilation }: ng.NgtscProgram['compiler'], + includeTTC: boolean, + oldBuilder: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined, + filesWithoutDtsSignature: Set, +): Set { + const affectedFiles = new Set(); + + // Temporarily disable `isolatedModules` and `verbatimModuleSyntax` while walking affected files. + // In TypeScript, `getIsolatedModules(options)` is true when either `isolatedModules` or + // `verbatimModuleSyntax` is enabled, which causes `getFilesAffectedByUpdatedShapeWhenModuleEmit` + // to short-circuit and return only `[sourceFileWithUpdatedShape]` instead of walking + // `referencedMap` during `getSemanticDiagnosticsOfNextAffectedFile`. + // Disabling both flags forces TypeScript to traverse `referencedMap` when a file's `.d.ts` shape + // signature changes so that dependent files—especially `.ngtypecheck.ts` shims that reference + // directives or pipes used in templates—are visited by the `ignoreSourceFile` callback and have + // their own `.d.ts` shape signatures updated along the dependency chain. + const compilerOptions = builder.getCompilerOptions(); + const prevIsolatedModules = compilerOptions.isolatedModules; + const prevVerbatimModuleSyntax = compilerOptions.verbatimModuleSyntax; + compilerOptions.isolatedModules = false; + compilerOptions.verbatimModuleSyntax = false; + + const program = builder.getProgram(); + const baseEmit = program.emit; + const oldProgram = oldBuilder?.getProgram(); + const hadDtsSignatureComputed = new Set(); + const tsAffectedFiles: ts.SourceFile[] = []; + program.emit = ( + targetSourceFile, + writeFile, + cancellationToken, + emitOnly, + customTransformers, + ...rest + ) => { + if (targetSourceFile) { + if (isNgTypeCheckFile(targetSourceFile.fileName)) { + return { emitSkipped: true, diagnostics: [] }; + } + + if (oldProgram && filesWithoutDtsSignature.has(targetSourceFile.fileName)) { + const oldSourceFile = oldProgram.getSourceFile(targetSourceFile.fileName); + if (oldSourceFile) { + let oldDtsText: string | undefined; + let oldHasDiagnostics = false; + oldProgram.emit( + oldSourceFile, + (_fileName, text, _bom, _onError, _sourceFiles, data) => { + oldDtsText = text; + oldHasDiagnostics = !!(data as { diagnostics?: unknown[] } | undefined)?.diagnostics + ?.length; + }, + cancellationToken, + emitOnly, + customTransformers, + ...(rest as []), + ); + + return baseEmit.call( + program, + targetSourceFile, + (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => { + const newHasDiagnostics = !!(data as { diagnostics?: unknown[] } | undefined) + ?.diagnostics?.length; + if (text !== oldDtsText || oldHasDiagnostics || newHasDiagnostics) { + filesWithoutDtsSignature.delete(targetSourceFile.fileName); + hadDtsSignatureComputed.add(targetSourceFile.fileName); + writeFile?.(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + } + }, + cancellationToken, + emitOnly, + customTransformers, + ...(rest as []), + ); + } + + filesWithoutDtsSignature.delete(targetSourceFile.fileName); + } + + hadDtsSignatureComputed.add(targetSourceFile.fileName); + } + + return baseEmit.call( + program, + targetSourceFile, + writeFile, + cancellationToken, + emitOnly, + customTransformers, + ...(rest as []), + ); + }; + + try { + while ( + builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, (sourceFile) => { + if (ignoreForDiagnostics.has(sourceFile)) { + // If the affected file is a TTC shim, add the shim's original source file. + // This ensures that changes that affect TTC are typechecked even when the changes + // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes. + // For example, changing @Input property types of a directive used in another component's + // template. + // A TTC shim is a file that has been ignored for diagnostics and has a filename ending in `.ngtypecheck.ts`. + if (isNgTypeCheckFile(sourceFile.fileName)) { + // This file name conversion relies on internal compiler logic and should be converted + // to an official method when available. + const originalFilename = getOriginalFilename(sourceFile.fileName); + const originalSourceFile = builder.getSourceFile(originalFilename); + if (originalSourceFile) { + affectedFiles.add(originalSourceFile); + } + } + } else { + affectedFiles.add(sourceFile); + tsAffectedFiles.push(sourceFile); + } + + return true; + }) + ) { + /* empty */ + } + } finally { + program.emit = baseEmit; + compilerOptions.isolatedModules = prevIsolatedModules; + compilerOptions.verbatimModuleSyntax = prevVerbatimModuleSyntax; + } + + // Transitive importers visited by `getSemanticDiagnosticsOfNextAffectedFile` via + // `handleDtsMayChangeOf` do not have a `.d.ts` signature computed via `program.emit` and + // instead have their BuilderProgram signature reset to `sourceFile.version`. Track them so + // `populatePreviousDtsSignatures` restores their `.d.ts` signature if they are modified later. + for (const sourceFile of tsAffectedFiles) { + if (!sourceFile.isDeclarationFile && !hadDtsSignatureComputed.has(sourceFile.fileName)) { + filesWithoutDtsSignature.add(sourceFile.fileName); + } + } + + // Also include files identified by Angular's incremental compilation graph as needing + // re-emission or template re-typechecking (such as selector renames or required input changes + // that only affect Angular metadata without altering standard TypeScript `.d.ts` signatures). + for (const sourceFile of builder.getSourceFiles()) { + if (sourceFile.isDeclarationFile || ignoreForDiagnostics.has(sourceFile)) { + continue; + } + + if ( + !incrementalCompilation.safeToSkipEmit(sourceFile) || + incrementalCompilation.priorTypeCheckingResultsFor(sourceFile) === null + ) { + affectedFiles.add(sourceFile); + } + } + + // Add all files with associated template type checking files. + // Stored TS build info does not have knowledge of the AOT compiler or the typechecking state of the templates. + // To ensure that errors are reported correctly, all AOT component diagnostics need to be analyzed even if build + // info is present. + if (includeTTC) { + for (const sourceFile of builder.getSourceFiles()) { + if (ignoreForDiagnostics.has(sourceFile) && isNgTypeCheckFile(sourceFile.fileName)) { + // This file name conversion relies on internal compiler logic and should be converted + // to an official method when available. + const originalFilename = getOriginalFilename(sourceFile.fileName); + const originalSourceFile = builder.getSourceFile(originalFilename); + if (originalSourceFile) { + affectedFiles.add(originalSourceFile); + } + } + } + } + + return affectedFiles; +} + +/** + * Ensures `.d.ts` shape signatures are computed on the previous `BuilderProgram` for modified + * files before the next `BuilderProgram` is created. + * + * On the initial build (`oldProgram === undefined`), TypeScript initializes each file's shape + * signature to its `.ts` source version hash rather than emitting `.d.ts` declarations for every + * file. When a file is modified on a watch rebuild, TypeScript computes its new `.d.ts` signature + * and compares it against the previous program's stored signature. Emitting the `.d.ts` signature + * on `oldProgram` for the modified file replaces its initial `.ts` version hash with its true + * `.d.ts` signature prior to diffing, avoiding false-positive `.d.ts` cascades across importers. + */ +function populatePreviousDtsSignatures( + oldProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram, + modifiedFiles: ReadonlySet, + filesWithoutDtsSignature: Set, +): void { + const filesToUpdate: ts.SourceFile[] = []; + for (const modifiedFile of modifiedFiles) { + const sf = oldProgram.getSourceFile(modifiedFile); + if (sf && !sf.isDeclarationFile && filesWithoutDtsSignature.delete(sf.fileName)) { + filesToUpdate.push(sf); + } + } + + if (filesToUpdate.length === 0) { + return; + } + + const compilerOptions = oldProgram.getCompilerOptions(); + const prevDeclaration = compilerOptions.declaration; + const prevComposite = compilerOptions.composite; + const prevNoEmit = compilerOptions.noEmit; + const prevNoEmitOnError = compilerOptions.noEmitOnError; + + compilerOptions.declaration = true; + compilerOptions.composite = false; + compilerOptions.noEmit = false; + compilerOptions.noEmitOnError = false; + + const program = oldProgram.getProgram(); + const baseEmit = program.emit as ( + targetSourceFile?: ts.SourceFile, + writeFile?: ts.WriteFileCallback, + cancellationToken?: ts.CancellationToken, + emitOnlyDtsFiles?: boolean | EmitOnly, + customTransformers?: ts.CustomTransformers, + forceDtsEmit?: boolean, + ) => ts.EmitResult; + program.emit = (targetSourceFile, writeFile, cancellationToken) => + baseEmit.call( + program, + targetSourceFile, + writeFile, + cancellationToken, + EmitOnly.BuilderSignature, + undefined, + true, // forceDtsEmit + ); + + try { + for (const sf of filesToUpdate) { + oldProgram.emit(sf, () => {}, undefined, true); + } + } finally { + program.emit = baseEmit; + compilerOptions.declaration = prevDeclaration; + compilerOptions.composite = prevComposite; + compilerOptions.noEmit = prevNoEmit; + compilerOptions.noEmitOnError = prevNoEmitOnError; + } +} + +/** + * Checks whether the analyzed Angular program contains any non-standalone `@Component` + * declarations in user source files that lack an owning `NgModule` scope. + */ +function hasUnscopedComponent(angularCompiler: ng.NgCompiler): boolean { + // `incrementalCompilation.state` is typed as the `IncrementalState` union + // (`AnalyzedIncrementalState | DeltaIncrementalState | FreshIncrementalState`), where only + // `AnalyzedIncrementalState` (populated once `analyzeAsync()` completes) contains + // `priorAnalysis`. Because the `IncrementalStateKind` discriminant enum is not re-exported + // from `@angular/compiler-cli`, narrow the union via `'priorAnalysis' in state`. + const state = angularCompiler.incrementalCompilation.state; + if (!('priorAnalysis' in state)) { + return false; + } + + let templateTypeChecker: ReturnType | undefined; + + for (const [sourceFile, records] of state.priorAnalysis) { + if (records.length === 0 || angularCompiler.ignoreForEmit.has(sourceFile)) { + continue; + } + + for (const { node } of records) { + if (!ts.isClassDeclaration(node)) { + continue; + } + + const meta = angularCompiler.getMeta(node); + if (meta && 'isComponent' in meta && meta.isComponent && !meta.isStandalone) { + if (!templateTypeChecker) { + // `NgtscProgram` initializes `NgCompiler` with `enableTemplateTypeChecker = false`, which + // guards the public `getTemplateTypeChecker()` getter. Temporarily enable the flag after + // `analyzeAsync()` has already constructed `TemplateTypeCheckerImpl` so we can query + // `getOwningNgModule()` without altering `typeCheckingConfig.enableTemplateTypeChecker`. + const compiler = angularCompiler as { enableTemplateTypeChecker: boolean }; + const previous = compiler.enableTemplateTypeChecker; + try { + compiler.enableTemplateTypeChecker = true; + templateTypeChecker = angularCompiler.getTemplateTypeChecker(); + } finally { + compiler.enableTemplateTypeChecker = previous; + } + } + + if (templateTypeChecker.getOwningNgModule(node) === null) { + return true; + } + } + } + } + + return false; +} diff --git a/packages/angular/build/src/tools/angular/compilation/compiler-options.ts b/packages/angular/build/src/tools/angular/compilation/compiler-options.ts new file mode 100644 index 000000000000..87a7c7822fc3 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/compiler-options.ts @@ -0,0 +1,166 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import type { PartialMessage } from 'esbuild'; +import * as path from 'node:path'; +import type ts from 'typescript'; +import { toPosixPath } from '../../../utils/path'; + +export interface CompilerOptionOverrides { + sourcemap?: boolean; + preserveSymlinks?: boolean; + cachePath?: string; + externalRuntimeStyles?: boolean; + enableHmr?: boolean; + instrumentForCoverage?: boolean; + includeTestMetadata?: boolean; + customConditions?: string[]; + rootFiles?: string[]; + declarationMap?: boolean; + compilationMode?: 'full' | 'partial'; + paths?: Record; + basePath?: string; +} + +export function transformCompilerOptions( + typeScript: typeof ts, + baseCompilerOptions: ng.CompilerOptions, + overrides?: CompilerOptionOverrides, + tsconfig?: string, + buildType: 'application' | 'library' = 'application', +): { compilerOptions: ng.CompilerOptions; warnings: PartialMessage[] } { + const compilerOptions = { ...baseCompilerOptions }; + const warnings: PartialMessage[] = []; + const isLibrary = buildType === 'library'; + + if (isLibrary) { + compilerOptions.target = typeScript.ScriptTarget.ES2022; + compilerOptions.module = typeScript.ModuleKind.Preserve; + compilerOptions.importHelpers = true; + compilerOptions.declaration = true; + compilerOptions.declarationMap = !!( + overrides?.declarationMap ?? compilerOptions.declarationMap + ); + compilerOptions.declarationDir = undefined; + } + + if ( + compilerOptions.target === undefined || + compilerOptions.target < typeScript.ScriptTarget.ES2022 + ) { + // If 'useDefineForClassFields' is already defined in the users project leave the value as is. + // Otherwise fallback to false due to https://github.com/microsoft/TypeScript/issues/45995 + // which breaks the deprecated `@Effects` NGRX decorator and potentially other existing code as well. + compilerOptions.target = typeScript.ScriptTarget.ES2022; + compilerOptions.useDefineForClassFields ??= false; + + warnings.push({ + text: + `TypeScript compiler options 'target' and 'useDefineForClassFields' are set to 'ES2022' and ` + + `'false' respectively by the Angular CLI.`, + location: tsconfig ? { file: tsconfig } : null, + notes: [ + { + text: + 'To control ECMA version and features use the Browserslist configuration. ' + + 'For more information, see https://angular.dev/tools/cli/build#configuring-browser-compatibility', + }, + ], + }); + } + + if (!isLibrary && compilerOptions.compilationMode === 'partial') { + warnings.push({ + text: 'Angular partial compilation mode is not supported when building applications.', + location: null, + notes: [{ text: 'Full compilation mode will be used instead.' }], + }); + compilerOptions.compilationMode = 'full'; + } else if (overrides?.compilationMode) { + compilerOptions.compilationMode = overrides.compilationMode; + } else if (isLibrary) { + compilerOptions.compilationMode ??= 'partial'; + } + + // Enable incremental compilation by default if caching is enabled and incremental is not explicitly disabled + if (compilerOptions.incremental !== false && overrides?.cachePath) { + compilerOptions.incremental = true; + // Set the build info file location to the configured cache directory + compilerOptions.tsBuildInfoFile = path.join(overrides.cachePath, '.tsbuildinfo'); + } else { + compilerOptions.incremental = false; + } + + if ( + compilerOptions.module === undefined || + compilerOptions.module < typeScript.ModuleKind.ES2015 + ) { + compilerOptions.module = typeScript.ModuleKind.ES2022; + warnings.push({ + text: `TypeScript compiler options 'module' values 'CommonJS', 'UMD', 'System' and 'AMD' are not supported.`, + location: null, + notes: [{ text: `The 'module' option will be set to 'ES2022' instead.` }], + }); + } + + if (compilerOptions.isolatedModules && compilerOptions.emitDecoratorMetadata) { + warnings.push({ + text: `TypeScript compiler option 'isolatedModules' may prevent the 'emitDecoratorMetadata' option from emitting all metadata.`, + location: null, + notes: [ + { + text: + `The 'emitDecoratorMetadata' option is not required by Angular ` + + 'and can be removed if not explicitly required by the project.', + }, + ], + }); + } + + // Synchronize custom resolve conditions. + // Set if using the supported bundler resolution mode (bundler is the default in new projects) + if ( + compilerOptions.moduleResolution === typeScript.ModuleResolutionKind.Bundler || + compilerOptions.module === typeScript.ModuleKind.Preserve + ) { + compilerOptions.customConditions = overrides?.customConditions; + } + + return { + compilerOptions: { + ...compilerOptions, + basePath: overrides?.basePath ? toPosixPath(overrides.basePath) : compilerOptions.basePath, + noEmit: false, + noEmitOnError: false, + emitDeclarationOnly: false, + composite: false, + inlineSources: !!overrides?.sourcemap, + inlineSourceMap: !isLibrary && !!overrides?.sourcemap, + sourceMap: isLibrary ? !!overrides?.sourcemap : undefined, + mapRoot: undefined, + sourceRoot: undefined, + preserveSymlinks: overrides?.preserveSymlinks, + externalRuntimeStyles: overrides?.externalRuntimeStyles, + _enableHmr: !!overrides?.enableHmr, + // TypeScript transpilation is forced if: + // - Building a library (TypeScript emits both .js and .d.ts in a single pass). + // - isolatedModules is disabled (TS needs full module types to emit JS). + // - Karma code coverage is active (the coverage instrumentation transformer is Babel-based + // and cannot parse raw TypeScript code; Vitest handles coverage instrumentation downstream). + _useTypeScriptTranspilation: + isLibrary || !compilerOptions.isolatedModules || !!overrides?.instrumentForCoverage, + supportTestBed: isLibrary ? undefined : !!overrides?.includeTestMetadata, + supportJitMode: isLibrary ? undefined : !!overrides?.includeTestMetadata, + paths: overrides?.paths + ? { ...baseCompilerOptions.paths, ...overrides.paths } + : baseCompilerOptions.paths, + }, + warnings, + }; +} diff --git a/packages/angular/build/src/tools/angular/compilation/diagnostics.ts b/packages/angular/build/src/tools/angular/compilation/diagnostics.ts new file mode 100644 index 000000000000..41563b90ebbd --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/diagnostics.ts @@ -0,0 +1,101 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { PartialMessage, PartialNote } from 'esbuild'; +import { platform } from 'node:os'; +import type ts from 'typescript'; + +/** + * Converts TypeScript Diagnostic related information into an esbuild compatible note object. + * Related information is a subset of a full TypeScript Diagnostic and also used for diagnostic + * notes associated with the main Diagnostic. + * @param info The TypeScript diagnostic relative information to convert. + * @returns An esbuild diagnostic message as a PartialMessage object + */ +function convertTypeScriptDiagnosticInfo( + typescript: typeof ts, + info: ts.DiagnosticRelatedInformation, + textPrefix?: string, +): PartialNote { + const newLine = platform() === 'win32' ? '\r\n' : '\n'; + let text = typescript.flattenDiagnosticMessageText(info.messageText, newLine); + if (textPrefix) { + text = textPrefix + text; + } + + const note: PartialNote = { text }; + + if (info.file) { + note.location = { + file: info.file.fileName, + length: info.length, + }; + + // Calculate the line/column location and extract the full line text that has the diagnostic + if (info.start !== undefined) { + const { line, character } = typescript.getLineAndCharacterOfPosition(info.file, info.start); + note.location.line = line + 1; + note.location.column = character; + + // The start position for the slice is the first character of the error line + const lineStartPosition = typescript.getPositionOfLineAndCharacter(info.file, line, 0); + + // The end position for the slice is the first character of the next line or the length of + // the entire file if the line is the last line of the file (getPositionOfLineAndCharacter + // will error if a nonexistent line is passed). + const { line: lastLineOfFile } = typescript.getLineAndCharacterOfPosition( + info.file, + Math.max(0, info.file.text.length - 1), + ); + const lineEndPosition = + line < lastLineOfFile + ? typescript.getPositionOfLineAndCharacter(info.file, line + 1, 0) + : info.file.text.length; + + note.location.lineText = info.file.text.slice(lineStartPosition, lineEndPosition).trimEnd(); + } + } + + return note; +} + +/** + * Converts a TypeScript Diagnostic message into an esbuild compatible message object. + * @param diagnostic The TypeScript diagnostic to convert. + * @returns An esbuild diagnostic message as a PartialMessage object + */ +export function convertTypeScriptDiagnostic( + typescript: typeof ts, + diagnostic: ts.Diagnostic, +): PartialMessage { + let codePrefix = 'TS'; + let code = `${diagnostic.code}`; + + // Custom ngtsc diagnostics are prefixed with -99 which isn't a valid TypeScript diagnostic code. + // Strip it and mark the diagnostic as coming from Angular. Note that we can't rely on + // `diagnostic.source`, because it isn't always produced. This is identical to: + // https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/util.ts + if (code.startsWith('-99')) { + codePrefix = 'NG'; + code = code.slice(3); + } + + const message: PartialMessage = convertTypeScriptDiagnosticInfo( + typescript, + diagnostic, + `${codePrefix}${code}: `, + ); + + if (diagnostic.relatedInformation?.length) { + message.notes = diagnostic.relatedInformation.map((info) => + convertTypeScriptDiagnosticInfo(typescript, info), + ); + } + + return message; +} diff --git a/packages/angular/build/src/tools/angular/compilation/diagnostics_spec.ts b/packages/angular/build/src/tools/angular/compilation/diagnostics_spec.ts new file mode 100644 index 000000000000..8ea79c20ba43 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/diagnostics_spec.ts @@ -0,0 +1,111 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; +import { convertTypeScriptDiagnostic } from './diagnostics'; + +describe('convertTypeScriptDiagnostic', () => { + it('populates line, column, and lineText when diagnostic or relatedInformation starts at offset 0', () => { + const sourceFile = ts.createSourceFile( + '/src/app/app.component.ts', + 'const invalid: number = "string";\nconst secondLine = 2;\n', + ts.ScriptTarget.Latest, + ); + const templateFile = ts.createSourceFile( + '/src/app/app.component.html', + '\n
Valid
\n', + ts.ScriptTarget.Latest, + ); + + const diagnostic: ts.Diagnostic = { + category: ts.DiagnosticCategory.Error, + code: -998001, + file: templateFile, + start: 0, + length: 17, + messageText: "'unknown-element' is not a known element.", + relatedInformation: [ + { + category: ts.DiagnosticCategory.Message, + code: 0, + file: sourceFile, + start: 0, + length: 5, + messageText: 'Error occurs in the template of component AppComponent.', + }, + ], + }; + + const result = convertTypeScriptDiagnostic(ts, diagnostic); + + expect(result.text).toBe("NG8001: 'unknown-element' is not a known element."); + expect(result.location).toEqual({ + file: '/src/app/app.component.html', + length: 17, + line: 1, + column: 0, + lineText: '', + }); + + expect(result.notes).toEqual([ + { + text: 'Error occurs in the template of component AppComponent.', + location: { + file: '/src/app/app.component.ts', + length: 5, + line: 1, + column: 0, + lineText: 'const invalid: number = "string";', + }, + }, + ]); + }); + + it('does not throw a TypeScript Debug Failure when diagnostic is reported on an empty file', () => { + const emptyFile = ts.createSourceFile('/src/empty.ts', '', ts.ScriptTarget.Latest); + + const diagnosticAtZero: ts.Diagnostic = { + category: ts.DiagnosticCategory.Error, + code: 2306, + file: emptyFile, + start: 0, + length: 0, + messageText: "File '/src/empty.ts' is not a module.", + }; + + expect(() => convertTypeScriptDiagnostic(ts, diagnosticAtZero)).not.toThrow(); + expect(convertTypeScriptDiagnostic(ts, diagnosticAtZero)).toEqual({ + text: "TS2306: File '/src/empty.ts' is not a module.", + location: { + file: '/src/empty.ts', + length: 0, + line: 1, + column: 0, + lineText: '', + }, + }); + + const diagnosticPastEnd: ts.Diagnostic = { + category: ts.DiagnosticCategory.Error, + code: 1005, + file: emptyFile, + start: 1, + length: 0, + messageText: 'Unexpected end of text.', + }; + + expect(() => convertTypeScriptDiagnostic(ts, diagnosticPastEnd)).not.toThrow(); + expect(convertTypeScriptDiagnostic(ts, diagnosticPastEnd).location).toEqual({ + file: '/src/empty.ts', + length: 0, + line: 1, + column: 1, + lineText: '', + }); + }); +}); diff --git a/packages/angular/build/src/tools/angular/compilation/factory.ts b/packages/angular/build/src/tools/angular/compilation/factory.ts new file mode 100644 index 000000000000..3944979f1ee5 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/factory.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { useParallelTs } from '../../../utils/environment-options'; +import type { AngularCompilation } from './angular-compilation'; + +export type AngularCompilationMode = 'aot' | 'jit' | 'transform'; + +/** + * Creates an Angular compilation object that can be used to perform Angular application + * compilation either for AOT, JIT, or on-demand transform mode. By default a parallel compilation is created + * that uses a Node.js worker thread. + * @param mode True or 'jit' for JIT mode; False or 'aot' for AOT compilation; 'transform' for on-demand transformation. + * @param browserOnlyBuild True, for browser only builds; False, for browser and server builds. + * @param parallel True to execute compilation in a worker thread. + * @returns An instance of an Angular compilation object. + */ +export async function createAngularCompilation( + mode: boolean | AngularCompilationMode, + browserOnlyBuild: boolean, + parallel: boolean = useParallelTs, +): Promise { + if (mode === 'transform') { + throw new Error('Transform compilation mode is not supported.'); + } + + const isJit = mode === true || mode === 'jit'; + + if (parallel) { + const { ParallelCompilation } = await import('./parallel-compilation'); + + return new ParallelCompilation(isJit, browserOnlyBuild); + } + + if (isJit) { + const { JitCompilation } = await import('./jit-compilation'); + + return new JitCompilation(browserOnlyBuild); + } else { + const { AotCompilation } = await import('./aot-compilation'); + + return new AotCompilation(browserOnlyBuild); + } +} diff --git a/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts b/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts new file mode 100644 index 000000000000..cba0b18e7414 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts @@ -0,0 +1,347 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import assert from 'node:assert'; +import ts from 'typescript'; + +/** + * Analyzes one or more modified files for changes to determine if any + * class declarations for Angular components are candidates for hot + * module replacement (HMR). If any source files are also modified but + * are not candidates then all candidates become invalid. This invalidation + * ensures that a full rebuild occurs and the running application stays + * synchronized with the code. + * @param modifiedFiles A set of modified files to analyze. + * @param param1 An Angular compiler instance + * @param staleSourceFiles A map of paths to previous source file instances. + * @returns A set of HMR candidate component class declarations. + */ +export function collectHmrCandidates( + modifiedFiles: Set, + { compiler }: ng.NgtscProgram, + staleSourceFiles: Map | undefined, +): Set { + const candidates = new Set(); + + for (const file of modifiedFiles) { + // If the file is a template for component(s), add component classes as candidates + const templateFileNodes = compiler.getComponentsWithTemplateFile(file); + if (templateFileNodes.size) { + templateFileNodes.forEach((node) => candidates.add(node as ts.ClassDeclaration)); + continue; + } + + // If the file is a style for component(s), add component classes as candidates + const styleFileNodes = compiler.getComponentsWithStyleFile(file); + if (styleFileNodes.size) { + styleFileNodes.forEach((node) => candidates.add(node as ts.ClassDeclaration)); + continue; + } + + const staleSource = staleSourceFiles?.get(file); + if (staleSource === undefined) { + // Unknown file requires a rebuild so clear out the candidates and stop collecting + candidates.clear(); + break; + } + + const updatedSource = compiler.getCurrentProgram().getSourceFile(file); + if (updatedSource === undefined) { + // No longer existing program file requires a rebuild so clear out the candidates and stop collecting + candidates.clear(); + break; + } + + // Analyze the stale and updated file for changes + const fileCandidates = analyzeFileUpdates(staleSource, updatedSource, compiler); + if (fileCandidates) { + fileCandidates.forEach((node) => candidates.add(node)); + } else { + // Unsupported HMR changes present + // Only template and style literal changes are allowed. + candidates.clear(); + break; + } + } + + return candidates; +} + +/** + * Analyzes the updates of a source file for potential HMR component class candidates. + * A source file can contain candidates if only the Angular component metadata of a class + * has been changed and the metadata changes are only of supported fields. + * @param stale The stale (previous) source file instance. + * @param updated The updated source file instance. + * @param compiler An Angular compiler instance. + * @returns An array of candidate class declarations; or `null` if unsupported changes are present. + */ +function analyzeFileUpdates( + stale: ts.SourceFile, + updated: ts.SourceFile, + compiler: ng.NgtscProgram['compiler'], +): ts.ClassDeclaration[] | null { + if (stale.statements.length !== updated.statements.length) { + return null; + } + + const candidates: ts.ClassDeclaration[] = []; + + for (let i = 0; i < updated.statements.length; ++i) { + const updatedNode = updated.statements[i]; + const staleNode = stale.statements[i]; + + if (ts.isClassDeclaration(updatedNode)) { + if (!ts.isClassDeclaration(staleNode)) { + return null; + } + + // Check class declaration differences (name/heritage/modifiers) + if (updatedNode.name?.text !== staleNode.name?.text) { + return null; + } + if (!equalRangeText(updatedNode.heritageClauses, updated, staleNode.heritageClauses, stale)) { + return null; + } + const updatedModifiers = ts.getModifiers(updatedNode); + const staleModifiers = ts.getModifiers(staleNode); + if ( + updatedModifiers?.length !== staleModifiers?.length || + !updatedModifiers?.every((updatedModifier) => + staleModifiers?.some((staleModifier) => updatedModifier.kind === staleModifier.kind), + ) + ) { + return null; + } + + // Check for component class nodes + const meta = compiler.getMeta(updatedNode); + if (meta?.decorator && (meta as { isComponent?: boolean }).isComponent === true) { + const updatedDecorators = ts.getDecorators(updatedNode); + const staleDecorators = ts.getDecorators(staleNode); + if (!staleDecorators || staleDecorators.length !== updatedDecorators?.length) { + return null; + } + + // TODO: Check other decorators instead of assuming all multi-decorator components are unsupported + if (staleDecorators.length > 1) { + return null; + } + + // Find index of component metadata decorator + const metaDecoratorIndex = updatedDecorators?.indexOf(meta.decorator); + assert( + metaDecoratorIndex !== undefined, + 'Component metadata decorator should always be present on component class.', + ); + const updatedDecoratorExpression = meta.decorator.expression; + assert( + ts.isCallExpression(updatedDecoratorExpression) && + updatedDecoratorExpression.arguments.length === 1, + 'Component metadata decorator should contain a call expression with a single argument.', + ); + + // Check the matching stale index for the component decorator + const staleDecoratorExpression = staleDecorators[metaDecoratorIndex]?.expression; + if ( + !staleDecoratorExpression || + !ts.isCallExpression(staleDecoratorExpression) || + staleDecoratorExpression.arguments.length !== 1 + ) { + return null; + } + + // Check decorator name/expression + // NOTE: This would typically be `Component` but can also be a property expression or some other alias. + // To avoid complex checks, this ensures the textual representation does not change. This has a low chance + // of a false positive if the expression is changed to still reference the `Component` type but has different + // text. However, it is rare for `Component` to not be used directly and additionally unlikely that it would + // be changed between edits. A false positive would also only lead to a difference of a full page reload versus + // an HMR update. + if ( + !equalRangeText( + updatedDecoratorExpression.expression, + updated, + staleDecoratorExpression.expression, + stale, + ) + ) { + return null; + } + + // Compare component meta decorator object literals + const analysis = analyzeMetaUpdates( + staleDecoratorExpression, + stale, + updatedDecoratorExpression, + updated, + ); + if (analysis === MetaUpdateAnalysis.Unsupported) { + return null; + } + + // Compare text of the member nodes to determine if any changes have occurred + if (!equalRangeText(updatedNode.members, updated, staleNode.members, stale)) { + // A change to a member outside a component's metadata is unsupported + return null; + } + + // If all previous class checks passed, this class is supported for HMR updates + if (analysis === MetaUpdateAnalysis.Supported) { + candidates.push(updatedNode); + } + continue; + } + } + + // Compare text of the statement nodes to determine if any changes have occurred + // TODO: Consider expanding this to check semantic updates for each node kind + if (!equalRangeText(updatedNode, updated, staleNode, stale)) { + // A change to a statement outside a component's metadata is unsupported + return null; + } + } + + return candidates; +} + +/** + * The set of Angular component metadata fields that are supported by HMR updates. + */ +const SUPPORTED_FIELD_NAMES = new Set([ + 'template', + 'templateUrl', + 'styles', + 'styleUrl', + 'stylesUrl', +]); + +enum MetaUpdateAnalysis { + Supported, + Unsupported, + None, +} + +/** + * Analyzes the metadata fields of a decorator call expression for unsupported HMR updates. + * Only updates to supported fields can be present for HMR to be viable. + * @param staleCall A call expression instance. + * @param staleSource The source file instance containing the stale call instance. + * @param updatedCall A call expression instance. + * @param updatedSource The source file instance containing the updated call instance. + * @returns A MetaUpdateAnalysis enum value. + */ +function analyzeMetaUpdates( + staleCall: ts.CallExpression, + staleSource: ts.SourceFile, + updatedCall: ts.CallExpression, + updatedSource: ts.SourceFile, +): MetaUpdateAnalysis { + const staleObject = staleCall.arguments[0]; + const updatedObject = updatedCall.arguments[0]; + let hasSupportedUpdate = false; + + if (!ts.isObjectLiteralExpression(staleObject) || !ts.isObjectLiteralExpression(updatedObject)) { + return MetaUpdateAnalysis.Unsupported; + } + + const supportedFields = new Map(); + const unsupportedFields: ts.Node[] = []; + + for (const property of staleObject.properties) { + if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) { + // Unsupported object literal property + return MetaUpdateAnalysis.Unsupported; + } + + const name = property.name.text; + if (SUPPORTED_FIELD_NAMES.has(name)) { + supportedFields.set(name, property.initializer); + continue; + } + + unsupportedFields.push(property.initializer); + } + + let i = 0; + for (const property of updatedObject.properties) { + if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) { + // Unsupported object literal property + return MetaUpdateAnalysis.Unsupported; + } + + const name = property.name.text; + if (SUPPORTED_FIELD_NAMES.has(name)) { + const staleInitializer = supportedFields.get(name); + // If the supported field was added or has its content changed, there has been a supported update + if ( + !staleInitializer || + !equalRangeText(property.initializer, updatedSource, staleInitializer, staleSource) + ) { + hasSupportedUpdate = true; + } + // Remove the field entry to allow tracking removed fields + supportedFields.delete(name); + continue; + } + + // Compare in order + if (!equalRangeText(property.initializer, updatedSource, unsupportedFields[i++], staleSource)) { + return MetaUpdateAnalysis.Unsupported; + } + } + + if (i !== unsupportedFields.length) { + return MetaUpdateAnalysis.Unsupported; + } + + // Any remaining supported field indicates a field removal. This is also considered a supported update. + hasSupportedUpdate ||= supportedFields.size > 0; + + return hasSupportedUpdate ? MetaUpdateAnalysis.Supported : MetaUpdateAnalysis.None; +} + +/** + * Compares the text from a provided range in a source file to the text of a range in a second source file. + * The comparison avoids making any intermediate string copies. + * @param firstRange A text range within the first source file. + * @param firstSource A source file instance. + * @param secondRange A text range within the second source file. + * @param secondSource A source file instance. + * @returns true, if the text from both ranges is equal; false, otherwise. + */ +function equalRangeText( + firstRange: ts.ReadonlyTextRange | undefined, + firstSource: ts.SourceFile, + secondRange: ts.ReadonlyTextRange | undefined, + secondSource: ts.SourceFile, +): boolean { + // Check matching undefined values + if (!firstRange || !secondRange) { + return firstRange === secondRange; + } + + // Ensure lengths are equal + const firstLength = firstRange.end - firstRange.pos; + const secondLength = secondRange.end - secondRange.pos; + if (firstLength !== secondLength) { + return false; + } + + // Check each character + for (let i = 0; i < firstLength; ++i) { + const firstChar = firstSource.text.charCodeAt(i + firstRange.pos); + const secondChar = secondSource.text.charCodeAt(i + secondRange.pos); + if (firstChar !== secondChar) { + return false; + } + } + + return true; +} diff --git a/packages/angular/build/src/tools/angular/compilation/index.ts b/packages/angular/build/src/tools/angular/compilation/index.ts new file mode 100644 index 000000000000..268abec678ca --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/index.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + AngularCompilation, + type AngularCompilationOptions, + type AngularCompilationResult, + DiagnosticModes, + type EmitFileResult, + type FileTransformResult, +} from './angular-compilation'; +export type { CompilerOptionOverrides } from './compiler-options'; +export { createAngularCompilation, type AngularCompilationMode } from './factory'; diff --git a/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts b/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts new file mode 100644 index 000000000000..ec88987369b0 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts @@ -0,0 +1,169 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import assert from 'node:assert'; +import ts from 'typescript'; +import { profileSync } from '../../../utils/profiling'; +import { AngularHostOptions, createAngularCompilerHost } from '../angular-host'; +import { createJitResourceTransformer } from '../transformers/jit-resource-transformer'; +import { lazyRoutesTransformer } from '../transformers/lazy-routes-transformer'; +import { createWorkerTransformer } from '../transformers/web-worker-transformer'; +import { + type AngularCompilationResult, + DiagnosticModes, + type EmitFileResult, +} from './angular-compilation'; +import type { CompilerOptionOverrides } from './compiler-options'; +import { TypeScriptCompilation } from './typescript-compilation'; + +class JitCompilationState { + constructor( + public readonly compilerHost: ng.CompilerHost, + public readonly typeScriptProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram, + public readonly constructorParametersDownlevelTransform: ts.TransformerFactory, + public readonly replaceResourcesTransform: ts.TransformerFactory, + public readonly webWorkerTransform: ts.TransformerFactory, + ) {} +} + +export class JitCompilation extends TypeScriptCompilation { + #state?: JitCompilationState; + + constructor(private readonly browserOnlyBuild: boolean) { + super(); + } + + async initialize( + tsconfig: string, + hostOptions: AngularHostOptions, + compilerOptionOverrides?: CompilerOptionOverrides, + buildType: 'application' | 'library' = 'application', + ): Promise { + // Dynamically load the Angular compiler CLI package + const { constructorParametersDownlevelTransform } = + await import('@angular/compiler-cli/private/tooling'); + + // Load the compiler configuration and transform as needed + const { + compilerOptions, + rootNames, + errors: configurationDiagnostics, + warnings, + tsConfigFiles, + } = await this.loadConfiguration(tsconfig, compilerOptionOverrides, buildType); + + if (hostOptions.modifiedFiles) { + this.invalidateFiles(hostOptions.modifiedFiles); + } + + // Create Angular compiler host + const host = createAngularCompilerHost( + ts, + compilerOptions, + hostOptions, + undefined, + this.sourceFiles, + ); + + // Create the TypeScript Program + const typeScriptProgram = profileSync('TS_CREATE_PROGRAM', () => + ts.createEmitAndSemanticDiagnosticsBuilderProgram( + rootNames, + compilerOptions, + host, + this.#state?.typeScriptProgram ?? ts.readBuilderProgram(compilerOptions, host), + configurationDiagnostics, + ), + ); + + this.#state = new JitCompilationState( + host, + typeScriptProgram, + constructorParametersDownlevelTransform(typeScriptProgram.getProgram()), + createJitResourceTransformer(() => typeScriptProgram.getProgram().getTypeChecker()), + createWorkerTransformer(hostOptions.processWebWorker.bind(hostOptions)), + ); + + const referencedFiles = [ + ...tsConfigFiles, + ...typeScriptProgram.getSourceFiles().map((sourceFile) => sourceFile.fileName), + ]; + + return { compilerOptions, referencedFiles, warnings }; + } + + protected override *collectDiagnostics(modes: DiagnosticModes): Iterable { + assert(this.#state, 'Compilation must be initialized prior to collecting diagnostics.'); + const { typeScriptProgram } = this.#state; + + // Collect program level diagnostics + if (modes & DiagnosticModes.Option) { + yield* typeScriptProgram.getConfigFileParsingDiagnostics(); + yield* typeScriptProgram.getOptionsDiagnostics(); + } + if (modes & DiagnosticModes.Syntactic) { + yield* typeScriptProgram.getGlobalDiagnostics(); + yield* profileSync('NG_DIAGNOSTICS_SYNTACTIC', () => + typeScriptProgram.getSyntacticDiagnostics(), + ); + } + if (modes & DiagnosticModes.Semantic) { + yield* profileSync('NG_DIAGNOSTICS_SEMANTIC', () => + typeScriptProgram.getSemanticDiagnostics(), + ); + } + } + + override emitAffectedFiles(): Iterable { + assert(this.#state, 'Compilation must be initialized prior to emitting files.'); + const { + compilerHost, + typeScriptProgram, + constructorParametersDownlevelTransform, + replaceResourcesTransform, + webWorkerTransform, + } = this.#state; + const compilerOptions = typeScriptProgram.getCompilerOptions(); + const buildInfoFilename = compilerOptions.tsBuildInfoFile ?? '.tsbuildinfo'; + + const emittedFiles: EmitFileResult[] = []; + const writeFileCallback: ts.WriteFileCallback = (filename, contents, _a, _b, sourceFiles) => { + if (!sourceFiles?.length && filename.endsWith(buildInfoFilename)) { + // Save builder info contents to specified location + compilerHost.writeFile(filename, contents, false); + + return; + } + + assert(sourceFiles?.length === 1, 'Invalid TypeScript program emit for ' + filename); + + emittedFiles.push({ filename: sourceFiles[0].fileName, contents }); + }; + const transformers = { + before: [ + replaceResourcesTransform, + constructorParametersDownlevelTransform, + webWorkerTransform, + ], + }; + + if (!this.browserOnlyBuild) { + transformers.before.push(lazyRoutesTransformer(compilerOptions, compilerHost)); + } + + // TypeScript will loop until there are no more affected files in the program + while ( + typeScriptProgram.emitNextAffectedFile(writeFileCallback, undefined, undefined, transformers) + ) { + /* empty */ + } + + return emittedFiles; + } +} diff --git a/packages/angular/build/src/tools/angular/compilation/parallel-compilation.ts b/packages/angular/build/src/tools/angular/compilation/parallel-compilation.ts new file mode 100644 index 000000000000..60945a758081 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/parallel-compilation.ts @@ -0,0 +1,157 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { PartialMessage } from 'esbuild'; +import { createRequire } from 'node:module'; +import { MessageChannel } from 'node:worker_threads'; +import { mergeCumulativeDurations } from '../../../utils/profiling'; +import { WorkerPool } from '../../../utils/worker-pool'; +import type { AngularHostOptions } from '../angular-host'; +import { + AngularCompilation, + AngularCompilationResult, + DiagnosticModes, + EmitFileResult, +} from './angular-compilation'; +import type { CompilerOptionOverrides } from './compiler-options'; + +/** + * An Angular compilation which uses a Node.js Worker thread to load and execute + * the TypeScript and Angular compilers. This allows for longer synchronous actions + * such as semantic and template diagnostics to be calculated in parallel to the + * other aspects of the application bundling process. The worker thread also has + * a separate memory pool which significantly reduces the need for adjusting the + * main Node.js CLI process memory settings with large application code sizes. + */ +export class ParallelCompilation extends AngularCompilation { + readonly #worker: WorkerPool; + #webWorkerChannel?: MessageChannel; + + constructor( + private readonly jit: boolean, + private readonly browserOnlyBuild: boolean, + ) { + super(); + + // TODO: Convert to import.meta usage during ESM transition + const localRequire = createRequire(__filename); + + this.#worker = new WorkerPool({ + maxThreads: 1, + idleTimeout: Infinity, + filename: localRequire.resolve('./parallel-worker'), + }); + } + + override async initialize( + tsconfig: string, + hostOptions: AngularHostOptions, + compilerOptionOverrides?: CompilerOptionOverrides, + buildType: 'application' | 'library' = 'application', + ): Promise { + const stylesheetChannel = new MessageChannel(); + // The request identifier is required because Angular can issue multiple concurrent requests + stylesheetChannel.port1.on( + 'message', + ({ requestId, data, containingFile, stylesheetFile, order, className }) => { + hostOptions + .transformStylesheet(data, containingFile, stylesheetFile, order, className) + .then((value) => stylesheetChannel.port1.postMessage({ requestId, value })) + .catch((error) => stylesheetChannel.port1.postMessage({ requestId, error })); + }, + ); + + this.#webWorkerChannel?.port1.close(); + this.#webWorkerChannel = undefined; + + let webWorkerSignal: Int32Array | undefined; + if (buildType !== 'library') { + // The web worker processing is a synchronous operation and uses shared memory combined with + // the Atomics API to block execution here until a response is received. + const webWorkerChannel = new MessageChannel(); + this.#webWorkerChannel = webWorkerChannel; + const signal = new Int32Array(new SharedArrayBuffer(4)); + webWorkerSignal = signal; + webWorkerChannel.port1.on('message', ({ workerFile, containingFile }) => { + try { + const workerCodeFile = hostOptions.processWebWorker(workerFile, containingFile); + webWorkerChannel.port1.postMessage({ workerCodeFile }); + } catch (error) { + webWorkerChannel.port1.postMessage({ error }); + } finally { + Atomics.store(signal, 0, 1); + Atomics.notify(signal, 0); + } + }); + } + + let success = false; + try { + // Execute the initialize function in the worker thread + const result = await this.#worker.run( + { + fileReplacements: hostOptions.fileReplacements, + tsconfig, + jit: this.jit, + browserOnlyBuild: this.browserOnlyBuild, + compilerOptionOverrides, + buildType, + stylesheetPort: stylesheetChannel.port2, + webWorkerPort: this.#webWorkerChannel?.port2, + webWorkerSignal, + }, + { + name: 'initialize', + transferList: this.#webWorkerChannel + ? [stylesheetChannel.port2, this.#webWorkerChannel.port2] + : [stylesheetChannel.port2], + }, + ); + success = true; + + return result; + } finally { + stylesheetChannel.port1.close(); + if (!success) { + this.#webWorkerChannel?.port1.close(); + this.#webWorkerChannel = undefined; + } + } + } + + override async diagnoseFiles( + modes = DiagnosticModes.All, + ): Promise<{ errors?: PartialMessage[]; warnings?: PartialMessage[] }> { + const { timings, ...result } = await this.#worker.run(modes, { name: 'diagnose' }); + if (timings) { + mergeCumulativeDurations(timings); + } + + return result; + } + + override async emitAffectedFiles(): Promise> { + try { + return await this.#worker.run(undefined, { name: 'emit' }); + } finally { + this.#webWorkerChannel?.port1.close(); + this.#webWorkerChannel = undefined; + } + } + + override update(files: Set): Promise { + return this.#worker.run(files, { name: 'update' }); + } + + override close() { + this.#webWorkerChannel?.port1.close(); + this.#webWorkerChannel = undefined; + + return this.#worker.destroy(); + } +} diff --git a/packages/angular/build/src/tools/angular/compilation/parallel-compilation_spec.ts b/packages/angular/build/src/tools/angular/compilation/parallel-compilation_spec.ts new file mode 100644 index 000000000000..7157251e1ab9 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/parallel-compilation_spec.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { MessageChannel } from 'node:worker_threads'; +import { AotCompilation } from './aot-compilation'; +import { initialize } from './parallel-worker'; + +describe('parallel-worker', () => { + it('uses incrementing numeric request IDs for transformStylesheet and handles omitted webWorkerPort in library builds', async () => { + const receivedRequestIds: unknown[] = []; + let workerResult: string | undefined; + + spyOn(AotCompilation.prototype, 'initialize').and.callFake(async (_tsconfig, hostOptions) => { + const [style1, style2] = await Promise.all([ + hostOptions.transformStylesheet('body {}', '/src/a.ts', '/src/a.css', 0, 'CompA'), + hostOptions.transformStylesheet('div {}', '/src/b.ts', '/src/b.css', 1, 'CompB'), + ]); + expect(style1).toBe('transformed:body {}'); + expect(style2).toBe('transformed:div {}'); + + workerResult = hostOptions.processWebWorker('./my.worker', '/src/a.ts'); + + return { + compilerOptions: {}, + referencedFiles: ['/src/a.ts'], + }; + }); + + const stylesheetChannel = new MessageChannel(); + stylesheetChannel.port1.on('message', ({ requestId, data }) => { + receivedRequestIds.push(requestId); + stylesheetChannel.port1.postMessage({ + requestId, + value: `transformed:${data}`, + }); + }); + + try { + const result = await initialize({ + jit: false, + browserOnlyBuild: false, + tsconfig: '/src/tsconfig.lib.json', + buildType: 'library', + stylesheetPort: stylesheetChannel.port2, + }); + + expect(receivedRequestIds).toEqual([1, 2]); + expect(workerResult).toBe('./my.worker'); + expect(result.referencedFiles).toEqual(['/src/a.ts']); + } finally { + stylesheetChannel.port1.close(); + } + }); +}); diff --git a/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts b/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts new file mode 100644 index 000000000000..dde3df4c0c20 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts @@ -0,0 +1,185 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { PartialMessage } from 'esbuild'; +import assert from 'node:assert'; +import { type MessagePort, receiveMessageOnPort } from 'node:worker_threads'; +import { initializeHash } from '../../../utils/hash'; +import { getAndClearCumulativeDurations } from '../../../utils/profiling'; +import type { + AngularCompilation, + AngularCompilationResult, + DiagnosticModes, +} from './angular-compilation'; +import { AotCompilation } from './aot-compilation'; +import type { CompilerOptionOverrides } from './compiler-options'; +import { JitCompilation } from './jit-compilation'; + +export interface InitRequest { + jit: boolean; + browserOnlyBuild: boolean; + tsconfig: string; + fileReplacements?: Record; + compilerOptionOverrides?: CompilerOptionOverrides; + buildType?: 'application' | 'library'; + stylesheetPort: MessagePort; + webWorkerPort?: MessagePort; + webWorkerSignal?: Int32Array; +} + +let compilation: AngularCompilation | undefined; +let activeWebWorkerPort: MessagePort | undefined; + +const modifiedFiles = new Set(); + +export async function initialize(request: InitRequest): Promise { + activeWebWorkerPort?.close(); + activeWebWorkerPort = request.webWorkerPort; + + const currentModifiedFiles = new Set(modifiedFiles); + modifiedFiles.clear(); + + let success = false; + try { + await initializeHash(); + compilation ??= request.jit + ? new JitCompilation(request.browserOnlyBuild) + : new AotCompilation(request.browserOnlyBuild); + + let nextRequestId = 0; + const stylesheetRequests = new Map< + number, + [(value: string) => void, (reason: Error) => void] + >(); + request.stylesheetPort.on('message', ({ requestId, value, error }) => { + const handlers = stylesheetRequests.get(requestId); + if (handlers) { + stylesheetRequests.delete(requestId); + if (error) { + handlers[1](error); + } else { + handlers[0](value); + } + } + }); + + const { + compilerOptions, + referencedFiles, + externalStylesheets, + templateUpdates, + componentResourcesDependencies, + warnings, + } = await compilation.initialize( + request.tsconfig, + { + fileReplacements: request.fileReplacements, + modifiedFiles: currentModifiedFiles, + transformStylesheet(data, containingFile, stylesheetFile, order, className) { + const requestId = ++nextRequestId; + const resultPromise = new Promise((resolve, reject) => + stylesheetRequests.set(requestId, [resolve, reject]), + ); + + request.stylesheetPort.postMessage({ + requestId, + data, + containingFile, + stylesheetFile, + order, + className, + }); + + return resultPromise; + }, + processWebWorker(workerFile, containingFile) { + if (!request.webWorkerPort || !request.webWorkerSignal) { + return workerFile; + } + + Atomics.store(request.webWorkerSignal, 0, 0); + request.webWorkerPort.postMessage({ workerFile, containingFile }); + + Atomics.wait(request.webWorkerSignal, 0, 0); + const result = receiveMessageOnPort(request.webWorkerPort)?.message; + + if (result?.error) { + throw result.error; + } + + return result?.workerCodeFile ?? workerFile; + }, + }, + request.compilerOptionOverrides, + request.buildType, + ); + + success = true; + + return { + externalStylesheets, + templateUpdates, + referencedFiles, + warnings, + // TODO: Expand? `allowJs`, `isolatedModules`, `sourceMap`, `inlineSourceMap` are the only fields needed currently. + compilerOptions: { + allowJs: compilerOptions.allowJs, + compilationMode: compilerOptions.compilationMode, + declarationMap: compilerOptions.declarationMap, + isolatedModules: compilerOptions.isolatedModules, + sourceMap: compilerOptions.sourceMap, + inlineSourceMap: compilerOptions.inlineSourceMap, + _useTypeScriptTranspilation: compilerOptions['_useTypeScriptTranspilation'] as + boolean | undefined, + }, + componentResourcesDependencies, + }; + } finally { + request.stylesheetPort.close(); + if (!success) { + activeWebWorkerPort?.close(); + activeWebWorkerPort = undefined; + } + } +} + +export async function diagnose(modes: DiagnosticModes): Promise<{ + errors?: PartialMessage[]; + warnings?: PartialMessage[]; + timings?: Record; +}> { + assert(compilation); + + const diagnostics = await compilation.diagnoseFiles(modes); + const timings = getAndClearCumulativeDurations(); + + return { + ...diagnostics, + timings, + }; +} + +export async function emit() { + assert(compilation); + + try { + const files = await compilation.emitAffectedFiles(); + + return [...files]; + } finally { + activeWebWorkerPort?.close(); + activeWebWorkerPort = undefined; + } +} + +export async function update(files: Set): Promise { + for (const file of files) { + modifiedFiles.add(file); + } + await compilation?.update?.(files); +} diff --git a/packages/angular/build/src/tools/angular/compilation/typescript-compilation.ts b/packages/angular/build/src/tools/angular/compilation/typescript-compilation.ts new file mode 100644 index 000000000000..6601500fbcc9 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/typescript-compilation.ts @@ -0,0 +1,183 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type * as ng from '@angular/compiler-cli'; +import type { PartialMessage } from 'esbuild'; +import ts from 'typescript'; +import { canonicalizePath, toPosixPath } from '../../../utils/path'; +import { profileAsync, profileSync } from '../../../utils/profiling'; +import { AngularCompilation, DiagnosticModes } from './angular-compilation'; +import { type CompilerOptionOverrides, transformCompilerOptions } from './compiler-options'; +import { convertTypeScriptDiagnostic } from './diagnostics'; + +export interface TransformedConfiguration { + compilerOptions: ng.CompilerOptions; + rootNames: string[]; + fallbackRootNames?: string[]; + errors: ts.Diagnostic[]; + warnings: PartialMessage[]; + tsConfigFiles: readonly string[]; +} + +export abstract class TypeScriptCompilation extends AngularCompilation { + static #angularCompilerCliModule?: typeof ng; + readonly #extendedConfigCache = new Map(); + + static async loadCompilerCli(): Promise { + TypeScriptCompilation.#angularCompilerCliModule ??= await import('@angular/compiler-cli'); + + return TypeScriptCompilation.#angularCompilerCliModule; + } + + protected async loadConfiguration( + tsconfig: string, + compilerOptionOverrides?: CompilerOptionOverrides, + buildType: 'application' | 'library' = 'application', + ): Promise { + const { readConfiguration } = await TypeScriptCompilation.loadCompilerCli(); + + const { + options: originalCompilerOptions, + rootNames: originalRootNames, + errors, + } = profileSync('NG_READ_CONFIG', () => + readConfiguration( + tsconfig, + { + // Angular specific configuration defaults and overrides to ensure a functioning compilation. + suppressOutputPathCheck: true, + outDir: undefined, + sourceMap: false, + ...(buildType === 'library' + ? { declaration: true } + : { + declaration: false, + declarationMap: false, + }), + allowEmptyCodegenFiles: false, + annotationsAs: 'decorators', + enableResourceInlining: false, + supportTestBed: false, + supportJitMode: false, + // Disable removing of comments as TS is quite aggressive with these and can + // remove important annotations, such as /* @__PURE__ */ and comments like /* vite-ignore */. + removeComments: false, + }, + undefined, + this.#extendedConfigCache, + ), + ); + + const tsConfigFiles = [toPosixPath(tsconfig), ...this.#extendedConfigCache.keys()]; + + let rootNames = originalRootNames; + let fallbackRootNames: string[] | undefined; + if (compilerOptionOverrides?.rootFiles?.length) { + // When explicit rootFiles are provided (e.g., filtered unit test entry points), restrict + // the initial program to only those entry points so TypeScript resolves only their + // transitive imports and skips unrelated or non-included test/application files. + const rootFilesSet = new Set( + compilerOptionOverrides.rootFiles.map((file) => canonicalizePath(toPosixPath(file))), + ); + const fallbackFilesSet = new Set(rootFilesSet); + for (const file of originalRootNames) { + const canonicalFile = canonicalizePath(toPosixPath(file)); + // Ambient declaration files (.d.ts) are not imported directly, so they must always be + // retained from the tsconfig to preserve global type definitions. + if (/\.d\.[cm]?ts$/i.test(file)) { + rootFilesSet.add(canonicalFile); + } + fallbackFilesSet.add(canonicalFile); + } + rootNames = [...rootFilesSet]; + // For application builds (including unit tests), preserve the full set of tsconfig root + // files as a fallback in case the AOT compilation encounters a non-standalone component + // whose declaring NgModule is not directly imported by the entry points. Note that when a + // test tsconfig uses broad globs (e.g., `src/**/*.ts`), this fallback set will also include + // non-included spec files; this is an acceptable trade-off to keep compilation agnostic of + // test-file naming conventions and only occurs for legacy non-standalone components lacking + // explicit NgModule imports. Library builds are excluded because all public NgModules must + // be reachable from the library entry points and should never resolve compilation scope from + // unexported tsconfig files. + if (buildType === 'application' && fallbackFilesSet.size > rootFilesSet.size) { + fallbackRootNames = [...fallbackFilesSet]; + } + } + + const { compilerOptions, warnings } = transformCompilerOptions( + ts, + originalCompilerOptions, + compilerOptionOverrides, + tsconfig, + buildType, + ); + + return { + compilerOptions, + rootNames, + fallbackRootNames, + errors, + warnings, + tsConfigFiles, + }; + } + + protected readonly sourceFiles = new Map(); + + protected invalidateFiles(files: Iterable): void { + for (const file of files) { + const posixFile = toPosixPath(file); + this.sourceFiles.delete(posixFile); + + if (this.#extendedConfigCache.size === 0) { + continue; + } + + if (this.#extendedConfigCache.delete(posixFile)) { + continue; + } + + // Check with lowercased key because TypeScript lowercases the keys + // of the extended config cache on case-insensitive operating systems. + this.#extendedConfigCache.delete(posixFile.toLowerCase()); + } + } + + override async update(files: Set): Promise { + this.invalidateFiles(files); + } + + protected abstract collectDiagnostics( + modes: DiagnosticModes, + ): Iterable | Promise>; + + override async diagnoseFiles( + modes = DiagnosticModes.All, + ): Promise<{ errors?: PartialMessage[]; warnings?: PartialMessage[] }> { + if (modes === DiagnosticModes.None) { + return {}; + } + + const result: { errors?: PartialMessage[]; warnings?: PartialMessage[] } = {}; + + await profileAsync('NG_DIAGNOSTICS_TOTAL', async () => { + const diagnostics = await this.collectDiagnostics(modes); + + for (const diagnostic of diagnostics) { + const message = convertTypeScriptDiagnostic(ts, diagnostic); + if (diagnostic.category === ts.DiagnosticCategory.Error) { + (result.errors ??= []).push(message); + } else { + (result.warnings ??= []).push(message); + } + } + }); + + return result; + } +} diff --git a/packages/angular/build/src/tools/angular/compilation/typescript-printer.ts b/packages/angular/build/src/tools/angular/compilation/typescript-printer.ts new file mode 100644 index 000000000000..04d90ddb01c0 --- /dev/null +++ b/packages/angular/build/src/tools/angular/compilation/typescript-printer.ts @@ -0,0 +1,161 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview Helper functions and typings for utilizing internal TypeScript printer + * and sourcemap generation APIs. + */ + +import assert from 'node:assert'; +import { dirname } from 'node:path'; +import ts from 'typescript'; + +/** + * Partial interface representing the internal TypeScript `EmitTextWriter` API. + * Used to collect printed text output from the printer. + */ +export interface EmitTextWriter { + write(s: string): void; + rawWrite(s: string): void; + writeLine(force?: boolean): void; + getText(): string; + clear(): void; + isAtStartOfLine(): boolean; + getTextPos(): number; + writeComment(s: string): void; +} + +/** + * Partial interface representing the internal TypeScript `SourceMapGenerator` API. + * Used to construct mappings and serialize a sourcemap. + */ +export interface SourceMapGenerator { + getSources(): string[]; + addSource(fileName: string): number; + setSourceContent(sourceIndex: number, content: string | null): void; + addMapping( + generatedLine: number, + generatedCharacter: number, + sourceIndex: number, + sourceLine: number, + sourceCharacter: number, + nameIndex?: number, + ): void; + toJSON(): object; + toString(): string; +} + +/** + * Extended `ts.Printer` interface containing the internal `writeFile` method + * which supports sourcemap generation. + */ +export interface ExtendedPrinter extends ts.Printer { + writeFile( + sourceFile: ts.SourceFile, + writer: EmitTextWriter, + sourceMapGenerator?: SourceMapGenerator, + ): void; +} + +/** + * Typing structure for internal TypeScript module exports that are not exposed + * in the public `@types/typescript` package. + */ +export interface TypeScriptInternals { + createTextWriter(newLine: string): EmitTextWriter; + createSourceMapGenerator( + host: { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + }, + file: string, + sourceRoot: string | undefined, + sourcesDirectoryPath: string, + generatorOptions: ts.CompilerOptions, + ): SourceMapGenerator; +} + +const tsInternals = ts as unknown as TypeScriptInternals; + +/** + * Asserts that the required internal TypeScript APIs are present in the currently + * loaded TypeScript module. + * + * @throws {AssertionError} If any required internal API is missing. + */ +export function assertTypeScriptPrinterInternals(): void { + assert( + typeof tsInternals.createTextWriter === 'function', + 'TypeScript internal "createTextWriter" is missing.', + ); + assert( + typeof tsInternals.createSourceMapGenerator === 'function', + 'TypeScript internal "createSourceMapGenerator" is missing.', + ); +} + +/** + * Result object returned from printing a source file. + */ +export interface PrintResult { + /** The printed source code text. */ + code: string; + + /** The generated sourcemap JSON string, if sourcemap generation was requested. */ + map?: string; +} + +/** + * Prints a TypeScript source file AST to a string, optionally generating a sourcemap + * using internal TypeScript APIs. + * + * @param sourceFile The TypeScript AST node representing the file to print. + * @param printer The printer instance to print the file with. + * @param compilerHost The TypeScript compiler host, used for path canonicalization and context. + * @param compilerOptions The compiler options configured for the build target. + * @returns A result containing the printed code and optional sourcemap text. + */ +export function printSourceFileWithMap( + sourceFile: ts.SourceFile, + printer: ts.Printer, + compilerHost: ts.CompilerHost, + compilerOptions: ts.CompilerOptions, +): PrintResult { + const shouldGenerateMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap; + if (!shouldGenerateMap) { + return { code: printer.printFile(sourceFile) }; + } + + assertTypeScriptPrinterInternals(); + + const extendedPrinter = printer as ExtendedPrinter; + assert( + typeof extendedPrinter.writeFile === 'function', + 'TypeScript Printer is missing internal "writeFile" method.', + ); + + const writer = tsInternals.createTextWriter(compilerHost.getNewLine()); + + const sourceMapGenerator = tsInternals.createSourceMapGenerator( + { + getCurrentDirectory: () => compilerHost.getCurrentDirectory(), + getCanonicalFileName: (fileName) => compilerHost.getCanonicalFileName(fileName), + }, + sourceFile.fileName, + compilerOptions.sourceRoot, + dirname(sourceFile.fileName), + compilerOptions, + ); + + extendedPrinter.writeFile(sourceFile, writer, sourceMapGenerator); + + const code = writer.getText(); + const map = sourceMapGenerator.toString(); + + return { code, map }; +} diff --git a/packages/angular/build/src/tools/angular/linker/oxc-ast-host.ts b/packages/angular/build/src/tools/angular/linker/oxc-ast-host.ts new file mode 100644 index 000000000000..245443781601 --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/oxc-ast-host.ts @@ -0,0 +1,337 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { AstHost, Range } from '@angular/compiler-cli/linker'; +import { FatalLinkerError } from '@angular/compiler-cli/linker'; +import type { + ArrayExpression, + ArrowFunctionExpression, + BooleanLiteral, + CallExpression, + Function as FunctionNode, + Node, + NullLiteral, + NumericLiteral, + ObjectExpression, + StringLiteral, + UnaryExpression, +} from '@oxc-project/types'; + +function isNode(node: unknown): node is Node { + return typeof node === 'object' && node !== null && 'type' in node; +} + +function unwrapParentheses(node: unknown): unknown { + while (isNode(node) && node.type === 'ParenthesizedExpression') { + node = node.expression; + } + + return node; +} + +/** + * An implementation of `AstHost` that queries information from `oxc-parser` AST nodes. + */ +export class OxcAstHost implements AstHost { + getSymbolName(node: unknown): string | null { + node = unwrapParentheses(node); + if (!isNode(node)) { + return null; + } + + if (node.type === 'Identifier') { + return node.name; + } else if (node.type === 'MemberExpression') { + if (!node.computed && node.property.type === 'Identifier') { + return node.property.name; + } + } + + return null; + } + + isStringLiteral(node: unknown): node is StringLiteral { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'Literal' && typeof node.value === 'string'; + } + + parseStringLiteral(str: unknown): string { + str = unwrapParentheses(str); + if (!this.isStringLiteral(str)) { + throw new FatalLinkerError(str as object, 'Unsupported syntax, expected a string literal.'); + } + + return str.value; + } + + isNumericLiteral(node: unknown): node is NumericLiteral { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'Literal' && typeof node.value === 'number'; + } + + parseNumericLiteral(num: unknown): number { + num = unwrapParentheses(num); + if (!this.isNumericLiteral(num)) { + throw new FatalLinkerError(num as object, 'Unsupported syntax, expected a numeric literal.'); + } + + return num.value; + } + + isBooleanLiteral(node: unknown): node is BooleanLiteral | UnaryExpression { + node = unwrapParentheses(node); + if (!isNode(node)) { + return false; + } + + return ( + (node.type === 'Literal' && typeof node.value === 'boolean') || isMinifiedBooleanLiteral(node) + ); + } + + parseBooleanLiteral(bool: unknown): boolean { + bool = unwrapParentheses(bool); + if (isNode(bool)) { + if (bool.type === 'Literal' && typeof bool.value === 'boolean') { + return bool.value; + } + if (isMinifiedBooleanLiteral(bool)) { + return !bool.argument.value; + } + } + + throw new FatalLinkerError(bool as object, 'Unsupported syntax, expected a boolean literal.'); + } + + isNull(node: unknown): node is NullLiteral { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'Literal' && node.value === null; + } + + isArrayLiteral(node: unknown): node is ArrayExpression { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'ArrayExpression'; + } + + parseArrayLiteral(array: unknown): unknown[] { + array = unwrapParentheses(array); + if (!this.isArrayLiteral(array)) { + throw new FatalLinkerError(array as object, 'Unsupported syntax, expected an array literal.'); + } + + const result: unknown[] = []; + + for (const element of array.elements) { + if (element === null) { + throw new FatalLinkerError( + array as object, + 'Unsupported syntax, element in array not to be empty.', + ); + } + const unwrappedElement = unwrapParentheses(element); + if (isNode(unwrappedElement) && unwrappedElement.type === 'SpreadElement') { + throw new FatalLinkerError( + unwrappedElement as object, + 'Unsupported syntax, element in array not to use spread syntax.', + ); + } + result.push(unwrappedElement); + } + + return result; + } + + isObjectLiteral(node: unknown): node is ObjectExpression { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'ObjectExpression'; + } + + parseObjectLiteral(obj: unknown): Map { + obj = unwrapParentheses(obj); + if (!this.isObjectLiteral(obj)) { + throw new FatalLinkerError(obj as object, 'Unsupported syntax, expected an object literal.'); + } + + const result = new Map(); + + for (const property of obj.properties) { + if (property.type !== 'Property') { + throw new FatalLinkerError( + property as object, + 'Unsupported syntax, expected a property assignment.', + ); + } + + const keyNode = unwrapParentheses(property.key); + if (!isNode(keyNode)) { + throw new FatalLinkerError( + property.key as object, + 'Unsupported syntax, expected a property name.', + ); + } + + let key: string; + if (keyNode.type === 'Identifier') { + key = keyNode.name; + } else if (this.isStringLiteral(keyNode)) { + key = keyNode.value; + } else if (this.isNumericLiteral(keyNode)) { + key = String(keyNode.value); + } else { + throw new FatalLinkerError( + keyNode as object, + 'Unsupported syntax, expected a property name.', + ); + } + + result.set(key, unwrapParentheses(property.value)); + } + + return result; + } + + isFunctionExpression(node: unknown): node is FunctionNode | ArrowFunctionExpression { + node = unwrapParentheses(node); + if (!isNode(node)) { + return false; + } + + return ( + node.type === 'FunctionDeclaration' || + node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression' + ); + } + + parseReturnValue(fn: unknown): unknown { + fn = unwrapParentheses(fn); + if (!this.isFunctionExpression(fn)) { + throw new FatalLinkerError(fn as object, 'Unsupported syntax, expected a function.'); + } + + const body = fn.body; + if (!body || !isNode(body)) { + throw new FatalLinkerError(fn as object, 'Unsupported syntax, expected a function body.'); + } + + if (body.type !== 'BlockStatement') { + return unwrapParentheses(body); + } + + const statements = body.body; + if (statements.length !== 1) { + throw new FatalLinkerError( + body as object, + 'Unsupported syntax, expected a function body with a single return statement.', + ); + } + + const stmt = statements[0]; + if (stmt.type !== 'ReturnStatement') { + throw new FatalLinkerError( + stmt as object, + 'Unsupported syntax, expected a function body with a single return statement.', + ); + } + + if (!stmt.argument) { + throw new FatalLinkerError( + stmt as object, + 'Unsupported syntax, expected function to return a value.', + ); + } + + return unwrapParentheses(stmt.argument); + } + + parseParameters(fn: unknown): unknown[] { + fn = unwrapParentheses(fn); + if (!this.isFunctionExpression(fn)) { + throw new FatalLinkerError(fn as object, 'Unsupported syntax, expected a function.'); + } + + return fn.params; + } + + isCallExpression(node: unknown): node is CallExpression { + node = unwrapParentheses(node); + + return isNode(node) && node.type === 'CallExpression'; + } + + parseCallee(call: unknown): unknown { + call = unwrapParentheses(call); + if (!this.isCallExpression(call)) { + throw new FatalLinkerError(call as object, 'Unsupported syntax, expected a call expression.'); + } + + return unwrapParentheses(call.callee); + } + + parseArguments(call: unknown): unknown[] { + call = unwrapParentheses(call); + if (!this.isCallExpression(call)) { + throw new FatalLinkerError(call as object, 'Unsupported syntax, expected a call expression.'); + } + + const result: unknown[] = []; + + for (const arg of call.arguments) { + const unwrappedArg = unwrapParentheses(arg); + if (isNode(unwrappedArg) && unwrappedArg.type === 'SpreadElement') { + throw new FatalLinkerError( + unwrappedArg as object, + 'Unsupported syntax, argument not to use spread syntax.', + ); + } + result.push(unwrappedArg); + } + + return result; + } + + getRange(node: unknown): Range { + node = unwrapParentheses(node); + if (!isNode(node) || typeof node.start !== 'number' || typeof node.end !== 'number') { + throw new FatalLinkerError( + node as object, + 'Unable to read range for node - it is missing location information.', + ); + } + + return { + startPos: node.start, + startLine: 0, + startCol: 0, + endPos: node.end, + }; + } +} + +function isMinifiedBooleanLiteral( + node: Node, +): node is UnaryExpression & { argument: NumericLiteral } { + if (node.type !== 'UnaryExpression') { + return false; + } + + const arg = node.argument; + + return ( + node.prefix === true && + node.operator === '!' && + arg.type === 'Literal' && + typeof arg.value === 'number' && + (arg.value === 0 || arg.value === 1) + ); +} diff --git a/packages/angular/build/src/tools/angular/linker/oxc-ast-host_spec.ts b/packages/angular/build/src/tools/angular/linker/oxc-ast-host_spec.ts new file mode 100644 index 000000000000..cbe0d6a25292 --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/oxc-ast-host_spec.ts @@ -0,0 +1,269 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { FatalLinkerError } from '@angular/compiler-cli/linker'; +import { parseSync } from 'oxc-parser'; +import { OxcAstHost } from './oxc-ast-host'; + +describe('OxcAstHost', () => { + let host: OxcAstHost; + + beforeEach(() => { + host = new OxcAstHost(); + }); + + function parseExpression(code: string): unknown { + const { program } = parseSync('test.js', `const x = ${code};`, { range: true }); + const stmt = program.body[0] as { declarations: Array<{ init: unknown }> }; + + return stmt.declarations[0].init; + } + + function parseStatement(code: string): unknown { + const { program } = parseSync('test.js', code, { range: true }); + + return program.body[0]; + } + + describe('getSymbolName', () => { + it('should return the name of an identifier', () => { + const expr = parseExpression('foo'); + expect(host.getSymbolName(expr)).toBe('foo'); + expect(host.getSymbolName(parseExpression('(foo)'))).toBe('foo'); + }); + + it('should return the property name of a member expression', () => { + const expr = parseExpression('foo.bar'); + expect(host.getSymbolName(expr)).toBe('bar'); + expect(host.getSymbolName(parseExpression('(foo.bar)'))).toBe('bar'); + }); + + it('should return null for non-identifier or computed member expressions', () => { + expect(host.getSymbolName(parseExpression('foo[0]'))).toBeNull(); + expect(host.getSymbolName(parseExpression('42'))).toBeNull(); + expect(host.getSymbolName(null)).toBeNull(); + }); + }); + + describe('string literals', () => { + it('should recognize and parse valid string literals', () => { + const expr = parseExpression('"hello"'); + expect(host.isStringLiteral(expr)).toBe(true); + expect(host.parseStringLiteral(expr)).toBe('hello'); + + const parenthesized = parseExpression('("hello")'); + expect(host.isStringLiteral(parenthesized)).toBe(true); + expect(host.parseStringLiteral(parenthesized)).toBe('hello'); + }); + + it('should throw when parsing non-string literals', () => { + const expr = parseExpression('123'); + expect(host.isStringLiteral(expr)).toBe(false); + expect(() => host.parseStringLiteral(expr)).toThrowError(FatalLinkerError); + }); + }); + + describe('numeric literals', () => { + it('should recognize and parse valid numeric literals', () => { + const expr = parseExpression('123'); + expect(host.isNumericLiteral(expr)).toBe(true); + expect(host.parseNumericLiteral(expr)).toBe(123); + + const parenthesized = parseExpression('(123)'); + expect(host.isNumericLiteral(parenthesized)).toBe(true); + expect(host.parseNumericLiteral(parenthesized)).toBe(123); + }); + + it('should throw when parsing non-numeric literals', () => { + const expr = parseExpression('"123"'); + expect(host.isNumericLiteral(expr)).toBe(false); + expect(() => host.parseNumericLiteral(expr)).toThrowError(FatalLinkerError); + }); + }); + + describe('boolean literals', () => { + it('should recognize and parse true and false literals', () => { + const trueExpr = parseExpression('true'); + const falseExpr = parseExpression('false'); + expect(host.isBooleanLiteral(trueExpr)).toBe(true); + expect(host.parseBooleanLiteral(trueExpr)).toBe(true); + expect(host.isBooleanLiteral(falseExpr)).toBe(true); + expect(host.parseBooleanLiteral(falseExpr)).toBe(false); + + const parenthesizedTrue = parseExpression('(true)'); + expect(host.isBooleanLiteral(parenthesizedTrue)).toBe(true); + expect(host.parseBooleanLiteral(parenthesizedTrue)).toBe(true); + }); + + it('should recognize and parse minified boolean literals (!0 and !1)', () => { + const trueExpr = parseExpression('!0'); + const falseExpr = parseExpression('!1'); + expect(host.isBooleanLiteral(trueExpr)).toBe(true); + expect(host.parseBooleanLiteral(trueExpr)).toBe(true); + expect(host.isBooleanLiteral(falseExpr)).toBe(true); + expect(host.parseBooleanLiteral(falseExpr)).toBe(false); + + const parenthesizedMinified = parseExpression('(!0)'); + expect(host.isBooleanLiteral(parenthesizedMinified)).toBe(true); + expect(host.parseBooleanLiteral(parenthesizedMinified)).toBe(true); + }); + + it('should return false for invalid boolean expressions', () => { + expect(host.isBooleanLiteral(parseExpression('!2'))).toBe(false); + expect(() => host.parseBooleanLiteral(parseExpression('!2'))).toThrowError(FatalLinkerError); + }); + }); + + describe('array literals', () => { + it('should recognize and parse array literals', () => { + const expr = parseExpression('[1, "a", true]'); + expect(host.isArrayLiteral(expr)).toBe(true); + expect(host.parseArrayLiteral(expr).length).toBe(3); + + const parenthesized = parseExpression('([1, "a", true])'); + expect(host.isArrayLiteral(parenthesized)).toBe(true); + expect(host.parseArrayLiteral(parenthesized).length).toBe(3); + }); + + it('should unwrap parenthesized elements in array literals', () => { + const expr = parseExpression('[(1), ("a")]'); + const elements = host.parseArrayLiteral(expr); + expect(elements.length).toBe(2); + expect(host.isNumericLiteral(elements[0])).toBe(true); + expect(host.isStringLiteral(elements[1])).toBe(true); + }); + + it('should throw when array contains empty elements or spread syntax', () => { + expect(() => host.parseArrayLiteral(parseExpression('[1, , 2]'))).toThrowError( + FatalLinkerError, + ); + expect(() => host.parseArrayLiteral(parseExpression('[1, ...a]'))).toThrowError( + FatalLinkerError, + ); + expect(() => host.parseArrayLiteral(parseExpression('[1, ...(a)]'))).toThrowError( + FatalLinkerError, + ); + }); + }); + + describe('object literals', () => { + it('should recognize and parse object literals into a Map', () => { + const expr = parseExpression('{ a: 1, "b": 2, 3: "c" }'); + expect(host.isObjectLiteral(expr)).toBe(true); + + const map = host.parseObjectLiteral(expr); + expect(map.size).toBe(3); + expect(map.has('a')).toBe(true); + expect(map.has('b')).toBe(true); + expect(map.has('3')).toBe(true); + }); + + it('should recognize and parse parenthesized object literals', () => { + const expr = parseExpression('({ a: (1), b: ("c") })'); + expect(host.isObjectLiteral(expr)).toBe(true); + + const map = host.parseObjectLiteral(expr); + expect(map.size).toBe(2); + expect(host.isNumericLiteral(map.get('a'))).toBe(true); + expect(host.isStringLiteral(map.get('b'))).toBe(true); + }); + + it('should throw when object literal contains spread or non-property assignments', () => { + expect(() => host.parseObjectLiteral(parseExpression('{ ...a }'))).toThrowError( + FatalLinkerError, + ); + }); + }); + + describe('functions', () => { + it('should parse return value and parameters from arrow functions', () => { + const expr = parseExpression('(a, b) => 42'); + expect(host.isFunctionExpression(expr)).toBe(true); + expect(host.parseParameters(expr).length).toBe(2); + + const returnValue = host.parseReturnValue(expr); + expect(host.isNumericLiteral(returnValue)).toBe(true); + }); + + it('should parse parenthesized arrow functions and concise bodies returning parenthesized object literals', () => { + const expr = parseExpression('() => ({ a: 1 })'); + expect(host.isFunctionExpression(expr)).toBe(true); + + const returnValue = host.parseReturnValue(expr); + expect(host.isObjectLiteral(returnValue)).toBe(true); + const map = host.parseObjectLiteral(returnValue); + expect(map.has('a')).toBe(true); + + const wrappedArrow = parseExpression('((a) => (42))'); + expect(host.isFunctionExpression(wrappedArrow)).toBe(true); + expect(host.parseParameters(wrappedArrow).length).toBe(1); + expect(host.isNumericLiteral(host.parseReturnValue(wrappedArrow))).toBe(true); + }); + + it('should parse return value from function with block statement containing single return', () => { + const stmt = parseStatement('function foo(a) { return "hello"; }'); + expect(host.isFunctionExpression(stmt)).toBe(true); + + const returnValue = host.parseReturnValue(stmt); + expect(host.isStringLiteral(returnValue)).toBe(true); + }); + + it('should parse return value from function returning parenthesized expression', () => { + const stmt = parseStatement('function foo() { return ({ a: 1 }); }'); + expect(host.isFunctionExpression(stmt)).toBe(true); + + const returnValue = host.parseReturnValue(stmt); + expect(host.isObjectLiteral(returnValue)).toBe(true); + }); + + it('should throw when function body has multiple statements or no return', () => { + expect(() => + host.parseReturnValue(parseStatement('function foo() { const x = 1; return x; }')), + ).toThrowError(FatalLinkerError); + expect(() => host.parseReturnValue(parseStatement('function foo() {}'))).toThrowError( + FatalLinkerError, + ); + }); + }); + + describe('call expressions', () => { + it('should parse callee and arguments', () => { + const expr = parseExpression('foo(1, "a")'); + expect(host.isCallExpression(expr)).toBe(true); + expect(host.getSymbolName(host.parseCallee(expr))).toBe('foo'); + expect(host.parseArguments(expr).length).toBe(2); + + const parenthesized = parseExpression('((foo)((1), ("a")))'); + expect(host.isCallExpression(parenthesized)).toBe(true); + expect(host.getSymbolName(host.parseCallee(parenthesized))).toBe('foo'); + const args = host.parseArguments(parenthesized); + expect(args.length).toBe(2); + expect(host.isNumericLiteral(args[0])).toBe(true); + expect(host.isStringLiteral(args[1])).toBe(true); + }); + + it('should throw when call expression arguments contain spread syntax', () => { + expect(() => host.parseArguments(parseExpression('foo(...args)'))).toThrowError( + FatalLinkerError, + ); + }); + }); + + describe('getRange', () => { + it('should return range object for valid AST nodes', () => { + const expr = parseExpression('foo'); + const range = host.getRange(expr); + expect(range.startPos).toBeGreaterThanOrEqual(0); + expect(range.endPos).toBeGreaterThan(range.startPos); + }); + + it('should throw when node is missing range offsets', () => { + expect(() => host.getRange({})).toThrowError(FatalLinkerError); + }); + }); +}); diff --git a/packages/angular/build/src/tools/angular/linker/oxc-linker.ts b/packages/angular/build/src/tools/angular/linker/oxc-linker.ts new file mode 100644 index 000000000000..8870fe1cc7da --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/oxc-linker.ts @@ -0,0 +1,122 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Logger } from '@angular/compiler-cli'; +import { type DeclarationScope, FileLinker, LinkerEnvironment } from '@angular/compiler-cli/linker'; +import type { + AbsoluteFsPath, + ReadonlyFileSystem, +} from '@angular/compiler-cli/src/ngtsc/file_system'; +import type { CallExpression } from '@oxc-project/types'; +import { OxcAstHost } from './oxc-ast-host'; +import { StringAstFactory } from './string-ast-factory'; + +/** + * A declaration scope that instructs the Angular compiler to emit constant pools + * inside a local IIFE around each linked declaration rather than hoisting shared + * constants to the module level. + * + * Preferred due to: + * - In-Place String Replacement: Enables fast in-place string replacements in + * `MagicString` without parsing or mutating surrounding ES module statements. + * - Better Tree-Shaking Locality: Component constants are strictly encapsulated + * within the component's `@__PURE__` IIFE closure (`(function() { ... })()`). If a + * bundler tree-shakes an unused component from a library FESM, all of its associated + * constants are automatically eliminated without leaving orphan top-level variables. + * - Negligible Wire Size Impact: LZ77/Brotli compression deduplicates repeated IIFE + * wrappers and array literals over the wire to near-zero marginal cost. + */ +class InlineDeclarationScope implements DeclarationScope { + getConstantScopeRef(): null { + return null; + } +} + +const noopFileSystem: ReadonlyFileSystem = { + exists: () => false, + readFile: () => '', + resolve: (...paths: string[]) => paths.join('/'), + dirname: (path: string) => path.split('/').slice(0, -1).join('/'), + relative: (_from: string, to: string) => to, +} as unknown as ReadonlyFileSystem; + +const defaultLogger: Logger = { + level: 1, // LogLevel.info + debug(...args: string[]) { + if (this.level <= 0) { + // eslint-disable-next-line no-console + console.debug(...args); + } + }, + info(...args: string[]) { + if (this.level <= 1) { + // eslint-disable-next-line no-console + console.info(...args); + } + }, + warn(...args: string[]) { + if (this.level <= 2) { + // eslint-disable-next-line no-console + console.warn(...args); + } + }, + error(...args: string[]) { + if (this.level <= 3) { + // eslint-disable-next-line no-console + console.error(...args); + } + }, +}; + +let SHARED_AST_HOST: OxcAstHost; +let SHARED_DECLARATION_SCOPE: InlineDeclarationScope; + +/** + * Manages Angular partial declaration linking using Oxc AST nodes. + */ +export class OxcLinker { + readonly #fileLinker: FileLinker; + + constructor(filename: string, code: string, jit = false) { + SHARED_AST_HOST ??= new OxcAstHost(); + SHARED_DECLARATION_SCOPE ??= new InlineDeclarationScope(); + + const astFactory = new StringAstFactory(code); + const linkerEnvironment = LinkerEnvironment.create( + noopFileSystem, + defaultLogger, + SHARED_AST_HOST, + astFactory, + { linkerJitMode: jit, sourceMapping: false }, + ); + + this.#fileLinker = new FileLinker(linkerEnvironment, filename as AbsoluteFsPath, code); + } + + /** + * Attempts to link an Angular partial declaration CallExpression. + * + * @param node The CallExpression AST node to check and link. + * @returns The linked code string if the node is a partial declaration, or undefined otherwise. + */ + linkCallExpression(node: CallExpression): string | undefined { + const calleeName = SHARED_AST_HOST.getSymbolName(node.callee); + if (!calleeName || !this.#fileLinker.isPartialDeclaration(calleeName)) { + return undefined; + } + + const args = SHARED_AST_HOST.parseArguments(node); + const linkedCode = this.#fileLinker.linkPartialDeclaration( + calleeName, + args, + SHARED_DECLARATION_SCOPE, + ); + + return linkedCode as string; + } +} diff --git a/packages/angular/build/src/tools/angular/linker/oxc-linker_spec.ts b/packages/angular/build/src/tools/angular/linker/oxc-linker_spec.ts new file mode 100644 index 000000000000..467658eb1991 --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/oxc-linker_spec.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { transform } from '../../oxc/oxc-transform'; + +describe('oxc-linker', () => { + it('should not modify code that does not need linking', () => { + const input = 'const x = 1;'; + const result = transform('test.js', input, { link: true, advancedOptimizations: false }); + expect(result.code).toBe(input); + expect(result.map).toBeUndefined(); + }); + + it('should link a partial directive declaration', () => { + const input = ` + import * as i0 from "@angular/core"; + export class MyDirective {} + MyDirective.ɵdir = i0.ɵɵngDeclareDirective({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyDirective, + selector: "[my-dir]" + }); + `; + + const result = transform('test.js', input, { link: true, advancedOptimizations: false }); + expect(result.code).toContain('i0.ɵɵdefineDirective'); + expect(result.code).not.toContain('i0.ɵɵngDeclareDirective'); + }); + + it('should link a partial component declaration', () => { + const input = ` + import * as i0 from "@angular/core"; + export class MyComponent {} + MyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyComponent, + isStandalone: true, + selector: "my-cmp", + template: "Hello" + }); + `; + + const result = transform('test.js', input, { link: true, advancedOptimizations: false }); + expect(result.code).toContain('i0.ɵɵdefineComponent'); + expect(result.code).not.toContain('i0.ɵɵngDeclareComponent'); + }); + + it('should generate a decoded sourcemap when sourcemap option is enabled', () => { + const input = ` + import * as i0 from "@angular/core"; + export class MyDirective {} + MyDirective.ɵdir = i0.ɵɵngDeclareDirective({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyDirective, + selector: "[my-dir]" + }); + `; + + const result = transform('test.js', input, { + link: true, + advancedOptimizations: false, + sourcemap: true, + }); + expect(result.map).toBeDefined(); + expect(result.map?.version).toBe(3); + expect(result.map?.sources).toContain('test.js'); + }); + + it('should link ɵɵngDeclareClassMetadataAsync with parenthesized resolveMetadata return', () => { + const input = ` + import * as i0 from "@angular/core"; + export class DeferredFixture {} + i0.ɵɵngDeclareClassMetadataAsync({ + minVersion: "18.0.0", + version: "22.1.7", + ngImport: i0, + type: DeferredFixture, + resolveDeferredDeps: () => [], + resolveMetadata: () => ({ + decorators: [], + ctorParameters: null, + propDecorators: null, + }), + }); + `; + + const result = transform('test.js', input, { link: true, advancedOptimizations: false }); + expect(result.code).toContain('ɵsetClassMetadataAsync'); + expect(result.code).not.toContain('ɵɵngDeclareClassMetadataAsync'); + }); +}); diff --git a/packages/angular/build/src/tools/angular/linker/string-ast-factory.ts b/packages/angular/build/src/tools/angular/linker/string-ast-factory.ts new file mode 100644 index 000000000000..a703856c39bd --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/string-ast-factory.ts @@ -0,0 +1,335 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + AstFactory, + BinaryOperator, + LeadingComment, + ObjectLiteralProperty, + SourceMapRange, + TemplateLiteral, + UnaryOperator, + VariableDeclarationType, +} from '@angular/compiler-cli/src/ngtsc/translator'; +import type { + BuiltInType, + Parameter, +} from '@angular/compiler-cli/src/ngtsc/translator/src/api/ast_factory'; + +const OBJECT_LITERAL_PREFIX = '\0obj_'; + +/** + * An implementation of `AstFactory` that generates JavaScript code strings directly. + */ +export class StringAstFactory implements AstFactory { + constructor(private readonly sourceCode: string = '') {} + + private render(expr: unknown): string { + let rendered: string; + if (typeof expr === 'string') { + rendered = expr; + } else if ( + typeof expr === 'object' && + expr !== null && + typeof (expr as { start?: number; end?: number }).start === 'number' && + typeof (expr as { end?: number }).end === 'number' + ) { + const { start, end } = expr as { start: number; end: number }; + + rendered = this.sourceCode.slice(start, end); + } else { + rendered = String(expr); + } + + if (rendered.startsWith(OBJECT_LITERAL_PREFIX)) { + return rendered.slice(OBJECT_LITERAL_PREFIX.length); + } + + return rendered; + } + + /** + * Wraps an expression in parentheses if it has syntax or operator precedence + * traps when used as the receiver/callee of property access, element access, + * call chains, `new` expressions, or tagged templates. + * + * For example, arrow functions (`(() => {}).foo`), numbers (`(5).foo`), object + * literals (`({ a: 1 }).foo`), and unary operators (`(void 0)()`) require + * parenthesization when used as receivers. + */ + private wrapReceiver(receiver: unknown): string { + let rendered = this.render(receiver); + if ( + rendered.startsWith('function') || + rendered.startsWith('{') || + rendered.includes('=>') || + /^(?:typeof|void|delete|new|await|throw|return)\b/.test(rendered) || + /^[!~+-]/.test(rendered) || + /^\d/.test(rendered) + ) { + rendered = `(${rendered})`; + } + + return rendered; + } + + /** + * Wraps an expression in parentheses if it is an un-parenthesized complex + * operand (such as an un-parenthesized binary, logical, or assignment expression) + * to prevent operator precedence inversion when embedded inside an outer expression. + * + * Atomic expressions (identifiers, member/element access chains, and simple + * literals matching `/^[a-zA-Z0-9_$.[\]"'`]+$/`) and already-parenthesized + * expressions are returned as-is. + */ + private wrapOperand(expr: unknown): string { + const rendered = this.render(expr); + if ( + (rendered.startsWith('(') && rendered.endsWith(')')) || + /^[a-zA-Z0-9_$.[\]"'`]+$/.test(rendered) + ) { + return rendered; + } + + return `(${rendered})`; + } + + /** + * Attaching statement-level comments is a no-op in `StringAstFactory`. + * + * Why this is safe: + * - Load-bearing tree-shaking annotations (`@__PURE__` markers) are explicitly prepended by + * `createCallExpression` and `createCallChain` whenever `pure: true`. + * - In `@angular/compiler`, `LeadingComment` is only used for `@ts-ignore` (suppressing + * TypeScript checker errors in generated `.ts` code) and `webpackChunkName` (in dynamic + * imports), neither of which occur during `.js`/`.mjs` library partial linking. + */ + attachComments(_statement: string, _leadingComments: LeadingComment[]): void {} + + createArrayLiteral(elements: unknown[]): string { + return `[${elements.map((e) => this.render(e)).join(', ')}]`; + } + + createAssignment(target: unknown, operator: BinaryOperator, value: unknown): string { + return `(${this.render(target)} ${operator} ${this.render(value)})`; + } + + createBinaryExpression( + leftOperand: unknown, + operator: BinaryOperator, + rightOperand: unknown, + ): string { + return `(${this.wrapOperand(leftOperand)} ${operator} ${this.wrapOperand(rightOperand)})`; + } + + createBlock(body: string[]): string { + return `{\n${body.join('\n')}\n}`; + } + + createCallExpression(callee: unknown, args: unknown[], pure: boolean): string { + const annotation = pure ? '/*@__PURE__*/ ' : ''; + + return `${annotation}${this.wrapReceiver(callee)}(${args.map((a) => this.render(a)).join(', ')})`; + } + + createCallChain(callee: unknown, args: unknown[], pure: boolean, isOptional: boolean): string { + const annotation = pure ? '/*@__PURE__*/ ' : ''; + const operator = isOptional ? '?.' : ''; + + return `${annotation}${this.wrapReceiver(callee)}${operator}(${args.map((a) => this.render(a)).join(', ')})`; + } + + createConditional(condition: unknown, thenExpression: unknown, elseExpression: unknown): string { + return `(${this.render(condition)} ? ${this.render(thenExpression)} : ${this.render(elseExpression)})`; + } + + createElementAccess(expression: unknown, element: unknown): string { + return `${this.wrapReceiver(expression)}[${this.render(element)}]`; + } + + createElementAccessChain(expression: unknown, element: unknown, isOptional: boolean): string { + const operator = isOptional ? '?.' : ''; + + return `${this.wrapReceiver(expression)}${operator}[${this.render(element)}]`; + } + + createExpressionStatement(expression: unknown): string { + return `${this.render(expression)};`; + } + + createFunctionDeclaration( + functionName: string, + parameters: Parameter[], + body: string, + ): string { + const params = parameters.map((p) => p.name).join(', '); + + return `function ${functionName}(${params}) ${body}`; + } + + createFunctionExpression( + functionName: string | null, + parameters: Parameter[], + body: string, + ): string { + const name = functionName ? ` ${functionName}` : ''; + const params = parameters.map((p) => p.name).join(', '); + + return `function${name}(${params}) ${body}`; + } + + createArrowFunctionExpression(parameters: Parameter[], body: unknown): string { + const params = parameters.map((p) => p.name).join(', '); + const isObjectLiteral = typeof body === 'string' && body.startsWith(OBJECT_LITERAL_PREFIX); + const renderedBody = this.render(body); + const formattedBody = isObjectLiteral ? `(${renderedBody})` : renderedBody; + + return `(${params}) => ${formattedBody}`; + } + + createDynamicImport(url: unknown): string { + return `import(${this.render(url)})`; + } + + createIdentifier(name: string): string { + return name; + } + + createIfStatement( + condition: unknown, + thenStatement: string, + elseStatement: string | null, + ): string { + const elseClause = elseStatement ? ` else ${elseStatement}` : ''; + + return `if (${this.render(condition)}) ${thenStatement}${elseClause}`; + } + + createLiteral(value: string | number | boolean | null | undefined): string { + return typeof value === 'string' ? JSON.stringify(value) : String(value); + } + + createNewExpression(expression: unknown, args: unknown[]): string { + return `new ${this.wrapReceiver(expression)}(${args.map((a) => this.render(a)).join(', ')})`; + } + + createObjectLiteral(properties: ObjectLiteralProperty[]): string { + const props = properties.map((p) => { + if (p.kind === 'spread') { + return `...${this.render(p.expression)}`; + } + + const key = p.quoted ? JSON.stringify(p.propertyName) : p.propertyName; + + return `${key}: ${this.render(p.value)}`; + }); + + return `${OBJECT_LITERAL_PREFIX}{\n${props.join(',\n')}\n}`; + } + + createParenthesizedExpression(expression: unknown): string { + return `(${this.render(expression)})`; + } + + createPropertyAccess(expression: unknown, propertyName: string): string { + return `${this.wrapReceiver(expression)}.${propertyName}`; + } + + createPropertyAccessChain( + expression: unknown, + propertyName: string, + isOptional: boolean, + ): string { + const operator = isOptional ? '?.' : '.'; + + return `${this.wrapReceiver(expression)}${operator}${propertyName}`; + } + + createReturnStatement(expression: unknown | null): string { + return `return${expression !== null ? ` ${this.render(expression)}` : ''};`; + } + + createTaggedTemplate(tag: unknown, template: TemplateLiteral): string { + return `${this.wrapReceiver(tag)}${this.createTemplateLiteral(template)}`; + } + + createTemplateLiteral(template: TemplateLiteral): string { + let result = '`'; + for (let i = 0; i < template.elements.length; i++) { + result += template.elements[i].raw; + if (i < template.expressions.length) { + result += `\${${this.render(template.expressions[i])}}`; + } + } + result += '`'; + + return result; + } + + createThrowStatement(expression: unknown): string { + return `throw ${this.render(expression)};`; + } + + createTypeOfExpression(expression: unknown): string { + return `typeof ${this.wrapOperand(expression)}`; + } + + createVoidExpression(expression: unknown): string { + return `void ${this.wrapOperand(expression)}`; + } + + createUnaryExpression(operator: UnaryOperator, operand: unknown): string { + return `${operator}${this.wrapOperand(operand)}`; + } + + createVariableDeclaration( + variableName: string, + initializer: unknown | null, + variableType: VariableDeclarationType, + _type: string | null = null, + ): string { + const init = initializer !== null ? ` = ${this.render(initializer)}` : ''; + + return `${variableType} ${variableName}${init};`; + } + + createRegularExpressionLiteral(body: string, flags: string | null): string { + return `/${body}/${flags ?? ''}`; + } + + createSpreadElement(expression: unknown): string { + return `...${this.render(expression)}`; + } + + createBuiltInType(_type: BuiltInType): string { + return ''; + } + + createExpressionType(_expression: unknown, _typeParams: string[] | null): string { + return ''; + } + + createArrayType(_elementType: string): string { + return ''; + } + + createMapType(_valueType: string): string { + return ''; + } + + transplantType(_type: string): string { + return ''; + } + + setSourceMapRange( + node: T, + _sourceMapRange: SourceMapRange | null, + ): T { + return node; + } +} diff --git a/packages/angular/build/src/tools/angular/linker/string-ast-factory_spec.ts b/packages/angular/build/src/tools/angular/linker/string-ast-factory_spec.ts new file mode 100644 index 000000000000..eb62a358dfcd --- /dev/null +++ b/packages/angular/build/src/tools/angular/linker/string-ast-factory_spec.ts @@ -0,0 +1,210 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { StringAstFactory } from './string-ast-factory'; + +describe('StringAstFactory', () => { + let factory: StringAstFactory; + + beforeEach(() => { + factory = new StringAstFactory('const foo = bar;'); + }); + + describe('source slicing (render)', () => { + it('should slice original source code when given an AST object with start and end offsets', () => { + const astNode = { start: 6, end: 9 }; + expect(factory.createExpressionStatement(astNode)).toBe('foo;'); + }); + }); + + describe('literals and identifiers', () => { + it('should correctly format string literals', () => { + expect(factory.createLiteral('hello')).toBe('"hello"'); + }); + + it('should correctly format numeric literals including NaN and Infinity', () => { + expect(factory.createLiteral(123)).toBe('123'); + expect(factory.createLiteral(NaN)).toBe('NaN'); + expect(factory.createLiteral(Infinity)).toBe('Infinity'); + }); + + it('should correctly format boolean literals', () => { + expect(factory.createLiteral(true)).toBe('true'); + expect(factory.createLiteral(false)).toBe('false'); + }); + + it('should correctly format null and undefined literals', () => { + expect(factory.createLiteral(null)).toBe('null'); + expect(factory.createLiteral(undefined)).toBe('undefined'); + }); + + it('should correctly create identifiers', () => { + expect(factory.createIdentifier('myVar')).toBe('myVar'); + }); + + it('should correctly format regular expression literals', () => { + expect(factory.createRegularExpressionLiteral('abc+', 'g')).toBe('/abc+/g'); + expect(factory.createRegularExpressionLiteral('abc+', null)).toBe('/abc+/'); + }); + }); + + describe('array and object literals', () => { + it('should correctly format array literals', () => { + expect(factory.createArrayLiteral(['1', '2', '3'])).toBe('[1, 2, 3]'); + }); + + it('should correctly format object literals with quoted and unquoted keys', () => { + const props = [ + { kind: 'property' as const, propertyName: 'foo', value: '1', quoted: false }, + { kind: 'property' as const, propertyName: 'foo-bar', value: '2', quoted: true }, + ]; + expect(factory.createObjectLiteral(props)).toContain('{\nfoo: 1,\n"foo-bar": 2\n}'); + }); + + it('should correctly format object literals with spread properties', () => { + const props = [ + { kind: 'property' as const, propertyName: 'foo', value: '1', quoted: false }, + { kind: 'spread' as const, expression: 'bar' }, + ]; + expect(factory.createObjectLiteral(props)).toContain('{\nfoo: 1,\n...bar\n}'); + }); + }); + + describe('property and element access', () => { + it('should correctly format property access and property access chains', () => { + expect(factory.createPropertyAccess('foo', 'bar')).toBe('foo.bar'); + expect(factory.createPropertyAccessChain('foo', 'bar', true)).toBe('foo?.bar'); + expect(factory.createPropertyAccessChain('foo', 'bar', false)).toBe('foo.bar'); + }); + + it('should correctly format element access and element access chains', () => { + expect(factory.createElementAccess('foo', '"bar"')).toBe('foo["bar"]'); + expect(factory.createElementAccessChain('foo', '"bar"', true)).toBe('foo?.["bar"]'); + expect(factory.createElementAccessChain('foo', '"bar"', false)).toBe('foo["bar"]'); + }); + + it('should parenthesize precedence-sensitive receivers in property and element access', () => { + expect(factory.createPropertyAccess('() => {}', 'bar')).toBe('(() => {}).bar'); + expect(factory.createPropertyAccess('5', 'bar')).toBe('(5).bar'); + expect(factory.createPropertyAccess('typeof x', 'bar')).toBe('(typeof x).bar'); + expect(factory.createElementAccess('() => {}', '"bar"')).toBe('(() => {})["bar"]'); + }); + }); + + describe('call expressions and chains', () => { + it('should format standard and pure call expressions', () => { + expect(factory.createCallExpression('foo', ['1', '2'], false)).toBe('foo(1, 2)'); + expect(factory.createCallExpression('foo', ['1', '2'], true)).toBe('/*@__PURE__*/ foo(1, 2)'); + }); + + it('should wrap arrow functions and function expressions in parentheses when used as callees', () => { + expect(factory.createCallExpression('() => {}', [], false)).toBe('(() => {})()'); + expect(factory.createCallExpression('function() {}', [], false)).toBe('(function() {})()'); + expect(factory.createCallChain('() => {}', [], false, true)).toBe('(() => {})?.()'); + expect(factory.createNewExpression('() => Foo', [])).toBe('new (() => Foo)()'); + }); + + it('should format optional call chains', () => { + expect(factory.createCallChain('foo', ['1'], false, true)).toBe('foo?.(1)'); + expect(factory.createCallChain('foo', ['1'], false, false)).toBe('foo(1)'); + }); + + it('should format new expressions', () => { + expect(factory.createNewExpression('Foo', ['1', '2'])).toBe('new Foo(1, 2)'); + }); + }); + + describe('operators and expressions', () => { + it('should format binary and assignment expressions with parentheses', () => { + expect(factory.createBinaryExpression('a', '+', 'b')).toBe('(a + b)'); + expect(factory.createBinaryExpression('a + b', '*', 'c + d')).toBe('((a + b) * (c + d))'); + expect(factory.createAssignment('a', '=', 'b')).toBe('(a = b)'); + }); + + it('should format conditional expressions with parentheses', () => { + expect(factory.createConditional('cond', 'trueVal', 'falseVal')).toBe( + '(cond ? trueVal : falseVal)', + ); + }); + + it('should format unary expressions', () => { + expect(factory.createUnaryExpression('!', 'foo')).toBe('!foo'); + expect(factory.createTypeOfExpression('foo')).toBe('typeof foo'); + expect(factory.createVoidExpression('foo')).toBe('void foo'); + expect(factory.createUnaryExpression('!', 'a + b')).toBe('!(a + b)'); + }); + }); + + describe('functions and statements', () => { + it('should format function declarations and expressions', () => { + const params = [ + { name: 'a', type: null }, + { name: 'b', type: null }, + ]; + expect(factory.createFunctionDeclaration('foo', params, '{ return a + b; }')).toBe( + 'function foo(a, b) { return a + b; }', + ); + expect(factory.createFunctionExpression('foo', params, '{ return a + b; }')).toBe( + 'function foo(a, b) { return a + b; }', + ); + expect(factory.createFunctionExpression(null, params, '{ return a + b; }')).toBe( + 'function(a, b) { return a + b; }', + ); + }); + + it('should format arrow functions', () => { + const params = [ + { name: 'a', type: null }, + { name: 'b', type: null }, + ]; + expect(factory.createArrowFunctionExpression(params, 'a + b')).toBe('(a, b) => a + b'); + }); + + it('should parenthesize object literal expression bodies in arrow functions even when containing semicolons', () => { + const params = [{ name: 'a', type: null }]; + const obj = factory.createObjectLiteral([ + { + kind: 'property', + propertyName: 'factory', + value: '() => { return new Service(); }', + quoted: false, + }, + ]); + expect(factory.createArrowFunctionExpression(params, obj)).toBe( + '(a) => ({\nfactory: () => { return new Service(); }\n})', + ); + }); + + it('should format statements', () => { + expect(factory.createBlock(['foo();', 'bar();'])).toBe('{\nfoo();\nbar();\n}'); + expect(factory.createIfStatement('cond', 'foo();', 'bar();')).toBe( + 'if (cond) foo(); else bar();', + ); + expect(factory.createIfStatement('cond', 'foo();', null)).toBe('if (cond) foo();'); + expect(factory.createReturnStatement('val')).toBe('return val;'); + expect(factory.createReturnStatement(null)).toBe('return;'); + expect(factory.createThrowStatement('err')).toBe('throw err;'); + expect(factory.createVariableDeclaration('x', '1', 'const')).toBe('const x = 1;'); + expect(factory.createVariableDeclaration('y', null, 'let')).toBe('let y;'); + }); + }); + + describe('template literals', () => { + it('should format template literals and tagged templates', () => { + const template = { + elements: [ + { raw: 'Hello ', cooked: 'Hello ', range: null }, + { raw: '!', cooked: '!', range: null }, + ], + expressions: ['name'], + }; + expect(factory.createTemplateLiteral(template)).toBe('`Hello ${name}!`'); + expect(factory.createTaggedTemplate('tag', template)).toBe('tag`Hello ${name}!`'); + }); + }); +}); diff --git a/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts new file mode 100644 index 000000000000..4dbaf010f3a2 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts @@ -0,0 +1,335 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; + +/** + * The name of the Angular platform that should be replaced within + * bootstrap call expressions to support AOT. + */ +const PLATFORM_BROWSER_DYNAMIC_NAME = 'platformBrowserDynamic'; + +export function replaceBootstrap( + getTypeChecker: () => ts.TypeChecker, +): ts.TransformerFactory { + return (context: ts.TransformationContext) => { + let bootstrapImport: ts.ImportDeclaration | undefined; + let bootstrapNamespace: ts.Identifier | undefined; + const replacedNodes: ts.Node[] = []; + const nodeFactory = context.factory; + + const visitNode: ts.Visitor = (node: ts.Node) => { + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) { + const target = node.expression; + if (target.text === PLATFORM_BROWSER_DYNAMIC_NAME) { + if (!bootstrapNamespace) { + bootstrapNamespace = nodeFactory.createUniqueName('__NgCli_bootstrap_'); + bootstrapImport = nodeFactory.createImportDeclaration( + undefined, + nodeFactory.createImportClause( + undefined, + undefined, + nodeFactory.createNamespaceImport(bootstrapNamespace), + ), + nodeFactory.createStringLiteral('@angular/platform-browser'), + ); + } + replacedNodes.push(target); + + return nodeFactory.updateCallExpression( + node, + nodeFactory.createPropertyAccessExpression(bootstrapNamespace, 'platformBrowser'), + node.typeArguments, + node.arguments, + ); + } + } + + return ts.visitEachChild(node, visitNode, context); + }; + + return (sourceFile: ts.SourceFile) => { + if (!sourceFile.text.includes(PLATFORM_BROWSER_DYNAMIC_NAME)) { + return sourceFile; + } + + let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context); + + if (bootstrapImport) { + // Remove any unused platform browser dynamic imports + const removals = elideImports( + updatedSourceFile, + replacedNodes, + getTypeChecker, + context.getCompilerOptions(), + ); + if (removals.size > 0) { + updatedSourceFile = ts.visitEachChild( + updatedSourceFile, + function visitForRemoval(node): ts.Node | undefined { + if (removals.has(node)) { + return undefined; + } + + return ts.isImportDeclaration(node) || + ts.isImportClause(node) || + ts.isNamedImports(node) + ? ts.visitEachChild(node, visitForRemoval, context) + : node; + }, + context, + ); + } + + // Add new platform browser import + return nodeFactory.updateSourceFile( + updatedSourceFile, + ts.setTextRange( + nodeFactory.createNodeArray([bootstrapImport, ...updatedSourceFile.statements]), + sourceFile.statements, + ), + ); + } else { + return updatedSourceFile; + } + }; + }; +} + +// Remove imports for which all identifiers have been removed. +// Needs type checker, and works even if it's not the first transformer. +// Works by removing imports for symbols whose identifiers have all been removed. +// Doesn't use the `symbol.declarations` because that previous transforms might have removed nodes +// but the type checker doesn't know. +// See https://github.com/Microsoft/TypeScript/issues/17552 for more information. +export function elideImports( + sourceFile: ts.SourceFile, + removedNodes: ts.Node[], + getTypeChecker: () => ts.TypeChecker, + compilerOptions: ts.CompilerOptions, +): Set { + const importNodeRemovals = new Set(); + + if (removedNodes.length === 0) { + return importNodeRemovals; + } + + const typeChecker = getTypeChecker(); + + // Collect all imports and used identifiers + const usedSymbols = new Set(); + const imports: ts.ImportDeclaration[] = []; + + ts.forEachChild(sourceFile, function visit(node) { + // Skip removed nodes. + if (removedNodes.includes(node)) { + return; + } + + // Consider types for 'implements' as unused. + // A HeritageClause token can also be an 'AbstractKeyword' + // which in that case we should not elide the import. + if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) { + return; + } + + // Record import and skip + if (ts.isImportDeclaration(node)) { + if (!node.importClause?.isTypeOnly) { + imports.push(node); + } + + return; + } + + // Type nodes do not need to be emitted when `emitDecoratorMetadata` is disabled. + // `ExpressionWithTypeArguments` is excluded as it also represents runtime values such as + // `class ... extends Base` heritage clauses and instantiation expressions (`Map`). + if ( + ts.isTypeNode(node) && + !ts.isExpressionWithTypeArguments(node) && + !compilerOptions.emitDecoratorMetadata + ) { + return; + } + + // Pure type declarations, type queries, ambient statements, external re-exports, + // and type-only exports are erased or do not reference local imports at runtime. + if ( + ts.isInterfaceDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isTypeParameterDeclaration(node) || + ts.isTypeQueryNode(node) || + ts.isImportTypeNode(node) || + ts.isIndexSignatureDeclaration(node) || + (ts.isStatement(node) && + ts.canHaveModifiers(node) && + ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword)) || + (ts.isExportDeclaration(node) && (node.isTypeOnly || node.moduleSpecifier !== undefined)) || + (ts.isExportSpecifier(node) && node.isTypeOnly) + ) { + return; + } + + let symbol: ts.Symbol | undefined; + switch (node.kind) { + case ts.SyntaxKind.Identifier: + if (node.parent && ts.isShorthandPropertyAssignment(node.parent)) { + const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(node.parent); + if (shorthandSymbol) { + symbol = shorthandSymbol; + } + } else { + symbol = typeChecker.getSymbolAtLocation(node); + } + break; + case ts.SyntaxKind.ExportSpecifier: + symbol = typeChecker.getExportSpecifierLocalTargetSymbol(node as ts.ExportSpecifier); + break; + case ts.SyntaxKind.ShorthandPropertyAssignment: + symbol = typeChecker.getShorthandAssignmentValueSymbol(node); + break; + } + + if (symbol) { + usedSymbols.add(symbol); + } + + ts.forEachChild(node, visit); + }); + + if (imports.length === 0) { + return importNodeRemovals; + } + + /** + * Determines how an imported binding should be handled: + * - `keep`: the binding is still referenced. + * - `value`: the binding is a runtime value that is no longer referenced. + * - `type`: the binding does not exist at runtime and is always elided by TypeScript. + */ + const getRemovalKind = (node: ts.Identifier): 'keep' | 'value' | 'type' => { + // Do not remove JSX factory imports + if (node.text === compilerOptions.jsxFactory) { + return 'keep'; + } + + const symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return 'keep'; + } + + // Note: with `verbatimModuleSyntax`, TypeScript reports an error for imports of non-value aliases + // that do not use a `type` modifier (TS1484/TS1485), so no special handling is needed for it. + if ((symbol.flags & ts.SymbolFlags.Alias) !== 0 && !isValueAlias(symbol, typeChecker)) { + return 'type'; + } + + return usedSymbols.has(symbol) ? 'keep' : 'value'; + }; + + for (const node of imports) { + if (!node.importClause) { + // "import 'abc';" + continue; + } + + const namedBindings = node.importClause.namedBindings; + + if (namedBindings && ts.isNamespaceImport(namedBindings)) { + // "import * as XYZ from 'abc';" + if (getRemovalKind(namedBindings.name) !== 'keep') { + importNodeRemovals.add(node); + } + } else { + const specifierNodeRemovals = []; + let clausesCount = 0; + // TypeScript skips its own import elision for declarations replaced by a transformer. + // A declaration is therefore only partially rewritten when a runtime value import must be + // removed, or when it was already replaced by a previous transformer. Otherwise, it is left + // untouched so that TypeScript continues to elide any type-only specifiers itself. + let requiresRewrite = !ts.isParseTreeNode(node); + + // "import { XYZ, ... } from 'abc';" + if (namedBindings && ts.isNamedImports(namedBindings)) { + let removedClausesCount = 0; + clausesCount += namedBindings.elements.length; + + for (const specifier of namedBindings.elements) { + const removalKind = specifier.isTypeOnly ? 'type' : getRemovalKind(specifier.name); + if (removalKind !== 'keep') { + requiresRewrite ||= removalKind === 'value'; + removedClausesCount++; + // in case we don't have any more namedImports we should remove the parent ie the {} + const nodeToRemove = + clausesCount === removedClausesCount ? specifier.parent : specifier; + + specifierNodeRemovals.push(nodeToRemove); + } + } + } + + // "import XYZ from 'abc';" + if (node.importClause.name) { + clausesCount++; + + const removalKind = node.importClause.isTypeOnly + ? 'type' + : getRemovalKind(node.importClause.name); + if (removalKind !== 'keep') { + requiresRewrite ||= removalKind === 'value'; + specifierNodeRemovals.push(node.importClause.name); + } + } + + if (specifierNodeRemovals.length === clausesCount) { + importNodeRemovals.add(node); + } else if (requiresRewrite) { + for (const specifierNodeRemoval of specifierNodeRemovals) { + importNodeRemovals.add(specifierNodeRemoval); + } + } + } + } + + return importNodeRemovals; +} + +/** + * Determines whether an import alias resolves to a runtime value. Aliases that only resolve to + * types, or that pass through a type-only import or export declaration anywhere along the alias + * chain, are always elided by TypeScript. + */ +function isValueAlias(symbol: ts.Symbol, typeChecker: ts.TypeChecker): boolean { + const seen = new Set(); + let current = symbol; + + while ((current.flags & ts.SymbolFlags.Alias) !== 0) { + if (seen.has(current)) { + // Circular alias (a TypeScript error) — assume runtime value so we don't over-elide. + return true; + } + seen.add(current); + + if ( + current.declarations?.length && + current.declarations.every(ts.isTypeOnlyImportOrExportDeclaration) + ) { + return false; + } + + const next = typeChecker.getImmediateAliasedSymbol(current); + if (!next) { + // Unresolved alias (e.g., missing module) — assume runtime value so we don't over-elide. + return true; + } + current = next; + } + + return (current.flags & ts.SymbolFlags.Value) !== 0; +} diff --git a/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer_spec.ts b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer_spec.ts new file mode 100644 index 000000000000..cb81319e0db3 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer_spec.ts @@ -0,0 +1,103 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; +import { replaceBootstrap } from './jit-bootstrap-transformer'; + +describe('replaceBootstrap', () => { + function transformCode( + files: Record, + entryFile = '/project/src/main.ts', + ): string { + const compilerOptions: ts.CompilerOptions = { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ES2022, + moduleResolution: ts.ModuleResolutionKind.Bundler, + noLib: true, + }; + + const host: ts.CompilerHost = { + getSourceFile: (fileName, languageVersion) => + files[fileName] !== undefined + ? ts.createSourceFile(fileName, files[fileName], languageVersion, true) + : undefined, + getDefaultLibFileName: () => '/lib.d.ts', + writeFile: () => undefined, + getCurrentDirectory: () => '/project', + getCanonicalFileName: (fileName) => fileName, + useCaseSensitiveFileNames: () => true, + getNewLine: () => '\n', + fileExists: (fileName) => files[fileName] !== undefined, + readFile: (fileName) => files[fileName], + }; + + const program = ts.createProgram([entryFile], compilerOptions, host); + let output = ''; + const sourceFile = program.getSourceFile(entryFile); + expect(sourceFile).toBeDefined(); + + program.emit( + sourceFile, + (_fileName, text) => { + output = text; + }, + undefined, + false, + { before: [replaceBootstrap(() => program.getTypeChecker())] }, + ); + + return output; + } + + const platformBrowserDynamicStub = ` + export declare function platformBrowserDynamic(extraProviders?: unknown[]): { + bootstrapModule(moduleType: unknown): Promise; + }; + export const VERSION = '0.0.0'; + export interface PlatformHelper {} + `; + + it('replaces platformBrowserDynamic and removes its import when no other specifiers remain', () => { + const output = transformCode({ + '/project/node_modules/@angular/platform-browser-dynamic/index.d.ts': + platformBrowserDynamicStub, + '/project/src/app.module.ts': 'export class AppModule {}', + '/project/src/main.ts': ` + import { platformBrowserDynamic, PlatformHelper } from '@angular/platform-browser-dynamic'; + import { AppModule } from './app.module'; + + export { PlatformHelper }; + platformBrowserDynamic().bootstrapModule(AppModule); + `, + }); + + expect(output).toContain(`import * as __NgCli_bootstrap_1 from "@angular/platform-browser";`); + expect(output).toContain(`__NgCli_bootstrap_1.platformBrowser().bootstrapModule(AppModule);`); + expect(output).not.toContain('@angular/platform-browser-dynamic'); + }); + + it('removes only platformBrowserDynamic specifier when another runtime export from the same module is used', () => { + const output = transformCode({ + '/project/node_modules/@angular/platform-browser-dynamic/index.d.ts': + platformBrowserDynamicStub, + '/project/src/app.module.ts': 'export class AppModule {}', + '/project/src/main.ts': ` + import { platformBrowserDynamic, VERSION, PlatformHelper } from '@angular/platform-browser-dynamic'; + import { AppModule } from './app.module'; + + export type { PlatformHelper }; + export const version = VERSION; + platformBrowserDynamic().bootstrapModule(AppModule); + `, + }); + + expect(output).toContain(`import { VERSION } from '@angular/platform-browser-dynamic';`); + expect(output).not.toContain('PlatformHelper'); + expect(output).toContain(`__NgCli_bootstrap_1.platformBrowser().bootstrapModule(AppModule);`); + }); +}); diff --git a/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts b/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts new file mode 100644 index 000000000000..2a064ba63cb5 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts @@ -0,0 +1,308 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; +import { generateJitFileUri, generateJitInlineUri } from '../uri'; + +/** + * Creates a TypeScript Transformer to transform Angular Component resource references into + * static import statements. This transformer is used in Angular's JIT compilation mode to + * support processing of component resources. When in AOT mode, the Angular AOT compiler handles + * this processing and this transformer is not used. + * @param getTypeChecker A function that returns a TypeScript TypeChecker instance for the program. + * @returns A TypeScript transformer factory. + */ +export function createJitResourceTransformer( + getTypeChecker: () => ts.TypeChecker, +): ts.TransformerFactory { + return (context: ts.TransformationContext) => { + const typeChecker = getTypeChecker(); + const nodeFactory = context.factory; + const resourceImportDeclarations: ts.ImportDeclaration[] = []; + + const visitNode: ts.Visitor = (node: ts.Node) => { + if (ts.isClassDeclaration(node)) { + const decorators = ts.getDecorators(node); + + if (!decorators || decorators.length === 0) { + return node; + } + + return nodeFactory.updateClassDeclaration( + node, + [ + ...decorators.map((current) => + visitDecorator(nodeFactory, current, typeChecker, resourceImportDeclarations), + ), + ...(ts.getModifiers(node) ?? []), + ], + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ); + } + + return ts.visitEachChild(node, visitNode, context); + }; + + return (sourceFile) => { + const updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context); + + if (resourceImportDeclarations.length > 0) { + return nodeFactory.updateSourceFile( + updatedSourceFile, + ts.setTextRange( + nodeFactory.createNodeArray( + [...resourceImportDeclarations, ...updatedSourceFile.statements], + updatedSourceFile.statements.hasTrailingComma, + ), + updatedSourceFile.statements, + ), + updatedSourceFile.isDeclarationFile, + updatedSourceFile.referencedFiles, + updatedSourceFile.typeReferenceDirectives, + updatedSourceFile.hasNoDefaultLib, + updatedSourceFile.libReferenceDirectives, + ); + } else { + return updatedSourceFile; + } + }; + }; +} + +function visitDecorator( + nodeFactory: ts.NodeFactory, + node: ts.Decorator, + typeChecker: ts.TypeChecker, + resourceImportDeclarations: ts.ImportDeclaration[], +): ts.Decorator { + const origin = getDecoratorOrigin(node, typeChecker); + if (!origin || origin.module !== '@angular/core' || origin.name !== 'Component') { + return node; + } + + if (!ts.isCallExpression(node.expression)) { + return node; + } + + const decoratorFactory = node.expression; + const args = decoratorFactory.arguments; + if (args.length !== 1 || !ts.isObjectLiteralExpression(args[0])) { + // Unsupported component metadata + return node; + } + + const objectExpression = args[0]; + const styleReplacements: ts.Expression[] = []; + + // visit all properties + let properties = ts.visitNodes(objectExpression.properties, (node) => + ts.isObjectLiteralElementLike(node) + ? visitComponentMetadata(nodeFactory, node, styleReplacements, resourceImportDeclarations) + : node, + ) as ts.NodeArray; + + // replace properties with updated properties + if (styleReplacements.length > 0) { + const styleProperty = nodeFactory.createPropertyAssignment( + nodeFactory.createIdentifier('styles'), + nodeFactory.createArrayLiteralExpression(styleReplacements), + ); + + properties = nodeFactory.createNodeArray([...properties, styleProperty]); + } + + return nodeFactory.updateDecorator( + node, + nodeFactory.updateCallExpression( + decoratorFactory, + decoratorFactory.expression, + decoratorFactory.typeArguments, + [nodeFactory.updateObjectLiteralExpression(objectExpression, properties)], + ), + ); +} + +function visitComponentMetadata( + nodeFactory: ts.NodeFactory, + node: ts.ObjectLiteralElementLike, + styleReplacements: ts.Expression[], + resourceImportDeclarations: ts.ImportDeclaration[], +): ts.ObjectLiteralElementLike | undefined { + if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) { + return node; + } + + switch (node.name.text) { + case 'templateUrl': + // Only analyze string literals + if (!ts.isStringLiteralLike(node.initializer)) { + return node; + } + + return node.initializer.text.length === 0 + ? node + : nodeFactory.updatePropertyAssignment( + node, + nodeFactory.createIdentifier('template'), + createResourceImport( + nodeFactory, + generateJitFileUri(node.initializer.text, 'template'), + resourceImportDeclarations, + ), + ); + case 'styles': + if (ts.isStringLiteralLike(node.initializer)) { + styleReplacements.unshift( + createResourceImport( + nodeFactory, + generateJitInlineUri(node.initializer.text, 'style'), + resourceImportDeclarations, + ), + ); + + return undefined; + } + + if (ts.isArrayLiteralExpression(node.initializer)) { + const inlineStyles = ts.visitNodes(node.initializer.elements, (node) => { + if (!ts.isStringLiteralLike(node)) { + return node; + } + + return node.text.length === 0 + ? undefined // An empty inline style is equivalent to not having a style element + : createResourceImport( + nodeFactory, + generateJitInlineUri(node.text, 'style'), + resourceImportDeclarations, + ); + }) as ts.NodeArray; + + // Inline styles should be placed first + styleReplacements.unshift(...inlineStyles); + + // The inline styles will be added afterwards in combination with any external styles + return undefined; + } + + return node; + + case 'styleUrl': + if (ts.isStringLiteralLike(node.initializer)) { + styleReplacements.push( + createResourceImport( + nodeFactory, + generateJitFileUri(node.initializer.text, 'style'), + resourceImportDeclarations, + ), + ); + + return undefined; + } + + return node; + + case 'styleUrls': { + if (!ts.isArrayLiteralExpression(node.initializer)) { + return node; + } + + const externalStyles = ts.visitNodes(node.initializer.elements, (node) => { + if (!ts.isStringLiteralLike(node)) { + return node; + } + + return node.text + ? createResourceImport( + nodeFactory, + generateJitFileUri(node.text, 'style'), + resourceImportDeclarations, + ) + : undefined; + }) as ts.NodeArray; + + // External styles are applied after any inline styles + styleReplacements.push(...externalStyles); + + // The external styles will be added afterwards in combination with any inline styles + return undefined; + } + default: + // All other elements are passed through + return node; + } +} + +function createResourceImport( + nodeFactory: ts.NodeFactory, + url: string, + resourceImportDeclarations: ts.ImportDeclaration[], +): ts.Identifier { + const urlLiteral = nodeFactory.createStringLiteral(url); + + const importName = nodeFactory.createIdentifier( + `__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`, + ); + resourceImportDeclarations.push( + nodeFactory.createImportDeclaration( + undefined, + nodeFactory.createImportClause(undefined, importName, undefined), + urlLiteral, + ), + ); + + return importName; +} + +function getDecoratorOrigin( + decorator: ts.Decorator, + typeChecker: ts.TypeChecker, +): { name: string; module: string } | null { + if (!ts.isCallExpression(decorator.expression)) { + return null; + } + + let identifier: ts.Node; + let name = ''; + + if (ts.isPropertyAccessExpression(decorator.expression.expression)) { + identifier = decorator.expression.expression.expression; + name = decorator.expression.expression.name.text; + } else if (ts.isIdentifier(decorator.expression.expression)) { + identifier = decorator.expression.expression; + } else { + return null; + } + + // NOTE: resolver.getReferencedImportDeclaration would work as well but is internal + const symbol = typeChecker.getSymbolAtLocation(identifier); + if (symbol && symbol.declarations && symbol.declarations.length > 0) { + const declaration = symbol.declarations[0]; + let module: string; + + if (ts.isImportSpecifier(declaration)) { + name = (declaration.propertyName || declaration.name).text; + module = (declaration.parent.parent.parent.moduleSpecifier as ts.StringLiteral).text; + } else if (ts.isNamespaceImport(declaration)) { + // Use the name from the decorator namespace property access + module = (declaration.parent.parent.moduleSpecifier as ts.StringLiteral).text; + } else if (ts.isImportClause(declaration)) { + name = (declaration.name as ts.Identifier).text; + module = (declaration.parent.moduleSpecifier as ts.StringLiteral).text; + } else { + return null; + } + + return { name, module }; + } + + return null; +} diff --git a/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer.ts b/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer.ts new file mode 100644 index 000000000000..10d45d00d714 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer.ts @@ -0,0 +1,225 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { relative } from 'node:path/posix'; +import ts from 'typescript'; + +/** + * A transformer factory that adds a property to the lazy-loaded route object. + * This property is used to allow for the retrieval of the module path during SSR. + * + * @param compilerOptions The compiler options. + * @param compilerHost The compiler host. + * @returns A transformer factory. + * + * @example + * **Before:** + * ```ts + * const routes: Routes = [ + * { + * path: 'lazy', + * loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) + * } + * ]; + * ``` + * + * **After:** + * ```ts + * const routes: Routes = [ + * { + * path: 'lazy', + * loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule), + * ...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "./lazy/lazy.module.ts" }: {}) + * } + * ]; + * ``` + */ +export function lazyRoutesTransformer( + compilerOptions: ts.CompilerOptions, + compilerHost: ts.CompilerHost, +): ts.TransformerFactory { + const moduleResolutionCache = compilerHost.getModuleResolutionCache?.(); + assert( + typeof compilerOptions.basePath === 'string', + 'compilerOptions.basePath should be a string.', + ); + const basePath = compilerOptions.basePath; + + return (context: ts.TransformationContext) => { + const factory = context.factory; + + const visitor = (node: ts.Node): ts.Node => { + if (!ts.isObjectLiteralExpression(node)) { + // Not an object literal, so skip it. + return ts.visitEachChild(node, visitor, context); + } + + const loadFunction = getLoadComponentOrChildrenProperty(node)?.initializer; + // Check if the initializer is an arrow function or a function expression + if ( + !loadFunction || + (!ts.isArrowFunction(loadFunction) && !ts.isFunctionExpression(loadFunction)) + ) { + return ts.visitEachChild(node, visitor, context); + } + + let callExpression: ts.CallExpression | undefined; + + if (ts.isArrowFunction(loadFunction)) { + // Handle arrow functions: body can either be a block or a direct call expression + const body = loadFunction.body; + + if (ts.isBlock(body)) { + // Arrow function with a block: check the first statement for a return call expression + const firstStatement = body.statements[0]; + + if ( + firstStatement && + ts.isReturnStatement(firstStatement) && + firstStatement.expression && + ts.isCallExpression(firstStatement.expression) + ) { + callExpression = firstStatement.expression; + } + } else if (ts.isCallExpression(body)) { + // Arrow function with a direct call expression as its body + callExpression = body; + } + } else if (ts.isFunctionExpression(loadFunction)) { + // Handle function expressions: check for a return statement with a call expression + const returnExpression = loadFunction.body.statements.find( + ts.isReturnStatement, + )?.expression; + + if (returnExpression && ts.isCallExpression(returnExpression)) { + callExpression = returnExpression; + } + } + + if (!callExpression) { + return ts.visitEachChild(node, visitor, context); + } + + // Optionally check for the 'then' property access expression + const expression = callExpression.expression; + if ( + !ts.isCallExpression(expression) && + ts.isPropertyAccessExpression(expression) && + expression.name.text !== 'then' + ) { + return ts.visitEachChild(node, visitor, context); + } + + const importExpression = ts.isPropertyAccessExpression(expression) + ? expression.expression // Navigate to the underlying expression for 'then' + : callExpression; + + // Ensure the underlying expression is an import call + if ( + !ts.isCallExpression(importExpression) || + importExpression.expression.kind !== ts.SyntaxKind.ImportKeyword + ) { + return ts.visitEachChild(node, visitor, context); + } + + // Check if the argument to the import call is a string literal + const callExpressionArgument = importExpression.arguments[0]; + if (!ts.isStringLiteralLike(callExpressionArgument)) { + // Not a string literal, so skip it. + return ts.visitEachChild(node, visitor, context); + } + + const resolvedPath = ts.resolveModuleName( + callExpressionArgument.text, + node.getSourceFile().fileName, + compilerOptions, + compilerHost, + moduleResolutionCache, + )?.resolvedModule?.resolvedFileName; + + if (!resolvedPath) { + // Could not resolve the module, so skip it. + return ts.visitEachChild(node, visitor, context); + } + + const resolvedRelativePath = relative(basePath, resolvedPath); + + // Create the new property + // Example: `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" }: {})` + const newProperty = factory.createSpreadAssignment( + factory.createParenthesizedExpression( + factory.createConditionalExpression( + factory.createBinaryExpression( + factory.createBinaryExpression( + factory.createTypeOfExpression(factory.createIdentifier('ngServerMode')), + factory.createToken(ts.SyntaxKind.ExclamationEqualsEqualsToken), + factory.createStringLiteral('undefined'), + ), + factory.createToken(ts.SyntaxKind.AmpersandAmpersandToken), + factory.createIdentifier('ngServerMode'), + ), + factory.createToken(ts.SyntaxKind.QuestionToken), + factory.createObjectLiteralExpression([ + factory.createPropertyAssignment( + factory.createIdentifier('ɵentryName'), + factory.createStringLiteral(resolvedRelativePath), + ), + ]), + factory.createToken(ts.SyntaxKind.ColonToken), + factory.createObjectLiteralExpression([]), + ), + ), + ); + + // Add the new property to the object literal. + return factory.updateObjectLiteralExpression(node, [...node.properties, newProperty]); + }; + + return (sourceFile) => { + const text = sourceFile.text; + if (!text.includes('loadC')) { + // Fast check for 'loadComponent' and 'loadChildren'. + return sourceFile; + } + + return ts.visitEachChild(sourceFile, visitor, context); + }; + }; +} + +/** + * Retrieves the property assignment for the `loadComponent` or `loadChildren` property of a route object. + * + * @param node The object literal expression to search. + * @returns The property assignment if found, otherwise `undefined`. + */ +function getLoadComponentOrChildrenProperty( + node: ts.ObjectLiteralExpression, +): ts.PropertyAssignment | undefined { + let hasPathProperty = false; + let loadComponentOrChildrenProperty: ts.PropertyAssignment | undefined; + for (const prop of node.properties) { + if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) { + continue; + } + + const propertyNameText = prop.name.text; + if (propertyNameText === 'path') { + hasPathProperty = true; + } else if (propertyNameText === 'loadComponent' || propertyNameText === 'loadChildren') { + loadComponentOrChildrenProperty = prop; + } + + if (hasPathProperty && loadComponentOrChildrenProperty) { + break; + } + } + + return loadComponentOrChildrenProperty; +} diff --git a/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer_spec.ts b/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer_spec.ts new file mode 100644 index 000000000000..4dd388f28eb1 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/lazy-routes-transformer_spec.ts @@ -0,0 +1,208 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; +import { lazyRoutesTransformer } from './lazy-routes-transformer'; + +describe('lazyRoutesTransformer', () => { + let program: ts.Program; + let compilerHost: ts.CompilerHost; + + beforeEach(() => { + // Mock a basic TypeScript program and compilerHost + program = ts.createProgram(['/project/src/dummy.ts'], { basePath: '/project/' }); + compilerHost = { + getNewLine: () => '\n', + fileExists: () => true, + readFile: () => '', + writeFile: () => undefined, + getCanonicalFileName: (fileName: string) => fileName, + getCurrentDirectory: () => '/project', + getDefaultLibFileName: () => 'lib.d.ts', + getSourceFile: () => undefined, + useCaseSensitiveFileNames: () => true, + resolveModuleNames: (moduleNames, containingFile) => + moduleNames.map( + (name) => + ({ + resolvedFileName: `/project/src/${name}.ts`, + }) as ts.ResolvedModule, + ), + }; + }); + + const transformSourceFile = (sourceCode: string): ts.SourceFile => { + const sourceFile = ts.createSourceFile( + '/project/src/dummy.ts', + sourceCode, + ts.ScriptTarget.ESNext, + true, + ts.ScriptKind.TS, + ); + + const transformer = lazyRoutesTransformer(program.getCompilerOptions(), compilerHost); + const result = ts.transform(sourceFile, [transformer]); + + return result.transformed[0]; + }; + + it('should return the same object when the routes array contains an empty object', () => { + const source = ` + const routes = [{}]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain(`const routes = [{}]`); + }); + + it('should add ɵentryName property to object with loadComponent and path (Arrow function)', () => { + const source = ` + const routes = [ + { + path: 'home', + loadComponent: () => import('./home').then(m => m.HomeComponent) + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : {})`, + ); + }); + + it('should add ɵentryName property to object with loadComponent and path (Arrow function with return)', () => { + const source = ` + const routes = [ + { + path: 'home', + loadComponent: () => { + return import('./home').then(m => m.HomeComponent); + } + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : {})`, + ); + }); + + it('should add ɵentryName property to object with loadComponent and path (Arrow function without .then)', () => { + const source = ` + const routes = [ + { + path: 'about', + loadComponent: () => import('./about') + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/about.ts" } : {})`, + ); + }); + + it('should add ɵentryName property to object with loadComponent using return and .then', () => { + const source = ` + const routes = [ + { + path: '', + loadComponent: () => { + return import('./home').then((m) => m.HomeComponent); + } + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : {})`, + ); + }); + + it('should add ɵentryName property to object with loadComponent and path (Function expression)', () => { + const source = ` + const routes = [ + { + path: 'home', + loadComponent: function () { return import('./home').then(m => m.HomeComponent) } + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/home.ts" } : {})`, + ); + }); + + it('should not modify unrelated object literals', () => { + const source = ` + const routes = [ + { + path: 'home', + component: HomeComponent + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).not.toContain(`ɵentryName`); + }); + + it('should ignore loadComponent without a valid import call', () => { + const source = ` + const routes = [ + { + path: 'home', + loadComponent: () => someFunction() + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).not.toContain(`ɵentryName`); + }); + + it('should resolve paths relative to basePath', () => { + const source = ` + const routes = [ + { + path: 'about', + loadChildren: () => import('./features/about').then(m => m.AboutModule) + } + ]; + `; + + const transformedSourceFile = transformSourceFile(source); + const transformedCode = ts.createPrinter().printFile(transformedSourceFile); + + expect(transformedCode).toContain( + `...(typeof ngServerMode !== "undefined" && ngServerMode ? { ɵentryName: "src/features/about.ts" } : {})`, + ); + }); +}); diff --git a/packages/angular/build/src/tools/angular/transformers/web-worker-transformer.ts b/packages/angular/build/src/tools/angular/transformers/web-worker-transformer.ts new file mode 100644 index 000000000000..329320843838 --- /dev/null +++ b/packages/angular/build/src/tools/angular/transformers/web-worker-transformer.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import ts from 'typescript'; + +/** + * Creates a TypeScript Transformer to process Worker and SharedWorker entry points and transform + * the URL instances to reference the built and bundled worker code. This uses a callback process + * similar to the component stylesheets to allow the main esbuild plugin to process files as needed. + * Unsupported worker expressions will be left in their origin form. + * @param getTypeChecker A function that returns a TypeScript TypeChecker instance for the program. + * @returns A TypeScript transformer factory. + */ +export function createWorkerTransformer( + fileProcessor: (file: string, importer: string) => string, +): ts.TransformerFactory { + return (context: ts.TransformationContext) => { + const nodeFactory = context.factory; + + const visitNode: ts.Visitor = (node: ts.Node) => { + // Check if the node is a valid new expression for a Worker or SharedWorker + // TODO: Add global scope check + if ( + !ts.isNewExpression(node) || + !ts.isIdentifier(node.expression) || + (node.expression.text !== 'Worker' && node.expression.text !== 'SharedWorker') + ) { + // Visit child nodes of non-Worker expressions + return ts.visitEachChild(node, visitNode, context); + } + + // Worker should have atleast one argument but not more than two + if (!node.arguments || node.arguments.length < 1 || node.arguments.length > 2) { + return node; + } + + // First argument must be a new URL expression + const workerUrlNode = node.arguments[0]; + // TODO: Add global scope check + if ( + !ts.isNewExpression(workerUrlNode) || + !ts.isIdentifier(workerUrlNode.expression) || + workerUrlNode.expression.text !== 'URL' + ) { + return node; + } + + // URL must have 2 arguments + if (!workerUrlNode.arguments || workerUrlNode.arguments.length !== 2) { + return node; + } + + // URL arguments must be a string and then `import.meta.url` + if ( + !ts.isStringLiteralLike(workerUrlNode.arguments[0]) || + !ts.isPropertyAccessExpression(workerUrlNode.arguments[1]) || + !ts.isMetaProperty(workerUrlNode.arguments[1].expression) || + workerUrlNode.arguments[1].name.text !== 'url' + ) { + return node; + } + + const filePath = workerUrlNode.arguments[0].text; + const importer = node.getSourceFile().fileName; + + // Process the file + const replacementPath = fileProcessor(filePath, importer); + + // Update if the path changed + if (replacementPath !== filePath) { + return nodeFactory.updateNewExpression( + node, + node.expression, + node.typeArguments, + // Update Worker arguments + ts.setTextRange( + nodeFactory.createNodeArray( + [ + nodeFactory.updateNewExpression( + workerUrlNode, + workerUrlNode.expression, + workerUrlNode.typeArguments, + // Update URL arguments + ts.setTextRange( + nodeFactory.createNodeArray( + [ + nodeFactory.createStringLiteral(replacementPath), + workerUrlNode.arguments[1], + ], + workerUrlNode.arguments.hasTrailingComma, + ), + workerUrlNode.arguments, + ), + ), + // Use the second Worker argument (options) if present. + // Otherwise create a default options object for module Workers. + node.arguments[1] ?? + nodeFactory.createObjectLiteralExpression([ + nodeFactory.createPropertyAssignment( + 'type', + nodeFactory.createStringLiteral('module'), + ), + ]), + ], + node.arguments.hasTrailingComma, + ), + node.arguments, + ), + ); + } else { + return node; + } + }; + + return (sourceFile) => { + // Skip transformer if there are no Workers + if (!sourceFile.text.includes('Worker')) { + return sourceFile; + } + + return ts.visitEachChild(sourceFile, visitNode, context); + }; + }; +} diff --git a/packages/angular/build/src/tools/angular/uri.ts b/packages/angular/build/src/tools/angular/uri.ts new file mode 100644 index 000000000000..0b662f58c670 --- /dev/null +++ b/packages/angular/build/src/tools/angular/uri.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * A string value representing the base namespace for Angular JIT mode related imports. + */ +const JIT_BASE_NAMESPACE = 'angular:jit'; + +/** + * A string value representing the namespace for Angular JIT mode related imports for + * Component styles. This namespace is used for both inline (`styles`) and external + * (`styleUrls`) styles. + */ +export const JIT_STYLE_NAMESPACE = `${JIT_BASE_NAMESPACE}:style` as const; + +/** + * A string value representing the namespace for Angular JIT mode related imports for + * Component templates. This namespace is currently only used for external (`templateUrl`) + * templates. + */ +export const JIT_TEMPLATE_NAMESPACE = `${JIT_BASE_NAMESPACE}:template` as const; + +/** + * A regular expression that can be used to match a Angular JIT mode namespace URI. + * It contains capture groups for the type (template/style), origin (file/inline), and specifier. + * The {@link parseJitUri} function can be used to parse and return an object representation of a JIT URI. + */ +export const JIT_NAMESPACE_REGEXP = new RegExp( + `^${JIT_BASE_NAMESPACE}:(template|style):(file|inline);(.*)$`, +); + +/** + * Generates an Angular JIT mode namespace URI for a given file. + * @param file The path of the file to be included. + * @param type The type of the file (`style` or `template`). + * @returns A string containing the full JIT namespace URI. + */ +export function generateJitFileUri(file: string, type: 'style' | 'template') { + return `${JIT_BASE_NAMESPACE}:${type}:file;${file}`; +} + +/** + * Generates an Angular JIT mode namespace URI for a given inline style or template. + * The provided content is base64 encoded and included in the URI. + * @param data The content to encode within the URI. + * @param type The type of the content (`style` or `template`). + * @returns A string containing the full JIT namespace URI. + */ +export function generateJitInlineUri(data: string | Uint8Array, type: 'style' | 'template') { + // Node.js types do not allow a string even though this is valid. + return `${JIT_BASE_NAMESPACE}:${type}:inline;${Buffer.from(data as Uint8Array).toString('base64')}`; +} + +/** + * Parses a string containing a JIT namespace URI. + * JIT namespace URIs are used to encode the information for an Angular component's stylesheets + * and templates when compiled in JIT mode. + * @param uri The URI to parse into its underlying components. + * @returns An object containing the namespace, type, origin, and specifier of the URI; + * `undefined` if not a JIT namespace URI. + */ +export function parseJitUri(uri: string) { + const matches = JIT_NAMESPACE_REGEXP.exec(uri); + if (!matches) { + return undefined; + } + + return { + namespace: `${JIT_BASE_NAMESPACE}:${matches[1]}`, + type: matches[1] as 'style' | 'template', + origin: matches[2] as 'file' | 'inline', + specifier: matches[3], + }; +} diff --git a/packages/angular/build/src/tools/esbuild/angular-localize-init-warning-plugin.ts b/packages/angular/build/src/tools/esbuild/angular-localize-init-warning-plugin.ts new file mode 100644 index 000000000000..d0aa9aff841d --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular-localize-init-warning-plugin.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; + +const NG_LOCALIZE_RESOLUTION = Symbol('NG_LOCALIZE_RESOLUTION'); + +/** + * This plugin addresses an issue where '@angular/localize/init' is directly imported, + * potentially resulting in undefined behavior. By detecting such imports, the plugin + * issues a warning and suggests including '@angular/localize/init' as a polyfill. + * + * @returns An esbuild plugin. + */ +export function createAngularLocalizeInitWarningPlugin(): Plugin { + return { + name: 'angular-localize-init-warning', + setup(build) { + build.onResolve({ filter: /^@angular\/localize\/init/ }, async (args) => { + if (args.pluginData?.[NG_LOCALIZE_RESOLUTION]) { + return null; + } + + if (args.namespace?.startsWith('angular:')) { + return null; + } + + const { importer, kind, resolveDir, namespace, pluginData = {} } = args; + pluginData[NG_LOCALIZE_RESOLUTION] = true; + + const result = await build.resolve(args.path, { + importer, + kind, + namespace, + pluginData, + resolveDir, + }); + + return { + ...result, + warnings: [ + ...result.warnings, + { + text: `Direct import of '@angular/localize/init' detected. This may lead to undefined behavior.`, + notes: [{ text: `Include '@angular/localize/init' as a polyfill instead.` }], + }, + ], + }; + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/angular/compilation-state.ts b/packages/angular/build/src/tools/esbuild/angular/compilation-state.ts new file mode 100644 index 000000000000..541f52bbca76 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/compilation-state.ts @@ -0,0 +1,143 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { CompilerOptions } from '@angular/compiler-cli'; +import type { AngularCompilation } from '../../angular/compilation'; + +export abstract class AngularCompilationContext { + abstract readonly compilation?: AngularCompilation; + abstract isPrimary(): this is PrimaryCompilationContext; + abstract readonly waitUntilReady: Promise; + abstract getCompilerOptions(): Promise; + abstract dispose(): Promise; + + createSecondaryContext(): AngularCompilationContext { + return new SecondaryCompilationContext(this); + } +} + +export class PrimaryCompilationContext extends AngularCompilationContext { + readonly #compilation: AngularCompilation; + #pendingCompilation = true; + #resolveCompilationReady: ((value: boolean) => void) | undefined; + #compilationReadyPromise: Promise | undefined; + #hasErrors = true; + + #compilerOptions: CompilerOptions | undefined; + #resolveCompilerOptions: ((options: CompilerOptions) => void) | undefined; + #compilerOptionsPromise: Promise | undefined; + + constructor(compilation: AngularCompilation) { + super(); + this.#compilation = compilation; + } + + override isPrimary(): this is PrimaryCompilationContext { + return true; + } + + override get compilation(): AngularCompilation { + return this.#compilation; + } + + override get waitUntilReady(): Promise { + if (!this.#pendingCompilation) { + return Promise.resolve(this.#hasErrors); + } + + this.#compilationReadyPromise ??= new Promise((resolve) => { + this.#resolveCompilationReady = resolve; + }); + + return this.#compilationReadyPromise; + } + + override getCompilerOptions(): Promise { + if (this.#compilerOptions) { + return Promise.resolve(this.#compilerOptions); + } + + if (!this.#pendingCompilation) { + return Promise.resolve({}); + } + + this.#compilerOptionsPromise ??= new Promise((resolve) => { + this.#resolveCompilerOptions = resolve; + }); + + return this.#compilerOptionsPromise; + } + + setCompilerOptions(options: CompilerOptions): void { + this.#compilerOptions = options; + this.#resolveCompilerOptions?.(options); + this.#resolveCompilerOptions = undefined; + this.#compilerOptionsPromise = undefined; + } + + markAsReady(hasErrors: boolean): void { + this.#hasErrors = hasErrors; + this.#resolveCompilationReady?.(hasErrors); + this.#resolveCompilationReady = undefined; + this.#compilationReadyPromise = undefined; + this.#pendingCompilation = false; + + if (this.#resolveCompilerOptions) { + this.#resolveCompilerOptions(this.#compilerOptions ?? {}); + this.#resolveCompilerOptions = undefined; + this.#compilerOptionsPromise = undefined; + } + } + + markAsInProgress(): void { + this.#pendingCompilation = true; + this.#compilerOptions = undefined; + } + + #disposal: Promise | undefined; + + override dispose(): Promise { + // Reuse any in progress disposal to ensure all callers can await completion + return (this.#disposal ??= this.#close()); + } + + async #close(): Promise { + this.markAsReady(true); + try { + await this.#compilation.close?.(); + } catch { + // Suppress closure errors to avoid unhandled rejections during teardown. + } + } +} + +export class SecondaryCompilationContext extends AngularCompilationContext { + constructor(private readonly primaryContext?: AngularCompilationContext) { + super(); + } + + override isPrimary(): this is PrimaryCompilationContext { + return false; + } + + override get compilation(): undefined { + return undefined; + } + + override get waitUntilReady(): Promise { + return this.primaryContext?.waitUntilReady ?? Promise.resolve(false); + } + + override getCompilerOptions(): Promise { + return this.primaryContext?.getCompilerOptions() ?? Promise.resolve({}); + } + + override async dispose(): Promise { + // No-op for secondary context to avoid disposing the primary compilation worker + } +} diff --git a/packages/angular/build/src/tools/esbuild/angular/compilation-state_spec.ts b/packages/angular/build/src/tools/esbuild/angular/compilation-state_spec.ts new file mode 100644 index 000000000000..8007427d497c --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/compilation-state_spec.ts @@ -0,0 +1,178 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { CompilerOptions } from '@angular/compiler-cli'; +import type { AngularCompilation } from '../../angular/compilation'; +import { PrimaryCompilationContext, SecondaryCompilationContext } from './compilation-state'; + +describe('compilation-state', () => { + let mockCompilation: jasmine.SpyObj; + + beforeEach(() => { + mockCompilation = jasmine.createSpyObj('AngularCompilation', [ + 'initialize', + 'close', + ]); + }); + + describe('PrimaryCompilationContext', () => { + it('identifies as primary and provides the underlying compilation', () => { + const context = new PrimaryCompilationContext(mockCompilation); + + expect(context.isPrimary()).toBe(true); + expect(context.compilation).toBe(mockCompilation); + }); + + it('resolves getCompilerOptions after setCompilerOptions is called', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + const options: CompilerOptions = { target: 9, allowJs: true }; + + context.setCompilerOptions(options); + + const resolved = await context.getCompilerOptions(); + expect(resolved).toEqual(options); + }); + + it('resolves pending getCompilerOptions when setCompilerOptions is called later', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + const options: CompilerOptions = { target: 9, allowJs: true }; + + const optionsPromise = context.getCompilerOptions(); + context.setCompilerOptions(options); + + const resolved = await optionsPromise; + expect(resolved).toEqual(options); + }); + + it('manages ready state lifecycle correctly', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + + // Initially in progress + const readyPromise = context.waitUntilReady; + context.markAsReady(false); + + const hasErrors = await readyPromise; + expect(hasErrors).toBe(false); + + // When already ready, immediately returns error state + expect(await context.waitUntilReady).toBe(false); + + // Mark in progress again + context.markAsInProgress(); + const secondReadyPromise = context.waitUntilReady; + context.markAsReady(true); + + expect(await secondReadyPromise).toBe(true); + }); + + it('closes compilation and marks ready with errors on dispose', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + + const readyPromise = context.waitUntilReady; + await context.dispose(); + + expect(mockCompilation.close).toHaveBeenCalledTimes(1); + expect(await readyPromise).toBe(true); + }); + + it('unblocks pending getCompilerOptions on markAsReady error', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + + const optionsPromise = context.getCompilerOptions(); + context.markAsReady(true); + + const options = await optionsPromise; + expect(options).toEqual({}); + }); + + it('returns empty options from getCompilerOptions when compilation is not pending and options are unset', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + + context.markAsReady(false); + + const options = await context.getCompilerOptions(); + expect(options).toEqual({}); + }); + + it('clears cached compiler options on markAsInProgress to wait for fresh options on rebuild', async () => { + const context = new PrimaryCompilationContext(mockCompilation); + const initialOptions: CompilerOptions = { target: 9, allowJs: false }; + context.setCompilerOptions(initialOptions); + context.markAsReady(false); + + expect(await context.getCompilerOptions()).toEqual(initialOptions); + + // Rebuild starts + context.markAsInProgress(); + + // Pending call should wait for new options rather than returning stale ones + const nextOptionsPromise = context.getCompilerOptions(); + const updatedOptions: CompilerOptions = { target: 10, allowJs: true }; + context.setCompilerOptions(updatedOptions); + + expect(await nextOptionsPromise).toEqual(updatedOptions); + }); + + it('creates a linked SecondaryCompilationContext', () => { + const context = new PrimaryCompilationContext(mockCompilation); + const secondary = context.createSecondaryContext(); + + expect(secondary).toBeInstanceOf(SecondaryCompilationContext); + expect(secondary.isPrimary()).toBe(false); + expect(secondary.compilation).toBeUndefined(); + }); + }); + + describe('SecondaryCompilationContext', () => { + it('identifies as non-primary and has undefined compilation', () => { + const primary = new PrimaryCompilationContext(mockCompilation); + const secondary = primary.createSecondaryContext(); + + expect(secondary.isPrimary()).toBe(false); + expect(secondary.compilation).toBeUndefined(); + }); + + it('delegates waitUntilReady to primary context', async () => { + const primary = new PrimaryCompilationContext(mockCompilation); + const secondary = primary.createSecondaryContext(); + + const secondaryReadyPromise = secondary.waitUntilReady; + primary.markAsReady(false); + + expect(await secondaryReadyPromise).toBe(false); + }); + + it('delegates getCompilerOptions to primary context', async () => { + const primary = new PrimaryCompilationContext(mockCompilation); + const secondary = primary.createSecondaryContext(); + const options: CompilerOptions = { target: 9, allowJs: false }; + + primary.setCompilerOptions(options); + + expect(await secondary.getCompilerOptions()).toEqual(options); + }); + + it('does not dispose primary compilation when secondary is disposed', async () => { + const primary = new PrimaryCompilationContext(mockCompilation); + const secondary = primary.createSecondaryContext(); + + await secondary.dispose(); + + expect(mockCompilation.close).not.toHaveBeenCalled(); + }); + + it('handles standalone instantiation with sensible defaults', async () => { + const standalone = new SecondaryCompilationContext(); + + expect(standalone.isPrimary()).toBe(false); + expect(standalone.compilation).toBeUndefined(); + expect(await standalone.waitUntilReady).toBe(false); + expect(await standalone.getCompilerOptions()).toEqual({}); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts b/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts new file mode 100644 index 000000000000..23e7e88dba74 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts @@ -0,0 +1,803 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + BuildFailure, + Loader, + Metafile, + OnStartResult, + OutputFile, + PartialMessage, + PartialNote, + Plugin, + PluginBuild, +} from 'esbuild'; +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import * as path from 'node:path'; +import { type PersistentCacheStore, createPersistentCacheStore } from '../../../utils/cache'; +import { maxTransformWorkers, useTypeChecking } from '../../../utils/environment-options'; +import { calculateHash, initializeHash } from '../../../utils/hash'; +import { + logCumulativeDurations, + profileAsync, + resetCumulativeDurations, +} from '../../../utils/profiling'; +import { AngularHostOptions } from '../../angular/angular-host'; +import { AngularCompilation, DiagnosticModes } from '../../angular/compilation'; +import { JavaScriptTransformer } from '../../javascript-transformer'; +import { LoadResultCache, createCachedLoad } from '../load-result-cache'; +import { AngularCompilationContext, PrimaryCompilationContext } from './compilation-state'; +import { ComponentStylesheetBundler } from './component-stylesheets'; +import { FileReferenceTracker } from './file-reference-tracker'; +import { setupJitPluginCallbacks } from './jit-plugin-callbacks'; +import { rewriteForBazel } from './rewrite-bazel-paths'; +import { SourceFileCache } from './source-file-cache'; + +export interface CompilerPluginOptions { + sourcemap: boolean | 'external'; + tsconfig: string; + jit?: boolean; + + /** + * Include class metadata and JIT information in built code. + * The Angular TestBed APIs require additional metadata for the Angular aspects of the application + * such as Components, Modules, Pipes, etc. + * TestBed may also leverage JIT capabilities during testing (e.g., overrideComponent). + */ + includeTestMetadata?: boolean; + + advancedOptimizations?: boolean; + thirdPartySourcemaps?: boolean; + fileReplacements?: Record; + sourceFileCache?: SourceFileCache; + loadResultCache?: LoadResultCache; + incremental: boolean; + externalRuntimeStyles?: boolean; + instrumentForCoverage?: (request: string) => boolean; + templateUpdates?: Map; + rootFiles?: string[]; +} + +// eslint-disable-next-line max-lines-per-function +export function createCompilerPlugin( + pluginOptions: CompilerPluginOptions, + compilationContextOrCompilation: + AngularCompilationContext | AngularCompilation | (() => Promise), + stylesheetBundler: ComponentStylesheetBundler, +): Plugin { + return { + name: 'angular-compiler', + // eslint-disable-next-line max-lines-per-function + async setup(build: PluginBuild): Promise { + let setupWarnings: PartialMessage[] | undefined = []; + let diagnosticsPromise: ReturnType | undefined; + const preserveSymlinks = build.initialOptions.preserveSymlinks; + + // Initialize a worker pool for JavaScript transformations. + // Webcontainers currently do not support this persistent cache store. + let cacheStore: PersistentCacheStore | undefined; + if (pluginOptions.sourceFileCache?.persistentCachePath && !process.versions.webcontainer) { + try { + cacheStore = await createPersistentCacheStore( + path.join(pluginOptions.sourceFileCache.persistentCachePath, 'angular-compiler'), + ); + } catch (e) { + setupWarnings.push({ + text: 'Unable to initialize JavaScript cache storage.', + location: null, + notes: [ + ...(e as Error).message + .split('\n') + .slice(1) + .map((text) => ({ text })), + { + text: 'This will not affect the build output content but may result in slower builds.', + }, + ], + }); + } + } + const javascriptTransformer = new JavaScriptTransformer( + { + sourcemap: !!pluginOptions.sourcemap, + thirdPartySourcemaps: pluginOptions.thirdPartySourcemaps, + advancedOptimizations: pluginOptions.advancedOptimizations, + jit: pluginOptions.jit || pluginOptions.includeTestMetadata, + maxConcurrency: maxTransformWorkers, + }, + cacheStore?.createCache('jstransformer'), + ); + + // Setup defines based on the values used by the Angular compiler-cli + build.initialOptions.define ??= {}; + build.initialOptions.define['ngI18nClosureMode'] ??= 'false'; + + // The factory is only relevant for compatibility purposes with the private API. + // TODO: Update private API in the next major to allow compilation function factory removal here. + const angularCompilationContext = + compilationContextOrCompilation instanceof AngularCompilationContext + ? compilationContextOrCompilation + : new PrimaryCompilationContext( + typeof compilationContextOrCompilation === 'function' + ? await compilationContextOrCompilation() + : compilationContextOrCompilation, + ); + const compilation: AngularCompilation | undefined = angularCompilationContext.compilation; + + // The in-memory cache of TypeScript file outputs will be used during the build in `onLoad` callbacks for TS files. + // A string value indicates direct TS/NG output and a Uint8Array indicates fully transformed code. + const typeScriptFileCache = + pluginOptions.sourceFileCache?.typeScriptFileCache ?? + new Map(); + + // The resources from component stylesheets and web workers that will be added to the build results output files + const additionalResults = new Map< + string, + { outputFiles?: OutputFile[]; metafile?: Metafile; errors?: PartialMessage[] } + >(); + + // Compilation is initially assumed to have errors until emitted + let hasCompilationErrors = true; + + // Determines if TypeScript should process JavaScript files based on tsconfig `allowJs` option + let shouldTsIgnoreJs = true; + // Determines if transpilation should be handle by TypeScript or esbuild + let useTypeScriptTranspilation = true; + + // To fully invalidate files, track resource referenced files and their referencing source + const referencedFileTracker = new FileReferenceTracker(); + + // eslint-disable-next-line max-lines-per-function + build.onStart(async () => { + hasCompilationErrors = true; + await initializeHash(); + + const result: OnStartResult = { + warnings: setupWarnings, + }; + + if (!angularCompilationContext.isPrimary()) { + hasCompilationErrors = await angularCompilationContext.waitUntilReady; + const compilerOptions = await angularCompilationContext.getCompilerOptions(); + shouldTsIgnoreJs = !compilerOptions.allowJs; + useTypeScriptTranspilation = !!compilerOptions['_useTypeScriptTranspilation']; + + return result; + } + + angularCompilationContext.markAsInProgress(); + const compilation = angularCompilationContext.compilation; + + // Reset debug performance tracking + resetCumulativeDurations(); + + // Update the reference tracker and generate a full set of modified files for the + // Angular compiler which does not have direct knowledge of transitive resource + // dependencies or web worker processing. + let modifiedFiles; + if (pluginOptions.sourceFileCache?.modifiedFiles.size) { + // TODO: Differentiate between changed input files and stale output files + modifiedFiles = referencedFileTracker.update(pluginOptions.sourceFileCache.modifiedFiles); + pluginOptions.sourceFileCache.invalidate(modifiedFiles); + // External runtime styles are invalidated and rebuilt at the beginning of a rebuild to avoid + // the need to execute the application bundler for component style only changes. + if (!pluginOptions.externalRuntimeStyles) { + stylesheetBundler.invalidate(modifiedFiles); + } + // Remove any stale additional results based on modified files + modifiedFiles.forEach((file) => additionalResults.delete(file)); + } + + if (compilation.update && pluginOptions.sourceFileCache?.modifiedFiles.size) { + await compilation.update(modifiedFiles ?? pluginOptions.sourceFileCache.modifiedFiles); + } + + // Create Angular compiler host options + const hostOptions: AngularHostOptions = { + fileReplacements: pluginOptions.fileReplacements, + modifiedFiles, + async transformStylesheet(data, containingFile, stylesheetFile, order, className) { + let stylesheetResult; + let resultSource = stylesheetFile ?? containingFile; + + // Stylesheet file only exists for external stylesheets + if (stylesheetFile) { + stylesheetResult = await stylesheetBundler.bundleFile(stylesheetFile); + } else { + stylesheetResult = await stylesheetBundler.bundleInline( + data, + containingFile, + // Inline stylesheets from a template style element are always CSS; Otherwise, use default. + containingFile.endsWith('.html') ? 'css' : undefined, + // When external runtime styles are enabled, an identifier for the style that does not change + // based on the content is required to avoid emitted JS code changes. Any JS code changes will + // invalid the output and force a full page reload for HMR cases. The containing file and order + // of the style within the containing file is used. + pluginOptions.externalRuntimeStyles + ? calculateHash(`${containingFile}${order ?? 0}${className ?? ''}`) + : undefined, + ); + // Adjust result source for inline styles. + // There may be multiple inline styles with the same containing file and to ensure that the results + // do not overwrite each other the result source identifier needs to be unique for each. The class + // name and order fields can be used for this. The structure is arbitrary as long as it is unique. + resultSource += `?class=${className}&order=${order}`; + } + + (result.warnings ??= []).push(...stylesheetResult.warnings); + if (stylesheetResult.errors) { + (result.errors ??= []).push(...stylesheetResult.errors); + + const { referencedFiles } = stylesheetResult; + if (referencedFiles) { + referencedFileTracker.add(containingFile, referencedFiles); + if (stylesheetFile) { + referencedFileTracker.add(stylesheetFile, referencedFiles); + } + } + + return ''; + } + + const { contents, outputFiles, metafile, referencedFiles } = stylesheetResult; + + additionalResults.set(resultSource, { + outputFiles, + metafile, + }); + + if (referencedFiles) { + referencedFileTracker.add(containingFile, referencedFiles); + if (stylesheetFile) { + // Angular AOT compiler needs modified direct resource files to correctly invalidate its analysis + referencedFileTracker.add(stylesheetFile, referencedFiles); + } + } + + return contents; + }, + processWebWorker(workerFile, containingFile) { + const fullWorkerPath = path.join(path.dirname(containingFile), workerFile); + // The synchronous API must be used due to the TypeScript compilation currently being + // fully synchronous and this process callback being called from within a TypeScript + // transformer. + const workerResult = bundleWebWorker(build, pluginOptions, fullWorkerPath); + + (result.warnings ??= []).push(...workerResult.warnings); + if (workerResult.errors.length > 0) { + (result.errors ??= []).push(...workerResult.errors); + // Track worker file errors to allow rebuilds on changes + referencedFileTracker.add( + containingFile, + workerResult.errors + .map((error) => error.location?.file) + .filter((file): file is string => !!file) + .map((file) => path.join(build.initialOptions.absWorkingDir ?? '', file)), + ); + additionalResults.set(fullWorkerPath, { errors: result.errors }); + + // Return the original path if the build failed + return workerFile; + } + + assert('outputFiles' in workerResult, 'Invalid web worker bundle result.'); + additionalResults.set(fullWorkerPath, { + outputFiles: workerResult.outputFiles, + metafile: workerResult.metafile, + }); + + referencedFileTracker.add( + containingFile, + Object.keys(workerResult.metafile.inputs).map((input) => + path.join(build.initialOptions.absWorkingDir ?? '', input), + ), + ); + + // Return bundled worker file entry name to be used in the built output + const workerCodeFile = workerResult.outputFiles.find((file) => + /^worker-[A-Z0-9]{8}.[cm]?js$/.test(path.basename(file.path)), + ); + assert(workerCodeFile, 'Web Worker bundled code file should always be present.'); + const workerCodePath = path.relative( + build.initialOptions.outdir ?? '', + workerCodeFile.path, + ); + + return workerCodePath.replaceAll('\\', '/'); + }, + }; + + // Initialize the Angular compilation for the current build. + // In watch mode, previous build state will be reused. + let referencedFiles; + let externalStylesheets; + try { + const initializationResult = await compilation.initialize( + pluginOptions.tsconfig, + hostOptions, + { + sourcemap: !!pluginOptions.sourcemap, + preserveSymlinks, + cachePath: pluginOptions.sourceFileCache?.persistentCachePath, + externalRuntimeStyles: pluginOptions.externalRuntimeStyles, + enableHmr: !!pluginOptions.templateUpdates, + instrumentForCoverage: !!pluginOptions.instrumentForCoverage, + includeTestMetadata: !!pluginOptions.includeTestMetadata, + customConditions: build.initialOptions.conditions, + rootFiles: pluginOptions.rootFiles, + basePath: build.initialOptions.absWorkingDir, + }, + ); + + if (initializationResult.warnings?.length) { + setupWarnings?.push(...initializationResult.warnings); + } + + angularCompilationContext.setCompilerOptions(initializationResult.compilerOptions); + shouldTsIgnoreJs = !initializationResult.compilerOptions.allowJs; + useTypeScriptTranspilation = + !!initializationResult.compilerOptions['_useTypeScriptTranspilation']; + referencedFiles = initializationResult.referencedFiles; + externalStylesheets = initializationResult.externalStylesheets; + + if (initializationResult.templateUpdates) { + // Propagate any template updates + initializationResult.templateUpdates.forEach((value, key) => + pluginOptions.templateUpdates?.set(key, value), + ); + } + } catch (error) { + (result.errors ??= []).push({ + text: 'Angular compilation initialization failed.', + location: null, + notes: [ + { + text: error instanceof Error ? (error.stack ?? error.message) : `${error}`, + location: null, + }, + ], + }); + + // Initialization failure prevents further compilation steps + hasCompilationErrors = true; + angularCompilationContext.markAsReady(true); + + return result; + } + + if (externalStylesheets) { + // Process any new external stylesheets + for (const [stylesheetFile, externalId] of externalStylesheets) { + await bundleExternalStylesheet( + stylesheetBundler, + stylesheetFile, + externalId, + result, + additionalResults, + ); + } + } + + // Update TypeScript file output cache for all affected files if not using on-demand transforms + if (!compilation.transformFile) { + try { + await profileAsync('NG_EMIT_TS', async () => { + for (const { filename, contents } of await compilation.emitAffectedFiles()) { + typeScriptFileCache.set(path.normalize(filename), contents); + } + }); + } catch (error) { + (result.errors ??= []).push({ + text: 'Angular compilation emit failed.', + location: null, + notes: [ + { + text: error instanceof Error ? (error.stack ?? error.message) : `${error}`, + location: null, + }, + ], + }); + } + + const diagnosticModes = useTypeChecking + ? DiagnosticModes.All + : DiagnosticModes.All & ~DiagnosticModes.Semantic; + diagnosticsPromise = compilation.diagnoseFiles(diagnosticModes).catch((error) => ({ + errors: [ + { + text: 'Angular compilation diagnostics failed.', + notes: [ + { + text: error instanceof Error ? (error.stack ?? error.message) : String(error), + }, + ], + }, + ], + })); + } + + // Add errors from failed additional results. + // This must be done after emit to capture latest web worker results. + for (const { errors } of additionalResults.values()) { + if (errors) { + (result.errors ??= []).push(...errors); + } + } + + // Store referenced files for updated file watching if enabled + if (pluginOptions.sourceFileCache) { + pluginOptions.sourceFileCache.referencedFiles = [ + ...referencedFiles, + ...referencedFileTracker.referencedFiles, + ]; + } + + hasCompilationErrors = !!result.errors?.length; + + // Reset the setup warnings so that they are only shown during the first build. + setupWarnings = undefined; + + angularCompilationContext.markAsReady(hasCompilationErrors); + + return result; + }); + + build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => { + const request = rewriteForBazel( + path.normalize(pluginOptions.fileReplacements?.[path.normalize(args.path)] ?? args.path), + ); + const isJS = /\.[cm]?js$/.test(request); + + // Skip TS load attempt if JS TypeScript compilation not enabled and file is JS + if (shouldTsIgnoreJs && isJS) { + return undefined; + } + + // The filename is currently used as a cache key. Since the cache is memory only, + // the options cannot change and do not need to be represented in the key. If the + // cache is later stored to disk, then the options that affect transform output + // would need to be added to the key as well as a check for any change of content. + let contents = typeScriptFileCache.get(request); + let directContents: string | undefined; + + if (contents === undefined && compilation?.transformFile) { + try { + directContents = await readFile(request, 'utf-8'); + const transformResult = await compilation.transformFile(request, directContents); + if (transformResult) { + contents = transformResult.contents; + if (transformResult.watchFiles) { + referencedFileTracker.add(request, transformResult.watchFiles); + } + } + } catch (error) { + return { + errors: [ + { + text: 'Angular compilation transform failed.', + location: { file: request }, + notes: [ + { + text: error instanceof Error ? (error.stack ?? error.message) : `${error}`, + location: null, + }, + ], + }, + ], + }; + } + } + + if (contents === undefined) { + // If the Angular compilation had errors the file may not have been emitted. + // To avoid additional errors about missing files, return empty contents. + if (hasCompilationErrors) { + return { contents: '', loader: 'js' }; + } + + // No TS result indicates the file is not part of the TypeScript program. + // If allowJs is enabled and the file is JS then defer to the next load hook. + if (!shouldTsIgnoreJs && isJS) { + return undefined; + } + + const diangosticRoot = build.initialOptions.absWorkingDir ?? ''; + + // Evaluate whether the file requires the Angular compiler transpilation. + // If not, issue a warning but allow bundler to process the file (no type-checking). + directContents ??= await readFile(request, 'utf-8'); + if (!requiresAngularCompiler(directContents)) { + return { + warnings: [createMissingFileDiagnostic(request, args.path, diangosticRoot, false)], + contents: directContents, + loader: 'ts', + resolveDir: path.dirname(request), + }; + } + + // Otherwise return an error + return { + errors: [createMissingFileDiagnostic(request, args.path, diangosticRoot, true)], + }; + } else if (typeof contents === 'string' && (useTypeScriptTranspilation || isJS)) { + // A string indicates untransformed output from the TS/NG compiler. + // This step is unneeded when using esbuild transpilation. + contents = await javascriptTransformer.transformData(request, contents, { + skipLinker: true, + sideEffects: () => hasSideEffects(request), + instrumentForCoverage: pluginOptions.instrumentForCoverage?.(request), + }); + + // Store as the returned Uint8Array to allow caching the fully transformed code + typeScriptFileCache.set(request, contents); + } + + let loader: Loader; + if (useTypeScriptTranspilation || isJS) { + // TypeScript has transpiled to JS or is already JS + loader = 'js'; + } else if (request.at(-1) === 'x') { + // TSX and TS have different syntax rules. Only set if input is a TSX file. + loader = 'tsx'; + } else { + // Otherwise, directly bundle TS + loader = 'ts'; + } + + return { + contents, + loader, + resolveDir: path.dirname(request), + }; + }); + + build.onLoad( + { filter: /\.[cm]?js$/ }, + createCachedLoad(pluginOptions.loadResultCache, async (args) => { + let request = rewriteForBazel(args.path); + if (pluginOptions.fileReplacements) { + const replacement = pluginOptions.fileReplacements[path.normalize(args.path)]; + if (replacement) { + request = path.normalize(replacement); + } + } + + return profileAsync( + 'NG_EMIT_JS*', + async () => { + const contents = await javascriptTransformer.transformFile(request, { + skipLinker: pluginOptions.jit, + sideEffects: () => hasSideEffects(request), + }); + + return { + contents, + loader: 'js', + resolveDir: path.dirname(request), + watchFiles: request !== args.path ? [request] : undefined, + }; + }, + true, + ); + }), + ); + + // Add a load handler if there are file replacement option entries for JSON files + if ( + pluginOptions.fileReplacements && + Object.keys(pluginOptions.fileReplacements).some((value) => value.endsWith('.json')) + ) { + build.onLoad( + { filter: /\.json$/ }, + createCachedLoad(pluginOptions.loadResultCache, async (args) => { + const replacement = pluginOptions.fileReplacements?.[path.normalize(args.path)]; + if (replacement) { + return { + contents: await readFile(path.normalize(replacement)), + loader: 'json' as const, + watchFiles: [replacement], + }; + } + + // If no replacement defined, let esbuild handle it directly + return null; + }), + ); + } + + // Setup bundling of component templates and stylesheets when in JIT mode + if (pluginOptions.jit) { + setupJitPluginCallbacks( + build, + stylesheetBundler, + additionalResults, + pluginOptions.loadResultCache, + ); + } + + build.onEnd(async (result) => { + // Ensure other compilations are unblocked if the main compilation throws during start + if (angularCompilationContext.isPrimary()) { + angularCompilationContext.markAsReady(hasCompilationErrors); + } + + for (const { outputFiles, metafile } of additionalResults.values()) { + // Add any additional output files to the main output files + if (outputFiles?.length) { + result.outputFiles?.push(...outputFiles); + } + + // Combine additional metafiles with main metafile + if (result.metafile && metafile) { + // Append the existing object, by appending to it we prevent unnecessary new objections creations with spread + // mitigating significant performance overhead for large apps. + // See: https://bugs.chromium.org/p/v8/issues/detail?id=11536 + Object.assign(result.metafile.inputs, metafile.inputs); + for (const [outputPath, output] of Object.entries(metafile.outputs)) { + // Two stylesheets can bundle to the same output file. Clone the inputs on first + // insert so colliding inputs can be unioned in place with Object.assign, keeping + // every input attributed without per-collision spread allocations and leaving the + // cached `additionalResults` metafile untouched. + const existing = result.metafile.outputs[outputPath]; + if (existing) { + Object.assign(existing.inputs, output.inputs); + } else { + result.metafile.outputs[outputPath] = { + ...output, + inputs: { ...output.inputs }, + }; + } + } + } + } + + logCumulativeDurations(); + + if (diagnosticsPromise) { + try { + const diagnostics = await diagnosticsPromise; + const errors = diagnostics.errors?.length ? diagnostics.errors : undefined; + const warnings = diagnostics.warnings?.length ? diagnostics.warnings : undefined; + + if (errors || warnings) { + return { errors, warnings }; + } + } finally { + diagnosticsPromise = undefined; + } + } + }); + + build.onDispose(() => { + void angularCompilationContext.dispose(); + void javascriptTransformer.close(); + void cacheStore?.close(); + }); + + /** + * Checks if the file has side-effects when `advancedOptimizations` is enabled. + */ + async function hasSideEffects(path: string): Promise { + if (!pluginOptions.advancedOptimizations) { + return undefined; + } + + const { sideEffects } = await build.resolve(path, { + kind: 'import-statement', + resolveDir: build.initialOptions.absWorkingDir ?? '', + }); + + return sideEffects; + } + }, + }; +} + +async function bundleExternalStylesheet( + stylesheetBundler: ComponentStylesheetBundler, + stylesheetFile: string, + externalId: string | boolean, + result: OnStartResult, + additionalResults: Map< + string, + { outputFiles?: OutputFile[]; metafile?: Metafile; errors?: PartialMessage[] } + >, +) { + const styleResult = await stylesheetBundler.bundleFile(stylesheetFile, externalId); + + (result.warnings ??= []).push(...styleResult.warnings); + if (styleResult.errors) { + (result.errors ??= []).push(...styleResult.errors); + } else { + const { outputFiles, metafile } = styleResult; + // Clear inputs to prevent triggering a rebuild of the application code for component + // stylesheet file only changes when the dev server enables the internal-only external + // stylesheet option. This does not affect builds since only the dev server can enable + // the internal option. + metafile.inputs = {}; + additionalResults.set(stylesheetFile, { + outputFiles, + metafile, + }); + } +} + +function bundleWebWorker( + build: PluginBuild, + pluginOptions: CompilerPluginOptions, + workerFile: string, +) { + try { + return build.esbuild.buildSync({ + ...build.initialOptions, + platform: 'browser', + write: false, + bundle: true, + metafile: true, + format: 'esm', + entryNames: 'worker-[hash]', + chunkNames: 'worker-chunk-[hash]', + entryPoints: [workerFile], + sourcemap: pluginOptions.sourcemap, + // Zone.js is not used in Web workers so no need to disable + supported: undefined, + // Plugins are not supported in sync esbuild calls + plugins: undefined, + }); + } catch (error) { + if (error && typeof error === 'object' && 'errors' in error && 'warnings' in error) { + return error as BuildFailure; + } + throw error; + } +} + +function createMissingFileDiagnostic( + request: string, + original: string, + root: string, + angular: boolean, +): PartialMessage { + const relativeRequest = path.relative(root, request); + const notes: PartialNote[] = []; + + if (angular) { + notes.push({ + text: + `Files containing Angular metadata ('@Component'/'@Directive'/etc.) must be part of the TypeScript compilation.` + + ` You can ensure the file is part of the TypeScript program via the 'files' or 'include' property.`, + }); + } else { + notes.push({ + text: + `The file will be bundled and included in the output but will not be type-checked at build time.` + + ` To remove this message you can add the file to the TypeScript program via the 'files' or 'include' property.`, + }); + } + + const relativeOriginal = path.relative(root, original); + if (relativeRequest !== relativeOriginal) { + notes.push({ + text: `File is requested from a file replacement of '${relativeOriginal}'.`, + }); + } + + const diagnostic = { + text: `File '${relativeRequest}' not found in TypeScript compilation.`, + notes, + }; + + return diagnostic; +} + +const POTENTIAL_METADATA_REGEX = /@angular\/core|@Component|@Directive|@Injectable|@Pipe|@NgModule/; + +function requiresAngularCompiler(contents: string): boolean { + return POTENTIAL_METADATA_REGEX.test(contents); +} diff --git a/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts new file mode 100644 index 000000000000..f8b048ce5459 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets.ts @@ -0,0 +1,338 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import path from 'node:path'; +import { MemoryCache } from '../../../utils/cache'; +import { createContentHash } from '../../../utils/hash'; +import { BundleContextResult, BundlerContext } from '../bundler-context'; +import { type BuildOutputFile, BuildOutputFileType } from '../bundler-files'; +import { MemoryLoadResultCache } from '../load-result-cache'; +import { + BundleStylesheetOptions, + createStylesheetBundleOptions, +} from '../stylesheets/bundle-options'; + +export type ComponentStylesheetResult = BundleContextResult & { + contents: string; + referencedFiles: Set | undefined; +}; + +/** + * Bundles component stylesheets. A stylesheet can be either an inline stylesheet that + * is contained within the Component's metadata definition or an external file referenced + * from the Component's metadata definition. + */ +export class ComponentStylesheetBundler { + readonly #fileContexts = new MemoryCache(); + readonly #inlineContexts = new MemoryCache(); + readonly #loadCache = new MemoryLoadResultCache(); + + /** + * @param options An object containing the stylesheet bundling options. + * @param defaultInlineLanguage The default language to use for inline component styles. + * @param incremental True if incremental watch mode is enabled. + */ + constructor( + private readonly options: BundleStylesheetOptions, + private readonly defaultInlineLanguage: string, + private readonly incremental: boolean, + ) {} + + /** + * Bundle a file-based component stylesheet for use within an AOT compiled Angular application. + * @param entry The file path of the stylesheet. + * @param externalId Either an external identifier string for initial bundling or a boolean for rebuilds, if external. + * @param direct If true, the output will be used directly by the builder; false if used inside the compiler plugin. + * @returns A component bundle result object. + */ + async bundleFile( + entry: string, + externalId?: string | boolean, + direct?: boolean, + ): Promise { + entry = path.normalize(entry); + + const bundlerContext = await this.#fileContexts.getOrCreate(entry, () => { + return new BundlerContext( + this.options.workspaceRoot, + this.incremental, + (loadCache) => { + const buildOptions = createStylesheetBundleOptions(this.options, loadCache); + if (externalId) { + assert( + typeof externalId === 'string', + 'Initial external component stylesheets must have a string identifier', + ); + + buildOptions.entryPoints = { [externalId]: entry }; + buildOptions.entryNames = '[name]'; + delete buildOptions.publicPath; + } else { + buildOptions.entryPoints = [entry]; + } + + // Angular encapsulation does not support nesting + // See: https://github.com/angular/angular/issues/58996 + buildOptions.supported ??= {}; + buildOptions.supported['nesting'] = false; + + return buildOptions; + }, + /* useContext */ false, + /* initialFilter */ undefined, + this.#loadCache, + ); + }); + + return this.extractResult( + await bundlerContext.bundle(), + bundlerContext.watchFiles, + !!externalId, + !!direct, + ); + } + + bundleAllFiles(external: boolean, direct: boolean) { + return Promise.all( + Array.from(this.#fileContexts.entries()).map(([entry]) => + this.bundleFile(entry, external, direct), + ), + ); + } + + async bundleInline( + data: string, + filename: string, + language = this.defaultInlineLanguage, + externalId?: string, + ): Promise { + filename = path.normalize(filename); + + // Use a hash of the inline stylesheet content to ensure a consistent identifier. External stylesheets will resolve + // to the actual stylesheet file path. + const hasher = createContentHash(); + hasher.update(data); + hasher.update(externalId ?? ''); + const id = hasher.digest(); + const entry = [language, id, filename].join(';'); + + const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => { + const namespace = 'angular:styles/component'; + + return new BundlerContext( + this.options.workspaceRoot, + this.incremental, + (loadCache) => { + const buildOptions = createStylesheetBundleOptions(this.options, loadCache, { + [entry]: data, + }); + if (externalId) { + buildOptions.entryPoints = { [externalId]: `${namespace};${entry}` }; + buildOptions.entryNames = '[name]'; + delete buildOptions.publicPath; + } else { + buildOptions.entryPoints = [`${namespace};${entry}`]; + } + + // Angular encapsulation does not support nesting + // See: https://github.com/angular/angular/issues/58996 + buildOptions.supported ??= {}; + buildOptions.supported['nesting'] = false; + + buildOptions.plugins.push({ + name: 'angular-component-styles', + setup(build) { + build.onResolve({ filter: /^angular:styles\/component;/ }, (args) => { + if (args.kind !== 'entry-point') { + return null; + } + + return { + path: entry, + namespace, + }; + }); + build.onLoad({ filter: /^css;/, namespace }, () => { + return { + contents: data, + loader: 'css', + resolveDir: path.dirname(filename), + }; + }); + }, + }); + + return buildOptions; + }, + /* useContext */ false, + /* initialFilter */ undefined, + this.#loadCache, + ); + }); + + const result = await bundlerContext.bundle(); + if (result.errors || result.warnings.length > 0) { + if (this.incremental && result.errors) { + bundlerContext.watchFiles.add( + path.isAbsolute(filename) ? filename : path.join(this.options.workspaceRoot, filename), + ); + } + for (const message of [...(result.errors ?? []), ...result.warnings]) { + for (const item of [message, ...(message.notes ?? [])]) { + if (item.location?.file?.startsWith('angular:styles/component:')) { + item.location.file = filename; + } + } + } + } + + // Extract the result of the bundling from the output files + return this.extractResult(result, bundlerContext.watchFiles, !!externalId, false); + } + + /** + * Invalidates both file and inline based component style bundling state for a set of modified files. + * @param files The group of files that have been modified + * @returns An array of file based stylesheet entries if any were invalidated; otherwise, undefined. + */ + invalidate(files: Iterable | ReadonlySet): string[] | undefined { + if (!this.incremental) { + return; + } + + const normalizedFiles = new Set(); + for (const file of files) { + const normalized = path.normalize(file); + normalizedFiles.add(normalized); + if (!path.isAbsolute(normalized)) { + normalizedFiles.add(path.normalize(path.join(this.options.workspaceRoot, normalized))); + } + } + + let entries: string[] | undefined; + + for (const [entry, bundler] of this.#fileContexts.entries()) { + if (bundler.invalidate(normalizedFiles)) { + entries ??= []; + entries.push(entry); + } + } + for (const [entry, bundler] of this.#inlineContexts.entries()) { + // Entry is format: [language, id, filename].join(';') + const firstSemi = entry.indexOf(';'); + const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1; + const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : ''; + if (filename && normalizedFiles.has(path.normalize(filename))) { + this.#inlineContexts.delete(entry); + void bundler.dispose().catch(() => {}); + } else { + bundler.invalidate(normalizedFiles); + } + } + + return entries; + } + + collectReferencedFiles(): string[] { + const files: string[] = []; + for (const context of this.#fileContexts.values()) { + files.push(...context.watchFiles); + } + for (const context of this.#inlineContexts.values()) { + files.push(...context.watchFiles); + } + + return files; + } + + async dispose(): Promise { + const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()]; + this.#fileContexts.clear(); + this.#inlineContexts.clear(); + this.#loadCache.clear(); + + await Promise.allSettled(contexts.map((context) => context.dispose())); + } + + private extractResult( + result: BundleContextResult, + referencedFiles: Set | undefined, + external: boolean, + direct: boolean, + ): ComponentStylesheetResult { + let contents = ''; + const outputFiles: BuildOutputFile[] = []; + + const { errors, warnings } = result; + if (errors) { + return { errors, warnings, referencedFiles, contents: '' }; + } + + for (const outputFile of result.outputFiles) { + const filename = path.basename(outputFile.path); + + if (outputFile.type === BuildOutputFileType.Media || filename.endsWith('.css.map')) { + // The output files could also contain resources (images/fonts/etc.) that were referenced and the map files. + + // Clone the output file to avoid amending the original path which would causes problems during rebuild. + const clonedOutputFile = outputFile.clone(); + + // Needed for Bazel as otherwise the files will not be written in the correct place, + // this is because esbuild will resolve the output file from the outdir which is currently set to `workspaceRoot` twice, + // once in the stylesheet and the other in the application code bundler. + // Ex: `../../../../../app.component.css.map`. + if (!direct) { + clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path); + } + + outputFiles.push(clonedOutputFile); + } else if (filename.endsWith('.css')) { + if (external) { + const clonedOutputFile = outputFile.clone(); + if (!direct) { + clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path); + } + outputFiles.push(clonedOutputFile); + contents = path.posix.join(this.options.publicPath ?? '', filename); + } else { + contents = outputFile.text; + } + } else { + throw new Error( + `Unexpected non CSS/Media file "${filename}" outputted during component stylesheet processing.`, + ); + } + } + + // Clone metafile to prevent mutation of the cached result by downstream plugins + const metafile = { + inputs: { ...result.metafile.inputs }, + outputs: Object.fromEntries( + Object.entries(result.metafile.outputs).map(([key, output]) => { + const cloned = { ...output, ['ng-component']: true }; + delete cloned.entryPoint; + + return [key, cloned]; + }), + ), + }; + + return { + errors, + warnings, + contents, + outputFiles, + metafile, + referencedFiles, + externalImports: result.externalImports, + platform: result.platform, + initialFiles: new Map(), + }; + } +} diff --git a/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts new file mode 100644 index 000000000000..0363f2f43ba9 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/component-stylesheets_spec.ts @@ -0,0 +1,87 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { initializeHash } from '../../../utils/hash'; +import { ComponentStylesheetBundler } from './component-stylesheets'; + +describe('ComponentStylesheetBundler', () => { + let tempRoot: string; + + beforeAll(async () => { + await initializeHash(); + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-component-stylesheets-')); + }); + + afterAll(async () => { + await rm(tempRoot, { force: true, recursive: true }); + }); + + it('uses the component filename instead of angular:styles/component virtual URI in bundleInline error locations', async () => { + const bundler = new ComponentStylesheetBundler( + { + workspaceRoot: tempRoot, + optimization: false, + inlineFonts: false, + sourcemap: false, + outputNames: { bundles: '[name]', media: 'media/[name]' }, + target: ['es2022'], + cacheOptions: { enabled: false, path: '', basePath: tempRoot }, + }, + 'css', + true, + ); + + const componentFile = join(tempRoot, 'src', 'lib', 'lib.component.ts'); + + try { + const result = await bundler.bundleInline( + '.icon { background: url("./missing.png"); }', + componentFile, + ); + + assert(result.errors, 'Expected bundleInline to report a resolution error'); + expect(result.errors.length).toBeGreaterThan(0); + expect(result.errors[0].location?.file).toBe(componentFile); + expect(result.referencedFiles).toContain(componentFile); + } finally { + await bundler.dispose(); + } + }); + + it('uses the component filename instead of angular:styles/component virtual URI in bundleInline warning locations', async () => { + const bundler = new ComponentStylesheetBundler( + { + workspaceRoot: tempRoot, + optimization: false, + inlineFonts: false, + sourcemap: false, + outputNames: { bundles: '[name]', media: 'media/[name]' }, + target: ['es2022'], + cacheOptions: { enabled: false, path: '', basePath: tempRoot }, + }, + 'css', + false, + ); + + const componentFile = join(tempRoot, 'src', 'lib', 'lib.component.ts'); + + try { + const result = await bundler.bundleInline('.box { color: red', componentFile); + + expect(result.warnings.length).toBeGreaterThan(0); + expect(result.warnings[0].location?.file).toBe(componentFile); + } finally { + await bundler.dispose(); + } + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/angular/file-reference-tracker.ts b/packages/angular/build/src/tools/esbuild/angular/file-reference-tracker.ts new file mode 100644 index 000000000000..7d420679e67a --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/file-reference-tracker.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { normalize } from 'node:path'; + +export class FileReferenceTracker { + #referencingFiles = new Map>(); + + get referencedFiles() { + return this.#referencingFiles.keys(); + } + + add(containingFile: string, referencedFiles: Iterable): void { + const normalizedContainingFile = normalize(containingFile); + for (const file of referencedFiles) { + const normalizedReferencedFile = normalize(file); + if (normalizedReferencedFile === normalizedContainingFile) { + // Containing file is already known to the AOT compiler + continue; + } + + const referencing = this.#referencingFiles.get(normalizedReferencedFile); + if (referencing === undefined) { + this.#referencingFiles.set(normalizedReferencedFile, new Set([normalizedContainingFile])); + } else { + referencing.add(normalizedContainingFile); + } + } + } + + /** + * + * @param changed The set of changed files. + */ + update(changed: Set): Set { + // Lazily initialized to avoid unneeded copying if there are no additions to return + let allChangedFiles: Set | undefined; + + // Add referencing files to fully notify the AOT compiler of required component updates + for (const modifiedFile of changed) { + const normalizedModifiedFile = normalize(modifiedFile); + const referencing = this.#referencingFiles.get(normalizedModifiedFile); + if (referencing) { + allChangedFiles ??= new Set(changed); + for (const referencingFile of referencing) { + allChangedFiles.add(referencingFile); + } + // Cleanup the stale record which will be updated by new resource transforms + this.#referencingFiles.delete(normalizedModifiedFile); + } + } + + return allChangedFiles ?? changed; + } +} diff --git a/packages/angular/build/src/tools/esbuild/angular/jit-plugin-callbacks.ts b/packages/angular/build/src/tools/esbuild/angular/jit-plugin-callbacks.ts new file mode 100644 index 000000000000..6b99b92dd1fa --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/jit-plugin-callbacks.ts @@ -0,0 +1,155 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile, OutputFile, PluginBuild } from 'esbuild'; +import { readFile } from 'node:fs/promises'; +import { dirname, join, relative } from 'node:path'; +import { + JIT_NAMESPACE_REGEXP, + JIT_STYLE_NAMESPACE, + JIT_TEMPLATE_NAMESPACE, + parseJitUri, +} from '../../angular/uri'; +import { LoadResultCache, createCachedLoad } from '../load-result-cache'; +import { ComponentStylesheetBundler } from './component-stylesheets'; + +/** + * Loads/extracts the contents from a load callback Angular JIT entry. + * An Angular JIT entry represents either a file path for a component resource or base64 + * encoded data for an inline component resource. + * @param entry The value that represents content to load. + * @param root The absolute path for the root of the build (typically the workspace root). + * @param skipRead If true, do not attempt to read the file; if false, read file content from disk. + * This option has no effect if the entry does not originate from a file. Defaults to false. + * @returns An object containing the absolute path of the contents and optionally the actual contents. + * For inline entries the contents will always be provided. + */ +async function loadEntry( + entry: string, + root: string, + skipRead?: boolean, +): Promise<{ path: string; contents?: string }> { + if (entry.startsWith('inline:')) { + const [importer, data] = entry.slice(7).split(';', 2); + + return { + path: join(root, importer), + contents: Buffer.from(data, 'base64').toString(), + }; + } + + const path = join(root, entry); + + return { + path, + contents: skipRead ? undefined : await readFile(path, 'utf-8'), + }; +} + +/** + * Sets up esbuild resolve and load callbacks to support Angular JIT mode processing + * for both Component stylesheets and templates. These callbacks work alongside the JIT + * resource TypeScript transformer to convert and then bundle Component resources as + * static imports. + * @param build An esbuild {@link PluginBuild} instance used to add callbacks. + * @param styleOptions The options to use when bundling stylesheets. + * @param additionalResultFiles A Map where stylesheet resources will be added. + */ +export function setupJitPluginCallbacks( + build: PluginBuild, + stylesheetBundler: ComponentStylesheetBundler, + additionalResultFiles: Map, + loadCache?: LoadResultCache, +): void { + const root = build.initialOptions.absWorkingDir ?? ''; + + // Add a resolve callback to capture and parse any JIT URIs that were added by the + // JIT resource TypeScript transformer. + // Resources originating from a file are resolved as relative from the containing file (importer). + build.onResolve({ filter: JIT_NAMESPACE_REGEXP }, (args) => { + const parsed = parseJitUri(args.path); + if (!parsed) { + return undefined; + } + + const { namespace, origin, specifier } = parsed; + + if (origin === 'file') { + return { + // Use a relative path to prevent fully resolved paths in the metafile (JSON stats file). + // This is only necessary for custom namespaces. esbuild will handle the file namespace. + path: relative(root, join(dirname(args.importer), specifier)), + namespace, + }; + } else { + // Inline data may need the importer to resolve imports/references within the content + const importer = relative(root, args.importer); + + return { + path: `inline:${importer};${specifier}`, + namespace, + }; + } + }); + + // Add a load callback to handle Component stylesheets (both inline and external) + build.onLoad( + { filter: /./, namespace: JIT_STYLE_NAMESPACE }, + createCachedLoad(loadCache, async (args) => { + // skipRead is used here because the stylesheet bundling will read a file stylesheet + // directly either via a preprocessor or esbuild itself. + const entry = await loadEntry(args.path, root, true /* skipRead */); + + let stylesheetResult; + + // Stylesheet contents only exist for internal stylesheets + if (entry.contents === undefined) { + stylesheetResult = await stylesheetBundler.bundleFile(entry.path); + } else { + stylesheetResult = await stylesheetBundler.bundleInline(entry.contents, entry.path); + } + + const { errors, warnings, referencedFiles } = stylesheetResult; + if (stylesheetResult.errors) { + return { + errors, + warnings, + watchFiles: referencedFiles && [...referencedFiles], + }; + } + + const { contents, outputFiles, metafile } = stylesheetResult; + + additionalResultFiles.set(entry.path, { outputFiles, metafile }); + + return { + errors, + warnings, + contents, + loader: 'text', + watchFiles: referencedFiles && [...referencedFiles], + }; + }), + ); + + // Add a load callback to handle Component templates + // NOTE: While this callback supports both inline and external templates, the transformer + // currently only supports generating URIs for external templates. + build.onLoad( + { filter: /./, namespace: JIT_TEMPLATE_NAMESPACE }, + createCachedLoad(loadCache, async (args) => { + const { contents, path } = await loadEntry(args.path, root); + + return { + contents, + loader: 'text', + watchFiles: [path], + }; + }), + ); +} diff --git a/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts b/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts new file mode 100644 index 000000000000..b7cd376d560e --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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, relative, sep } from 'node:path'; + +const bazelBinDirectory = process.env['BAZEL_BINDIR']; +const bazelExecRoot = process.env['JS_BINARY__EXECROOT']; +const execRootMarker = `${sep}execroot${sep}`; + +/** + * Sandboxed actions run in a copy of the execroot whose absolute path differs from + * `JS_BINARY__EXECROOT`, so the effective execroot is derived from the working directory. + */ +function effectiveExecRoot(): string | undefined { + const cwd = process.cwd(); + const markerIndex = cwd.indexOf(execRootMarker); + if (markerIndex === -1) { + return bazelExecRoot; + } + + const workspaceEnd = cwd.indexOf(sep, markerIndex + execRootMarker.length); + + return workspaceEnd === -1 ? cwd : cwd.slice(0, workspaceEnd); +} + +export function rewriteForBazel(path: string): string { + if (!bazelBinDirectory || !bazelExecRoot) { + return path; + } + + const execRoot = effectiveExecRoot() ?? bazelExecRoot; + + const fromExecRoot = relative(execRoot, path); + if (!fromExecRoot.startsWith('..')) { + return path; + } + + const fromBinDirectory = relative(bazelBinDirectory, path); + if (!fromBinDirectory.startsWith('..')) { + return join(execRoot, fromBinDirectory); + } + + // A path that realpath resolved out of a symlink-staged sandbox into the + // unsandboxed execroot: re-anchor its execroot-relative tail. + const markerIndex = path.indexOf(execRootMarker); + if (markerIndex !== -1) { + const tail = path.slice(markerIndex + execRootMarker.length); + const workspaceEnd = tail.indexOf(sep); + if (workspaceEnd !== -1) { + return join(execRoot, tail.slice(workspaceEnd + 1)); + } + } + + return path; +} diff --git a/packages/angular/build/src/tools/esbuild/angular/source-file-cache.ts b/packages/angular/build/src/tools/esbuild/angular/source-file-cache.ts new file mode 100644 index 000000000000..136fbb651ba2 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/source-file-cache.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 'node:path'; +import { MemoryLoadResultCache } from '../load-result-cache'; + +export class SourceFileCache { + readonly modifiedFiles = new Set(); + readonly typeScriptFileCache = new Map(); + readonly loadResultCache = new MemoryLoadResultCache(); + + referencedFiles?: readonly string[]; + + constructor(readonly persistentCachePath?: string) {} + + /** + * Releases all cached content. The cached data is only needed for incremental + * rebuilds and can include the emitted contents of every TypeScript file in the + * program. The cache is repopulated if a build is performed after this is called. + */ + clear(): void { + this.modifiedFiles.clear(); + this.typeScriptFileCache.clear(); + this.loadResultCache.clear(); + this.referencedFiles = undefined; + } + + invalidate(files: Iterable): boolean { + if (files !== this.modifiedFiles) { + this.modifiedFiles.clear(); + } + + const extraWatchFiles = new Set(this.referencedFiles?.map(path.normalize)); + + let invalid = false; + for (let file of files) { + file = path.normalize(file); + invalid = this.loadResultCache.invalidate(file) || invalid; + invalid = extraWatchFiles.has(file) || invalid; + this.modifiedFiles.add(file); + } + + return invalid; + } +} diff --git a/packages/angular/build/src/tools/esbuild/angular/source-file-cache_spec.ts b/packages/angular/build/src/tools/esbuild/angular/source-file-cache_spec.ts new file mode 100644 index 000000000000..1a3b2c402618 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/source-file-cache_spec.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { SourceFileCache } from './source-file-cache'; + +describe('SourceFileCache', () => { + let cache: SourceFileCache; + + beforeEach(() => { + cache = new SourceFileCache(); + }); + + it('should clean up all caches on clear()', async () => { + cache.typeScriptFileCache.set('/test/app.component.ts', 'console.log("test");'); + cache.modifiedFiles.add('/test/app.component.ts'); + cache.referencedFiles = ['/test/app.component.ts']; + await cache.loadResultCache.put('file:/test/app.component.ts', { + contents: 'test', + loader: 'js', + }); + + cache.clear(); + + expect(cache.typeScriptFileCache.size).toBe(0); + expect(cache.modifiedFiles.size).toBe(0); + expect(cache.referencedFiles).toBeUndefined(); + expect(cache.loadResultCache.get('file:/test/app.component.ts')).toBeUndefined(); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts new file mode 100644 index 000000000000..6cd2b09f5a67 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts @@ -0,0 +1,790 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuildOptions, Plugin } from 'esbuild'; +import assert from 'node:assert'; +import { extname, relative } from 'node:path'; +import type { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import { Platform } from '../../builders/application/schema'; +import { allowMangle } from '../../utils/environment-options'; +import { calculateHash } from '../../utils/hash'; +import { toPosixPath } from '../../utils/path'; +import { + SERVER_APP_ENGINE_MANIFEST_FILENAME, + SERVER_APP_MANIFEST_FILENAME, + SERVER_GENERATED_EXTERNALS, +} from '../../utils/server-rendering/manifest'; +import { AngularCompilationContext } from './angular/compilation-state'; +import { createCompilerPlugin } from './angular/compiler-plugin'; +import { ComponentStylesheetBundler } from './angular/component-stylesheets'; +import { SourceFileCache } from './angular/source-file-cache'; +import { createAngularLocalizeInitWarningPlugin } from './angular-localize-init-warning-plugin'; +import { BundlerOptionsFactory } from './bundler-context'; +import { createCompilerPluginOptions } from './compiler-plugin-options'; +import { createExternalPackagesPlugin } from './external-packages-plugin'; +import { createAngularLocaleDataPlugin } from './i18n-locale-plugin'; +import type { LoadResultCache } from './load-result-cache'; +import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin'; +import { + createPlatformServerDominoExposePlugin, + createPlatformServerDominoRedirectPlugin, +} from './platform-server-domino-plugin'; +import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin'; +import { createServerBundleMetadata } from './server-bundle-metadata-plugin'; +import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin'; +import { getFeatureSupport, isZonelessApp } from './utils'; +import { createVirtualModulePlugin } from './virtual-module-plugin'; +import { createWasmPlugin } from './wasm-plugin'; + +export function createBrowserCodeBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + sourceFileCache: SourceFileCache, + stylesheetBundler: ComponentStylesheetBundler, + angularCompilationContext: AngularCompilationContext, + templateUpdates: Map | undefined, +): BundlerOptionsFactory { + return (loadCache) => { + const { entryPoints, outputNames, polyfills } = options; + const zoneless = isZonelessApp(polyfills); + + const pluginOptions = createCompilerPluginOptions( + options, + sourceFileCache, + loadCache, + templateUpdates, + ); + + const buildOptions: BuildOptions = { + ...getEsBuildCommonOptions(options), + platform: 'browser', + // Note: `es2015` is needed for RxJS v6. If not specified, `module` would + // match and the ES5 distribution would be bundled and ends up breaking at + // runtime with the RxJS testing library. + // More details: https://github.com/angular/angular-cli/issues/25405. + mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'], + entryNames: outputNames.bundles, + entryPoints, + target, + supported: getFeatureSupport(zoneless), + }; + + if (options.disableCodeSplitting) { + // Splitting emits shared chunks that are read across chunk boundaries as live ESM bindings, + // which the unit-test runners' module loading does not reliably preserve. + buildOptions.splitting = false; + // In unit test builds, package.json "sideEffects": false annotations can cause esbuild + // to incorrectly elide statically-referenced barrel module bodies across multiple entry points. + buildOptions.ignoreAnnotations = true; + } + + buildOptions.plugins ??= []; + buildOptions.plugins.push( + createWasmPlugin({ allowAsync: zoneless, cache: loadCache }), + createAngularLocalizeInitWarningPlugin(), + createCompilerPlugin( + // JS/TS options + pluginOptions, + angularCompilationContext, + // Component stylesheet bundler + stylesheetBundler, + ), + ); + + if (options.plugins) { + buildOptions.plugins.push(...options.plugins); + } + + return buildOptions; + }; +} + +export function createBrowserPolyfillBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + sourceFileCache: SourceFileCache, + stylesheetBundler: ComponentStylesheetBundler, + angularCompilationContext: AngularCompilationContext, +): BuildOptions | BundlerOptionsFactory | undefined { + const namespace = 'angular:polyfills'; + const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions( + options, + namespace, + true, + sourceFileCache.loadResultCache, + ); + if (!polyfillBundleOptions) { + return; + } + + const { outputNames, polyfills } = options; + const hasTypeScriptEntries = polyfills?.some((entry) => /\.[cm]?tsx?$/.test(entry)); + + const buildOptions: BuildOptions = { + ...polyfillBundleOptions, + platform: 'browser', + // Note: `es2015` is needed for RxJS v6. If not specified, `module` would + // match and the ES5 distribution would be bundled and ends up breaking at + // runtime with the RxJS testing library. + // More details: https://github.com/angular/angular-cli/issues/25405. + mainFields: ['es2020', 'es2015', 'browser', 'module', 'main'], + entryNames: outputNames.bundles, + target, + entryPoints: { + 'polyfills': namespace, + }, + }; + + // Only add the Angular TypeScript compiler if TypeScript files are provided in the polyfills + if (hasTypeScriptEntries) { + buildOptions.plugins ??= []; + const pluginOptions = createCompilerPluginOptions( + options, + sourceFileCache, + sourceFileCache.loadResultCache, + ); + buildOptions.plugins.push( + createCompilerPlugin( + // JS/TS options + pluginOptions, + angularCompilationContext, + // Component stylesheet options are unused for polyfills but required by the plugin + stylesheetBundler, + ), + ); + } + + // Use an options factory to allow fully incremental bundling when no TypeScript files are present. + // The TypeScript compilation is not currently integrated into the bundler invalidation so + // cannot be used with fully incremental bundling yet. + return hasTypeScriptEntries ? buildOptions : () => buildOptions; +} + +export function createServerPolyfillBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + loadResultCache: LoadResultCache | undefined, +): BundlerOptionsFactory | undefined { + const serverPolyfills: string[] = []; + const polyfillsFromConfig = new Set(options.polyfills); + const isNodePlatform = options.ssrOptions?.platform !== Platform.Neutral; + + if (!isZonelessApp(options.polyfills)) { + serverPolyfills.push(isNodePlatform ? 'zone.js/node' : 'zone.js'); + } + + if ( + polyfillsFromConfig.has('@angular/localize') || + polyfillsFromConfig.has('@angular/localize/init') + ) { + serverPolyfills.push('@angular/localize/init'); + } + + serverPolyfills.push('@angular/platform-server/init'); + + const namespace = 'angular:polyfills-server'; + const polyfillBundleOptions = getEsBuildCommonPolyfillsOptions( + { + ...options, + polyfills: serverPolyfills, + }, + namespace, + false, + loadResultCache, + ); + + if (!polyfillBundleOptions) { + return; + } + + const jsBanner: string[] = []; + if (polyfillBundleOptions.external?.length) { + jsBanner.push(`globalThis['ngServerMode'] = true;`); + } + + if (isNodePlatform) { + // Note: Needed as esbuild does not provide require shims / proxy from ESModules. + // See: https://github.com/evanw/esbuild/issues/1921. + // Use an alias to avoid colliding with any `createRequire` import that may + // already exist in the bundled user code. ESBuild processes banner content + // as raw text outside of its module graph, so it cannot deduplicate or + // rename banner imports the way it does for user imports. Without the alias, + // a duplicate `import { createRequire }` binding would cause a runtime error. + jsBanner.push( + `import { createRequire as __ngCreateRequire } from 'node:module';`, + `globalThis['require'] ??= __ngCreateRequire(import.meta.url);`, + ); + } + + const buildOptions: BuildOptions = { + ...polyfillBundleOptions, + platform: isNodePlatform ? 'node' : 'neutral', + outExtension: { '.js': '.mjs' }, + // Note: `es2015` is needed for RxJS v6. If not specified, `module` would + // match and the ES5 distribution would be bundled and ends up breaking at + // runtime with the RxJS testing library. + // More details: https://github.com/angular/angular-cli/issues/25405. + mainFields: ['es2020', 'es2015', 'module', 'main'], + entryNames: '[name]', + banner: { + js: jsBanner.join('\n'), + }, + target, + entryPoints: { + 'polyfills.server': namespace, + }, + }; + + buildOptions.plugins ??= []; + buildOptions.plugins.push(createServerBundleMetadata(), createPlatformServerDominoExposePlugin()); + + return () => buildOptions; +} + +export function createServerMainCodeBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + sourceFileCache: SourceFileCache, + stylesheetBundler: ComponentStylesheetBundler, + angularCompilationContext: AngularCompilationContext, +): BundlerOptionsFactory { + const { + serverEntryPoint: mainServerEntryPoint, + workspaceRoot, + outputMode, + externalPackages, + ssrOptions, + polyfills, + } = options; + + assert( + mainServerEntryPoint, + 'createServerCodeBundleOptions should not be called without a defined serverEntryPoint.', + ); + + return (loadResultCache) => { + const pluginOptions = createCompilerPluginOptions(options, sourceFileCache, loadResultCache); + const mainServerNamespace = 'angular:main-server'; + const mainServerInjectManifestNamespace = 'angular:main-server-inject-manifest'; + const zoneless = isZonelessApp(polyfills); + const entryPoints: Record = { + 'main.server': mainServerNamespace, + }; + + const ssrEntryPoint = ssrOptions?.entry; + const isOldBehaviour = !outputMode; + + if (ssrEntryPoint && isOldBehaviour) { + // Old behavior: 'server.ts' was bundled together with the SSR (Server-Side Rendering) code. + // This approach combined server-side logic and rendering into a single bundle. + entryPoints['server'] = ssrEntryPoint; + } + + const buildOptions: BuildOptions = { + ...getEsBuildServerCommonOptions(options), + target, + banner: { + js: `import './polyfills.server.mjs';`, + }, + entryPoints, + supported: getFeatureSupport(zoneless), + }; + + buildOptions.plugins ??= []; + buildOptions.plugins.push( + createWasmPlugin({ allowAsync: zoneless, cache: loadResultCache }), + createAngularLocalizeInitWarningPlugin(), + createCompilerPlugin( + // JS/TS options + pluginOptions, + angularCompilationContext, + // Component stylesheet bundler + stylesheetBundler, + ), + ); + + if (!externalPackages) { + buildOptions.plugins.push(createRxjsEsmResolutionPlugin()); + } + + // Mark manifest and polyfills file as external as these are generated by a different bundle step. + (buildOptions.external ??= []).push(...SERVER_GENERATED_EXTERNALS); + const isNodePlatform = options.ssrOptions?.platform !== Platform.Neutral; + + if (!isNodePlatform) { + // `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client. + // Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms. + // Note: The framework already issues a warning when using XHR with SSR. + buildOptions.external.push('xhr2'); + } + + buildOptions.plugins.push( + createServerBundleMetadata(), + createPlatformServerDominoRedirectPlugin(), + createVirtualModulePlugin({ + namespace: mainServerInjectManifestNamespace, + cache: loadResultCache, + entryPointOnly: false, + loadContent: async () => { + const contents: string[] = [ + // Configure `@angular/ssr` manifest. + `import manifest from './${SERVER_APP_MANIFEST_FILENAME}';`, + `import { ɵsetAngularAppManifest } from '@angular/ssr';`, + `ɵsetAngularAppManifest(manifest);`, + ]; + + return { + contents: contents.join('\n'), + loader: 'js', + resolveDir: workspaceRoot, + }; + }, + }), + createVirtualModulePlugin({ + namespace: mainServerNamespace, + cache: loadResultCache, + loadContent: async () => { + const mainServerEntryPointJsImport = entryFileToWorkspaceRelative( + workspaceRoot, + mainServerEntryPoint, + ); + + const contents: string[] = [ + // Inject manifest + `import '${mainServerInjectManifestNamespace}';`, + + // Add @angular/ssr exports + `export { + ɵdestroyAngularServerApp, + ɵextractRoutesAndCreateRouteTree, + ɵgetOrCreateAngularServerApp, + } from '@angular/ssr';`, + + // Need for HMR + `export { ɵresetCompiledComponents } from '@angular/core';`, + + // Re-export all symbols including default export from 'main.server.ts' + `export { default } from ${JSON.stringify(mainServerEntryPointJsImport)};`, + `export * from ${JSON.stringify(mainServerEntryPointJsImport)};`, + ]; + + return { + contents: contents.join('\n'), + loader: 'js', + resolveDir: workspaceRoot, + }; + }, + }), + ); + + if (options.plugins) { + buildOptions.plugins.push(...options.plugins); + } + + return buildOptions; + }; +} + +export function createSsrEntryCodeBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + sourceFileCache: SourceFileCache, + stylesheetBundler: ComponentStylesheetBundler, + angularCompilationContext: AngularCompilationContext, +): BundlerOptionsFactory { + const { workspaceRoot, ssrOptions, externalPackages } = options; + const serverEntryPoint = ssrOptions?.entry; + assert( + serverEntryPoint, + 'createSsrEntryCodeBundleOptions should not be called without a defined serverEntryPoint.', + ); + + return (loadResultCache) => { + const pluginOptions = createCompilerPluginOptions(options, sourceFileCache, loadResultCache); + const ssrEntryNamespace = 'angular:ssr-entry'; + const ssrInjectManifestNamespace = 'angular:ssr-entry-inject-manifest'; + const isNodePlatform = options.ssrOptions?.platform !== Platform.Neutral; + + const jsBanner: string[] = []; + if (options.externalDependencies?.length) { + jsBanner.push(`globalThis['ngServerMode'] = true;`); + } + + if (isNodePlatform) { + // Note: Needed as esbuild does not provide require shims / proxy from ESModules. + // See: https://github.com/evanw/esbuild/issues/1921. + // Use an alias to avoid colliding with any `createRequire` import that may + // already exist in the bundled user code. ESBuild processes banner content + // as raw text outside of its module graph, so it cannot deduplicate or + // rename banner imports the way it does for user imports. Without the alias, + // a duplicate `import { createRequire }` binding would cause a runtime error. + jsBanner.push( + `import { createRequire as __ngCreateRequire } from 'node:module';`, + `globalThis['require'] ??= __ngCreateRequire(import.meta.url);`, + ); + } + + const buildOptions: BuildOptions = { + ...getEsBuildServerCommonOptions(options), + target, + banner: { + js: jsBanner.join('\n'), + }, + entryPoints: { + 'server': ssrEntryNamespace, + }, + supported: getFeatureSupport(true), + }; + + buildOptions.plugins ??= []; + buildOptions.plugins.push( + createAngularLocalizeInitWarningPlugin(), + createCompilerPlugin( + // JS/TS options + pluginOptions, + angularCompilationContext, + // Component stylesheet bundler + stylesheetBundler, + ), + ); + + if (!externalPackages) { + buildOptions.plugins.push(createRxjsEsmResolutionPlugin()); + } + + // Mark manifest file as external. As this will be generated later on. + (buildOptions.external ??= []).push('*/main.server.mjs', ...SERVER_GENERATED_EXTERNALS); + + if (!isNodePlatform) { + // `@angular/platform-server` lazily depends on `xhr2` for XHR usage with the HTTP client. + // Since `xhr2` has Node.js dependencies, it cannot be used when targeting non-Node.js platforms. + // Note: The framework already issues a warning when using XHR with SSR. + buildOptions.external.push('xhr2'); + } + + buildOptions.plugins.push( + createServerBundleMetadata({ ssrEntryBundle: true }), + createVirtualModulePlugin({ + namespace: ssrInjectManifestNamespace, + cache: loadResultCache, + entryPointOnly: false, + loadContent: () => { + const contents: string[] = [ + // Configure `@angular/ssr` app engine manifest. + `import manifest from './${SERVER_APP_ENGINE_MANIFEST_FILENAME}';`, + `import { ɵsetAngularAppEngineManifest } from '@angular/ssr';`, + `ɵsetAngularAppEngineManifest(manifest);`, + ]; + + return { + contents: contents.join('\n'), + loader: 'js', + resolveDir: workspaceRoot, + }; + }, + }), + createVirtualModulePlugin({ + namespace: ssrEntryNamespace, + cache: loadResultCache, + loadContent: () => { + const serverEntryPointJsImport = entryFileToWorkspaceRelative( + workspaceRoot, + serverEntryPoint, + ); + const contents: string[] = [ + // Configure `@angular/ssr` app engine manifest. + `import '${ssrInjectManifestNamespace}';`, + + // Re-export all symbols including default export + `import * as server from ${JSON.stringify(serverEntryPointJsImport)};`, + `export * from ${JSON.stringify(serverEntryPointJsImport)};`, + // The below is needed to avoid + // `Import "default" will always be undefined because there is no matching export` warning when no default is present. + `const defaultExportName = 'default';`, + `export default server[defaultExportName];`, + + // Add @angular/ssr exports + `export { AngularAppEngine } from '@angular/ssr';`, + ]; + + return { + contents: contents.join('\n'), + loader: 'js', + resolveDir: workspaceRoot, + }; + }, + }), + ); + + if (options.plugins) { + buildOptions.plugins.push(...options.plugins); + } + + return buildOptions; + }; +} + +function getEsBuildServerCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions { + const isNodePlatform = options.ssrOptions?.platform !== Platform.Neutral; + + const commonOptions = getEsBuildCommonOptions(options); + commonOptions.define ??= {}; + commonOptions.define['ngServerMode'] = 'true'; + + return { + ...commonOptions, + platform: isNodePlatform ? 'node' : 'neutral', + outExtension: { '.js': '.mjs' }, + // Note: `es2015` is needed for RxJS v6. If not specified, `module` would + // match and the ES5 distribution would be bundled and ends up breaking at + // runtime with the RxJS testing library. + // More details: https://github.com/angular/angular-cli/issues/25405. + mainFields: ['es2020', 'es2015', 'module', 'main'], + entryNames: '[name]', + }; +} + +function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): BuildOptions { + const { + workspaceRoot, + outExtension, + optimizationOptions, + sourcemapOptions, + tsconfig, + externalDependencies, + outputNames, + preserveSymlinks, + jit, + loaderExtensions, + jsonLogs, + i18nOptions, + customConditions, + frameworkVersion, + } = options; + + // Ensure unique hashes for i18n translation changes when using post-process inlining. + // This hash value is added as a footer to each file and ensures that the output file names (with hashes) + // change when translation files have changed. If this is not done the post processed files may have + // different content but would retain identical production file names which would lead to browser caching problems. + let footer; + if (i18nOptions.shouldInline) { + // Update file hashes to include translation file content + const i18nHash = Object.values(i18nOptions.locales).reduce( + (data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'), + '', + ); + + footer = { js: `/**i18n:${calculateHash(i18nHash)}*/` }; + } + + // Core conditions that are always included + const conditions = [ + // Required to support rxjs 7.x which will use es5 code if this condition is not present + 'es2015', + 'es2020', + ]; + // The pre-linked code is not used with JIT for two reasons: + // 1) The pre-linked code may not have the metadata included that is required for JIT + // 2) The CLI is otherwise setup to use runtime linking for JIT to match the application template compilation + if (!jit) { + // The pre-linked package condition is based on the framework version. + // Currently this is specific to each patch version of the framework. + conditions.push('angular:linked-' + frameworkVersion); + } + + // Append custom conditions if present + if (customConditions) { + conditions.push(...customConditions); + } else { + // Include default conditions + conditions.push('module', optimizationOptions.scripts ? 'production' : 'development'); + } + + const plugins: Plugin[] = [ + createLoaderImportAttributePlugin(), + createSourcemapIgnorelistPlugin(), + ]; + + let packages: BuildOptions['packages'] = 'bundle'; + if (options.externalPackages) { + // Package files affected by a customized loader should not be implicitly marked as external + if ( + options.loaderExtensions || + options.plugins || + typeof options.externalPackages === 'object' + ) { + // Plugin must be added after custom plugins to ensure any added loader options are considered + plugins.push( + createExternalPackagesPlugin( + options.externalPackages !== true ? options.externalPackages : undefined, + ), + ); + + packages = 'bundle'; + } else { + // Safe to use the packages external option directly + packages = 'external'; + } + } + + return { + absWorkingDir: workspaceRoot, + format: 'esm', + bundle: true, + packages, + assetNames: outputNames.media, + conditions, + resolveExtensions: ['.ts', '.tsx', '.mjs', '.js', '.cjs'], + metafile: true, + legalComments: options.extractLicenses + ? 'none' + : optimizationOptions.scripts + ? 'eof' + : 'inline', + logLevel: options.verbose && !jsonLogs ? 'debug' : 'silent', + minifyIdentifiers: optimizationOptions.scripts && allowMangle, + minifySyntax: optimizationOptions.scripts, + minifyWhitespace: optimizationOptions.scripts, + pure: ['forwardRef'], + outdir: workspaceRoot, + outExtension: outExtension ? { '.js': `.${outExtension}` } : undefined, + sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), + sourcesContent: sourcemapOptions.sourcesContent, + splitting: true, + chunkNames: options.namedChunks ? '[name]-[hash]' : 'chunk-[hash]', + tsconfig, + external: externalDependencies ? [...externalDependencies] : undefined, + write: false, + preserveSymlinks, + define: { + ...options.define, + // Only set to false when script optimizations are enabled. It should not be set to true because + // Angular turns `ngDevMode` into an object for development debugging purposes when not defined + // which a constant true value would break. + ...(optimizationOptions.scripts ? { 'ngDevMode': 'false' } : undefined), + 'ngJitMode': jit ? 'true' : 'false', + 'ngServerMode': 'false', + 'ngHmrMode': options.templateUpdates ? 'true' : 'false', + }, + loader: loaderExtensions, + footer, + plugins, + }; +} + +function getEsBuildCommonPolyfillsOptions( + options: NormalizedApplicationBuildOptions, + namespace: string, + tryToResolvePolyfillsAsRelative: boolean, + loadResultCache: LoadResultCache | undefined, +): BuildOptions | undefined { + const { jit, workspaceRoot, i18nOptions, externalPackages } = options; + + let polyfills = options.polyfills ? [...options.polyfills] : []; + + const buildOptions = getEsBuildCommonOptions({ + ...options, + // If any polyfills are local files, disable external packages for the polyfills build. + // This ensures that local files are properly bundled. + externalPackages: polyfills.some(isLocalFile) ? false : externalPackages, + }); + buildOptions.splitting = false; + buildOptions.plugins ??= []; + + // Angular JIT mode requires the runtime compiler + if (jit) { + polyfills.unshift('@angular/compiler'); + } + + // Add Angular's global locale data if i18n options are present. + let needLocaleDataPlugin = false; + if (i18nOptions.shouldInline) { + // Remove localize polyfill when i18n inline transformation have been applied to all the packages. + polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize')); + } else if (i18nOptions.hasDefinedSourceLocale) { + // When not inlining and a source locale is present, use the source locale data directly + polyfills.unshift(`angular:locale/data:${i18nOptions.sourceLocale}`); + needLocaleDataPlugin = true; + } + if (needLocaleDataPlugin) { + buildOptions.plugins.unshift(createAngularLocaleDataPlugin()); + } + + if (polyfills.length === 0 && !i18nOptions.shouldInline && !i18nOptions.hasDefinedSourceLocale) { + return; + } + + buildOptions.plugins.push( + createVirtualModulePlugin({ + namespace, + cache: loadResultCache, + loadContent: async (_, build) => { + let polyfillPaths = polyfills; + + if (tryToResolvePolyfillsAsRelative) { + polyfillPaths = await Promise.all( + polyfills.map(async (path) => { + if (path.startsWith('zone.js') || !extname(path)) { + return path; + } + + const potentialPathRelative = './' + path; + const result = await build.resolve(potentialPathRelative, { + kind: 'import-statement', + resolveDir: workspaceRoot, + }); + + return result.path ? potentialPathRelative : path; + }), + ); + } + + // Generate module contents with an import statement per defined polyfill + let contents = polyfillPaths + .map((file) => `import ${JSON.stringify(toPosixPath(file))};`) + .join('\n'); + + // The below should be done after loading `$localize` as otherwise the locale will be overridden. + if (i18nOptions.shouldInline) { + // When inlining, a placeholder is used to allow the post-processing step to inject the $localize locale identifier. + contents += '(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n'; + } else if (i18nOptions.hasDefinedSourceLocale) { + // If not inlining translations and source locale is defined, inject the locale specifier. + contents += `(globalThis.$localize ??= {}).locale = "${i18nOptions.sourceLocale}";\n`; + } + + return { + contents, + loader: 'js', + resolveDir: workspaceRoot, + }; + }, + }), + ); + + return buildOptions; +} + +function entryFileToWorkspaceRelative(workspaceRoot: string, entryFile: string): string { + return './' + toPosixPath(relative(workspaceRoot, entryFile).replace(/\.[mc]?ts$/, '')); +} + +/** + * Determines if a polyfill path is a local file. + * A local file is defined as a path starting with a `.` or having a TypeScript/JavaScript extension. + * `zone.js` and its subpaths are specifically excluded and treated as packages. + * @param path The polyfill path to check. + * @returns true if the path is a local file; false otherwise. + */ +function isLocalFile(path: string): boolean { + if (path.startsWith('zone.js')) { + return false; + } + + return path[0] === '.' || /\.[mc]?[jt]sx?$/.test(path); +} diff --git a/packages/angular/build/src/tools/esbuild/budget-stats.ts b/packages/angular/build/src/tools/esbuild/budget-stats.ts new file mode 100644 index 000000000000..a14d9a24f1b6 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/budget-stats.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import type { BudgetStats } from '../../utils/bundle-calculator'; +import { type BuildOutputFile, BuildOutputFileType, type InitialFileRecord } from './bundler-files'; +import { getChunkNameFromMetafile } from './utils'; + +/** + * Generates a bundle budget calculator compatible stats object that provides + * the necessary information for the Webpack-based bundle budget code to + * interoperate with the esbuild-based builders. + * @param metafile The esbuild metafile of a build to use. + * @param initialFiles The records of all initial files of a build. + * @returns A bundle budget compatible stats object. + */ +export function generateBudgetStats( + metafile: Metafile, + outputFiles: BuildOutputFile[], + initialFiles: Map, +): BudgetStats { + const stats: Required = { + chunks: [], + assets: [], + }; + + for (const { path: file, size, type } of outputFiles) { + // Exclude server bundles + if (type === BuildOutputFileType.ServerApplication || type === BuildOutputFileType.ServerRoot) { + continue; + } + + if (!file.endsWith('.js') && !file.endsWith('.css')) { + continue; + } + + const initialRecord = initialFiles.get(file); + const name = initialRecord?.name ?? getChunkNameFromMetafile(metafile, file); + + stats.chunks.push({ + files: [file], + initial: !!initialRecord, + names: name ? [name] : undefined, + }); + + stats.assets.push({ + name: file, + size, + }); + } + + // Add component styles from metafile + // TODO: Provide this information directly from the AOT compiler + for (const [file, entry] of Object.entries(metafile.outputs)) { + if (!file.endsWith('.css')) { + continue; + } + // 'ng-component' is set by the angular plugin's component stylesheet bundler + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const componentStyle: boolean = (entry as any)['ng-component']; + if (!componentStyle) { + continue; + } + + stats.assets.push({ + // Component styles use the input file + name: Object.keys(entry.inputs)[0], + size: entry.bytes, + componentStyle, + }); + } + + return stats; +} diff --git a/packages/angular/build/src/tools/esbuild/bundler-context.ts b/packages/angular/build/src/tools/esbuild/bundler-context.ts new file mode 100644 index 000000000000..106619be2360 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/bundler-context.ts @@ -0,0 +1,601 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + BuildContext, + BuildFailure, + BuildOptions, + BuildResult, + Message, + Metafile, + build, + context, +} from 'esbuild'; +import assert from 'node:assert'; +import { basename, extname, isAbsolute, join, normalize, relative } from 'node:path'; +import { SERVER_GENERATED_EXTERNALS } from '../../utils/server-rendering/manifest'; +import { + type BuildOutputFile, + BuildOutputFileType, + type InitialFileRecord, + convertOutputFile, + findTransitiveInitialFiles, +} from './bundler-files'; +import { LoadResultCache, MemoryLoadResultCache } from './load-result-cache'; + +export type BundleContextResult = + | { errors: Message[]; warnings: Message[] } + | { + errors: undefined; + warnings: Message[]; + metafile: Metafile; + platform: 'browser' | 'server'; + outputFiles: BuildOutputFile[]; + initialFiles: Map; + externalImports: Set; + externalConfiguration?: string[]; + }; + +export type BundleMergedContextResult = + | { errors: Message[]; warnings: Message[] } + | { + errors: undefined; + warnings: Message[]; + metafiles: { + browser: Metafile; + server: Metafile; + }; + outputFiles: BuildOutputFile[]; + initialFiles: Map; + externalImports: { + server: Set; + browser: Set; + }; + externalConfiguration?: string[]; + }; + +export type BundlerOptionsFactory = ( + loadCache: LoadResultCache | undefined, +) => T; + +/** + * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild. + * @param value A potential esbuild BuildFailure error object. + * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`. + */ +function isEsBuildFailure(value: unknown): value is BuildFailure { + return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value; +} + +export class BundlerContext { + #esbuildContext?: BuildContext<{ metafile: true; write: false }>; + #esbuildOptions?: BuildOptions & { metafile: true; write: false }; + #esbuildResult?: BundleContextResult; + #activeBundlePromise?: Promise; + #disposed = false; + #optionsFactory: BundlerOptionsFactory; + #shouldCacheResult: boolean; + #loadCache?: LoadResultCache; + #loadCacheKeys?: Set; + #invalidationEpoch = 0; + readonly watchFiles = new Set(); + + constructor( + private workspaceRoot: string, + private incremental: boolean, + options: BuildOptions | BundlerOptionsFactory, + private useContext = incremental, + private initialFilter?: (initial: Readonly) => boolean, + sharedLoadCache?: LoadResultCache, + ) { + this.#loadCache = sharedLoadCache; + // To cache the results an option factory is needed to capture the full set of dependencies + this.#shouldCacheResult = incremental && typeof options === 'function'; + this.#optionsFactory = (...args) => { + const baseOptions = typeof options === 'function' ? options(...args) : options; + + return { + ...baseOptions, + metafile: true, + write: false, + }; + }; + } + + static bundleAll( + contexts: Iterable, + changedFiles?: Iterable | ReadonlySet, + ): Promise { + return Promise.all( + [...contexts].map((context) => { + if (changedFiles) { + context.invalidate(changedFiles); + } + + return context.bundle(); + }), + ); + } + + static mergeResults(results: BundleContextResult[]): BundleMergedContextResult { + let errors: Message[] | undefined; + const warnings: Message[] = []; + const browserMetafile: Metafile = { inputs: {}, outputs: {} }; + const serverMetafile: Metafile = { inputs: {}, outputs: {} }; + const initialFiles = new Map(); + const externalImportsBrowser = new Set(); + const externalImportsServer = new Set(); + + const outputFiles: BuildOutputFile[] = []; + let externalConfiguration: Set | undefined; + for (const result of results) { + warnings.push(...result.warnings); + if (result.errors) { + errors ??= []; + errors.push(...result.errors); + continue; + } + + const platformIsBrowser = result.platform === 'browser'; + + // Combine metafiles used for the bundle budgets and console output + if (result.metafile) { + const metafile = platformIsBrowser ? browserMetafile : serverMetafile; + Object.assign(metafile.inputs, result.metafile.inputs); + Object.assign(metafile.outputs, result.metafile.outputs); + } + + const externalImports = platformIsBrowser ? externalImportsBrowser : externalImportsServer; + result.externalImports?.forEach((value) => externalImports.add(value)); + + result.initialFiles.forEach((value, key) => initialFiles.set(key, value)); + outputFiles.push(...result.outputFiles); + + if (result.externalConfiguration) { + externalConfiguration ??= new Set(); + for (const value of result.externalConfiguration) { + externalConfiguration.add(value); + } + } + } + + if (errors !== undefined) { + return { errors, warnings }; + } + + return { + errors, + warnings, + initialFiles, + outputFiles, + externalImports: { + browser: externalImportsBrowser, + server: externalImportsServer, + }, + metafiles: { + browser: browserMetafile, + server: serverMetafile, + }, + externalConfiguration: externalConfiguration ? [...externalConfiguration] : undefined, + }; + } + + /** + * Executes the esbuild build function and normalizes the build result in the event of a + * build failure that results in no output being generated. + * All builds use the `write` option with a value of `false` to allow for the output files + * build result array to be populated. + * + * @param force If true, always rebundle. + * @returns If output files are generated, the full esbuild BuildResult; if not, the + * warnings and errors for the attempted build. + */ + async bundle(force?: boolean): Promise { + // Return existing result if present + if (!force && this.#esbuildResult) { + return this.#esbuildResult; + } + + if (!force && this.#activeBundlePromise) { + return this.#activeBundlePromise; + } + + const bundleEpoch = this.#invalidationEpoch; + const bundlePromise = this.#performBundle().finally(() => { + if (this.#activeBundlePromise === bundlePromise) { + this.#activeBundlePromise = undefined; + } + }); + this.#activeBundlePromise = bundlePromise; + + const result = await bundlePromise; + if (this.#shouldCacheResult && bundleEpoch === this.#invalidationEpoch) { + this.#esbuildResult = result; + } + + return result; + } + + // eslint-disable-next-line max-lines-per-function + async #performBundle(): Promise { + this.#loadCacheKeys?.clear(); + + // Create esbuild options if not present + if (this.#esbuildOptions === undefined) { + if (this.incremental && !this.#loadCache) { + this.#loadCache = new MemoryLoadResultCache(); + } + const loadCache = this.#loadCache; + const scopedLoadCache: LoadResultCache | undefined = + this.incremental && loadCache + ? { + get: (path) => { + (this.#loadCacheKeys ??= new Set()).add(path); + + return loadCache.get(path); + }, + put: (path, result) => { + (this.#loadCacheKeys ??= new Set()).add(path); + + return loadCache.put(path, result); + }, + invalidate: (path) => loadCache.invalidate(path), + get watchFiles() { + return loadCache.watchFiles; + }, + } + : loadCache; + this.#esbuildOptions = this.#optionsFactory(scopedLoadCache); + } + + let result: BuildResult<{ metafile: true; write: false }>; + try { + if (this.#esbuildContext) { + // Rebuild using the existing incremental build context + result = await this.#esbuildContext.rebuild(); + } else if (this.useContext) { + // Create a build context and perform the build. + // Context creation does not perform a build. + const esbuildContext = await context(this.#esbuildOptions); + if (this.#disposed) { + await esbuildContext.dispose(); + throw new Error('BundlerContext was disposed during build.'); + } + this.#esbuildContext = esbuildContext; + result = await this.#esbuildContext.rebuild(); + } else { + // For non-incremental builds, perform a single build + if (this.#disposed) { + throw new Error('BundlerContext was disposed during build.'); + } + result = await build(this.#esbuildOptions); + if (this.#disposed) { + throw new Error('BundlerContext was disposed during build.'); + } + } + } catch (failure) { + // Build failures will throw an exception which contains errors/warnings + if (isEsBuildFailure(failure)) { + this.#addErrorsToWatch(failure); + await this.#addLoadCacheFilesToWatch(); + + return failure; + } else { + throw failure; + } + } + + // Update files that should be watched. + // While this should technically not be linked to incremental mode, incremental is only + // currently enabled with watch mode where watch files are needed. + if (this.incremental) { + this.watchFiles.clear(); + + // Add input files except virtual angular files which do not exist on disk + for (const input of Object.keys(result.metafile.inputs)) { + const isInternal = isInternalAngularFile(input) || isInternalBundlerFile(input); + + // Input file paths are always relative to the workspace root unless already absolute + const normalizedAbsoluteInput = isAbsolute(input) + ? normalize(input) + : join(this.workspaceRoot, input); + + if (!isInternal) { + this.watchFiles.add(normalizedAbsoluteInput); + } + + if (this.#loadCache) { + const cachedLoad = + (await this.#loadCache.get(input)) ?? + (await this.#loadCache.get(input.replace(';', ':'))) ?? + (await this.#loadCache.get('file:' + normalizedAbsoluteInput)); + if (cachedLoad?.watchFiles) { + for (const file of cachedLoad.watchFiles) { + if (!isInternalAngularFile(file)) { + this.watchFiles.add( + isAbsolute(file) ? normalize(file) : join(this.workspaceRoot, file), + ); + } + } + } + } + } + } + + // Return if the build encountered any errors + if (result.errors.length) { + this.#addErrorsToWatch(result); + await this.#addLoadCacheFilesToWatch(); + + return { + errors: result.errors, + warnings: result.warnings, + }; + } + + const { + 'ng-platform-server': isPlatformServer = false, + 'ng-ssr-entry-bundle': isSsrEntryBundle = false, + } = result.metafile as Metafile & { + 'ng-platform-server'?: boolean; + 'ng-ssr-entry-bundle'?: boolean; + }; + + // Find all initial files + const initialFiles = new Map(); + for (const outputFile of result.outputFiles) { + // Entries in the metafile are relative to the `absWorkingDir` option which is set to the workspaceRoot + // `outputFile.path` may already be relative if the `OutputFile` instance was cached in `additionalResults` + // across an incremental rebuild. + const relativeFilePath = isAbsolute(outputFile.path) + ? relative(this.workspaceRoot, outputFile.path) + : outputFile.path; + const entryPoint = result.metafile.outputs[relativeFilePath]?.entryPoint; + + outputFile.path = relativeFilePath; + + if (entryPoint) { + // The first part of the filename is the name of file (e.g., "polyfills" for "polyfills-7S5G3MDY.js") + const name = basename(relativeFilePath).replace(/(?:-[\dA-Z]{8})?\.[a-z]{2,3}$/, ''); + // Entry points are only styles or scripts + const type = extname(relativeFilePath) === '.css' ? 'style' : 'script'; + + // Only entrypoints with an entry in the options are initial files. + // Dynamic imports also have an entryPoint value in the meta file. + if ((this.#esbuildOptions.entryPoints as Record)?.[name]) { + // An entryPoint value indicates an initial file + const record: InitialFileRecord = { + name, + type, + entrypoint: true, + serverFile: isPlatformServer, + depth: 0, + }; + + if (!this.initialFilter || this.initialFilter(record)) { + initialFiles.set(relativeFilePath, record); + } + } + } + } + + // Analyze for transitive initial files + findTransitiveInitialFiles(result.metafile, initialFiles, undefined, this.initialFilter); + + // Collect all external package names + const externalImports = new Set(); + for (const { imports } of Object.values(result.metafile.outputs)) { + for (const { external, kind, path } of imports) { + if ( + !external || + SERVER_GENERATED_EXTERNALS.has(path) || + isInternalAngularFile(path) || + (kind !== 'import-statement' && kind !== 'dynamic-import' && kind !== 'require-call') + ) { + continue; + } + + externalImports.add(path); + } + } + + assert(this.#esbuildOptions, 'esbuild options cannot be undefined.'); + + const outputFiles = result.outputFiles.map((file) => { + let fileType: BuildOutputFileType; + // All files that are not JS, CSS, WASM, or sourcemaps for them are considered media + if (!/\.([cm]?js|css|wasm)(\.map)?$/i.test(file.path)) { + fileType = BuildOutputFileType.Media; + } else if (isPlatformServer) { + fileType = isSsrEntryBundle + ? BuildOutputFileType.ServerRoot + : BuildOutputFileType.ServerApplication; + } else { + fileType = BuildOutputFileType.Browser; + } + + return convertOutputFile(file, fileType); + }); + + let externalConfiguration = this.#esbuildOptions.external; + if (isPlatformServer && externalConfiguration) { + externalConfiguration = externalConfiguration.filter( + (dep) => !SERVER_GENERATED_EXTERNALS.has(dep), + ); + + if (!externalConfiguration.length) { + externalConfiguration = undefined; + } + } + + // Return the successful build results + return { + ...result, + outputFiles, + initialFiles, + externalImports, + platform: isPlatformServer ? 'server' : 'browser', + externalConfiguration, + errors: undefined, + }; + } + + #addErrorsToWatch(result: BuildFailure | BuildResult): void { + const entryPoints = this.#esbuildOptions?.entryPoints; + if (entryPoints) { + const entries = Array.isArray(entryPoints) + ? entryPoints.map((entry) => (typeof entry === 'string' ? entry : entry.in)) + : Object.values(entryPoints); + for (const entry of entries) { + if (isInternalAngularFile(entry) || isInternalBundlerFile(entry)) { + continue; + } + + this.watchFiles.add(isAbsolute(entry) ? normalize(entry) : join(this.workspaceRoot, entry)); + } + } + + for (const error of result.errors) { + let file = error.location?.file; + if (file && !isInternalAngularFile(file)) { + this.watchFiles.add(isAbsolute(file) ? normalize(file) : join(this.workspaceRoot, file)); + } + for (const note of error.notes ?? []) { + file = note.location?.file; + if (file && !isInternalAngularFile(file)) { + this.watchFiles.add(isAbsolute(file) ? normalize(file) : join(this.workspaceRoot, file)); + } + } + } + } + + async #addLoadCacheFilesToWatch(): Promise { + const loadCache = this.#loadCache; + if (!this.incremental || !loadCache || !this.#loadCacheKeys) { + return; + } + + const results = await Promise.all(Array.from(this.#loadCacheKeys, (key) => loadCache.get(key))); + for (const cachedResult of results) { + if (!cachedResult?.watchFiles) { + continue; + } + + for (const file of cachedResult.watchFiles) { + if (isInternalAngularFile(file)) { + continue; + } + + this.watchFiles.add(isAbsolute(file) ? normalize(file) : join(this.workspaceRoot, file)); + } + } + } + + /** + * Invalidate a stored bundler result based on the previous watch files + * and a list of changed files. + * The context must be created with incremental mode enabled for results + * to be stored. + * @returns True, if the result was invalidated; False, otherwise. + */ + invalidate(files: Iterable | ReadonlySet): boolean { + if (!this.incremental) { + return false; + } + + let candidateFiles: ReadonlySet; + if (files instanceof Set) { + let isCandidateReady = true; + for (const file of files) { + if ( + file !== normalize(file) || + (!isAbsolute(file) && !files.has(normalize(join(this.workspaceRoot, file)))) + ) { + isCandidateReady = false; + break; + } + } + + if (isCandidateReady) { + candidateFiles = files; + } else { + const normalizedFiles = new Set(); + for (const file of files) { + const normalized = normalize(file); + normalizedFiles.add(normalized); + if (!isAbsolute(normalized)) { + normalizedFiles.add(normalize(join(this.workspaceRoot, normalized))); + } + } + candidateFiles = normalizedFiles; + } + } else { + const normalizedFiles = new Set(); + for (const file of files) { + const normalized = normalize(file); + normalizedFiles.add(normalized); + if (!isAbsolute(normalized)) { + normalizedFiles.add(normalize(join(this.workspaceRoot, normalized))); + } + } + candidateFiles = normalizedFiles; + } + + if (this.#loadCache) { + for (const file of candidateFiles) { + this.#loadCache.invalidate(file); + } + } + + const invalid = !this.watchFiles.isDisjointFrom(candidateFiles); + + if (invalid) { + this.#invalidationEpoch++; + this.#esbuildResult = undefined; + } + + return invalid; + } + + /** + * Disposes incremental build resources present in the context. + * + * @returns A promise that resolves when disposal is complete. + */ + async dispose(): Promise { + this.#disposed = true; + try { + this.#esbuildOptions = undefined; + this.#esbuildResult = undefined; + this.#activeBundlePromise = undefined; + this.#loadCache = undefined; + this.#loadCacheKeys = undefined; + await this.#esbuildContext?.dispose(); + } finally { + this.#esbuildContext = undefined; + } + } +} + +function isInternalAngularFile(file: string) { + return file.startsWith('angular:'); +} + +function isInternalBundlerFile(file: string) { + // Bundler virtual files such as "" or "" + if (file[0] === '<' && file.at(-1) === '>') { + return true; + } + + // Any (disabled): path is a virtual esbuild entry that doesn't exist on disk + if (file.includes('(disabled):')) { + return true; + } + + return false; +} diff --git a/packages/angular/build/src/tools/esbuild/bundler-context_spec.ts b/packages/angular/build/src/tools/esbuild/bundler-context_spec.ts new file mode 100644 index 000000000000..b98f266e36a7 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/bundler-context_spec.ts @@ -0,0 +1,221 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdtemp, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { BundlerContext } from './bundler-context'; +import { MemoryLoadResultCache, createCachedLoad } from './load-result-cache'; + +describe('BundlerContext', () => { + let tempRoot: string; + + beforeAll(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-bundler-context-test-')); + }); + + describe('invalidate', () => { + it('should return false when incremental is disabled', () => { + const context = new BundlerContext('/workspace', /* incremental */ false, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + expect(context.invalidate(['/workspace/src/app.css'])).toBeFalse(); + }); + + it('should return true when a watch file matches changed files as an array', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + expect(context.invalidate(['/workspace/src/app.css'])).toBeTrue(); + }); + + it('should return true when a watch file matches changed files as a ReadonlySet', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + const changedSet: ReadonlySet = new Set(['/workspace/src/app.css']); + expect(context.invalidate(changedSet)).toBeTrue(); + }); + + it('should return false when changed files do not intersect with watchFiles', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + expect(context.invalidate(['/workspace/src/other.css'])).toBeFalse(); + }); + + it('should correctly handle relative changed file paths', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + expect(context.invalidate(['src/app.css'])).toBeTrue(); + }); + + it('should correctly handle relative paths inside a ReadonlySet', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/app.css'); + + const set: ReadonlySet = new Set(['src/app.css']); + expect(context.invalidate(set)).toBeTrue(); + }); + + it('should invalidate shared load cache when files change', async () => { + const loadCache = new MemoryLoadResultCache(); + await loadCache.put('file:/workspace/src/app.css', { + contents: 'body {}', + loader: 'css', + watchFiles: ['/workspace/src/app.css'], + }); + + const context = new BundlerContext( + '/workspace', + /* incremental */ true, + () => ({ entryPoints: ['main.js'] }), + /* useContext */ false, + /* initialFilter */ undefined, + loadCache, + ); + context.watchFiles.add('/workspace/src/app.css'); + + expect(loadCache.get('file:/workspace/src/app.css')).toBeDefined(); + expect(context.invalidate(['/workspace/src/app.css'])).toBeTrue(); + expect(loadCache.get('file:/workspace/src/app.css')).toBeUndefined(); + }); + + it('should not invalidate unrelated contexts sharing a load cache', async () => { + const workspaceDir = await mkdtemp(join(tempRoot, 'shared-cache-')); + const compAPath = join(workspaceDir, 'comp-a.css'); + const compBPath = join(workspaceDir, 'comp-b.css'); + await writeFile(compAPath, '.a { color: red; }'); + await writeFile(compBPath, '.b { color: blue; }'); + + const sharedCache = new MemoryLoadResultCache(); + const createCssContext = (entry: string) => + new BundlerContext( + workspaceDir, + /* incremental */ true, + (loadCache) => ({ + absWorkingDir: workspaceDir, + bundle: true, + entryPoints: [entry], + outdir: workspaceDir, + plugins: [ + { + name: 'test-cached-css', + setup(build) { + build.onLoad( + { filter: /\.css$/ }, + createCachedLoad(loadCache, async (args) => ({ + contents: await readFile(args.path, 'utf8'), + loader: 'css', + watchFiles: [args.path], + })), + ); + }, + }, + ], + }), + /* useContext */ false, + /* initialFilter */ undefined, + sharedCache, + ); + + const contextA = createCssContext(compAPath); + const contextB = createCssContext(compBPath); + + const resultA1 = await contextA.bundle(); + const resultB1 = await contextB.bundle(); + expect(resultA1.errors).toBeUndefined(); + expect(resultB1.errors).toBeUndefined(); + + await writeFile(compAPath, '.a { color: green; }'); + + // Even if contextB.invalidate runs first against the shared cache, contextB must not be invalidated + expect(contextB.invalidate([compAPath])).toBeFalse(); + expect(contextA.invalidate([compAPath])).toBeTrue(); + + const resultB2 = await contextB.bundle(); + const resultA2 = await contextA.bundle(); + expect(resultB2).toBe(resultB1); + expect(resultA2).not.toBe(resultA1); + assert(!resultA2.errors); + expect(resultA2.outputFiles[0].text).toContain('green'); + }); + + it('should work when watchFiles is smaller than changed files', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + context.watchFiles.add('/workspace/src/file10.css'); + + const changedFiles = Array.from({ length: 100 }, (_, i) => `/workspace/src/file${i}.css`); + expect(context.invalidate(new Set(changedFiles))).toBeTrue(); + }); + + it('should work when changed files is smaller than watchFiles', () => { + const context = new BundlerContext('/workspace', /* incremental */ true, () => ({ + entryPoints: ['main.js'], + })); + for (let i = 0; i < 100; i++) { + context.watchFiles.add(`/workspace/src/file${i}.css`); + } + + expect(context.invalidate(new Set(['/workspace/src/file50.css']))).toBeTrue(); + }); + }); + + describe('bundle', () => { + it('should recover when fixing a broken @import in plain CSS in watch mode', async () => { + const workspaceDir = await mkdtemp(join(tempRoot, 'css-import-recovery-')); + const compCssPath = join(workspaceDir, 'comp.css'); + const subCssPath = join(workspaceDir, 'sub.css'); + await writeFile(compCssPath, "@import './sub.css';"); + await writeFile(subCssPath, "@import './non-existent.css';"); + + const context = new BundlerContext( + workspaceDir, + /* incremental */ true, + () => ({ + absWorkingDir: workspaceDir, + bundle: true, + entryPoints: [compCssPath], + outdir: workspaceDir, + logLevel: 'silent', + }), + /* useContext */ false, + ); + + const failedResult = await context.bundle(); + expect(failedResult.errors).toBeDefined(); + expect(context.watchFiles.has(subCssPath)).toBeTrue(); + expect(context.watchFiles.has(compCssPath)).toBeTrue(); + + // Fix sub.css and verify invalidation + recovery + await writeFile(subCssPath, '.sub { color: purple; }'); + expect(context.invalidate([subCssPath])).toBeTrue(); + + const recoveredResult = await context.bundle(); + assert(!recoveredResult.errors); + expect(recoveredResult.outputFiles[0].text).toContain('purple'); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/bundler-execution-result.ts b/packages/angular/build/src/tools/esbuild/bundler-execution-result.ts new file mode 100644 index 000000000000..3777d2835f5a --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/bundler-execution-result.ts @@ -0,0 +1,216 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Message, PartialMessage } from 'esbuild'; +import { normalize } from 'node:path'; +import type { ChangedFiles } from '../../utils/watcher'; +import type { ComponentStylesheetBundler } from './angular/component-stylesheets'; +import type { SourceFileCache } from './angular/source-file-cache'; +import type { BundlerContext } from './bundler-context'; +import { type BuildOutputFile, BuildOutputFileType, createOutputFile } from './bundler-files'; + +export interface BuildOutputAsset { + source: string; + destination: string; +} + +export interface RebuildState { + rebuildContexts: { + typescriptContexts: BundlerContext[]; + otherContexts: BundlerContext[]; + }; + componentStyleBundler: ComponentStylesheetBundler; + codeBundleCache?: SourceFileCache; + fileChanges: ChangedFiles; + previousOutputInfo: ReadonlyMap< + string, + { hash: string; type: BuildOutputFileType; path: string } + >; + previousAssetsInfo: ReadonlySet; + templateUpdates?: Map; +} + +export interface ExternalResultMetadata { + implicitBrowser: string[]; + implicitServer: string[]; + explicit: string[]; +} + +export type PrerenderedRoutesRecord = Record }>; + +/** + * Represents the result of a single builder execute call. + */ +export class ExecutionResult { + outputFiles: BuildOutputFile[] = []; + assetFiles: BuildOutputAsset[] = []; + errors: (Message | PartialMessage)[] = []; + prerenderedRoutes: PrerenderedRoutesRecord = {}; + warnings: (Message | PartialMessage)[] = []; + logs: string[] = []; + externalMetadata?: ExternalResultMetadata; + extraWatchFiles: string[] = []; + htmlIndexPath?: string; + htmlBaseHref?: string; + + constructor( + private rebuildContexts: { + typescriptContexts: BundlerContext[]; + otherContexts: BundlerContext[]; + }, + private componentStyleBundler: ComponentStylesheetBundler, + private codeBundleCache?: SourceFileCache, + readonly templateUpdates?: Map, + ) {} + + addOutputFile(path: string, content: string | Uint8Array, type: BuildOutputFileType): void { + this.outputFiles.push(createOutputFile(path, content, type)); + } + + addAssets(assets: BuildOutputAsset[]): void { + this.assetFiles.push(...assets); + } + + addLog(value: string): void { + this.logs.push(value); + } + + addError(error: PartialMessage | string): void { + if (typeof error === 'string') { + this.errors.push({ text: error, location: null }); + } else { + this.errors.push(error); + } + } + + addErrors(errors: (PartialMessage | string)[]): void { + for (const error of errors) { + this.addError(error); + } + } + + addPrerenderedRoutes(routes: PrerenderedRoutesRecord): void { + Object.assign(this.prerenderedRoutes, routes); + + // Sort the prerendered routes. + const sortedObj: PrerenderedRoutesRecord = {}; + for (const key of Object.keys(this.prerenderedRoutes).sort()) { + sortedObj[key] = this.prerenderedRoutes[key]; + } + + this.prerenderedRoutes = sortedObj; + } + + addWarning(error: PartialMessage | string): void { + if (typeof error === 'string') { + this.warnings.push({ text: error, location: null }); + } else { + this.warnings.push(error); + } + } + + addWarnings(errors: (PartialMessage | string)[]): void { + for (const error of errors) { + this.addWarning(error); + } + } + + /** + * Add external JavaScript import metadata to the result. This is currently used + * by the development server to optimize the prebundling process. + * @param implicitBrowser External dependencies for the browser bundles due to the external packages option. + * @param implicitServer External dependencies for the server bundles due to the external packages option. + * @param explicit External dependencies due to explicit project configuration. + */ + setExternalMetadata( + implicitBrowser: string[], + implicitServer: string[], + explicit: string[], + ): void { + this.externalMetadata = { implicitBrowser, implicitServer, explicit }; + } + + get output() { + return { + success: this.errors.length === 0, + }; + } + + get outputWithFiles() { + return { + success: this.errors.length === 0, + outputFiles: this.outputFiles, + assetFiles: this.assetFiles, + errors: this.errors, + externalMetadata: this.externalMetadata, + }; + } + + get watchFiles(): Readonly { + const { typescriptContexts, otherContexts } = this.rebuildContexts; + + return [ + // Bundler contexts internally normalize file dependencies. + ...typescriptContexts.flatMap((context) => [...context.watchFiles]), + ...otherContexts.flatMap((context) => [...context.watchFiles]), + // These files originate from TS/NG and can have POSIX path separators even on Windows. + // To ensure path comparisons are valid, all these paths must be normalized. + ...(this.codeBundleCache?.referencedFiles?.map(normalize) ?? []), + // The assets source files. + ...this.assetFiles.map(({ source }) => source), + ...this.extraWatchFiles, + ]; + } + + createRebuildState(fileChanges: ChangedFiles): RebuildState { + return { + rebuildContexts: this.rebuildContexts, + codeBundleCache: this.codeBundleCache, + componentStyleBundler: this.componentStyleBundler, + fileChanges, + previousOutputInfo: new Map( + this.outputFiles.map(({ path, hash, type }) => [`${type}:${path}`, { hash, type, path }]), + ), + // Tracked by destination since one source can be copied to several outputs (e.g. per locale). + previousAssetsInfo: new Set(this.assetFiles.map(({ destination }) => destination)), + templateUpdates: this.templateUpdates, + }; + } + + findChangedFiles( + previousOutputHashes: ReadonlyMap, + ): Set { + const changed = new Set(); + for (const file of this.outputFiles) { + const previousHash = previousOutputHashes.get(`${file.type}:${file.path}`)?.hash; + if (previousHash === undefined || previousHash !== file.hash) { + changed.add(file.path); + } + } + + return changed; + } + + #disposal?: Promise; + + dispose(): Promise { + return (this.#disposal ??= this.#dispose()); + } + + async #dispose(): Promise { + try { + await Promise.allSettled([ + ...this.rebuildContexts.typescriptContexts.map((context) => context.dispose()), + ...this.rebuildContexts.otherContexts.map((context) => context.dispose()), + this.componentStyleBundler.dispose(), + ]); + } finally { + this.codeBundleCache?.clear(); + } + } +} diff --git a/packages/angular/build/src/tools/esbuild/bundler-files.ts b/packages/angular/build/src/tools/esbuild/bundler-files.ts new file mode 100644 index 000000000000..f69835ab746b --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/bundler-files.ts @@ -0,0 +1,195 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile, OutputFile } from 'esbuild'; +import { calculateHash } from '../../utils/hash'; + +export interface InitialFileRecord { + entrypoint: boolean; + name?: string; + type: 'script' | 'style'; + external?: boolean; + serverFile: boolean; + depth: number; +} + +/** + * Analyzes a metafile to find and record all transitive initial files starting from the given + * initial entries using breadth-first traversal so each file is recorded at its minimum depth. + * + * @param metafile The esbuild metafile containing output import relationships. + * @param initialFiles The map of initial files to populate. + * @param entriesToAnalyze Optional starting entries to traverse; defaults to all current `initialFiles`. + * Entries must share the same starting depth (or be ordered by non-decreasing depth) to guarantee + * that each transitive file is visited at its minimum depth first. + * @param initialFilter Optional filter predicate to determine whether a discovered record should be added. + */ +export function findTransitiveInitialFiles( + metafile: Metafile, + initialFiles: Map, + entriesToAnalyze: Iterable<[string, InitialFileRecord]> = initialFiles, + initialFilter?: (initial: Readonly) => boolean, +): void { + const queue = [...entriesToAnalyze]; + for (let i = 0; i < queue.length; i++) { + const [entryPath, entryRecord] = queue[i]; + const entryOutput = metafile.outputs[entryPath]; + if (!entryOutput) { + continue; + } + + for (const initialImport of entryOutput.imports) { + if (initialFiles.has(initialImport.path)) { + continue; + } + + if (initialImport.kind === 'import-statement' || initialImport.kind === 'import-rule') { + const record: InitialFileRecord = { + type: initialImport.kind === 'import-rule' ? 'style' : 'script', + entrypoint: false, + external: initialImport.external, + serverFile: entryRecord.serverFile, + depth: entryRecord.depth + 1, + }; + + if (!initialFilter || initialFilter(record)) { + initialFiles.set(initialImport.path, record); + + if (!initialImport.external) { + queue.push([initialImport.path, record]); + } + } + } + } + } +} + +export enum BuildOutputFileType { + Browser, + Media, + ServerApplication, + ServerRoot, + Root, +} + +export interface BuildOutputFile extends OutputFile { + type: BuildOutputFileType; + readonly size: number; + clone: () => BuildOutputFile; +} + +export function createOutputFile( + path: string, + data: string | Uint8Array, + type: BuildOutputFileType, +): BuildOutputFile { + if (typeof data === 'string') { + let cachedContents: Uint8Array | null = null; + let cachedText: string | null = data; + let cachedHash: string | null = null; + + return { + path, + type, + get contents(): Uint8Array { + cachedContents ??= new TextEncoder().encode(data); + + return cachedContents; + }, + set contents(value: Uint8Array) { + cachedContents = value; + cachedText = null; + cachedHash = null; + }, + get text(): string { + cachedText ??= new TextDecoder('utf-8').decode(this.contents); + + return cachedText; + }, + get size(): number { + return this.contents.byteLength; + }, + get hash(): string { + cachedHash ??= calculateHash(cachedText ?? this.contents); + + return cachedHash; + }, + clone(): BuildOutputFile { + return createOutputFile(this.path, cachedText ?? this.contents, this.type); + }, + }; + } else { + let cachedContents = data; + let cachedText: string | null = null; + let cachedHash: string | null = null; + + return { + get contents(): Uint8Array { + return cachedContents; + }, + set contents(value: Uint8Array) { + cachedContents = value; + cachedText = null; + cachedHash = null; + }, + path, + type, + get size(): number { + return this.contents.byteLength; + }, + get text(): string { + cachedText ??= new TextDecoder('utf-8').decode(this.contents); + + return cachedText; + }, + get hash(): string { + cachedHash ??= calculateHash(this.contents); + + return cachedHash; + }, + clone(): BuildOutputFile { + return createOutputFile(this.path, this.contents, this.type); + }, + }; + } +} + +export function convertOutputFile(file: OutputFile, type: BuildOutputFileType): BuildOutputFile { + let { contents: cachedContents } = file; + let cachedText: string | null = null; + let cachedHash: string | null = file.hash; + + return { + get contents(): Uint8Array { + return cachedContents; + }, + set contents(value: Uint8Array) { + cachedContents = value; + cachedText = null; + cachedHash = null; + }, + get hash(): string { + cachedHash ??= calculateHash(cachedContents); + + return cachedHash; + }, + path: file.path, + type, + get size(): number { + return this.contents.byteLength; + }, + get text(): string { + cachedText ??= new TextDecoder('utf-8').decode(this.contents); + + return cachedText; + }, + clone(): BuildOutputFile { + return convertOutputFile(this, this.type); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/bundler-files_spec.ts b/packages/angular/build/src/tools/esbuild/bundler-files_spec.ts new file mode 100644 index 000000000000..be21f7ded608 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/bundler-files_spec.ts @@ -0,0 +1,298 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import { type InitialFileRecord, findTransitiveInitialFiles } from './bundler-files'; + +function createMetafile( + outputs: Record< + string, + { + imports: { + path: string; + kind: 'import-statement' | 'import-rule' | 'dynamic-import'; + external?: boolean; + }[]; + } + >, +): Metafile { + return { + inputs: {}, + outputs: Object.fromEntries( + Object.entries(outputs).map(([key, value]) => [ + key, + { + bytes: 0, + inputs: {}, + imports: value.imports, + exports: [], + }, + ]), + ), + }; +} + +describe('findTransitiveInitialFiles', () => { + it('should compute minimum depth and propagate it to transitive children in a DAG', () => { + // main (0) -> [a (1), b (1)] + // b (1) -> c (2) -> d (via b: 3, via a: 2) -> e (should be 3, not 4) + // a (1) -> d (2) + const metafile = createMetafile({ + 'main.js': { + imports: [ + { path: 'chunk-a.js', kind: 'import-statement' }, + { path: 'chunk-b.js', kind: 'import-statement' }, + ], + }, + 'chunk-a.js': { + imports: [{ path: 'chunk-d.js', kind: 'import-statement' }], + }, + 'chunk-b.js': { + imports: [{ path: 'chunk-c.js', kind: 'import-statement' }], + }, + 'chunk-c.js': { + imports: [{ path: 'chunk-d.js', kind: 'import-statement' }], + }, + 'chunk-d.js': { + imports: [{ path: 'chunk-e.js', kind: 'import-statement' }], + }, + 'chunk-e.js': { + imports: [], + }, + }); + + const initialFiles = new Map([ + ['main.js', { entrypoint: true, name: 'main', type: 'script', serverFile: false, depth: 0 }], + ]); + + findTransitiveInitialFiles(metafile, initialFiles); + + expect(initialFiles.get('chunk-a.js')?.depth).toBe(1); + expect(initialFiles.get('chunk-b.js')?.depth).toBe(1); + expect(initialFiles.get('chunk-c.js')?.depth).toBe(2); + expect(initialFiles.get('chunk-d.js')?.depth).toBe(2); + expect(initialFiles.get('chunk-e.js')?.depth).toBe(3); + }); + + it('should record files in breadth-first forward import order', () => { + const metafile = createMetafile({ + 'main.js': { + imports: [ + { path: 'chunk-a.js', kind: 'import-statement' }, + { path: 'chunk-b.js', kind: 'import-statement' }, + ], + }, + 'chunk-a.js': { + imports: [{ path: 'chunk-a1.js', kind: 'import-statement' }], + }, + 'chunk-b.js': { + imports: [{ path: 'chunk-b1.js', kind: 'import-statement' }], + }, + 'chunk-a1.js': { imports: [] }, + 'chunk-b1.js': { imports: [] }, + }); + + const initialFiles = new Map([ + ['main.js', { entrypoint: true, name: 'main', type: 'script', serverFile: false, depth: 0 }], + ]); + + findTransitiveInitialFiles(metafile, initialFiles); + + expect([...initialFiles.keys()]).toEqual([ + 'main.js', + 'chunk-a.js', + 'chunk-b.js', + 'chunk-a1.js', + 'chunk-b1.js', + ]); + }); + + it('should ignore dynamic imports and handle external and style imports', () => { + const metafile = createMetafile({ + 'main.js': { + imports: [ + { path: 'lazy.js', kind: 'dynamic-import' }, + { path: '@angular/core', kind: 'import-statement', external: true }, + ], + }, + 'styles.css': { + imports: [{ path: 'https://example.com/font.css', kind: 'import-rule', external: true }], + }, + 'lazy.js': { + imports: [{ path: 'lazy-dep.js', kind: 'import-statement' }], + }, + }); + + const initialFiles = new Map([ + ['main.js', { entrypoint: true, name: 'main', type: 'script', serverFile: false, depth: 0 }], + [ + 'styles.css', + { entrypoint: true, name: 'styles', type: 'style', serverFile: false, depth: 0 }, + ], + ]); + + findTransitiveInitialFiles(metafile, initialFiles); + + expect(initialFiles.has('lazy.js')).toBeFalse(); + expect(initialFiles.has('lazy-dep.js')).toBeFalse(); + expect(initialFiles.get('@angular/core')).toEqual({ + type: 'script', + entrypoint: false, + external: true, + serverFile: false, + depth: 1, + }); + expect(initialFiles.get('https://example.com/font.css')).toEqual({ + type: 'style', + entrypoint: false, + external: true, + serverFile: false, + depth: 1, + }); + }); + + it('should only traverse from provided entriesToAnalyze while preserving existing initialFiles', () => { + const metafile = createMetafile({ + 'main.js': { + imports: [{ path: 'chunk-main.js', kind: 'import-statement' }], + }, + 'polyfills.js': { + imports: [{ path: 'chunk-polyfills.js', kind: 'import-statement' }], + }, + 'chunk-main.js': { imports: [] }, + 'chunk-polyfills.js': { imports: [] }, + }); + + const mainRecord: InitialFileRecord = { + entrypoint: true, + name: 'main', + type: 'script', + serverFile: false, + depth: 0, + }; + const polyfillsRecord: InitialFileRecord = { + entrypoint: true, + name: 'polyfills', + type: 'script', + serverFile: false, + depth: 0, + }; + const initialFiles = new Map([ + ['main.js', mainRecord], + ['polyfills.js', polyfillsRecord], + ]); + + const entriesToAnalyze: [string, InitialFileRecord][] = [['main.js', mainRecord]]; + findTransitiveInitialFiles(metafile, initialFiles, entriesToAnalyze); + + expect(entriesToAnalyze.length).toBe(1); + expect(initialFiles.has('main.js')).toBeTrue(); + expect(initialFiles.has('polyfills.js')).toBeTrue(); + expect(initialFiles.has('chunk-main.js')).toBeTrue(); + expect(initialFiles.has('chunk-polyfills.js')).toBeFalse(); + }); + + it('should filter discovered records using initialFilter when provided', () => { + const metafile = createMetafile({ + 'main.js': { + imports: [ + { path: 'chunk-a.js', kind: 'import-statement' }, + { path: 'external-lib', kind: 'import-statement', external: true }, + ], + }, + 'chunk-a.js': { + imports: [{ path: 'chunk-b.js', kind: 'import-statement' }], + }, + 'chunk-b.js': { + imports: [{ path: 'chunk-c.js', kind: 'import-statement' }], + }, + 'chunk-c.js': { + imports: [{ path: 'chunk-b.js', kind: 'import-statement' }], + }, + }); + + const initialFiles = new Map([ + ['main.js', { entrypoint: true, name: 'main', type: 'script', serverFile: false, depth: 0 }], + ]); + + findTransitiveInitialFiles( + metafile, + initialFiles, + undefined, + (record) => !record.external && record.depth <= 1, + ); + + expect(initialFiles.has('chunk-a.js')).toBeTrue(); + expect(initialFiles.has('external-lib')).toBeFalse(); + expect(initialFiles.has('chunk-b.js')).toBeFalse(); + expect(initialFiles.has('chunk-c.js')).toBeFalse(); + }); + + it('should handle circular static imports between chunks without infinite recursion', () => { + const metafile = createMetafile({ + 'main.js': { + imports: [{ path: 'chunk-a.js', kind: 'import-statement' }], + }, + 'chunk-a.js': { + imports: [{ path: 'chunk-b.js', kind: 'import-statement' }], + }, + 'chunk-b.js': { + imports: [ + { path: 'chunk-a.js', kind: 'import-statement' }, + { path: 'main.js', kind: 'import-statement' }, + ], + }, + }); + + const initialFiles = new Map([ + ['main.js', { entrypoint: true, name: 'main', type: 'script', serverFile: false, depth: 0 }], + ]); + + findTransitiveInitialFiles(metafile, initialFiles); + + expect(initialFiles.get('main.js')?.depth).toBe(0); + expect(initialFiles.get('chunk-a.js')?.depth).toBe(1); + expect(initialFiles.get('chunk-b.js')?.depth).toBe(2); + }); + + it('should propagate serverFile flag from entry record to transitive imports', () => { + const metafile = createMetafile({ + 'server.mjs': { + imports: [{ path: 'chunk-server-1.mjs', kind: 'import-statement' }], + }, + 'chunk-server-1.mjs': { + imports: [{ path: 'chunk-server-2.mjs', kind: 'import-statement' }], + }, + 'chunk-server-2.mjs': { imports: [] }, + }); + + const initialFiles = new Map([ + [ + 'server.mjs', + { entrypoint: true, name: 'server', type: 'script', serverFile: true, depth: 0 }, + ], + ]); + + findTransitiveInitialFiles(metafile, initialFiles); + + expect(initialFiles.get('chunk-server-1.mjs')).toEqual({ + type: 'script', + entrypoint: false, + external: undefined, + serverFile: true, + depth: 1, + }); + expect(initialFiles.get('chunk-server-2.mjs')).toEqual({ + type: 'script', + entrypoint: false, + external: undefined, + serverFile: true, + depth: 2, + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/commonjs-checker.ts b/packages/angular/build/src/tools/esbuild/commonjs-checker.ts new file mode 100644 index 000000000000..305d6d74a44c --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/commonjs-checker.ts @@ -0,0 +1,178 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile, PartialMessage } from 'esbuild'; + +/** + * Checks the input files of a build to determine if any of the files included + * in the build are not ESM. ESM files can be tree-shaken and otherwise optimized + * in ways that CommonJS and other module formats cannot. The esbuild metafile + * information is used as the basis for the analysis as it contains information + * for each input file including its respective format. + * + * If any allowed dependencies are provided via the `allowedCommonJsDependencies` + * parameter, both the direct import and any deep imports will be ignored and no + * diagnostic will be generated. Use `'*'` as entry to skip the check. + * + * If a module has been issued a diagnostic message, then all descendant modules + * will not be checked. This prevents a potential massive amount of inactionable + * messages since the initial module import is the cause of the problem. + * + * @param metafile An esbuild metafile object to check. + * @param allowedCommonJsDependencies An optional list of allowed dependencies. + * @returns Zero or more diagnostic messages for any non-ESM modules. + */ +export function checkCommonJSModules( + metafile: Metafile, + allowedCommonJsDependencies?: string[], +): PartialMessage[] { + const messages: PartialMessage[] = []; + const allowedRequests = new Set(allowedCommonJsDependencies); + + if (allowedRequests.has('*')) { + return messages; + } + + // Ignore Angular locale definitions which are currently UMD + allowedRequests.add('@angular/common/locales'); + + // Ignore zone.js due to it currently being built with a UMD like structure. + // Once the build output is updated to be fully ESM, this can be removed. + allowedRequests.add('zone.js'); + + // Used by '@angular/platform-server' and is in a seperate chunk that is unused when + // using `provideHttpClient(withFetch())`. + allowedRequests.add('xhr2'); + + // Packages used by @angular/ssr. + // While beasties is ESM it has a number of direct and transtive CJS deps. + allowedRequests.add('express'); + allowedRequests.add('beasties'); + + // Find all entry points that contain code (JS/TS) + const files: string[] = []; + for (const { entryPoint } of Object.values(metafile.outputs)) { + if (!entryPoint) { + continue; + } + if (!isPathCode(entryPoint)) { + continue; + } + + files.push(entryPoint); + } + + // Track seen files so they are only analyzed once. + // Bundler runtime code is also ignored since it cannot be actionable. + const seenFiles = new Set(['']); + + // Analyze the files present by walking the import graph + let currentFile: string | undefined; + while ((currentFile = files.shift())) { + const input = metafile.inputs[currentFile]; + + for (const imported of input.imports) { + // Ignore imports that were already seen or not originally in the code (bundler injected) + if (!imported.original || seenFiles.has(imported.path)) { + continue; + } + + seenFiles.add(imported.path); + + // If the dependency is allowed ignore all other checks + if (allowedRequests.has(imported.original)) { + continue; + } + + // Only check actual code files + if (!isPathCode(imported.path)) { + continue; + } + + // Check if non-relative import is ESM format and issue a diagnostic if the file is not allowed + if ( + !isPotentialRelative(imported.original) && + metafile.inputs[imported.path].format !== 'esm' + ) { + const request = imported.original; + + let notAllowed = true; + if (allowedRequests.has(request)) { + notAllowed = false; + } else { + // Check for deep imports of allowed requests + for (const allowed of allowedRequests) { + if (request.startsWith(allowed + '/')) { + notAllowed = false; + break; + } + } + } + + if (notAllowed) { + // Issue a diagnostic message for CommonJS module + messages.push(createCommonJSModuleError(request, currentFile)); + } + + // Skip all descendants since they are also most likely not ESM but solved by addressing this import + continue; + } + + // Add the path so that its imports can be checked + files.push(imported.path); + } + } + + return messages; +} + +/** + * Determines if a file path has an extension that is a JavaScript or TypeScript + * code file. + * + * @param name A path to check for code file extensions. + * @returns True, if a code file path; false, otherwise. + */ +function isPathCode(name: string): boolean { + return /\.[cm]?[jt]sx?$/.test(name); +} + +/** + * Test an import module specifier to determine if the string potentially references a relative file. + * npm packages should not start with a period so if the first character is a period than it is not a + * package. While this is sufficient for the use case in the CommmonJS checker, only checking the + * first character does not definitely indicate the specifier is a relative path. + * + * @param specifier An import module specifier. + * @returns True, if specifier is potentially relative; false, otherwise. + */ +function isPotentialRelative(specifier: string): boolean { + return specifier[0] === '.'; +} + +/** + * Creates an esbuild diagnostic message for a given non-ESM module request. + * + * @param request The requested non-ESM module name. + * @param importer The path of the file containing the import. + * @returns A message representing the diagnostic. + */ +function createCommonJSModuleError(request: string, importer: string): PartialMessage { + const error = { + text: `Module '${request}' used by '${importer}' is not ESM`, + notes: [ + { + text: + 'CommonJS or AMD dependencies can cause optimization bailouts.\n' + + 'For more information see: https://angular.dev/tools/cli/build#configuring-commonjs-dependencies', + }, + ], + }; + + return error; +} diff --git a/packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts b/packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts new file mode 100644 index 000000000000..573b8616da60 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/compiler-plugin-options.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import type { createCompilerPlugin } from './angular/compiler-plugin'; +import type { SourceFileCache } from './angular/source-file-cache'; +import type { LoadResultCache } from './load-result-cache'; + +type CreateCompilerPluginParameters = Parameters; + +export function createCompilerPluginOptions( + options: NormalizedApplicationBuildOptions, + sourceFileCache: SourceFileCache, + loadResultCache?: LoadResultCache, + templateUpdates?: Map, +): CreateCompilerPluginParameters[0] { + const { + sourcemapOptions, + tsconfig, + fileReplacements, + advancedOptimizations, + jit, + externalRuntimeStyles, + instrumentForCoverage, + optimizationOptions, + rootFiles, + } = options; + const incremental = !!options.watch; + + return { + sourcemap: !!sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), + thirdPartySourcemaps: sourcemapOptions.vendor, + tsconfig, + jit, + advancedOptimizations, + fileReplacements, + sourceFileCache, + loadResultCache, + incremental, + externalRuntimeStyles, + instrumentForCoverage, + templateUpdates, + includeTestMetadata: !optimizationOptions.scripts, + rootFiles, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/external-packages-plugin.ts b/packages/angular/build/src/tools/esbuild/external-packages-plugin.ts new file mode 100644 index 000000000000..b968493005ac --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/external-packages-plugin.ts @@ -0,0 +1,117 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; +import { extname } from 'node:path'; + +const EXTERNAL_PACKAGE_RESOLUTION = Symbol('EXTERNAL_PACKAGE_RESOLUTION'); + +/** + * Creates a plugin that marks any resolved path as external if it is within a node modules directory. + * This is used instead of the esbuild `packages` option to avoid marking files that should be loaded + * via customized loaders. This is necessary to prevent Vite development server pre-bundling errors. + * + * @returns An esbuild plugin. + */ +export function createExternalPackagesPlugin(options?: { exclude?: string[] }): Plugin { + const exclusions = new Set(options?.exclude); + // Similar to esbuild, --external:@foo/bar automatically implies --external:@foo/bar/*, + // which matches import paths like @foo/bar/baz. + // This means all paths within the @foo/bar package are also marked as external. + const exclusionsPrefixes = options?.exclude?.map((exclusion) => exclusion + '/') ?? []; + const seenExclusions: Set = new Set(); + const seenExternals = new Set(); + const seenNonExclusions: Set = new Set(); + + return { + name: 'angular-external-packages', + setup(build) { + // Find all loader keys that are not using the 'file' loader. + // The 'file' loader is automatically handled by Vite and does not need exclusion. + const loaderOptionKeys = + build.initialOptions.loader && + Object.entries(build.initialOptions.loader) + .filter(([, value]) => value !== 'file') + .map(([key]) => key); + + // Safe to use native packages external option if no loader options or exclusions present + if (!exclusions.size && !loaderOptionKeys?.length) { + build.initialOptions.packages = 'external'; + + return; + } + + const loaderFileExtensions = new Set(loaderOptionKeys); + + // Only attempt resolve of non-relative and non-absolute paths + build.onResolve({ filter: /^[^./]/ }, async (args) => { + if (args.pluginData?.[EXTERNAL_PACKAGE_RESOLUTION]) { + return null; + } + + if (seenExternals.has(args.path)) { + return { external: true }; + } + + if (exclusions.has(args.path) || seenExclusions.has(args.path)) { + return null; + } + + if (!seenNonExclusions.has(args.path)) { + for (const exclusion of exclusionsPrefixes) { + if (args.path.startsWith(exclusion)) { + seenExclusions.add(args.path); + + return null; + } + } + + seenNonExclusions.add(args.path); + } + + const { importer, kind, resolveDir, namespace, pluginData = {} } = args; + pluginData[EXTERNAL_PACKAGE_RESOLUTION] = true; + + const result = await build.resolve(args.path, { + importer, + kind, + namespace, + pluginData, + resolveDir, + }); + + // Return result if unable to resolve + if (!result.path) { + return result; + } + + // Return if explicitly marked external (externalDependencies option) + if (result.external) { + seenExternals.add(args.path); + + return { external: true }; + } + + // Allow customized loaders to run against configured paths regardless of location + if (loaderFileExtensions.has(extname(result.path))) { + return result; + } + + // Mark paths from a node modules directory as external + if (/[\\/]node_modules[\\/]/.test(result.path)) { + seenExternals.add(args.path); + + return { external: true }; + } + + // Otherwise return original result + return result; + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/global-scripts.ts b/packages/angular/build/src/tools/esbuild/global-scripts.ts new file mode 100644 index 000000000000..2b6c581a572f --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/global-scripts.ts @@ -0,0 +1,142 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Bundle, MagicString } from 'magic-string'; +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import type { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import { assertIsError } from '../../utils/error'; +import { BundlerOptionsFactory } from './bundler-context'; +import { createCachedLoad } from './load-result-cache'; +import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin'; +import { createVirtualModulePlugin } from './virtual-module-plugin'; + +/** + * Create an esbuild 'build' options object for all global scripts defined in the user provied + * build options. + * @param options The builder's user-provider normalized options. + * @returns An esbuild BuildOptions object. + */ +export function createGlobalScriptsBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + initial: boolean, +): BundlerOptionsFactory | undefined { + const { + globalScripts, + optimizationOptions, + outputNames, + preserveSymlinks, + sourcemapOptions, + jsonLogs, + workspaceRoot, + define, + } = options; + + const namespace = 'angular:script/global'; + const entryPoints: Record = {}; + let found = false; + for (const script of globalScripts) { + if (script.initial === initial) { + found = true; + entryPoints[script.name] = `${namespace}:${script.name}`; + } + } + + // Skip if there are no entry points for the style loading type + if (found === false) { + return; + } + + return (loadCache) => { + return { + absWorkingDir: workspaceRoot, + bundle: false, + splitting: false, + entryPoints, + entryNames: initial ? outputNames.bundles : '[name]', + assetNames: outputNames.media, + mainFields: ['script', 'browser', 'main'], + conditions: ['script', optimizationOptions.scripts ? 'production' : 'development'], + resolveExtensions: ['.mjs', '.js', '.cjs'], + logLevel: options.verbose && !jsonLogs ? 'debug' : 'silent', + metafile: true, + minify: optimizationOptions.scripts, + outdir: workspaceRoot, + sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true), + write: false, + platform: 'neutral', + target, + preserveSymlinks, + define, + plugins: [ + createSourcemapIgnorelistPlugin(), + createVirtualModulePlugin({ + namespace, + external: true, + // Add the `js` extension here so that esbuild generates an output file with the extension + transformPath: (path) => path.slice(namespace.length + 1) + '.js', + loadContent: (args, build) => + createCachedLoad(loadCache, async (args) => { + const files = globalScripts.find( + ({ name }) => name === args.path.slice(0, -3), + )?.files; + assert(files, `Invalid operation: global scripts name not found [${args.path}]`); + + // Global scripts are concatenated using magic-string instead of bundled via esbuild. + const bundleContent = new Bundle(); + const watchFiles = []; + for (const filename of files) { + let fileContent; + try { + // Attempt to read as a relative path from the workspace root + const fullPath = path.join(workspaceRoot, filename); + fileContent = await readFile(fullPath, 'utf-8'); + watchFiles.push(fullPath); + } catch (e) { + assertIsError(e); + if (e.code !== 'ENOENT') { + throw e; + } + + // If not found, attempt to resolve as a module specifier + const resolveResult = await build.resolve(filename, { + kind: 'entry-point', + resolveDir: workspaceRoot, + }); + + if (resolveResult.errors.length) { + // Remove resolution failure notes about marking as external since it doesn't apply + // to global scripts. + resolveResult.errors.forEach((error) => (error.notes = [])); + + return { + errors: resolveResult.errors, + warnings: resolveResult.warnings, + }; + } + + watchFiles.push(resolveResult.path); + fileContent = await readFile(resolveResult.path, 'utf-8'); + } + + bundleContent.addSource(new MagicString(fileContent, { filename })); + } + + return { + contents: bundleContent.toString(), + loader: 'js', + watchFiles, + }; + }).call(build, args), + }), + ], + }; + }; +} diff --git a/packages/angular/build/src/tools/esbuild/global-styles.ts b/packages/angular/build/src/tools/esbuild/global-styles.ts new file mode 100644 index 000000000000..79afff2008af --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/global-styles.ts @@ -0,0 +1,107 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import { toPosixPath } from '../../utils/path'; +import { BundlerOptionsFactory } from './bundler-context'; +import { createStylesheetBundleOptions } from './stylesheets/bundle-options'; +import { createVirtualModulePlugin } from './virtual-module-plugin'; + +export function createGlobalStylesBundleOptions( + options: NormalizedApplicationBuildOptions, + target: string[], + initial: boolean, +): BundlerOptionsFactory | undefined { + const { + workspaceRoot, + optimizationOptions, + sourcemapOptions, + outputNames, + globalStyles, + preserveSymlinks, + externalDependencies, + stylePreprocessorOptions, + tailwindConfiguration, + postcssConfiguration, + cacheOptions, + } = options; + + const namespace = 'angular:styles/global'; + const entryPoints: Record = {}; + let found = false; + for (const style of globalStyles) { + if (style.initial === initial) { + found = true; + entryPoints[style.name] = `${namespace};${style.name}`; + } + } + + // Skip if there are no entry points for the style loading type + if (found === false) { + return; + } + + return (loadCache) => { + const buildOptions = createStylesheetBundleOptions( + { + workspaceRoot, + optimization: !!optimizationOptions.styles.minify, + inlineFonts: !!optimizationOptions.fonts.inline, + sourcemap: !!sourcemapOptions.styles && (sourcemapOptions.hidden ? 'external' : true), + sourcesContent: sourcemapOptions.sourcesContent, + preserveSymlinks, + target, + externalDependencies, + outputNames: initial + ? outputNames + : { + ...outputNames, + bundles: '[name]', + }, + includePaths: stylePreprocessorOptions?.includePaths, + // string[] | undefined' is not assignable to type '(Version | DeprecationOrId)[] | undefined'. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sass: stylePreprocessorOptions?.sass as any, + tailwindConfiguration, + postcssConfiguration, + cacheOptions, + }, + loadCache, + ); + + // Keep special CSS comments `/*! comment */` in place when `removeSpecialComments` is disabled. + // These comments are special for a number of CSS tools such as Beasties and PurgeCSS. + buildOptions.legalComments = optimizationOptions.styles?.removeSpecialComments + ? 'none' + : 'inline'; + + buildOptions.entryPoints = entryPoints; + + buildOptions.plugins.unshift( + createVirtualModulePlugin({ + namespace, + transformPath: (path) => path.split(';', 2)[1], + loadContent: (args) => { + const files = globalStyles.find(({ name }) => name === args.path)?.files; + assert(files, `global style name should always be found [${args.path}]`); + + return { + contents: files + .map((file) => `@import ${JSON.stringify(toPosixPath(file))};`) + .join('\n'), + loader: 'css', + resolveDir: workspaceRoot, + }; + }, + }), + ); + + return buildOptions; + }; +} diff --git a/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts b/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts new file mode 100644 index 000000000000..b4c89cf644c1 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; +import { createProjectResolver } from '../../utils/resolve-project'; +import { + LOCALE_DATA_NAMESPACE, + type LoadedLocaleData, + type LocaleDataResolution, + loadLocaleData, + resolveLocaleDataPath, +} from '../i18n/locale-data'; + +export { + LOCALE_DATA_NAMESPACE, + LOCALE_DATA_BASE_MODULE, + type LoadedLocaleData, + type LocaleDataResolution, + loadLocaleData, + resolveLocaleDataPath, +} from '../i18n/locale-data'; + +/** + * Creates an esbuild plugin that resolves Angular locale data files from `@angular/common`. + * + * @returns An esbuild plugin. + */ +export function createAngularLocaleDataPlugin(): Plugin { + return { + name: 'angular-locale-data', + setup(build): void { + build.onResolve({ filter: /^angular:locale\/data:/ }, async ({ path }) => { + const rawLocaleTag = path.split(':', 3)[2]; + const { absWorkingDir } = build.initialOptions; + let projectResolve: ((packageName: string) => string) | undefined; + + const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) => { + projectResolve ??= createProjectResolver(absWorkingDir ?? process.cwd()); + try { + return projectResolve(potentialPath); + } catch { + return undefined; + } + }); + + if (resolution.error) { + return { + path: rawLocaleTag, + namespace: LOCALE_DATA_NAMESPACE, + errors: [{ text: resolution.error }], + }; + } + + if (!resolution.path) { + return { + path: rawLocaleTag, + namespace: LOCALE_DATA_NAMESPACE, + warnings: resolution.warning + ? [{ location: null, text: resolution.warning }] + : undefined, + }; + } + + return { + path: resolution.path, + warnings: resolution.warning ? [{ location: null, text: resolution.warning }] : undefined, + }; + }); + + // Locales that cannot be found or are en/en-US will be loaded as empty content + build.onLoad({ filter: /./, namespace: LOCALE_DATA_NAMESPACE }, () => ({ + contents: '', + loader: 'empty', + })); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/license-extractor.ts b/packages/angular/build/src/tools/esbuild/license-extractor.ts new file mode 100644 index 000000000000..4c73012033bb --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/license-extractor.ts @@ -0,0 +1,193 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import { readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; + +/** + * The path segment used to signify that a file is part of a package. + */ +const NODE_MODULE_SEGMENT = 'node_modules'; + +/** + * String constant for the NPM recommended custom license wording. + * + * See: https://docs.npmjs.com/cli/v9/configuring-npm/package-json#license + * + * Example: + * ``` + * { + * "license" : "SEE LICENSE IN " + * } + * ``` + */ +const CUSTOM_LICENSE_TEXT = 'SEE LICENSE IN '; + +/** + * A regular expression for commonly named license files found within packages. + */ +const LICENSE_FILE_REGEXP = /^(?:mit-)?licen[cs]e(?:$|[-._])/i; + +/** + * Header text that will be added to the top of the output license extraction file. + */ +const EXTRACTION_FILE_HEADER = ''; + +/** + * The package entry separator to use within the output license extraction file. + */ +const EXTRACTION_FILE_SEPARATOR = '-'.repeat(80) + '\n'; + +/** + * Extracts license information for each node module package included in the output + * files of the built code. This includes JavaScript and CSS output files. The esbuild + * metafile generated during the bundling steps is used as the source of information + * regarding what input files where included and where they are located. A path segment + * of `node_modules` is used to indicate that a file belongs to a package and its license + * should be include in the output licenses file. + * + * The package name and license field are extracted from the `package.json` file for the + * package. If a license file (e.g., `LICENSE`) is present in the root of the package, it + * will also be included in the output licenses file. + * + * @param metafile An esbuild metafile object. + * @param rootDirectory The root directory of the workspace. + * @returns A string containing the content of the output licenses file. + */ +export async function extractLicenses( + metafiles: Metafile[], + rootDirectory: string, +): Promise { + let extractedLicenseContent = `${EXTRACTION_FILE_HEADER}\n${EXTRACTION_FILE_SEPARATOR}`; + + const seenPaths = new Set(); + const seenPackageDirectories = new Set(); + const seenPackages = new Set(); + + for (const metafile of metafiles) { + for (const entry of Object.values(metafile.outputs)) { + for (const [inputPath, { bytesInOutput }] of Object.entries(entry.inputs)) { + // Skip if not included in output + if (bytesInOutput <= 0) { + continue; + } + + // Skip already processed paths + if (seenPaths.has(inputPath)) { + continue; + } + seenPaths.add(inputPath); + + // Skip non-package paths + if (!inputPath.includes(NODE_MODULE_SEGMENT)) { + continue; + } + + // Extract the package name from the path + let baseDirectory = path.join(rootDirectory, inputPath); + let nameOrScope, nameOrFile; + let found = false; + while (baseDirectory !== path.dirname(baseDirectory)) { + const segment = path.basename(baseDirectory); + if (segment === NODE_MODULE_SEGMENT) { + found = true; + break; + } + + nameOrFile = nameOrScope; + nameOrScope = segment; + baseDirectory = path.dirname(baseDirectory); + } + + // Skip non-package path edge cases that are not caught in the includes check above + if (!found || !nameOrScope) { + continue; + } + + const packageName = nameOrScope.startsWith('@') + ? `${nameOrScope}/${nameOrFile}` + : nameOrScope; + const packageDirectory = path.join(baseDirectory, packageName); + + if (seenPackageDirectories.has(packageDirectory)) { + continue; + } + seenPackageDirectories.add(packageDirectory); + + // Load the package's metadata to find the package's name, version, and license type + const packageJsonPath = path.join(packageDirectory, 'package.json'); + let packageJson; + try { + packageJson = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as { + name: string; + version: string; + // The object form is deprecated and should only be present in old packages + license?: string | { type: string }; + }; + } catch { + // Invalid package + continue; + } + + // Skip already processed packages + const packageId = `${packageName}@${packageJson.version}`; + if (seenPackages.has(packageId)) { + continue; + } + seenPackages.add(packageId); + + // Attempt to find license text inside package + let licenseText = ''; + if ( + typeof packageJson.license === 'string' && + packageJson.license.toUpperCase().startsWith(CUSTOM_LICENSE_TEXT) + ) { + // Attempt to load the package's custom license + let customLicensePath; + const customLicenseFile = path.normalize( + packageJson.license.slice(CUSTOM_LICENSE_TEXT.length).trim(), + ); + if (customLicenseFile.startsWith('..') || path.isAbsolute(customLicenseFile)) { + // Path is attempting to access files outside of the package + // TODO: Issue warning? + } else { + customLicensePath = path.join(packageDirectory, customLicenseFile); + try { + licenseText = await readFile(customLicensePath, 'utf-8'); + } catch {} + } + } else { + // Search for a license file within the root of the package + const entries = await readdir(packageDirectory, { withFileTypes: true }).catch(() => []); + + for (const entry of entries) { + if ( + (entry.isFile() || entry.isSymbolicLink()) && + LICENSE_FILE_REGEXP.test(entry.name) + ) { + const packageLicensePath = path.join(packageDirectory, entry.name); + try { + licenseText = await readFile(packageLicensePath, 'utf-8'); + break; + } catch {} + } + } + } + + // Generate the package's license entry in the output content + extractedLicenseContent += `Package: ${packageJson.name}\n`; + extractedLicenseContent += `License: ${JSON.stringify(packageJson.license, null, 2)}\n`; + extractedLicenseContent += `\n${licenseText}\n`; + extractedLicenseContent += EXTRACTION_FILE_SEPARATOR; + } + } + } + + return extractedLicenseContent; +} diff --git a/packages/angular/build/src/tools/esbuild/load-result-cache.ts b/packages/angular/build/src/tools/esbuild/load-result-cache.ts new file mode 100644 index 000000000000..402069cff1a5 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/load-result-cache.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { OnLoadResult, PluginBuild } from 'esbuild'; +import { normalize } from 'node:path'; + +export interface LoadResultCache { + get(path: string): OnLoadResult | Promise | undefined; + put(path: string, result: OnLoadResult): Promise; + invalidate(path: string): boolean; + readonly watchFiles: ReadonlyArray; +} + +export function createCachedLoad( + cache: LoadResultCache | undefined, + callback: Parameters[1], +): Parameters[1] { + if (cache === undefined) { + return callback; + } + + return async (args) => { + const loadCacheKey = `${args.namespace}:${args.path}`; + let result: OnLoadResult | null | undefined = await cache.get(loadCacheKey); + + if (result === undefined) { + result = await callback(args); + + // Do not cache null or undefined + if (result) { + // Ensure requested path is included if it was a resolved file + if (args.namespace === 'file') { + result.watchFiles ??= []; + if (!result.watchFiles.includes(args.path)) { + result.watchFiles.push(args.path); + } + } + await cache.put(loadCacheKey, result); + } + } + + return result; + }; +} + +export class MemoryLoadResultCache implements LoadResultCache { + #loadResults = new Map(); + #fileDependencies = new Map>(); + #watchFilesPerKey = new Map>(); + + get(path: string): OnLoadResult | undefined { + return this.#loadResults.get(path); + } + + async put(path: string, result: OnLoadResult): Promise { + const previousWatchFiles = this.#watchFilesPerKey.get(path); + + if (result.errors && result.errors.length > 0) { + if (previousWatchFiles) { + result.watchFiles = Array.from( + new Set([...(result.watchFiles ?? []), ...previousWatchFiles]), + ); + } + } + + const currentNormalizedWatchFiles = new Set(result.watchFiles?.map(normalize) ?? []); + + // Clean up any previous file dependencies that are no longer referenced + if (previousWatchFiles) { + for (const watchFile of previousWatchFiles) { + const normalizedWatchFile = normalize(watchFile); + if (!currentNormalizedWatchFiles.has(normalizedWatchFile)) { + const affected = this.#fileDependencies.get(normalizedWatchFile); + if (affected) { + affected.delete(path); + if (affected.size === 0) { + this.#fileDependencies.delete(normalizedWatchFile); + } + } + } + } + } + + if (result.watchFiles && result.watchFiles.length > 0) { + this.#watchFilesPerKey.set(path, [...result.watchFiles]); + } else { + this.#watchFilesPerKey.delete(path); + } + + this.#loadResults.set(path, result); + if (result.watchFiles) { + for (const watchFile of result.watchFiles) { + // Normalize the watch file path to ensure OS consistent paths + const normalizedWatchFile = normalize(watchFile); + let affected = this.#fileDependencies.get(normalizedWatchFile); + if (affected === undefined) { + affected = new Set(); + this.#fileDependencies.set(normalizedWatchFile, affected); + } + affected.add(path); + } + } + } + + invalidate(path: string): boolean { + const affectedPaths = this.#fileDependencies.get(path); + if (!affectedPaths) { + return false; + } + + for (const affected of affectedPaths) { + this.#loadResults.delete(affected); + } + + return true; + } + + get watchFiles(): string[] { + // this.#loadResults.keys() is not included here because the keys + // are namespaced request paths and not disk-based file paths. + return [...this.#fileDependencies.keys()]; + } + + clear(): void { + this.#loadResults.clear(); + this.#fileDependencies.clear(); + this.#watchFilesPerKey.clear(); + } +} diff --git a/packages/angular/build/src/tools/esbuild/load-result-cache_spec.ts b/packages/angular/build/src/tools/esbuild/load-result-cache_spec.ts new file mode 100644 index 000000000000..8a8682beed61 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/load-result-cache_spec.ts @@ -0,0 +1,119 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { MemoryLoadResultCache } from './load-result-cache'; + +describe('MemoryLoadResultCache', () => { + let cache: MemoryLoadResultCache; + + beforeEach(() => { + cache = new MemoryLoadResultCache(); + }); + + it('should store and retrieve results', async () => { + const result = { + contents: 'body { color: red; }', + loader: 'css' as const, + }; + + await cache.put('file:/test/styles.css', result); + const cached = cache.get('file:/test/styles.css'); + + expect(cached).toBe(result); + }); + + it('should track watch files in fileDependencies', async () => { + const result = { + contents: 'body { color: red; }', + loader: 'css' as const, + watchFiles: ['/test/styles.css', '/test/theme.json'], + }; + + await cache.put('file:/test/styles.css', result); + + expect(cache.watchFiles).toContain('/test/styles.css'); + expect(cache.watchFiles).toContain('/test/theme.json'); + }); + + it('should invalidate cached results when a dependency changes', async () => { + const result = { + contents: 'body { color: red; }', + loader: 'css' as const, + watchFiles: ['/test/styles.css', '/test/theme.json'], + }; + + await cache.put('file:/test/styles.css', result); + expect(cache.get('file:/test/styles.css')).toBe(result); + + const invalidated = cache.invalidate('/test/theme.json'); + expect(invalidated).toBeTrue(); + expect(cache.get('file:/test/styles.css')).toBeUndefined(); + }); + + it('should preserve previous watch files when caching an error result', async () => { + const successResult = { + contents: 'body { color: red; }', + loader: 'css' as const, + watchFiles: ['/test/styles.css', '/test/theme.json'], + }; + + await cache.put('file:/test/styles.css', successResult); + cache.invalidate('/test/theme.json'); + + // Simulate an incremental rebuild error result that only has the entry file in watchFiles + const errorResult = { + errors: [{ text: 'Syntax error in theme.json' }], + watchFiles: ['/test/styles.css'], + }; + + await cache.put('file:/test/styles.css', errorResult); + + // Both the entry file and the previous dependency should be tracked + expect(cache.watchFiles).toContain('/test/styles.css'); + expect(cache.watchFiles).toContain('/test/theme.json'); + + // Invalidating the dependency should clear the cached error result + const invalidated = cache.invalidate('/test/theme.json'); + expect(invalidated).toBeTrue(); + expect(cache.get('file:/test/styles.css')).toBeUndefined(); + }); + + it('should clean up previous file dependencies when put updates watchFiles', async () => { + const initialResult = { + contents: 'body { color: red; }', + loader: 'css' as const, + watchFiles: ['/test/styles.css', '/test/old-dep.json'], + }; + + await cache.put('file:/test/styles.css', initialResult); + expect(cache.watchFiles).toContain('/test/old-dep.json'); + + // Update with new watch files (not containing old-dep.json) + const updatedResult = { + contents: 'body { color: blue; }', + loader: 'css' as const, + watchFiles: ['/test/styles.css', '/test/new-dep.json'], + }; + + await cache.put('file:/test/styles.css', updatedResult); + expect(cache.watchFiles).not.toContain('/test/old-dep.json'); + expect(cache.watchFiles).toContain('/test/new-dep.json'); + + // Invalidating old dependency should not affect the cache + expect(cache.invalidate('/test/old-dep.json')).toBeFalse(); + expect(cache.get('file:/test/styles.css')).toBe(updatedResult); + + // Invalidating new dependency should invalidate the cache + expect(cache.invalidate('/test/new-dep.json')).toBeTrue(); + expect(cache.get('file:/test/styles.css')).toBeUndefined(); + // Invalidating a file marks its cached results stale, but preserves watch file tracking + // so the file watcher continues monitoring the dependency for subsequent changes until + // a new build pass (via put) updates the active dependencies. + expect(cache.watchFiles).toContain('/test/new-dep.json'); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts b/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts new file mode 100644 index 000000000000..8a9588b63a7b --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Loader, Plugin } from 'esbuild'; +import { readFile } from 'node:fs/promises'; + +const SUPPORTED_LOADERS: Loader[] = ['base64', 'binary', 'dataurl', 'file', 'text']; + +export function createLoaderImportAttributePlugin(): Plugin { + return { + name: 'angular-loader-import-attributes', + setup(build) { + build.onLoad({ filter: /./ }, async (args) => { + const loader = args.with['loader'] as Loader | undefined; + if (!loader) { + return undefined; + } + + if (!SUPPORTED_LOADERS.includes(loader)) { + return { + errors: [ + { + text: 'Unsupported loader import attribute', + notes: [ + { text: 'Attribute value must be one of: ' + SUPPORTED_LOADERS.join(', ') }, + ], + }, + ], + }; + } + + return { + contents: await readFile(args.path), + loader, + }; + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/persistent-load-result-cache.ts b/packages/angular/build/src/tools/esbuild/persistent-load-result-cache.ts new file mode 100644 index 000000000000..7eaf11806f1d --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/persistent-load-result-cache.ts @@ -0,0 +1,325 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * Implements a generic, two-tier (L1 memory + L2 persistent disk store) caching system for + * esbuild plugin `OnLoadResult` outcomes across the `@angular/build` compiler pipeline. + * + * Supported Module Types: + * 1. **Disk File Modules** (`file:` namespace): Standard disk-based source files (TS, JS, CSS, Sass, Less). + * Cache keys are computed using the root `globalConfigHash`, file path, and file content. Validity is + * verified via fast-path metadata (`mtimeMs` + `size`) with fallback to content hashing (`sha256`). + * 2. **Custom Plugin Namespace Modules** (e.g. `angular:script/global`, `sass:`): Modules loaded through + * custom esbuild namespaces that resolve to disk source files. + * 3. **Virtual Modules & Remote Resources** (e.g. `angular:styles/component`, `css-inline-fonts`): Synthetic + * in-memory modules or remote asset declarations whose compiled outcomes depend on parent source file + * dependencies (`watchFiles`) or global configuration options (`globalConfigHash`). + * + * Key Exported Types: + * - {@link PersistentLoadResultCache}: Primary two-tier cache manager implementing `LoadResultCache`. + * - {@link CachedLoadResultEntry}: Serialized structure persisted to disk for cached esbuild `OnLoadResult` items. + * - {@link CachedDependencyMetadata}: Per-dependency file metadata (`hash`, `mtimeMs`, `size`) used for cache validation and healing. + */ + +import type { Loader, OnLoadResult, PartialMessage } from 'esbuild'; +import { readFile, stat } from 'node:fs/promises'; +import { isAbsolute } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Cache as PersistentCacheStore } from '../../utils/cache'; +import { MAX_CONCURRENT_READS, mapConcurrent, runConcurrent } from '../../utils/concurrency'; +import { calculateHash, createContentHash } from '../../utils/hash'; +import { LoadResultCache, MemoryLoadResultCache } from './load-result-cache'; + +/** + * Metadata for a single watch file dependency. + */ +export interface CachedDependencyMetadata { + hash: string; + mtimeMs: number; + size: number; +} + +/** + * Serialized representation of any esbuild load result stored in persistent cache. + */ +export interface CachedLoadResultEntry { + /** Compiled output string or binary data */ + contents: string | Uint8Array; + + /** esbuild loader type */ + loader?: Loader; + + /** Absolute paths of all imported/watched dependency files */ + watchFiles: string[]; + + /** Absolute paths of all watched directories */ + watchDirs?: string[]; + + /** Map of watchFile absolute paths to dependency metadata */ + watchFilesMetadata: Record; + + /** Warnings emitted during load processing */ + warnings?: PartialMessage[]; + + /** Errors emitted during load processing */ + errors?: PartialMessage[]; +} + +/** + * Calculates a unique cache key from the global configuration hash and path. + */ +function calculateCacheKey(globalConfigHash: string, path: string): string { + const hasher = createContentHash(); + hasher.update(globalConfigHash); + hasher.update('\0'); + hasher.update(path); + + return hasher.digest(); +} + +/** + * Normalizes a namespaced cache key into a valid disk file path if one exists. + * Handles 'file:' URIs, OS platform differences, and custom plugin namespaces. + */ +export function extractDiskFilePath(path: string): string | undefined { + if (path.startsWith('file:')) { + const urlStr = path.startsWith('file://') ? path : 'file://' + path.slice(5); + try { + return fileURLToPath(urlStr); + } catch { + const candidate = path.slice(5); + + return isAbsolute(candidate) ? candidate : undefined; + } + } + + // Handle custom namespace prefix (e.g. "sass:/path/to/file") + // Ensure colonIndex > 1 to avoid treating Windows drive letters (e.g. "C:/") as namespace prefixes. + const colonIndex = path.indexOf(':'); + if (colonIndex > 1) { + const candidatePath = path.slice(colonIndex + 1); + if (isAbsolute(candidatePath)) { + return candidatePath; + } + } + + return isAbsolute(path) ? path : undefined; +} + +/** + * Validates that all imported watch files exist on disk and their contents match. + * Performs a fast-path metadata check (mtime + size) first, falling back to content hashing. + * Heals/updates the cached metadata on disk if the content hash was valid but the metadata changed. + */ +async function validateAndHealCacheEntry( + watchFilesMetadata: Record | undefined, + store: PersistentCacheStore, + cacheKey: string, + cached: CachedLoadResultEntry, +): Promise { + if (!watchFilesMetadata) { + return false; + } + + const watchFiles = Object.keys(watchFilesMetadata); + let healed = false; + + const isValidResults = await mapConcurrent(watchFiles, MAX_CONCURRENT_READS, async (filePath) => { + try { + const stats = await stat(filePath); + const expected = watchFilesMetadata[filePath]; + if (!expected) { + return false; + } + + // 1. Fast Path: size and mtime match + if (stats.size === expected.size && stats.mtimeMs === expected.mtimeMs) { + return true; + } + + // 2. Slow Path: content hash fallback + const currentContent = await readFile(filePath); + const currentHash = calculateHash(currentContent); + if (currentHash === expected.hash) { + // Heal cache entry with new metadata + watchFilesMetadata[filePath] = { + ...expected, + mtimeMs: stats.mtimeMs, + size: stats.size, + }; + healed = true; + + return true; + } + + return false; + } catch { + return false; + } + }); + + if (isValidResults.some((isValid) => !isValid)) { + return false; + } + + if (healed) { + try { + await store.put(cacheKey, cached); + } catch { + // Ignore errors writing healed entries + } + } + + return true; +} + +/** + * Computes metadata (content hashes, mtime, size) for an array of watch file paths. + * Processes files with a sliding worker pool of 16 concurrent operations. + */ +async function computeMetadataForWatchFiles( + watchFiles: string[], + knownContents?: Map, +): Promise> { + const watchFilesMetadata: Record = {}; + + await runConcurrent(watchFiles, MAX_CONCURRENT_READS, async (filePath) => { + try { + const knownContent = knownContents?.get(filePath); + const [content, stats] = await Promise.all([ + knownContent !== undefined ? knownContent : readFile(filePath), + stat(filePath), + ]); + const hash = calculateHash(content); + watchFilesMetadata[filePath] = { + hash, + mtimeMs: stats.mtimeMs, + size: stats.size, + }; + } catch { + // Ignore unreadable files + } + }); + + return watchFilesMetadata; +} + +export class PersistentLoadResultCache implements LoadResultCache { + private readonly memoryCache = new MemoryLoadResultCache(); + + constructor( + private readonly persistentStore?: PersistentCacheStore, + private readonly globalConfigHash: string = '', + ) {} + + /** + * Retrieves a load result from cache. + * Checks L1 memory cache first for immediate watch-mode speed, falling back to L2 persistent disk + * store on L1 cache miss. L2 persistent cache entries are validated against dependency metadata. + */ + async get(path: string): Promise { + // 1. Check L1 Memory Cache + const memoryResult = this.memoryCache.get(path); + if (memoryResult) { + return memoryResult; + } + + if (!this.persistentStore) { + return undefined; + } + + // 2. Check L2 Persistent Disk Cache + const cacheKey = calculateCacheKey(this.globalConfigHash, path); + const cached = await this.persistentStore.get(cacheKey); + + if ( + cached && + (await validateAndHealCacheEntry( + cached.watchFilesMetadata, + this.persistentStore, + cacheKey, + cached, + )) + ) { + const result: OnLoadResult = { + contents: cached.contents, + loader: cached.loader, + watchFiles: cached.watchFiles, + watchDirs: cached.watchDirs, + warnings: cached.warnings, + errors: cached.errors, + }; + + // Populate L1 Memory Cache for subsequent lookups + await this.memoryCache.put(path, result); + + return result; + } + + return undefined; + } + + /** + * Stores a load result in both L1 memory cache and L2 persistent disk store. + */ + async put(path: string, result: OnLoadResult): Promise { + await this.memoryCache.put(path, result); + + // Persist to L2 store if persistentStore is configured and contents exist (including empty strings/buffers) + if (this.persistentStore && result.contents !== undefined) { + let content: string | Uint8Array = ''; + const filePath = extractDiskFilePath(path); + if (filePath) { + try { + content = await readFile(filePath); + } catch { + // Skip L2 persistent store if target disk file cannot be read + return; + } + } + + const cacheKey = calculateCacheKey(this.globalConfigHash, path); + + // Reuse the target file's pre-read content buffer to avoid redundant disk reads (readFile) + // during dependency watch file metadata computation. + const knownContents = filePath + ? new Map([[filePath, content]]) + : undefined; + const allWatchFiles = Array.from( + new Set(filePath ? [filePath, ...(result.watchFiles ?? [])] : result.watchFiles), + ); + const watchFilesMetadata = await computeMetadataForWatchFiles(allWatchFiles, knownContents); + + await this.persistentStore.put(cacheKey, { + contents: result.contents, + loader: result.loader, + watchFiles: result.watchFiles ?? [], + watchDirs: result.watchDirs, + watchFilesMetadata, + warnings: result.warnings, + errors: result.errors, + }); + } + } + + /** + * Invalidates cached entries affected by a modified dependency file during watch mode. + * + * Note: Invalidation of L1 memory cache is sufficient for active watch mode. + * Cross-process/cold start stale entries in L2 persistent store are automatically handled + * during `get()` via dependency metadata verification (`validateAndHealCacheEntry`). + */ + invalidate(path: string): boolean { + return this.memoryCache.invalidate(path); + } + + get watchFiles(): ReadonlyArray { + return this.memoryCache.watchFiles; + } +} diff --git a/packages/angular/build/src/tools/esbuild/persistent-load-result-cache_spec.ts b/packages/angular/build/src/tools/esbuild/persistent-load-result-cache_spec.ts new file mode 100644 index 000000000000..b41add55031d --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/persistent-load-result-cache_spec.ts @@ -0,0 +1,263 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { OnLoadResult } from 'esbuild'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import type { Cache as PersistentCacheStore } from '../../utils/cache'; +import { initializeHash } from '../../utils/hash'; +import { + type CachedLoadResultEntry, + PersistentLoadResultCache, + extractDiskFilePath, +} from './persistent-load-result-cache'; + +describe('extractDiskFilePath', () => { + it('should extract disk file path for file: URIs', () => { + const filePath = '/Users/test/project/file.js'; + expect(extractDiskFilePath(`file://${filePath}`)).toBe(filePath); + }); + + it('should extract disk file path for custom plugin namespaces', () => { + const filePath = '/Users/test/project/file.js'; + expect(extractDiskFilePath(`sass:${filePath}`)).toBe(filePath); + }); + + it('should not strip Windows drive letter as a namespace prefix', () => { + const winPath = 'C:/Users/test/project/file.js'; + expect(extractDiskFilePath(winPath)).not.toBe('/Users/test/project/file.js'); + }); +}); + +describe('PersistentLoadResultCache', () => { + let mockStore: Map; + let persistentStore: PersistentCacheStore; + let tmpDir: string; + let file1: string; + + beforeAll(async () => { + await initializeHash(); + }); + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'persistent-cache-test-')); + file1 = path.join(tmpDir, 'test.js'); + fs.writeFileSync(file1, 'console.log("hello");'); + + mockStore = new Map(); + persistentStore = { + async get(key: string) { + return mockStore.get(key); + }, + async put(key: string, value: CachedLoadResultEntry) { + mockStore.set(key, value); + }, + } as unknown as PersistentCacheStore; + }); + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('should return undefined on L1 and L2 cache miss', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const result = await cache.get(file1); + expect(result).toBeUndefined(); + }); + + it('should hit L2 persistent store and return cached output when dependencies are valid', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: 'console.log("hello");', + loader: 'js', + watchFiles: [file1], + }; + + await cache.put(file1, sampleResult); + + // Create a second cache instance (simulating cold start) + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeDefined(); + expect(hit?.contents).toBe('console.log("hello");'); + expect(hit?.loader).toBe('js'); + }); + + it('should hit L2 persistent store and return cached output for empty file contents', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: '', + loader: 'css', + watchFiles: [file1], + }; + + await cache.put(file1, sampleResult); + + // Create a second cache instance (simulating cold start) + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeDefined(); + expect(hit?.contents).toBe(''); + expect(hit?.loader).toBe('css'); + }); + + it('should preserve watchDirs when hitting L2 persistent store', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: 'console.log("hello");', + loader: 'js', + watchFiles: [file1], + watchDirs: [tmpDir], + }; + + await cache.put(file1, sampleResult); + + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeDefined(); + expect(hit?.watchDirs).toEqual([tmpDir]); + }); + + it('should hit L2 persistent store for custom plugin namespaces backed by disk files', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const customPath = `sass:${file1}`; + const sampleResult: OnLoadResult = { + contents: '.btn { color: red; }', + loader: 'css', + watchFiles: [file1], + }; + + await cache.put(customPath, sampleResult); + + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(customPath); + + expect(hit).toBeDefined(); + expect(hit?.contents).toBe('.btn { color: red; }'); + expect(hit?.loader).toBe('css'); + }); + + it('should hit L2 persistent store for virtual modules without disk representation', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const virtualPath = 'angular:styles/component:css;0;data'; + const sampleResult: OnLoadResult = { + contents: 'h1 { margin: 0; }', + loader: 'css', + watchFiles: [file1], + }; + + await cache.put(virtualPath, sampleResult); + + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(virtualPath); + + expect(hit).toBeDefined(); + expect(hit?.contents).toBe('h1 { margin: 0; }'); + expect(hit?.loader).toBe('css'); + }); + + it('should invalidate L2 persistent cache hit if a watch dependency file is modified', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: 'console.log("hello");', + loader: 'js', + watchFiles: [file1], + }; + + await cache.put(file1, sampleResult); + + // Modify dependency file content + fs.writeFileSync(file1, 'console.log("world");'); + + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeUndefined(); + }); + + it('should heal the cache entry with new metadata if content hash is still valid after mtime changes', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: 'console.log("hello");', + loader: 'js', + watchFiles: [file1], + }; + + await cache.put(file1, sampleResult); + + // Retrieve the cache key from store + const keys = Array.from(mockStore.keys()); + expect(keys.length).toBe(1); + const cacheKey = keys[0]; + + const initialEntry = mockStore.get(cacheKey); + const initialMtime = initialEntry?.watchFilesMetadata[file1].mtimeMs; + expect(initialMtime).toBeDefined(); + + // Artificially change file modification time without changing content + const futureTime = new Date(Date.now() + 50000); + fs.utimesSync(file1, futureTime, futureTime); + + const statsAfter = fs.statSync(file1); + expect(statsAfter.mtimeMs).not.toEqual(initialMtime as number); + + // Query cold cache to trigger fallback content hash check and healing + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeDefined(); + expect(hit?.contents).toBe('console.log("hello");'); + + // Verify metadata was healed in-place in the persistent store + const healedEntry = mockStore.get(cacheKey); + expect(healedEntry?.watchFilesMetadata[file1].mtimeMs).toEqual(statsAfter.mtimeMs); + }); + + it('should safely handle corrupted cache entries with missing watchFilesMetadata', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const sampleResult: OnLoadResult = { + contents: 'console.log("hello");', + loader: 'js', + watchFiles: [file1], + }; + + await cache.put(file1, sampleResult); + + // Corrupt entry in store by removing watchFilesMetadata + const keys = Array.from(mockStore.keys()); + expect(keys.length).toBe(1); + const entry = mockStore.get(keys[0]); + expect(entry).toBeDefined(); + if (entry) { + delete (entry as Partial).watchFilesMetadata; + } + + const coldCache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const hit = await coldCache.get(file1); + + expect(hit).toBeUndefined(); + }); + + it('should skip L2 store put if target file cannot be read from disk', async () => { + const cache = new PersistentLoadResultCache(persistentStore, 'global-hash'); + const nonExistentFile = path.join(tmpDir, 'non-existent.js'); + const sampleResult: OnLoadResult = { + contents: 'console.log("missing");', + loader: 'js', + watchFiles: [], + }; + + await cache.put(nonExistentFile, sampleResult); + + expect(mockStore.size).toBe(0); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/platform-server-domino-plugin.ts b/packages/angular/build/src/tools/esbuild/platform-server-domino-plugin.ts new file mode 100644 index 000000000000..198d44f0c6c4 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/platform-server-domino-plugin.ts @@ -0,0 +1,90 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; +import { toPosixPath } from '../../utils/path'; + +/** + * Filter matching the Domino bundle import inside `@angular/platform-server`. + */ +const BUNDLED_DOMINO_FILTER = /[\\/]third_party[\\/]domino[\\/]bundled-domino\.mjs$/; + +/** + * The property name on `globalThis` where the Domino instance is stored. + */ +const DOMINO_GLOBAL_PROPERTY = 'ɵdomino'; + +/** + * Creates an esbuild plugin that attaches the Domino instance to `globalThis` when + * `@angular/platform-server/init` is bundled into the server polyfills bundle. + * + * @returns An esbuild plugin. + */ +export function createPlatformServerDominoExposePlugin(): Plugin { + return { + name: 'angular-platform-server-domino-expose', + setup(build) { + build.onResolve({ filter: BUNDLED_DOMINO_FILTER }, (args) => + args.namespace !== 'angular:domino-expose' && args.kind === 'import-statement' + ? { + path: 'angular:platform-server-domino', + namespace: 'angular:domino-expose', + pluginData: { + importPath: args.path, + resolveDir: args.resolveDir, + }, + } + : null, + ); + + build.onLoad({ filter: /./, namespace: 'angular:domino-expose' }, (args) => { + const { importPath, resolveDir } = args.pluginData as { + importPath: string; + resolveDir: string; + }; + + return { + contents: [ + `import domino from ${JSON.stringify(toPosixPath(importPath))};`, + `globalThis['${DOMINO_GLOBAL_PROPERTY}'] = domino;`, + `export default domino;`, + ].join('\n'), + loader: 'js', + resolveDir, + }; + }); + }, + }; +} + +/** + * Creates an esbuild plugin that redirects imports of Domino in `@angular/platform-server` + * to the single copy attached to `globalThis` by the server polyfills bundle. + * + * @returns An esbuild plugin. + */ +export function createPlatformServerDominoRedirectPlugin(): Plugin { + return { + name: 'angular-platform-server-domino-redirect', + setup(build) { + build.onResolve({ filter: BUNDLED_DOMINO_FILTER }, (args) => + args.kind === 'import-statement' + ? { + path: 'angular:platform-server-domino', + namespace: 'angular:platform-server-domino', + } + : null, + ); + + build.onLoad({ filter: /./, namespace: 'angular:platform-server-domino' }, () => ({ + contents: `export default globalThis['${DOMINO_GLOBAL_PROPERTY}'];`, + loader: 'js', + })); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/rxjs-esm-resolution-plugin.ts b/packages/angular/build/src/tools/esbuild/rxjs-esm-resolution-plugin.ts new file mode 100644 index 000000000000..9f813d4e9a70 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/rxjs-esm-resolution-plugin.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; + +const RXJS_ESM_RESOLUTION = Symbol('RXJS_ESM_RESOLUTION'); + +/** + * Creates a plugin that forces ESM resolution of rxjs. + * This is needed as when targeting node, the CJS version is used to the current package conditional exports. + * @see: https://github.com/ReactiveX/rxjs/blob/2947583bb33e97f3db9e6d9f6cea70c62a173060/package.json#L19. + * + * NOTE: This can be removed when and if rxjs adds an import condition that allows ESM usage on Node.js. + * + * @returns An esbuild plugin. + */ +export function createRxjsEsmResolutionPlugin(): Plugin { + return { + name: 'angular-rxjs-resolution', + setup(build) { + build.onResolve({ filter: /^rxjs/ }, async (args) => { + if (args.pluginData?.[RXJS_ESM_RESOLUTION]) { + return null; + } + + const { importer, kind, resolveDir, namespace, pluginData = {} } = args; + pluginData[RXJS_ESM_RESOLUTION] = true; + + const result = await build.resolve(args.path, { + importer, + kind, + namespace, + pluginData, + resolveDir, + }); + + result.path = result.path.replace(/([\\/]dist[\\/])cjs([\\/])/, '$1esm$2'); + + return result; + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/server-bundle-metadata-plugin.ts b/packages/angular/build/src/tools/esbuild/server-bundle-metadata-plugin.ts new file mode 100644 index 000000000000..8d26782017c5 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/server-bundle-metadata-plugin.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; + +/** + * Generates an esbuild plugin that appends metadata to the output bundle, + * marking it with server-side rendering (SSR) details for Angular SSR scenarios. + * + * @param options Optional configuration object. + * - `ssrEntryBundle`: If `true`, marks the bundle as an SSR entry point. + * + * @remarks We can't rely on `platform: node` or `platform: neutral`, as the latter + * is used for non-SSR-related code too (e.g., global scripts). + * @returns An esbuild plugin that injects SSR metadata into the build result's metafile. + */ +export function createServerBundleMetadata(options?: { ssrEntryBundle?: boolean }): Plugin { + return { + name: 'angular-server-bundle-metadata', + setup(build) { + build.onEnd((result) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const metafile = result.metafile as any; + if (metafile) { + metafile['ng-ssr-entry-bundle'] = !!options?.ssrEntryBundle; + metafile['ng-platform-server'] = true; + } + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/sourcemap-ignorelist-plugin.ts b/packages/angular/build/src/tools/esbuild/sourcemap-ignorelist-plugin.ts new file mode 100644 index 000000000000..7bfc4c4a9f6a --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/sourcemap-ignorelist-plugin.ts @@ -0,0 +1,214 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'esbuild'; + +/** + * The field identifier for the sourcemap Chrome Devtools ignore list extension. + * + * Following the naming conventions from https://sourcemaps.info/spec.html#h.ghqpj1ytqjbm + */ +const IGNORE_LIST_ID = 'x_google_ignoreList'; + +/** + * The UTF-8 bytes for the node modules check text used to avoid unnecessary parsing + * of a full source map if not present in the source map data. + */ +const NODE_MODULE_BYTES = Buffer.from('node_modules/', 'utf-8'); + +/** + * The UTF-8 bytes for the "sources" property key used to locate the sources array. + */ +const SOURCES_KEY_BYTES = Buffer.from('"sources"', 'utf-8'); + +/** + * The UTF-8 bytes for the ignore list identifier to check if already present. + */ +const IGNORE_LIST_BYTES = Buffer.from(`"${IGNORE_LIST_ID}"`, 'utf-8'); + +/** + * Minimal sourcemap object required to create the ignore list. + */ +interface SourceMap { + sources: string[]; + [IGNORE_LIST_ID]?: number[]; +} + +function extractSources(contents: Buffer): string[] | undefined { + const sourcesKeyIndex = contents.indexOf(SOURCES_KEY_BYTES); + if (sourcesKeyIndex === -1) { + return undefined; + } + + // Find the ':' after "sources" + let colonIndex = sourcesKeyIndex + SOURCES_KEY_BYTES.length; + while (colonIndex < contents.length && contents[colonIndex] <= 0x20) { + colonIndex++; + } + if (contents[colonIndex] !== 0x3a /* : */) { + return undefined; + } + + // Find the '[' for the array + let arrayStartIndex = colonIndex + 1; + while (arrayStartIndex < contents.length && contents[arrayStartIndex] <= 0x20) { + arrayStartIndex++; + } + if (contents[arrayStartIndex] !== 0x5b /* [ */) { + return undefined; + } + + // Scan until matching ']' + let depth = 0; + let inString = false; + for (let i = arrayStartIndex; i < contents.length; i++) { + const byte = contents[i]; + if (inString) { + if (byte === 0x5c /* \ */) { + i++; // skip escaped character + } else if (byte === 0x22 /* " */) { + inString = false; + } + } else if (byte === 0x22 /* " */) { + inString = true; + } else if (byte === 0x5b /* [ */) { + depth++; + } else if (byte === 0x5d /* ] */) { + depth--; + if (depth === 0) { + try { + const slice = contents.toString('utf-8', arrayStartIndex, i + 1); + const parsed = JSON.parse(slice); + + return Array.isArray(parsed) && parsed.every((s) => typeof s === 'string') + ? (parsed as string[]) + : undefined; + } catch { + return undefined; + } + } + } + } + + return undefined; +} + +function updateSourcemapFast(contents: Buffer, ignoreList: readonly number[]): Buffer | undefined { + let braceIndex = 0; + while (braceIndex < contents.length && contents[braceIndex] <= 0x20) { + braceIndex++; + } + if (contents[braceIndex] !== 0x7b /* { */) { + return undefined; + } + + const injection = Buffer.from(`"${IGNORE_LIST_ID}":${JSON.stringify(ignoreList)},`, 'utf-8'); + + return Buffer.concat([ + contents.subarray(0, braceIndex + 1), + injection, + contents.subarray(braceIndex + 1), + ]); +} + +/** + * Creates an esbuild plugin that updates generated sourcemaps to include the Chrome + * DevTools ignore list extension. All source files that originate from a node modules + * directory are added to the ignore list by this plugin. + * + * For more information, see https://developer.chrome.com/articles/x-google-ignore-list/ + * @returns An esbuild plugin. + */ +export function createSourcemapIgnorelistPlugin(): Plugin { + return { + name: 'angular-sourcemap-ignorelist', + setup(build): void { + if (!build.initialOptions.sourcemap) { + return; + } + + build.onEnd((result) => { + if (!result.outputFiles) { + return; + } + + for (const file of result.outputFiles) { + // Only process sourcemap files + if (!file.path.endsWith('.map')) { + continue; + } + + // Create a Buffer object that shares the memory of the output file contents + const contents = Buffer.from( + file.contents.buffer, + file.contents.byteOffset, + file.contents.byteLength, + ); + + // Avoid parsing sourcemaps that have no node modules references + if (!contents.includes(NODE_MODULE_BYTES)) { + continue; + } + + let fastPathSuccess = false; + if (!contents.includes(IGNORE_LIST_BYTES)) { + const sources = extractSources(contents); + if (sources) { + const ignoreList: number[] = []; + for (let index = 0; index < sources.length; ++index) { + const location = sources[index].indexOf('node_modules/'); + if (location === 0 || (location > 0 && sources[index][location - 1] === '/')) { + ignoreList.push(index); + } + } + + if (ignoreList.length === 0) { + continue; + } + + const updated = updateSourcemapFast(contents, ignoreList); + if (updated) { + file.contents = updated; + fastPathSuccess = true; + } + } + } + + if (fastPathSuccess) { + continue; + } + + // Fallback to full JSON parse/stringify if fast scanning or splicing fails + const map = JSON.parse(contents.toString('utf-8')) as SourceMap; + if (map[IGNORE_LIST_ID]) { + continue; + } + + const ignoreList = []; + + // Check and store the index of each source originating from a node modules directory + for (let index = 0; index < map.sources.length; ++index) { + const location = map.sources[index].indexOf('node_modules/'); + if (location === 0 || (location > 0 && map.sources[index][location - 1] === '/')) { + ignoreList.push(index); + } + } + + // Avoid regenerating the source map if nothing changed + if (ignoreList.length === 0) { + continue; + } + + // Update the sourcemap in the output file + map[IGNORE_LIST_ID] = ignoreList; + file.contents = Buffer.from(JSON.stringify(map), 'utf-8'); + } + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts b/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts new file mode 100644 index 000000000000..bb5c945bab7d --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuildOptions, Plugin } from 'esbuild'; +import path from 'node:path'; +import { NormalizedCachedOptions } from '../../../utils/normalize-cache'; +import { PostcssConfiguration } from '../../../utils/postcss-configuration'; +import { LoadResultCache } from '../load-result-cache'; +import { createCssInlineFontsPlugin } from './css-inline-fonts-plugin'; +import { CssStylesheetLanguage } from './css-language'; +import { createCssResourcePlugin } from './css-resource-plugin'; +import { LessStylesheetLanguage } from './less-language'; +import { SassStylesheetLanguage } from './sass-language'; +import { StylesheetPluginFactory, StylesheetPluginsass } from './stylesheet-plugin-factory'; + +export interface BundleStylesheetOptions { + workspaceRoot: string; + optimization: boolean; + inlineFonts: boolean; + dataurl?: boolean; + preserveSymlinks?: boolean; + sourcemap: boolean | 'external' | 'inline' | 'linked'; + sourcesContent?: boolean; + outputNames: { bundles: string; media: string }; + includePaths?: string[]; + sass?: StylesheetPluginsass; + externalDependencies?: string[]; + target: string[]; + tailwindConfiguration?: { file: string; package: string }; + postcssConfiguration?: { config: PostcssConfiguration; configPath: string }; + publicPath?: string; + cacheOptions: NormalizedCachedOptions; +} + +export function createStylesheetBundleOptions( + options: BundleStylesheetOptions, + cache?: LoadResultCache, + inlineComponentData?: Record, +): BuildOptions & { plugins: NonNullable } { + // Ensure preprocessor include paths are absolute based on the workspace root + const includePaths = options.includePaths?.map((includePath) => + path.resolve(options.workspaceRoot, includePath), + ); + + const pluginFactory = new StylesheetPluginFactory( + { + sourcemap: !!options.sourcemap, + includePaths, + inlineComponentData, + tailwindConfiguration: options.tailwindConfiguration, + postcssConfiguration: options.postcssConfiguration, + sass: options.sass, + }, + cache, + ); + + const plugins: Plugin[] = [ + pluginFactory.create(SassStylesheetLanguage), + pluginFactory.create(LessStylesheetLanguage), + pluginFactory.create(CssStylesheetLanguage), + createCssResourcePlugin(cache, options.dataurl), + ]; + + if (options.inlineFonts) { + plugins.unshift(createCssInlineFontsPlugin({ cache, cacheOptions: options.cacheOptions })); + } + + return { + absWorkingDir: options.workspaceRoot, + bundle: true, + entryNames: options.outputNames.bundles, + assetNames: options.outputNames.media, + logLevel: 'silent', + minify: options.optimization, + metafile: true, + sourcemap: options.sourcemap, + sourcesContent: options.sourcesContent, + outdir: options.workspaceRoot, + write: false, + platform: 'browser', + target: options.target, + preserveSymlinks: options.preserveSymlinks, + external: options.externalDependencies, + publicPath: options.publicPath, + conditions: ['style', 'sass', 'less', options.optimization ? 'production' : 'development'], + mainFields: ['style', 'sass'], + // Unlike JS, CSS does not have implicit file extensions in the general case. + // Preprocessor specific behavior is handled in each stylesheet language plugin. + resolveExtensions: [], + plugins, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/css-inline-fonts-plugin.ts b/packages/angular/build/src/tools/esbuild/stylesheets/css-inline-fonts-plugin.ts new file mode 100644 index 000000000000..cbdba93c4940 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/css-inline-fonts-plugin.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin, PluginBuild } from 'esbuild'; +import { InlineFontsProcessor } from '../../../utils/index-file/inline-fonts'; +import { NormalizedCachedOptions } from '../../../utils/normalize-cache'; +import { LoadResultCache, createCachedLoad } from '../load-result-cache'; + +/** + * Options for the createCssInlineFontsPlugin + * @see createCssInlineFontsPlugin + */ +export interface CssInlineFontsPluginOptions { + /** Disk cache normalized options */ + cacheOptions?: NormalizedCachedOptions; + + /** Load results cache. */ + cache?: LoadResultCache; +} + +/** + * Creates an esbuild {@link Plugin} that inlines fonts imported via import-rule. + * within the build configuration. + */ +export function createCssInlineFontsPlugin({ + cache, + cacheOptions, +}: CssInlineFontsPluginOptions): Plugin { + return { + name: 'angular-css-inline-fonts-plugin', + setup(build: PluginBuild): void { + const inlineFontsProcessor = new InlineFontsProcessor({ cache: cacheOptions, minify: false }); + + build.onResolve({ filter: /fonts\.googleapis\.com|use\.typekit\.net/ }, (args) => { + // Only attempt to resolve import-rule tokens which only exist inside CSS. + if (args.kind !== 'import-rule') { + return null; + } + + if (!inlineFontsProcessor.canInlineRequest(args.path)) { + return null; + } + + return { + path: args.path, + namespace: 'css-inline-fonts', + }; + }); + + build.onLoad( + { filter: /./, namespace: 'css-inline-fonts' }, + createCachedLoad(cache, async (args) => { + try { + return { + contents: await inlineFontsProcessor.processURL(args.path), + loader: 'css', + }; + } catch (error) { + return { + loader: 'css', + errors: [ + { + text: `Failed to inline external stylesheet '${args.path}'.`, + notes: error instanceof Error ? [{ text: error.toString() }] : undefined, + }, + ], + }; + } + }), + ); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/css-language.ts b/packages/angular/build/src/tools/esbuild/stylesheets/css-language.ts new file mode 100644 index 000000000000..f631bab2247a --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/css-language.ts @@ -0,0 +1,15 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { StylesheetLanguage } from './stylesheet-plugin-factory'; + +export const CssStylesheetLanguage = Object.freeze({ + name: 'css', + componentFilter: /^css;/, + fileFilter: /\.css$/, +}); diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/css-resource-plugin.ts b/packages/angular/build/src/tools/esbuild/stylesheets/css-resource-plugin.ts new file mode 100644 index 000000000000..ced6422c3fd3 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/css-resource-plugin.ts @@ -0,0 +1,131 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin, PluginBuild } from 'esbuild'; +import { readFile } from 'node:fs/promises'; +import { extname, join, relative } from 'node:path'; +import { LoadResultCache, createCachedLoad } from '../load-result-cache'; + +const CSS_RESOURCE_NAMESPACE = 'angular:css-resource'; + +/** + * Symbol marker used to indicate CSS resource resolution is being attempted. + * This is used to prevent an infinite loop within the plugin's resolve hook. + */ +const CSS_RESOURCE_RESOLUTION = Symbol('CSS_RESOURCE_RESOLUTION'); + +/** + * Creates an esbuild {@link Plugin} that loads all CSS url token references using the + * built-in esbuild `file` loader. A plugin is used to allow for all file extensions + * and types to be supported without needing to manually specify all extensions + * within the build configuration. + * + * @param cache An optional load result cache. + * @param dataurl If true, resources will be loaded with the 'dataurl' loader to inline them as base64 data URIs. + * @returns An esbuild {@link Plugin} instance. + */ +export function createCssResourcePlugin(cache?: LoadResultCache, dataurl?: boolean): Plugin { + return { + name: 'angular-css-resource', + setup(build: PluginBuild): void { + build.onResolve({ filter: /.*/ }, async (args) => { + const { importer, path, kind, resolveDir, namespace, pluginData = {} } = args; + + // Only attempt to resolve url tokens which only exist inside CSS. + // Also, skip this plugin if already attempting to resolve the url-token. + if (kind !== 'url-token' || pluginData[CSS_RESOURCE_RESOLUTION]) { + return null; + } + + let [containingDir, resourceUrl] = path.split('||file:', 2); + if (resourceUrl === undefined) { + // This can happen due to early exit checks in rebasing-importer + // logic such as when the url is an external URL. + resourceUrl = containingDir; + containingDir = ''; + } + + // If root-relative, absolute or protocol relative url, mark as external to leave the + // path/URL in place. + if (/^((?:\w+:)?\/\/|data:|chrome:|#|\/)/.test(resourceUrl)) { + return { + path: resourceUrl, + external: true, + }; + } + + pluginData[CSS_RESOURCE_RESOLUTION] = true; + + const result = await build.resolve(resourceUrl, { + importer, + kind, + namespace, + pluginData, + resolveDir: join(resolveDir, containingDir), + }); + + if (result.errors.length) { + const error = result.errors[0]; + if (resourceUrl[0] === '~') { + error.notes = [ + { + location: null, + text: 'You can remove the tilde and use a relative path to reference it, which should remove this error.', + }, + ]; + } else if (resourceUrl[0] === '^') { + error.notes = [ + { + location: null, + text: + 'You can remove the caret and add the path to the `externalDependencies` build option,' + + ' which should remove this error.', + }, + ]; + } + + const extension = importer && extname(importer); + if (extension !== '.css') { + error.notes.push({ + location: null, + text: 'Preprocessor stylesheets may not show the exact file location of the error.', + }); + } + } + + // Return results that are not files since these are most likely specific to another plugin + // and cannot be loaded by this plugin. + if (result.namespace !== 'file') { + return result; + } + + // All file results are considered CSS resources and will be loaded via the file loader + return { + ...result, + // Use a relative path to prevent fully resolved paths in the metafile (JSON stats file). + // This is only necessary for custom namespaces. esbuild will handle the file namespace. + path: relative(build.initialOptions.absWorkingDir ?? '', result.path), + namespace: CSS_RESOURCE_NAMESPACE, + }; + }); + + build.onLoad( + { filter: /./, namespace: CSS_RESOURCE_NAMESPACE }, + createCachedLoad(cache, async (args) => { + const resourcePath = join(build.initialOptions.absWorkingDir ?? '', args.path); + + return { + contents: await readFile(resourcePath), + loader: dataurl ? 'dataurl' : 'file', + watchFiles: [resourcePath], + }; + }), + ); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts b/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts new file mode 100644 index 000000000000..68cacd576b10 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts @@ -0,0 +1,155 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Location, OnLoadResult, PluginBuild } from 'esbuild'; +import { readFile } from 'node:fs/promises'; +import { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory'; + +/** + * The lazy-loaded instance of the less stylesheet preprocessor. + * It is only imported and initialized if a less stylesheet is used. + */ +let lessPreprocessor: typeof import('less') | undefined; + +interface LessException extends Error { + filename: string; + line: number; + column: number; + extract?: string[]; +} + +function isLessException(error: unknown): error is LessException { + return !!error && typeof error === 'object' && 'column' in error; +} + +export const LessStylesheetLanguage = Object.freeze({ + name: 'less', + componentFilter: /^less;/, + fileFilter: /\.less$/, + process(data, file, _, options, build) { + return compileString(data, file, options, build.resolve.bind(build)); + }, +}); + +async function compileString( + data: string, + filename: string, + options: StylesheetPluginOptions, + resolver: PluginBuild['resolve'], +): Promise { + try { + lessPreprocessor ??= (await import('less')).default; + } catch { + return { + errors: [ + { + text: 'Unable to load the "less" stylesheet preprocessor.', + location: null, + notes: [ + { + text: + 'Ensure that the "less" Node.js package is installed within the project. ' + + "If not present, installation via the project's package manager should resolve the error.", + }, + ], + }, + ], + }; + } + const less = lessPreprocessor; + + const resolverPlugin: Less.Plugin = { + install({ FileManager }, pluginManager): void { + const resolverFileManager = new (class extends FileManager { + override supportsSync(): boolean { + return false; + } + + override supports(): boolean { + return true; + } + + override async loadFile( + filename: string, + currentDirectory: string, + options: Less.LoadFileOptions, + environment: Less.Environment, + ): Promise { + // Attempt direct loading as a relative path to avoid resolution overhead + try { + return await super.loadFile(filename, currentDirectory, options, environment); + } catch (error) { + // Attempt a full resolution if not found + const fullResult = await resolver(filename, { + kind: 'import-rule', + resolveDir: currentDirectory, + }); + if (fullResult.path) { + return { + filename: fullResult.path, + contents: await readFile(fullResult.path, 'utf-8'), + }; + } + // Otherwise error by throwing the failing direct result + throw error; + } + } + })(); + + pluginManager.addFileManager(resolverFileManager); + }, + }; + + try { + const { imports, css } = await less.render(data, { + filename, + paths: options.includePaths, + plugins: [resolverPlugin], + rewriteUrls: 'all', + sourceMap: options.sourcemap + ? { + sourceMapFileInline: true, + outputSourceFiles: true, + } + : undefined, + } as Less.Options); + + return { + contents: css, + loader: 'css', + watchFiles: [filename, ...imports], + }; + } catch (error) { + if (isLessException(error)) { + const location = convertExceptionLocation(error); + + return { + errors: [ + { + text: error.message, + location, + }, + ], + loader: 'css', + watchFiles: location.file ? [filename, location.file] : [filename], + }; + } + + throw error; + } +} + +function convertExceptionLocation(exception: LessException): Partial { + return { + file: exception.filename, + line: exception.line, + column: exception.column, + // Middle element represents the line containing the exception + lineText: exception.extract && exception.extract[Math.trunc(exception.extract.length / 2)], + }; +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/sass-language.ts b/packages/angular/build/src/tools/esbuild/stylesheets/sass-language.ts new file mode 100644 index 000000000000..5c09413bbb9b --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/sass-language.ts @@ -0,0 +1,302 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Location, OnLoadResult, PartialMessage, PartialNote, ResolveResult } from 'esbuild'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import type { CompileResult, Exception, SourceSpan, Syntax } from 'sass-embedded'; +import { MemoryCache } from '../../../utils/cache'; +import type { SassCompiler } from '../../sass/sass-service'; +import { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory'; + +let sassService: SassCompiler | undefined; +let sassServicePromise: Promise | undefined; +let resolutionCache: MemoryCache | undefined; +let packageRootCache: MemoryCache | undefined; + +function isSassException(error: unknown): error is Exception { + return !!error && typeof error === 'object' && 'sassMessage' in error; +} + +export function resetSassWorkerPoolCaches(): void { + resolutionCache?.clear(); + packageRootCache?.clear(); + if (sassService) { + sassService.clearCache(); + } else if (sassServicePromise) { + void sassServicePromise.then((service) => service.clearCache()); + } +} + +export function shutdownSassWorkerPool(): void { + resetSassWorkerPoolCaches(); + if (sassService) { + void sassService.close(); + sassService = undefined; + } else if (sassServicePromise) { + void sassServicePromise.then(shutdownSassWorkerPool); + } + sassServicePromise = undefined; +} + +export const SassStylesheetLanguage = Object.freeze({ + name: 'sass', + componentFilter: /^s[ac]ss;/, + fileFilter: /\.s[ac]ss$/, + process(data, file, format, options, build) { + const syntax = format === 'sass' ? 'indented' : 'scss'; + const resolveUrl = async (url: string, resolveDir: string | undefined) => { + const path = url.startsWith('pkg:') ? url.slice(4) : url; + const result = await build.resolve(path, { + kind: 'import-rule', + resolveDir, + }); + + return result; + }; + + return compileString( + data, + file, + syntax, + options, + resolveUrl, + build.initialOptions.absWorkingDir, + ); + }, +}); + +export function isPackageUrl(url: string): boolean { + if (url.startsWith('pkg:')) { + return true; + } + + return ( + url.length > 0 && + !url.startsWith('.') && + !url.startsWith('/') && + !url.startsWith('\\') && + !url.includes(':') + ); +} + +function parsePackageName(url: string): { packageName: string; readonly pathSegments: string[] } { + const parts = (url.startsWith('pkg:') ? url.slice(4) : url).split('/'); + const hasScope = parts.length >= 2 && parts[0][0] === '@'; + const [nameOrScope, nameOrFirstPath, ...pathPart] = parts; + const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope; + + return { + packageName, + get pathSegments() { + return !hasScope && nameOrFirstPath ? [nameOrFirstPath, ...pathPart] : pathPart; + }, + }; +} + +/** + * Returns the scope that qualifies the cached package resolutions of a stylesheet. A stylesheet + * within `node_modules` uses the root of its enclosing package, since every file of a package + * resolves its dependencies against the same `node_modules` directories. All other stylesheets use + * the working directory, allowing component stylesheets to share package resolutions. + */ +export function getPackageScope( + containingPath: string | undefined, + workingDirectory: string | undefined, +): string { + // The directory segments of the stylesheet, excluding the file name + const segments = containingPath?.split(/[\\/]/).slice(0, -1) ?? []; + const index = segments.lastIndexOf('node_modules'); + if (index === -1) { + return workingDirectory ?? ''; + } + + const packageNameLength = segments[index + 1]?.[0] === '@' ? 2 : 1; + + return segments.slice(0, index + 1 + packageNameLength).join('/'); +} + +async function compileString( + data: string, + filePath: string, + syntax: Syntax, + options: StylesheetPluginOptions, + resolveUrl: (url: string, resolveDir: string | undefined) => Promise, + workingDirectory: string | undefined, +): Promise { + // Lazily load Sass when a Sass file is found + if (sassService === undefined) { + if (sassServicePromise === undefined) { + sassServicePromise = import('../../sass/sass-service').then( + (sassService) => new sassService.SassCompiler(true), + ); + } + try { + sassService = await sassServicePromise; + } finally { + sassServicePromise = undefined; + } + } + + // Caching follows Sass behavior where a given package url will always resolve to the same value + // regardless of its importer's path, except for importers within `node_modules`, which are + // scoped to their enclosing package. Relative paths are qualified with the containing URL. + // A null value indicates that the cached resolution attempt failed to find a location and + // later stage resolution should be attempted. This avoids potentially expensive repeat + // failing resolution attempts. + resolutionCache ??= new MemoryCache(); + packageRootCache ??= new MemoryCache(); + const currentResolutionCache = resolutionCache; + const currentPackageRootCache = packageRootCache; + const warnings: PartialMessage[] = []; + const { silenceDeprecations, futureDeprecations, fatalDeprecations } = options.sass ?? {}; + + try { + const { css, sourceMap, loadedUrls } = await sassService.compileStringAsync(data, { + url: pathToFileURL(filePath), + style: 'expanded', + syntax, + loadPaths: options.includePaths, + sourceMap: options.sourcemap, + sourceMapIncludeSources: options.sourcemap, + silenceDeprecations, + fatalDeprecations, + futureDeprecations, + quietDeps: true, + importers: [ + { + findFileUrl: (url, options) => { + const containingPath = + options.containingUrl?.protocol === 'file:' + ? fileURLToPath(options.containingUrl) + : undefined; + const resolveDir = containingPath ? dirname(containingPath) : workingDirectory; + const isPackage = isPackageUrl(url); + const scope = getPackageScope(containingPath, workingDirectory); + const cacheKey = isPackage + ? `${scope}:${url}` + : `${options.containingUrl?.href ?? ''}:${url}`; + + return currentResolutionCache.getOrCreate(cacheKey, async () => { + const result = await resolveUrl(url, resolveDir); + if (result.path) { + return pathToFileURL(result.path); + } + + // Check for package deep imports + if (!isPackage) { + return null; + } + + const { packageName, pathSegments } = parsePackageName(url); + + // Caching package root locations is particularly beneficial for `@material/*` packages + // which extensively use deep imports. + const packageRoot = await currentPackageRootCache.getOrCreate( + `${scope}:${packageName}`, + async () => { + // Use the required presence of a package root `package.json` file to resolve the location + const packageResult = await resolveUrl(packageName + '/package.json', resolveDir); + + return packageResult.path ? dirname(packageResult.path) : null; + }, + ); + + // Package not found could be because of an error or the specifier is intended to be found + // via a later stage of the resolution process (`loadPaths`, etc.). + // Errors are reported after the full completion of the resolution process. Exceptions for + // not found packages should not be raised here. + if (packageRoot) { + return pathToFileURL(join(packageRoot, ...pathSegments)); + } + + // Not found + return null; + }); + }, + }, + ], + logger: { + warn: (text, { deprecation, stack, span }) => { + const notes: PartialNote[] = []; + if (deprecation) { + notes.push({ text }); + } + if (stack && !span) { + notes.push({ text: stack }); + } + + warnings.push({ + text: deprecation ? 'Deprecation' : text, + location: span && spanToLocation(span), + notes, + }); + }, + }, + }); + + return { + loader: 'css', + contents: sourceMap ? `${css}\n${sourceMapToUrlComment(sourceMap)}` : css, + watchFiles: loadedUrls.map((url) => fileURLToPath(url)), + warnings, + }; + } catch (error) { + if (isSassException(error)) { + const location = spanToLocation(error.span); + const watchFiles = [filePath, ...extractFilesFromStack(error.sassStack)]; + if (location.file) { + watchFiles.push(location.file); + } + + return { + loader: 'css', + errors: [ + { + text: error.message, + location, + }, + ], + warnings, + watchFiles, + }; + } + + throw error; + } +} + +function spanToLocation(span: SourceSpan): Partial { + return { + file: span.url && fileURLToPath(span.url), + lineText: span.context, + // Sass line numbers are 0-based while esbuild's are 1-based + line: span.start.line + 1, + column: span.start.column, + }; +} + +function sourceMapToUrlComment(sourceMap: Exclude): string { + const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64'); + + return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`; +} + +function* extractFilesFromStack(stack: string): Iterable { + const lines = stack.split('\n'); + const cwd = process.cwd(); + + // Stack line has format of ` : ` + for (const line of lines) { + const match = line.trim().match(/^(.+?)\s+\d+:\d+/); + if (match) { + // Stack paths from sass are relative to the current working directory (not input file or workspace root) + yield join(cwd, match[1]); + } + } +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/sass-language_spec.ts b/packages/angular/build/src/tools/esbuild/stylesheets/sass-language_spec.ts new file mode 100644 index 000000000000..ec424208eadc --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/sass-language_spec.ts @@ -0,0 +1,425 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { PluginBuild } from 'esbuild'; +import assert from 'node:assert'; +import { statSync } from 'node:fs'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { SassCompiler } from '../../sass/sass-service'; +import { + SassStylesheetLanguage, + getPackageScope, + isPackageUrl, + resetSassWorkerPoolCaches, + shutdownSassWorkerPool, +} from './sass-language'; + +describe('sass-language', () => { + describe('isPackageUrl', () => { + it('should identify pkg: scheme URLs as package URLs', () => { + expect(isPackageUrl('pkg:@angular/material')).toBeTrue(); + expect(isPackageUrl('pkg:bootstrap')).toBeTrue(); + expect(isPackageUrl('pkg:@material/button/button')).toBeTrue(); + }); + + it('should identify bare specifiers as package URLs', () => { + expect(isPackageUrl('@angular/material')).toBeTrue(); + expect(isPackageUrl('@angular/material/button')).toBeTrue(); + expect(isPackageUrl('@material/button/button.scss')).toBeTrue(); + expect(isPackageUrl('bootstrap')).toBeTrue(); + expect(isPackageUrl('bootstrap/scss/bootstrap')).toBeTrue(); + }); + + it('should not identify relative paths as package URLs', () => { + expect(isPackageUrl('./styles.scss')).toBeFalse(); + expect(isPackageUrl('../shared/variables')).toBeFalse(); + expect(isPackageUrl('.hidden')).toBeFalse(); + expect(isPackageUrl('.\\styles.scss')).toBeFalse(); + expect(isPackageUrl('..\\shared\\variables')).toBeFalse(); + }); + + it('should not identify absolute paths or non-pkg URLs as package URLs', () => { + expect(isPackageUrl('/styles/theme.scss')).toBeFalse(); + expect(isPackageUrl('\\styles\\theme.scss')).toBeFalse(); + expect(isPackageUrl('file:///path/to/theme.scss')).toBeFalse(); + expect(isPackageUrl('http://example.com/styles.css')).toBeFalse(); + expect(isPackageUrl('https://example.com/styles.css')).toBeFalse(); + expect(isPackageUrl('C:\\path\\to\\theme.scss')).toBeFalse(); + expect(isPackageUrl('C:/path/to/theme.scss')).toBeFalse(); + }); + + it('should not identify empty string as a package URL', () => { + expect(isPackageUrl('')).toBeFalse(); + }); + }); + + describe('getPackageScope', () => { + const scope = (containingPath?: string) => getPackageScope(containingPath, '/app'); + + it('should use the working directory for a stylesheet outside node_modules', () => { + expect(scope('/app/src/app.scss')).toBe('/app'); + expect(scope('/app/src/foo-node_modules/a.scss')).toBe('/app'); + expect(scope('/app/src/node_modules.scss')).toBe('/app'); + expect(scope(undefined)).toBe('/app'); + }); + + it('should use the enclosing package root for a stylesheet within node_modules', () => { + expect(scope('/app/node_modules/pkg/a.scss')).toBe('/app/node_modules/pkg'); + expect(scope('/app/node_modules/pkg/sub/a.scss')).toBe('/app/node_modules/pkg'); + expect(scope('/app/node_modules/@scope/pkg/sub/a.scss')).toBe('/app/node_modules/@scope/pkg'); + expect(scope('/app/node_modules/foo-node_modules/a.scss')).toBe( + '/app/node_modules/foo-node_modules', + ); + expect(scope('/app/node_modules/a.scss')).toBe('/app/node_modules'); + }); + + it('should use the innermost package root for a nested dependency', () => { + expect(scope('/app/node_modules/dep/node_modules/pkg/a.scss')).toBe( + '/app/node_modules/dep/node_modules/pkg', + ); + expect(scope('/app/node_modules/.pnpm/pkg@1.0.0/node_modules/pkg/a.scss')).toBe( + '/app/node_modules/.pnpm/pkg@1.0.0/node_modules/pkg', + ); + }); + + it('should support Windows path separators', () => { + expect(getPackageScope('C:\\app\\node_modules\\pkg\\sub\\a.scss', 'C:\\app')).toBe( + 'C:/app/node_modules/pkg', + ); + expect(getPackageScope('C:\\app\\src\\app.scss', 'C:\\app')).toBe('C:\\app'); + }); + }); + + describe('package resolution caching', () => { + let temporaryRoot: string; + let projectRoot: string; + let buttonStylesheet: string; + let cardStylesheet: string; + let dependencyStylesheet: string; + let resolveRequests: string[]; + + /** + * Creates a build stub that resolves a package specifier by searching the `node_modules` + * directories visible from the resolve directory, which is how esbuild resolves the + * package specifiers of a stylesheet. + */ + function createBuildStub(): PluginBuild { + return { + initialOptions: { absWorkingDir: projectRoot }, + resolve: async (path: string, options: { resolveDir: string }) => { + resolveRequests.push(`${options.resolveDir}:${path}`); + + for (let directory = options.resolveDir; ; directory = dirname(directory)) { + // A package specifier resolves to the index file of the package, and an explicit file + // within it to that file. A deeper subpath is left unresolved, as esbuild leaves one + // that the `exports` of the package does not name; the Sass importer then resolves it + // against the package root instead. + for (const candidate of [ + join(directory, 'node_modules', path, '_index.scss'), + join(directory, 'node_modules', path), + ]) { + if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) { + return { path: candidate, errors: [], warnings: [] }; + } + } + + if (dirname(directory) === directory) { + return { path: undefined, errors: [], warnings: [] }; + } + } + }, + } as unknown as PluginBuild; + } + + async function compile(stylesheet: string, source = "@use 'theme';"): Promise { + const result = await SassStylesheetLanguage.process?.( + source, + stylesheet, + 'scss', + { sourcemap: false }, + createBuildStub(), + ); + if (!result) { + throw new Error('The Sass stylesheet language has no process function.'); + } + + if (result.errors?.length) { + return `error: ${result.errors[0].text}`; + } + + return (result.contents as string).trim(); + } + + async function writePackage(directory: string, marker: string): Promise { + await mkdir(join(directory, 'sub'), { recursive: true }); + await writeFile(join(directory, 'package.json'), '{}'); + await writeFile(join(directory, '_index.scss'), `.marker { content: "${marker}"; }`); + await writeFile( + join(directory, 'sub', '_other.scss'), + `.deep { content: "${marker} deep"; }`, + ); + } + + beforeAll(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + temporaryRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-sass-language-')); + projectRoot = join(temporaryRoot, 'project'); + const dependencyRoot = join(projectRoot, 'node_modules', 'dependency'); + + // An application using a `theme` package, and a dependency with its own nested version of + // `theme` plus an `extra` package that only the dependency can see. + await writePackage(join(projectRoot, 'node_modules', 'theme'), 'project'); + await writePackage(join(dependencyRoot, 'node_modules', 'theme'), 'dependency'); + await writePackage(join(dependencyRoot, 'node_modules', 'extra'), 'extra'); + + buttonStylesheet = join(projectRoot, 'src', 'app', 'button', 'button.scss'); + cardStylesheet = join(projectRoot, 'src', 'app', 'card', 'card.scss'); + dependencyStylesheet = join(dependencyRoot, 'styles.scss'); + for (const stylesheet of [buttonStylesheet, cardStylesheet]) { + await mkdir(dirname(stylesheet), { recursive: true }); + } + }); + + afterAll(async () => { + shutdownSassWorkerPool(); + await rm(temporaryRoot, { force: true, recursive: true }); + }); + + beforeEach(() => { + resetSassWorkerPoolCaches(); + resolveRequests = []; + }); + + it('should not use the package resolution of a dependency for the application', async () => { + const dependency = await compile(dependencyStylesheet); + const application = await compile(buttonStylesheet); + + expect(dependency).toContain('content: "dependency";'); + expect(application).toContain('content: "project";'); + }); + + it('should not use the package resolution of the application for a dependency', async () => { + const application = await compile(buttonStylesheet); + const dependency = await compile(dependencyStylesheet); + + expect(application).toContain('content: "project";'); + expect(dependency).toContain('content: "dependency";'); + }); + + it('should not reuse a failed package resolution of the application for a dependency', async () => { + const source = "@use 'extra';"; + const application = await compile(buttonStylesheet, source); + const dependency = await compile(dependencyStylesheet, source); + + expect(application).toContain("Can't find stylesheet to import."); + expect(dependency).toContain('content: "extra";'); + }); + + it('should not use the package root of a dependency for a deep import of the application', async () => { + // A subpath that resolves to no file of its own is located through the root of the package, + // which is cached separately from the resolution of the specifier. + const source = "@use 'theme/sub/other';"; + const dependency = await compile(dependencyStylesheet, source); + const application = await compile(buttonStylesheet, source); + + expect(dependency).toContain('content: "dependency deep";'); + expect(application).toContain('content: "project deep";'); + }); + + it('should share a package resolution between the stylesheets of different components', async () => { + const button = await compile(buttonStylesheet); + const card = await compile(cardStylesheet); + + expect(button).toContain('content: "project";'); + expect(card).toContain('content: "project";'); + expect(resolveRequests.length).toBe(1); + }); + + it('should share a package resolution between the stylesheets of different folders of a dependency', async () => { + const dependencyRoot = join(projectRoot, 'node_modules', 'dependency'); + const first = await compile(join(dependencyRoot, 'sub1', 'styles.scss')); + const second = await compile(join(dependencyRoot, 'sub2', 'styles.scss')); + + expect(first).toContain('content: "dependency";'); + expect(second).toContain('content: "dependency";'); + expect(resolveRequests.length).toBe(1); + }); + + it('should share a package resolution between the stylesheets of different folders of a scoped package', async () => { + const packageRoot = join(projectRoot, 'node_modules', '@scope', 'pkg'); + const first = await compile(join(packageRoot, 'sub1', 'styles.scss')); + const second = await compile(join(packageRoot, 'sub2', 'styles.scss')); + + expect(first).toContain('content: "project";'); + expect(second).toContain('content: "project";'); + expect(resolveRequests.length).toBe(1); + }); + + it('should resolve a package url of a non-file containing URL from the working directory', async () => { + // The stylesheets of a build have file URLs, but Sass does not limit a containing URL to them. + spyOn(SassCompiler.prototype, 'compileStringAsync').and.callFake(async (_, options) => { + const importer = options.importers?.[0] as { + findFileUrl( + url: string, + context: { containingUrl: URL; fromImport: boolean }, + ): Promise; + }; + const url = await importer.findFileUrl('theme', { + containingUrl: new URL('custom:styles.scss'), + fromImport: false, + }); + + return { css: url?.href ?? '', loadedUrls: [] }; + }); + + const result = await compile(buttonStylesheet); + + expect(result).toBe( + pathToFileURL(join(projectRoot, 'node_modules', 'theme', '_index.scss')).href, + ); + }); + + it('should resolve imports when globalThis.Promise is replaced (e.g., by Zone.js)', async () => { + const originalPromise = globalThis.Promise; + + // Simulate Zone.js replacing globalThis.Promise with a constructor where + // native V8 async function return values fail `instanceof globalThis.Promise`. + class ZoneLikePromise { + #inner: Promise; + + constructor( + executor: ( + resolve: (value: T | PromiseLike) => void, + reject: (reason?: unknown) => void, + ) => void, + ) { + this.#inner = new originalPromise(executor); + } + + then( + onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null, + ): ZoneLikePromise { + return new ZoneLikePromise((resolve, reject) => { + this.#inner.then(onfulfilled, onrejected).then(resolve, reject); + }); + } + + catch( + onrejected?: ((reason: unknown) => TResult | PromiseLike) | null, + ): ZoneLikePromise { + return this.then(undefined, onrejected); + } + + finally(onfinally?: (() => void) | null): ZoneLikePromise { + return new ZoneLikePromise((resolve, reject) => { + this.#inner.finally(onfinally).then(resolve, reject); + }); + } + + static resolve(value?: U | PromiseLike): ZoneLikePromise> { + if (value instanceof ZoneLikePromise) { + return value; + } + + return new ZoneLikePromise((resolve) => resolve(value as Awaited)); + } + + static reject(reason?: unknown): ZoneLikePromise { + return new ZoneLikePromise((_, reject) => reject(reason)); + } + + static all(values: Iterable): ZoneLikePromise { + return ZoneLikePromise.resolve(originalPromise.all(values)); + } + } + + globalThis.Promise = ZoneLikePromise as unknown as PromiseConstructor; + try { + const application = await compile(buttonStylesheet); + expect(application).toContain('content: "project";'); + } finally { + globalThis.Promise = originalPromise; + } + }); + }); + + describe('error handling', () => { + const buildStub = { + initialOptions: { absWorkingDir: '/app' }, + resolve: async () => ({ path: undefined, errors: [], warnings: [] }), + } as unknown as PluginBuild; + + afterAll(() => { + shutdownSassWorkerPool(); + }); + + it('should populate structured location on Sass compilation errors', async () => { + const result = await SassStylesheetLanguage.process?.( + 'body {\n color: $undefined-var;\n}', + '/app/src/styles.scss', + 'scss', + { sourcemap: false }, + buildStub, + ); + + expect(result?.errors?.length).toBe(1); + expect(result?.errors?.[0].text).toContain('Undefined variable.'); + expect(result?.errors?.[0].location).toEqual({ + file: '/app/src/styles.scss', + line: 2, + column: 9, + lineText: jasmine.stringContaining('color: $undefined-var;'), + }); + expect(result?.watchFiles).toContain('/app/src/styles.scss'); + }); + + it('should skip stack trace lines without line:col and extract valid stack files', async () => { + spyOn(SassCompiler.prototype, 'compileStringAsync').and.rejectWith({ + message: 'Custom Sass error', + sassMessage: 'Custom Sass error', + sassStack: 'malformed stack line without location\nsrc/partials/_vars.scss 3:5 @use\n', + span: { + url: pathToFileURL('/app/src/partials/_vars.scss'), + context: '$bad: ;', + start: { line: 2, column: 4, offset: 10 }, + end: { line: 2, column: 5, offset: 11 }, + text: ';', + }, + }); + + const result = await SassStylesheetLanguage.process?.( + '@use "partials/vars";', + '/app/src/styles.scss', + 'scss', + { sourcemap: false }, + buildStub, + ); + + expect(result?.errors).toEqual([ + { + text: 'Custom Sass error', + location: { + file: '/app/src/partials/_vars.scss', + lineText: '$bad: ;', + line: 3, + column: 4, + }, + }, + ]); + expect(result?.watchFiles).toEqual([ + '/app/src/styles.scss', + join(process.cwd(), 'src/partials/_vars.scss'), + '/app/src/partials/_vars.scss', + ]); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key.ts b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key.ts new file mode 100644 index 000000000000..d760a14197ec --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { calculateHash } from '../../../utils/hash'; +import type { BundleStylesheetOptions } from './bundle-options'; + +/** + * Generates a global hash based on all build options that affect stylesheet compilation. + * + * IMPORTANT: This hash acts as the root cache key prefix for all persistent stylesheet cache + * entries. Any change in the values hashed below will invalidate all cached stylesheet outputs + * across the entire application. + * + * Included build options and their rationale: + * - `optimization`: Affects CSS minification, dead code elimination, and whitespace stripping. + * - `sourcemap`: Toggles inline/external source map generation and comment insertion. + * - `sourcesContent`: Toggles embedding original source content inside generated source maps. + * - `includePaths`: Changes Sass/Less `@import` and `@use` path resolution search directories. + * - `sassOptions`: Changes Sass compiler deprecations and behavior flags. + * - `target`: Affects CSS property lowering and browser vendor prefixing in esbuild. + * - `publicPath`: Affects relative asset URL rewriting (`url('...')`) inside CSS output. + * - `outputNames`: Affects asset output filename hashing schemes. + * - `inlineFonts`: Controls whether external web font `@import` / `` directives are inlined. + * - `dataurl`: Controls whether referenced assets are inlined as base64 data URIs. + * - `preserveSymlinks`: Controls symlink realpath resolution in monorepos/pnpm workspace packages. + * - `externalDependencies`: Controls which CSS modules/urls are excluded from bundling. + * - `postcssConfig`: Path to custom PostCSS configuration file. + * - `tailwindConfig`: Path to Tailwind CSS configuration file. + * - `packageVersion`: Invalidates cache across `@angular/build` compiler toolchain updates. + * + * @note Maintainers: If any new build option is added to `BundleStylesheetOptions` or `@angular/build` + * that alters generated stylesheet code or asset outputs, it MUST be added to this hash object. + */ +export function calculateGlobalStylesheetConfigHash( + options: BundleStylesheetOptions, + packageVersion: string = '', +): string { + return calculateHash( + JSON.stringify({ + optimization: options.optimization, + sourcemap: options.sourcemap, + sourcesContent: options.sourcesContent, + includePaths: options.includePaths, + sassOptions: options.sass + ? { + futureDeprecations: options.sass.futureDeprecations, + fatalDeprecations: options.sass.fatalDeprecations, + silenceDeprecations: options.sass.silenceDeprecations, + } + : undefined, + target: options.target, + publicPath: options.publicPath, + outputNames: options.outputNames, + inlineFonts: options.inlineFonts, + dataurl: options.dataurl ?? false, + preserveSymlinks: options.preserveSymlinks, + externalDependencies: options.externalDependencies, + postcssConfig: options.postcssConfiguration?.configPath + ? options.postcssConfiguration.configPath + : '', + tailwindConfig: options.tailwindConfiguration?.file ? options.tailwindConfiguration.file : '', + packageVersion, + }), + ); +} diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key_spec.ts b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key_spec.ts new file mode 100644 index 000000000000..49b232720fbf --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-cache-key_spec.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { initializeHash } from '../../../utils/hash'; +import type { BundleStylesheetOptions } from './bundle-options'; +import { calculateGlobalStylesheetConfigHash } from './stylesheet-cache-key'; + +describe('Stylesheet Global Config Hash', () => { + beforeAll(async () => { + await initializeHash(); + }); + + const baseOptions: BundleStylesheetOptions = { + workspaceRoot: '/root', + optimization: true, + inlineFonts: false, + sourcemap: true, + outputNames: { bundles: 'styles', media: 'media' }, + target: ['chrome100'], + cacheOptions: { enabled: true, path: '/cache', basePath: '/root' }, + }; + + describe('calculateGlobalStylesheetConfigHash', () => { + it('should generate consistent hashes for identical options', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash({ ...baseOptions }, '1.0.0'); + expect(hash1).toBe(hash2); + }); + + it('should produce different hashes when optimization changes', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, optimization: false }, + '1.0.0', + ); + expect(hash1).not.toBe(hash2); + }); + + it('should produce different hashes when sourcemap options change', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, sourcemap: false }, + '1.0.0', + ); + expect(hash1).not.toBe(hash2); + }); + + it('should produce different hashes when sourcesContent changes', () => { + const hash1 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, sourcesContent: true }, + '1.0.0', + ); + const hash2 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, sourcesContent: false }, + '1.0.0', + ); + expect(hash1).not.toBe(hash2); + }); + + it('should produce different hashes when target browsers change', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, target: ['firefox90'] }, + '1.0.0', + ); + expect(hash1).not.toBe(hash2); + }); + + it('should produce different hashes when dataurl changes', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash({ ...baseOptions, dataurl: true }, '1.0.0'); + expect(hash1).not.toBe(hash2); + }); + + it('should produce the same hash when dataurl is undefined or false', () => { + const hash1 = calculateGlobalStylesheetConfigHash(baseOptions, '1.0.0'); + const hash2 = calculateGlobalStylesheetConfigHash( + { ...baseOptions, dataurl: false }, + '1.0.0', + ); + expect(hash1).toBe(hash2); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts new file mode 100644 index 000000000000..79337fe1652e --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts @@ -0,0 +1,444 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { OnLoadResult, Plugin, PluginBuild } from 'esbuild'; +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { dirname, extname } from 'node:path'; +import type { Options } from 'sass-embedded'; +import { glob } from 'tinyglobby'; +import { assertIsError } from '../../../utils/error'; +import type { PostcssConfiguration } from '../../../utils/postcss-configuration'; +import { LoadResultCache, createCachedLoad } from '../load-result-cache'; + +/** + * Configuration options for handling Sass-specific deprecations in a stylesheet plugin. + */ +export type StylesheetPluginsass = Pick< + Options<'async'>, + 'futureDeprecations' | 'fatalDeprecations' | 'silenceDeprecations' +>; + +/** + * Convenience type for a postcss processor. + */ +type PostcssProcessor = import('postcss').Processor; + +/** + * The lazy-loaded instance of the postcss stylesheet postprocessor. + * It is only imported and initialized if postcss is needed. + */ +let postcss: (typeof import('postcss'))['default'] | undefined; + +/** + * An object containing the plugin options to use when processing stylesheets. + */ +export interface StylesheetPluginOptions { + /** + * Controls the use and creation of sourcemaps when processing the stylesheets. + * If true, sourcemap processing is enabled; if false, disabled. + */ + sourcemap: boolean; + + /** + * An optional array of paths that will be searched for stylesheets if the default + * resolution process for the stylesheet language does not succeed. + */ + includePaths?: string[]; + + /** + * Optional component data for any inline styles from Component decorator `styles` fields. + * The key is an internal angular resource URI and the value is the stylesheet content. + */ + inlineComponentData?: Record; + + /** + * Optional information used to load and configure Tailwind CSS. If present, the postcss + * will be added to the stylesheet processing with the Tailwind plugin setup as provided + * by the configuration file. + */ + tailwindConfiguration?: { file: string; package: string }; + + /** + * Optional configuration object for custom postcss usage. If present, postcss will be + * initialized and used for every stylesheet. This overrides the tailwind integration + * and any tailwind usage must be manually configured in the custom postcss usage. + */ + postcssConfiguration?: { config: PostcssConfiguration; configPath: string }; + + /** + * Optional Options for configuring Sass behavior. + */ + sass?: StylesheetPluginsass; +} + +/** + * An array of keywords that indicate Tailwind CSS processing is required for a stylesheet. + * + * Based on https://tailwindcss.com/docs/functions-and-directives + */ +const TAILWIND_KEYWORDS = [ + '@tailwind', + '@layer', + '@apply', + '@config', + 'theme(', + 'screen(', + '@screen', // Undocumented in version 3, see: https://github.com/tailwindlabs/tailwindcss/discussions/7516. +]; + +export interface StylesheetLanguage { + name: string; + componentFilter: RegExp; + fileFilter: RegExp; + process?( + data: string, + file: string, + format: string, + options: StylesheetPluginOptions, + build: PluginBuild, + ): OnLoadResult | Promise; +} + +/** + * Cached postcss instances that can be re-used between various StylesheetPluginFactory instances. + */ +const postcssProcessors = new Map>(); + +export class StylesheetPluginFactory { + constructor( + private readonly options: StylesheetPluginOptions, + private readonly cache?: LoadResultCache, + ) {} + + create(language: Readonly): Plugin { + const { cache, options, setupPostcss } = this; + + // Return a noop plugin if no load actions are required + if (!language.process && !options.postcssConfiguration && !options.tailwindConfiguration) { + return { + name: 'angular-' + language.name, + setup() {}, + }; + } + + return { + name: 'angular-' + language.name, + async setup(build) { + // Setup postcss if needed + let postcssProcessor: PostcssProcessor | undefined; + build.onStart(async () => { + try { + postcssProcessor = await setupPostcss; + } catch { + return { + errors: [ + { + text: 'Unable to load the "postcss" stylesheet processor.', + location: null, + notes: [ + { + text: + 'Ensure that the "postcss" Node.js package is installed within the project. ' + + "If not present, installation via the project's package manager should resolve the error.", + }, + ], + }, + ], + }; + } + }); + + // Add a load callback to support inline Component styles + build.onLoad( + { filter: language.componentFilter, namespace: 'angular:styles/component' }, + createCachedLoad(cache, (args) => { + const data = options.inlineComponentData?.[args.path]; + assert( + typeof data === 'string', + `component style name should always be found [${args.path}]`, + ); + + const [format, , filename] = args.path.split(';', 3); + + return processStylesheet( + language, + data, + filename, + format, + options, + build, + postcssProcessor, + ); + }), + ); + + // Add a load callback to support files from disk + build.onLoad( + { filter: language.fileFilter, namespace: 'file' }, + createCachedLoad(cache, async (args) => { + const data = await readFile(args.path, 'utf-8'); + + return processStylesheet( + language, + data, + args.path, + extname(args.path).toLowerCase().slice(1), + options, + build, + postcssProcessor, + ); + }), + ); + }, + }; + } + + private setupPostcssPromise: Promise | undefined; + private get setupPostcss(): Promise { + return (this.setupPostcssPromise ??= this.initPostcss()); + } + + private initPostcssCallCount = 0; + + /** + * This method should not be called directly. + * Use {@link setupPostcss} instead. + */ + private async initPostcss(): Promise { + assert.equal(++this.initPostcssCallCount, 1, '`initPostcss` was called more than once.'); + + const { options } = this; + if (options.postcssConfiguration) { + const { config, configPath } = options.postcssConfiguration; + const postCssInstanceKey = JSON.stringify(config); + let postcssProcessor = postcssProcessors.get(postCssInstanceKey)?.deref(); + + if (!postcssProcessor) { + postcss ??= (await import('postcss')).default; + postcssProcessor = postcss(); + + const postCssPluginRequire = createRequire(dirname(configPath) + '/'); + for (const [pluginName, pluginOptions] of config.plugins) { + const pluginMod = postCssPluginRequire(pluginName); + const plugin = pluginMod.__esModule ? pluginMod['default'] : pluginMod; + if (typeof plugin !== 'function' || plugin.postcss !== true) { + throw new Error(`Attempted to load invalid Postcss plugin: "${pluginName}"`); + } + + postcssProcessor.use(plugin(pluginOptions)); + } + + postcssProcessors.set(postCssInstanceKey, new WeakRef(postcssProcessor)); + } + + return postcssProcessor; + } else if (options.tailwindConfiguration) { + const { package: tailwindPackage, file: config } = options.tailwindConfiguration; + const postCssInstanceKey = tailwindPackage + ':' + config; + let postcssProcessor = postcssProcessors.get(postCssInstanceKey)?.deref(); + + if (!postcssProcessor) { + postcss ??= (await import('postcss')).default; + const tailwind = await import(tailwindPackage); + postcssProcessor = postcss().use(tailwind.default({ config })); + postcssProcessors.set(postCssInstanceKey, new WeakRef(postcssProcessor)); + } + + return postcssProcessor; + } + } +} + +async function processStylesheet( + language: Readonly, + data: string, + filename: string, + format: string, + options: StylesheetPluginOptions, + build: PluginBuild, + postcssProcessor: PostcssProcessor | undefined, +) { + let result: OnLoadResult; + + // Process the input data if the language requires preprocessing + if (language.process) { + result = await language.process(data, filename, format, options, build); + } else { + result = { + contents: data, + loader: 'css', + watchFiles: [filename], + }; + } + + // Return early if there are no contents to further process or there are errors + if (!result.contents || result.errors?.length) { + return result; + } + + // Only use postcss if Tailwind processing is required or custom postcss is present. + if (postcssProcessor && (options.postcssConfiguration || hasTailwindKeywords(result.contents))) { + const postcssResult = await compileString( + typeof result.contents === 'string' + ? result.contents + : Buffer.from(result.contents).toString('utf-8'), + filename, + postcssProcessor, + options, + ); + + // Merge results + if (postcssResult.errors?.length) { + delete result.contents; + } + if (result.warnings && postcssResult.warnings) { + postcssResult.warnings.unshift(...result.warnings); + } + if (result.watchFiles && postcssResult.watchFiles) { + postcssResult.watchFiles.unshift(...result.watchFiles); + } + if (result.watchDirs && postcssResult.watchDirs) { + postcssResult.watchDirs.unshift(...result.watchDirs); + } + result = { + ...result, + ...postcssResult, + }; + } + + return result; +} + +/** + * Searches the provided contents for keywords that indicate Tailwind is used + * within a stylesheet. + * @param contents A string or Uint8Array containing UTF-8 text. + * @returns True, if the contents contains tailwind keywords; False, otherwise. + */ +function hasTailwindKeywords(contents: string | Uint8Array): boolean { + // TODO: use better search algorithm for keywords + if (typeof contents === 'string') { + return TAILWIND_KEYWORDS.some((keyword) => contents.includes(keyword)); + } + + // Contents is a Uint8Array + const data = contents instanceof Buffer ? contents : Buffer.from(contents); + + return TAILWIND_KEYWORDS.some((keyword) => data.includes(keyword)); +} + +/** + * Compiles the provided CSS stylesheet data using a provided postcss processor and provides an + * esbuild load result that can be used directly by an esbuild Plugin. + * @param data The stylesheet content to process. + * @param filename The name of the file that contains the data. + * @param postcssProcessor A postcss processor instance to use. + * @param options The plugin options to control the processing. + * @returns An esbuild OnLoaderResult object with the processed content, warnings, and/or errors. + */ +async function compileString( + data: string, + filename: string, + postcssProcessor: import('postcss').Processor, + options: StylesheetPluginOptions, +): Promise { + try { + const postcssResult = await postcssProcessor.process(data, { + from: filename, + to: filename, + map: options.sourcemap && { + inline: true, + sourcesContent: true, + }, + }); + + const loadResult: OnLoadResult = { + contents: postcssResult.css, + loader: 'css', + }; + + const rawWarnings = postcssResult.warnings(); + if (rawWarnings.length > 0) { + const lineMappings = new Map(); + loadResult.warnings = rawWarnings.map((warning) => { + const file = warning.node.source?.input.file; + if (file === undefined) { + return { text: warning.text }; + } + + let lines = lineMappings.get(file); + if (lines === undefined) { + lines = warning.node.source?.input.css.split(/\r?\n/); + lineMappings.set(file, lines ?? null); + } + + return { + text: warning.text, + location: { + file, + line: warning.line, + column: warning.column - 1, + lineText: lines?.[warning.line - 1], + }, + }; + }); + } + + for (const resultMessage of postcssResult.messages) { + if (resultMessage.type === 'dependency' && typeof resultMessage['file'] === 'string') { + loadResult.watchFiles ??= []; + loadResult.watchFiles.push(resultMessage['file']); + } else if ( + resultMessage.type === 'dir-dependency' && + typeof resultMessage['dir'] === 'string' && + typeof resultMessage['glob'] === 'string' + ) { + loadResult.watchFiles ??= []; + const dependencies = await glob(resultMessage['glob'], { + absolute: true, + cwd: resultMessage['dir'], + }); + loadResult.watchFiles.push(...dependencies); + } + } + + return loadResult; + } catch (error) { + postcss ??= (await import('postcss')).default; + if (error instanceof postcss.CssSyntaxError) { + const lines = error.source?.split(/\r?\n/); + + return { + errors: [ + { + text: error.reason, + location: { + file: error.file, + line: error.line, + column: error.column && error.column - 1, + lineText: error.line === undefined ? undefined : lines?.[error.line - 1], + }, + }, + ], + watchFiles: error.file && error.file !== filename ? [filename, error.file] : [filename], + }; + } else { + assertIsError(error); + + return { + errors: [ + { + text: error.message, + }, + ], + }; + } + } +} diff --git a/packages/angular/build/src/tools/esbuild/target.ts b/packages/angular/build/src/tools/esbuild/target.ts new file mode 100644 index 000000000000..2925905276b7 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/target.ts @@ -0,0 +1,116 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { coerce, compare, minVersion } from 'semver'; + +/** + * Compares two target version strings. + * + * This function is used to determine the lowest version for a given browser target. + * + * @param a The first version string. + * @param b The second version string. + * @returns A negative value if `a` is lower than `b`, a positive value if `a` is higher than `b`, and 0 if they are equal. + */ +function compareTargetVersions(a: string, b: string): number { + const aVersion = coerce(a); + const bVersion = coerce(b); + + if (!aVersion || !bVersion) { + return aVersion ? -1 : bVersion ? 1 : 0; + } + + return compare(aVersion, bVersion); +} + +// https://esbuild.github.io/api/#target +const ESBUILD_SUPPORTED_BROWSERS: ReadonlySet = new Set([ + 'chrome', + 'edge', + 'firefox', + 'ie', + 'ios', + 'node', + 'opera', + 'safari', +]); + +/** + * Transform browserlists result to esbuild target. + * + * Only the lowest version for each browser is returned to avoid issues with esbuild and rolldown + * when multiple versions of the same target engine are specified. + * + * @see https://esbuild.github.io/api/#target + * @see https://github.com/evanw/esbuild/issues/4509 + * @see https://github.com/rolldown/rolldown/issues/10633 + */ +export function transformSupportedBrowsersToTargets(supportedBrowsers: string[]): string[] { + const browsers = new Map(); + + for (const browser of supportedBrowsers) { + let [browserName, version] = browser.toLowerCase().split(' '); + if (!browserName || !version) { + continue; + } + + // browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios` + if (browserName === 'ios_saf') { + browserName = 'ios'; + } + + if (!ESBUILD_SUPPORTED_BROWSERS.has(browserName)) { + continue; + } + + // browserslist uses ranges `15.2-15.3` versions but only the lowest is required + // to perform minimum supported feature checks. esbuild also expects a single version. + [version] = version.split('-'); + + if (browserName === 'safari' && version === 'tp') { + // esbuild only supports numeric versions so `TP` is converted to a high number (999) since + // a Technology Preview (TP) of Safari is assumed to support all currently known features. + version = '999'; + } else if (!version.includes('.')) { + // A lone major version is considered by esbuild to include all minor versions. However, + // browserslist does not and is also inconsistent in its `.0` version naming. For example, + // Safari 15.0 is named `safari 15` but Safari 16.0 is named `safari 16.0`. + version += '.0'; + } + + const current = browsers.get(browserName); + if (!current || compareTargetVersions(version, current) < 0) { + browsers.set(browserName, version); + } + } + + return Array.from(browsers, ([browserName, version]) => browserName + version); +} + +const SUPPORTED_NODE_VERSIONS = '0.0.0-ENGINES-NODE'; + +/** + * Transform supported Node.js versions to esbuild target. + * + * Only the lowest Node.js version is returned to avoid issues with esbuild and rolldown + * when multiple versions of the same target engine are specified. + * + * @see https://esbuild.github.io/api/#target + * @see https://github.com/evanw/esbuild/issues/4509 + * @see https://github.com/rolldown/rolldown/issues/10633 + */ +export function getSupportedNodeTargets(): string[] { + if (SUPPORTED_NODE_VERSIONS.charAt(0) === '0') { + // Unlike `pkg_npm`, `ts_library` which is used to run unit tests does not support substitutions. + return []; + } + + const parsed = minVersion(SUPPORTED_NODE_VERSIONS); + + return parsed ? ['node' + parsed.version] : []; +} diff --git a/packages/angular/build/src/tools/esbuild/target_spec.ts b/packages/angular/build/src/tools/esbuild/target_spec.ts new file mode 100644 index 000000000000..e5a375a1412b --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/target_spec.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { getSupportedNodeTargets, transformSupportedBrowsersToTargets } from './target'; + +describe('esbuild target', () => { + describe('transformSupportedBrowsersToTargets', () => { + it('should return the smallest version for each browser', () => { + const targets = transformSupportedBrowsersToTargets([ + 'chrome 122', + 'chrome 120', + 'chrome 121', + 'firefox 116', + 'firefox 115', + 'safari 17.0', + 'safari 16.4', + ]); + + expect(targets).toEqual(['chrome120.0', 'firefox115.0', 'safari16.4']); + }); + + it('should handle version ranges and pick the lowest version', () => { + const targets = transformSupportedBrowsersToTargets([ + 'ios_saf 15.4', + 'ios_saf 15.2-15.3', + 'ios_saf 16.0', + ]); + + expect(targets).toEqual(['ios15.2']); + }); + + it('should handle Safari TP (Technology Preview)', () => { + const targetsWithOlderSafari = transformSupportedBrowsersToTargets([ + 'safari TP', + 'safari 16.4', + ]); + expect(targetsWithOlderSafari).toEqual(['safari16.4']); + + const targetsWithOnlyTP = transformSupportedBrowsersToTargets(['safari TP']); + expect(targetsWithOnlyTP).toEqual(['safari999']); + }); + + it('should ignore browsers not supported by esbuild', () => { + const targets = transformSupportedBrowsersToTargets([ + 'android 4.4', + 'samsung 22', + 'kaios 2.5', + 'chrome 115', + ]); + + expect(targets).toEqual(['chrome115.0']); + }); + + it('should return empty array for empty supportedBrowsers', () => { + const targets = transformSupportedBrowsersToTargets([]); + expect(targets).toEqual([]); + }); + + it('should handle malformed or incomplete browser strings gracefully', () => { + const targets = transformSupportedBrowsersToTargets(['chrome', 'firefox ', '']); + expect(targets).toEqual([]); + }); + + it('should handle single major versions by appending .0', () => { + const targets = transformSupportedBrowsersToTargets(['chrome 120', 'edge 120']); + expect(targets).toEqual(['chrome120.0', 'edge120.0']); + }); + }); + + describe('getSupportedNodeTargets', () => { + it('should return empty array when node versions are not stamped', () => { + expect(getSupportedNodeTargets()).toEqual([]); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/utils.ts b/packages/angular/build/src/tools/esbuild/utils.ts new file mode 100644 index 000000000000..105471e32b2a --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/utils.ts @@ -0,0 +1,293 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import { BuildOptions, Metafile, OutputFile, formatMessages } from 'esbuild'; +import { Listr } from 'listr2'; +import { basename, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { brotliCompress } from 'node:zlib'; +import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import { OutputMode } from '../../builders/application/schema'; +import { BudgetCalculatorResult } from '../../utils/bundle-calculator'; + +import { BundleStats, generateEsbuildBuildStatsTable } from '../../utils/stats-table'; +import { ExecutionResult, PrerenderedRoutesRecord } from './bundler-execution-result'; +import { type BuildOutputFile, BuildOutputFileType, type InitialFileRecord } from './bundler-files'; + +export function logBuildStats( + metafiles: Metafile[], + outputFiles: BuildOutputFile[], + initial: Map, + budgetFailures: BudgetCalculatorResult[] | undefined, + colors: boolean, + changedFiles?: Set, + estimatedTransferSizes?: Map, + ssrOutputEnabled?: boolean, + verbose?: boolean, +): string { + // Remove the i18n subpath in case the build is using i18n. + // en-US/main.js -> main.js + const normalizedChangedFiles: Set = new Set( + [...(changedFiles ?? [])].map((f) => basename(f)), + ); + const browserStats: BundleStats[] = []; + const serverStats: BundleStats[] = []; + let unchangedCount = 0; + let componentStyleChange = false; + + for (const { path: file, size, type } of outputFiles) { + // Only display JavaScript and CSS files + if (!/\.(?:css|m?js)$/.test(file)) { + continue; + } + + // Show only changed files if a changed list is provided + if (normalizedChangedFiles.size && !normalizedChangedFiles.has(file)) { + ++unchangedCount; + continue; + } + + const isPlatformServer = + type === BuildOutputFileType.ServerApplication || type === BuildOutputFileType.ServerRoot; + if (isPlatformServer && !ssrOutputEnabled) { + // Only log server build stats when SSR is enabled. + continue; + } + + // Skip logging external component stylesheets used for HMR + if (metafiles.some((mf) => mf.outputs[file] && 'ng-component' in mf.outputs[file])) { + componentStyleChange = true; + continue; + } + + const name = initial.get(file)?.name ?? getChunkNameFromMetafile(metafiles, file); + const stat: BundleStats = { + initial: initial.has(file), + stats: [file, name ?? '-', size, estimatedTransferSizes?.get(file) ?? '-'], + }; + + if (isPlatformServer) { + serverStats.push(stat); + } else { + browserStats.push(stat); + } + } + + if (browserStats.length > 0 || serverStats.length > 0) { + const tableText = generateEsbuildBuildStatsTable( + [browserStats, serverStats], + colors, + unchangedCount === 0, + !!estimatedTransferSizes, + budgetFailures, + verbose, + ); + + return tableText + '\n'; + } else if (changedFiles !== undefined) { + if (componentStyleChange) { + return '\nComponent stylesheet(s) changed.\n'; + } else { + return '\nNo output file changes.\n'; + } + } + if (unchangedCount > 0) { + return `Unchanged output files: ${unchangedCount}`; + } + + return ''; +} + +export function getChunkNameFromMetafile( + metafiles: Metafile[] | Metafile, + file: string, +): string | undefined { + const metafileArray = Array.isArray(metafiles) ? metafiles : [metafiles]; + for (const metafile of metafileArray) { + if (metafile.outputs[file]?.entryPoint) { + return getEntryPointName(metafile.outputs[file].entryPoint); + } + } +} + +export async function calculateEstimatedTransferSizes( + outputFiles: OutputFile[], +): Promise> { + const sizes = new Map(); + if (outputFiles.length <= 0) { + return sizes; + } + + return new Promise((resolve, reject) => { + let completeCount = 0; + for (const outputFile of outputFiles) { + // Only calculate JavaScript and CSS files + if (!outputFile.path.endsWith('.js') && !outputFile.path.endsWith('.css')) { + ++completeCount; + continue; + } + + // Skip compressing small files which may end being larger once compressed and will most likely not be + // compressed in actual transit. + if (outputFile.contents.byteLength < 1024) { + sizes.set(outputFile.path, outputFile.contents.byteLength); + ++completeCount; + continue; + } + + // Directly use the async callback function to minimize the number of Promises that need to be created. + brotliCompress(outputFile.contents, (error, result) => { + if (error) { + reject(error); + + return; + } + + sizes.set(outputFile.path, result.byteLength); + if (++completeCount >= outputFiles.length) { + resolve(sizes); + } + }); + } + + // Covers the case where no files need to be compressed + if (completeCount >= outputFiles.length) { + resolve(sizes); + } + }); +} + +export async function withSpinner(text: string, action: () => T | Promise): Promise { + let result; + const taskList = new Listr( + [ + { + title: text, + async task() { + result = await action(); + }, + }, + ], + { rendererOptions: { clearOutput: true } }, + ); + + await taskList.run(); + + return result as T; +} + +export async function withNoProgress(text: string, action: () => T | Promise): Promise { + return action(); +} + +/** + * Generates a syntax feature object map for Angular applications. + * A full set of feature names can be found here: https://esbuild.github.io/api/#supported + * @param nativeAsyncAwait Indicate whether to support native async/await. + * @returns An object that can be used with the esbuild build `supported` option. + */ +export function getFeatureSupport(nativeAsyncAwait: boolean): BuildOptions['supported'] { + return { + // Native async/await is not supported with Zone.js. Disabling support here will cause + // esbuild to downlevel async/await, async generators, and for await...of to a Zone.js supported form. + 'async-await': nativeAsyncAwait, + // Workaround for an esbuild minification bug when async-await is disabled and the target is es2019+. + // The catch binding for downleveled for-await will be incorrectly removed in this specific situation. + ...(!nativeAsyncAwait ? { 'optional-catch-binding': false } : {}), + // V8 currently has a performance defect involving object spread operations that can cause signficant + // degradation in runtime performance. By not supporting the language feature here, a downlevel form + // will be used instead which provides a workaround for the performance issue. + // For more details: https://bugs.chromium.org/p/v8/issues/detail?id=11536 + 'object-rest-spread': false, + }; +} + +interface BuildManifest { + errors: string[]; + warnings: string[]; + outputPaths: { + root: URL; + server?: URL | undefined; + browser: URL; + }; + prerenderedRoutes: PrerenderedRoutesRecord; +} + +export async function createJsonBuildManifest( + result: ExecutionResult, + normalizedOptions: NormalizedApplicationBuildOptions, +): Promise { + const { + colors: color, + outputOptions: { base, server, browser }, + ssrOptions, + outputMode, + } = normalizedOptions; + + const { warnings, errors, prerenderedRoutes } = result; + + const manifest: BuildManifest = { + errors: errors.length ? await formatMessages(errors, { kind: 'error', color }) : [], + warnings: warnings.length ? await formatMessages(warnings, { kind: 'warning', color }) : [], + outputPaths: { + root: pathToFileURL(base), + browser: pathToFileURL(join(base, browser)), + server: + outputMode !== OutputMode.Static && ssrOptions + ? pathToFileURL(join(base, server)) + : undefined, + }, + prerenderedRoutes, + }; + + return JSON.stringify(manifest, undefined, 2); +} + +export async function logMessages( + logger: BuilderContext['logger'], + executionResult: ExecutionResult, + color?: boolean, + jsonLogs?: boolean, +): Promise { + const { warnings, errors, logs } = executionResult; + + if (logs.length) { + logger.info(logs.join('\n')); + } + + if (jsonLogs) { + return; + } + + if (warnings.length) { + logger.warn((await formatMessages(warnings, { kind: 'warning', color })).join('\n')); + } + + if (errors.length) { + logger.error((await formatMessages(errors, { kind: 'error', color })).join('\n')); + } +} + +/** + * Ascertain whether the application operates without `zone.js`, we currently rely on the polyfills setting to determine its status. + * If a file with an extension is provided or if `zone.js` is included in the polyfills, the application is deemed as not zoneless. + * @param polyfills An array of polyfills + * @returns true, when the application is considered as zoneless. + */ +export function isZonelessApp(polyfills: string[] | undefined): boolean { + // TODO: Instead, we should rely on the presence of zone.js in the polyfills build metadata. + return !polyfills?.some((p) => p === 'zone.js' || /\.[mc]?[jt]s$/.test(p)); +} + +function getEntryPointName(entryPoint: string): string { + return basename(entryPoint) + .replace(/(.*:)/, '') // global:bundle.css -> bundle.css + .replace(/\.[cm]?[jt]s$/, '') + .replace(/[\\/.]/g, '-'); +} diff --git a/packages/angular/build/src/tools/esbuild/virtual-module-plugin.ts b/packages/angular/build/src/tools/esbuild/virtual-module-plugin.ts new file mode 100644 index 000000000000..7f6b3729e3fb --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/virtual-module-plugin.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { OnLoadArgs, Plugin, PluginBuild } from 'esbuild'; +import { LoadResultCache, createCachedLoad } from './load-result-cache'; + +/** + * Options for the createVirtualModulePlugin + * @see createVirtualModulePlugin + */ +export interface VirtualModulePluginOptions { + /** Namespace. Example: `angular:polyfills`. */ + namespace: string; + + /** If the generated module should be marked as external. */ + external?: boolean; + + /** Method to transform the onResolve path. */ + transformPath?: (path: string) => string; + + /** Method to provide the module content. */ + loadContent: ( + args: OnLoadArgs, + build: PluginBuild, + ) => ReturnType[1]>; + + /** Restrict to only entry points. Defaults to `true`. */ + entryPointOnly?: boolean; + + /** Load results cache. */ + cache?: LoadResultCache; +} + +/** + * Creates an esbuild plugin that generated virtual modules. + * + * @returns An esbuild plugin. + */ +export function createVirtualModulePlugin(options: VirtualModulePluginOptions): Plugin { + const { + namespace, + external, + transformPath: pathTransformer, + loadContent, + cache, + entryPointOnly = true, + } = options; + + return { + name: namespace.replace(/[/:]/g, '-'), + setup(build): void { + build.onResolve({ filter: new RegExp('^' + namespace) }, ({ kind, path }) => { + if (entryPointOnly && kind !== 'entry-point') { + return null; + } + + return { + path: pathTransformer?.(path) ?? path, + namespace, + }; + }); + + if (external) { + build.onResolve({ filter: /./, namespace }, ({ path }) => { + return { + path, + external: true, + }; + }); + } + + build.onLoad( + { filter: /./, namespace }, + createCachedLoad(cache, (args) => loadContent(args, build)), + ); + }, + }; +} diff --git a/packages/angular/build/src/tools/esbuild/wasm-plugin.ts b/packages/angular/build/src/tools/esbuild/wasm-plugin.ts new file mode 100644 index 000000000000..1bc18dd747b2 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/wasm-plugin.ts @@ -0,0 +1,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 + */ + +import type { Plugin, ResolveOptions } from 'esbuild'; +import assert from 'node:assert'; +import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { basename, dirname, join } from 'node:path'; +import { assertIsError } from '../../utils/error'; +import { LoadResultCache, createCachedLoad } from './load-result-cache'; + +/** + * Options for the Angular WASM esbuild plugin + * @see createWasmPlugin + */ +export interface WasmPluginOptions { + /** Allow generation of async (proposal compliant) WASM imports. This requires zoneless to enable async/await. */ + allowAsync?: boolean; + + /** Load results cache. */ + cache?: LoadResultCache; +} + +const WASM_INIT_NAMESPACE = 'angular:wasm:init'; +const WASM_CONTENTS_NAMESPACE = 'angular:wasm:contents'; +const WASM_RESOLVE_SYMBOL = Symbol('WASM_RESOLVE_SYMBOL'); + +// See: https://github.com/tc39/proposal-regexp-unicode-property-escapes/blob/fe6d07fad74cd0192d154966baa1e95e7cda78a1/README.md#other-examples +const ecmaIdentifierNameRegExp = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u; + +/** + * Creates an esbuild plugin to use WASM files with import statements and expressions. + * The default behavior follows the WebAssembly/ES mode integration proposal found at + * https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration. + * This behavior requires top-level await support which is only available in zoneless + * Angular applications. + * @returns An esbuild plugin. + */ +export function createWasmPlugin(options: WasmPluginOptions): Plugin { + const { allowAsync = false, cache } = options; + + return { + name: 'angular-wasm', + setup(build): void { + build.onResolve({ filter: /\.wasm$/ }, async (args) => { + // Skip if already resolving the WASM file to avoid infinite resolution + if (args.pluginData?.[WASM_RESOLVE_SYMBOL]) { + return; + } + // Skip if not an import statement or expression + if (args.kind !== 'import-statement' && args.kind !== 'dynamic-import') { + return; + } + + // When in the initialization namespace, the content has already been resolved + // and only needs to be loaded for use with the initialization code. + if (args.namespace === WASM_INIT_NAMESPACE) { + return { + namespace: WASM_CONTENTS_NAMESPACE, + path: join(args.resolveDir, args.path), + pluginData: args.pluginData, + }; + } + + // Skip if a custom loader is defined + if (build.initialOptions.loader?.['.wasm'] || args.with['loader']) { + return; + } + + // Attempt full resolution of the WASM file + const resolveOptions: ResolveOptions & { path?: string } = { + ...args, + pluginData: { [WASM_RESOLVE_SYMBOL]: true }, + }; + // The "path" property will cause an error if used in the resolve call + delete resolveOptions.path; + + const result = await build.resolve(args.path, resolveOptions); + + // Skip if there are errors, is external, or another plugin resolves to a custom namespace + if (result.errors.length > 0 || result.external || result.namespace !== 'file') { + // Reuse already resolved result + return result; + } + + return { + ...result, + namespace: WASM_INIT_NAMESPACE, + }; + }); + + build.onLoad( + { filter: /\.wasm$/, namespace: WASM_INIT_NAMESPACE }, + createCachedLoad(cache, async (args) => { + // Ensure async mode is supported + if (!allowAsync) { + return { + errors: [ + { + text: 'WASM/ES module integration imports are not supported with Zone.js applications', + notes: [ + { + text: 'Information about zoneless Angular applications can be found here: https://angular.dev/guide/experimental/zoneless', + }, + ], + }, + ], + }; + } + + const wasmContents = await readFile(args.path); + // Inline WASM code less than 10kB + const inlineWasm = wasmContents.byteLength < 10_000; + + // Add import of WASM contents + let initContents = `import ${inlineWasm ? 'wasmData' : 'wasmPath'} from ${JSON.stringify(basename(args.path))}`; + initContents += inlineWasm ? ' with { loader: "binary" };' : ';\n\n'; + + // Read from the file system when on Node.js (SSR) and not inline + if (!inlineWasm && build.initialOptions.platform === 'node') { + initContents += 'import { readFile } from "node:fs/promises";\n'; + initContents += + 'const wasmData = await readFile(new URL(wasmPath, import.meta.url));\n'; + } + + // Create initialization function + initContents += generateInitHelper( + !inlineWasm && build.initialOptions.platform !== 'node', + wasmContents, + ); + + // Analyze WASM for imports and exports + let importModuleNames, exportNames; + try { + const wasm = await WebAssembly.compile(wasmContents); + importModuleNames = new Set( + WebAssembly.Module.imports(wasm).map((value) => value.module), + ); + exportNames = WebAssembly.Module.exports(wasm).map((value) => value.name); + } catch (error) { + assertIsError(error); + + return { + errors: [{ text: 'Unable to analyze WASM file', notes: [{ text: error.message }] }], + }; + } + + // Ensure export names are valid JavaScript identifiers + const invalidExportNames = exportNames.filter( + (name) => !ecmaIdentifierNameRegExp.test(name), + ); + if (invalidExportNames.length > 0) { + return { + errors: invalidExportNames.map((name) => ({ + text: 'WASM export names must be valid JavaScript identifiers', + notes: [ + { + text: `The export "${name}" is not valid. The WASM file should be updated to remove this error.`, + }, + ], + })), + }; + } + + // Add import statements and setup import object + initContents += 'const importObject = Object.create(null);\n'; + let importIndex = 0; + for (const moduleName of importModuleNames) { + // Add a namespace import for each module name + initContents += `import * as wasm_import_${++importIndex} from ${JSON.stringify(moduleName)};\n`; + // Add the namespace object to the import object + initContents += `importObject[${JSON.stringify(moduleName)}] = wasm_import_${importIndex};\n`; + } + + // Instantiate the module + initContents += 'const instance = await init(importObject);\n'; + + // Add exports + const exportNameList = exportNames.join(', '); + initContents += `const { ${exportNameList} } = instance.exports;\n`; + initContents += `export { ${exportNameList} }\n`; + + return { + contents: initContents, + loader: 'js', + resolveDir: dirname(args.path), + pluginData: { wasmContents }, + watchFiles: [args.path], + }; + }), + ); + + build.onLoad({ filter: /\.wasm$/, namespace: WASM_CONTENTS_NAMESPACE }, async (args) => { + const contents = args.pluginData.wasmContents ?? (await readFile(args.path)); + + let loader: 'binary' | 'file' = 'file'; + if (args.with.loader) { + assert( + args.with.loader === 'binary' || args.with.loader === 'file', + 'WASM loader type should only be binary or file.', + ); + loader = args.with.loader; + } + + return { + contents, + loader, + watchFiles: [args.path], + }; + }); + }, + }; +} + +/** + * Generates the string content of the WASM initialization helper function. + * This function supports both file fetching and inline byte data depending on + * the preferred option for the WASM file. When fetching, an integrity hash is + * also generated and used with the fetch action. + * + * @param streaming Uses fetch and WebAssembly.instantiateStreaming. + * @param wasmContents The binary contents to generate an integrity hash. + * @returns A string containing the initialization function. + */ +function generateInitHelper(streaming: boolean, wasmContents: Uint8Array) { + let resultContents; + if (streaming) { + const fetchOptions = { + integrity: 'sha256-' + createHash('sha256').update(wasmContents).digest('base64'), + }; + const fetchContents = `fetch(new URL(wasmPath, import.meta.url), ${JSON.stringify(fetchOptions)})`; + resultContents = `await WebAssembly.instantiateStreaming(${fetchContents}, imports)`; + } else { + resultContents = 'await WebAssembly.instantiate(wasmData, imports)'; + } + + const contents = ` +let mod; +async function init(imports) { + if (mod) { + return await WebAssembly.instantiate(mod, imports); + } + + const result = ${resultContents}; + mod = result.module; + + return result.instance; +} +`; + + return contents; +} diff --git a/packages/angular/build/src/tools/esbuild/wasm.d.ts b/packages/angular/build/src/tools/esbuild/wasm.d.ts new file mode 100644 index 000000000000..e3b45032eccc --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/wasm.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** @fileoverview + * TypeScript does not provide a separate lib for WASM types and the Node.js + * types (`@types/node`) does not contain them either. This type definition + * file provides type information for the subset of functionality required + * by the Angular build process. Ideally this can be removed when the WASM + * type situation has improved. + */ + +declare namespace WebAssembly { + class Module { + constructor(data: Uint8Array); + + static imports(mod: Module): { module: string; name: string }[]; + static exports(mode: Module): { name: string }[]; + } + function compile(data: Uint8Array): Promise; +} diff --git a/packages/angular/build/src/tools/i18n/i18n-inliner-worker.ts b/packages/angular/build/src/tools/i18n/i18n-inliner-worker.ts new file mode 100644 index 000000000000..778ca55bb814 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-inliner-worker.ts @@ -0,0 +1,581 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { type DecodedSourceMap, type SourceMapInput } from '@ampproject/remapping'; +import { + type ɵParsedTranslation, + ɵisMissingTranslationError, + ɵmakeTemplateObject, + ɵparseMessage, + ɵtranslate, +} from '@angular/localize'; +import { MagicString } from 'magic-string'; +import { deserialize } from 'node:v8'; +import { parseSync } from 'oxc-parser'; +import { traversePostOrder } from '../oxc/traversal'; +import { createSharedTranslationProxy } from './i18n-translation-reader'; +import { loadLocaleData } from './locale-data'; + +/** + * The options passed to the inliner for each code request + */ +export interface InlineCodeRequest { + /** + * The code that should be processed. + */ + code: string; + + /** + * The filename to use in error and warning messages for the provided code. + */ + filename: string; + + /** + * The locale specifier that should be used during the inlining process of the file. + */ + locale: string; + + /** + * The serialized translation messages for the locale that should be used during the inlining + * process of the file. A SharedArrayBuffer or Blob is used so that the messages are shared with + * the Worker by reference instead of being copied into it for every request. + */ + translation?: Blob | SharedArrayBuffer; + + /** + * How to handle missing translations. + */ + missingTranslation?: 'error' | 'warning' | 'ignore'; +} + +/** + * The response returned from a code request. + */ +export interface InlineCodeResult { + output: string; + messages: { type: 'error' | 'warning'; message: string }[]; +} + +/** + * The options passed to the inliner for a batch file request + */ +export interface InlineFileBatchRequest { + /** + * The filename that should be processed. + */ + filename: string; + + /** + * The file content as a Blob. + */ + code: Blob; + + /** + * Optional sourcemap content as a Blob. + */ + map?: Blob; + + /** + * The locale specifiers and optional translations to use during the inlining process of the file. + */ + locales: ReadonlyMap; + + /** + * How to handle missing translations. + */ + missingTranslation?: 'error' | 'warning' | 'ignore'; + + /** + * Whether the file data should be treated as ephemeral and not cached long-term in the Worker. + * Typically true when all remaining locales for the file are processed in a single batch. + */ + ephemeral?: boolean; + + /** + * The list of active locales in the current inlining window. Any cached translation dictionaries + * not present in this list will be evicted from the Worker's memory cache. + */ + activeLocales?: string[]; + + /** + * The current inlining generation counter. When a request with a new generation is received, + * all long-term worker caches are cleared. + */ + generation?: number; +} + +/** + * The result for a single locale within a batch file request. + */ +export interface InlineLocaleResult { + locale: string; + code?: string; + map?: string; + messages: { type: 'error' | 'warning'; message: string }[]; +} + +/** + * The response returned from a batch file request. + */ +export type InlineFileBatchResult = + | { + file: string; + unmodified: true; + messages: { type: 'error' | 'warning'; message: string }[]; + } + | { + file: string; + unmodified?: false; + results: InlineLocaleResult[]; + }; + +/** + * Cached file data including code and extracted localization metadata. + */ +interface CachedFileData { + code: string; + metadata: FileLocalizeMetadata; +} + +/** + * Cache of file data promises keyed by filename. + */ +const fileDataCache = new Map>(); + +/** + * Cache of deserialized translation messages keyed by locale. + */ +const deserializedTranslations = new Map>>(); + +/** + * The current inlining generation for this worker. + */ +let currentGeneration: number | undefined; + +let remapping: typeof import('@ampproject/remapping').default | undefined; + +/** + * Retrieves the file data for a filename, loading and extracting localization metadata. + * If `cache` is true, the result is cached in `fileDataCache` across requests in this Worker. + * If `cache` is false (ephemeral), the result is not retained in `fileDataCache`, allowing it + * to be garbage-collected once the batch request finishes. + * + * @param filename The name of the file to load. + * @param codeBlob The source code file as a Blob. + * @param cache Whether to cache the loaded file data in the Worker's long-term cache. + * @returns The cached or newly extracted code and localization metadata. + */ +function loadFileData(filename: string, codeBlob: Blob, cache = true): Promise { + const existing = fileDataCache.get(filename); + if (existing) { + if (!cache) { + fileDataCache.delete(filename); + } + + return existing; + } + + const fileDataPromise = (async () => { + const code = await codeBlob.text(); + const metadata = extractLocalizeMetadata(filename, code); + + return { code, metadata }; + })(); + + if (cache) { + fileDataPromise.catch(() => { + fileDataCache.delete(filename); + }); + fileDataCache.set(filename, fileDataPromise); + } + + return fileDataPromise; +} + +/** + * Deserializes or wraps the translation messages for a locale, reusing the result for any + * subsequent request that targets the same locale. + * @param locale The locale identifier. + * @param translation Optional serialized translation messages (SharedArrayBuffer or Blob). + * @returns The translation messages, or undefined if the locale has no translations. + */ +function loadTranslation( + locale: string, + translation?: Blob | SharedArrayBuffer, +): Promise> | undefined { + if (!translation) { + return undefined; + } + + let messagesPromise = deserializedTranslations.get(locale); + if (!messagesPromise) { + if (translation instanceof Blob) { + messagesPromise = translation + .arrayBuffer() + .then((buffer) => deserialize(new Uint8Array(buffer)) as Record) + .catch((error) => { + deserializedTranslations.delete(locale); + throw error; + }); + } else { + messagesPromise = Promise.resolve(createSharedTranslationProxy(translation)); + } + deserializedTranslations.set(locale, messagesPromise); + } + + return messagesPromise; +} + +/** + * Inlines multiple locales and translations into a JavaScript file that contains `$localize` usage. + * + * @param request An InlineFileBatchRequest object representing the options for inlining. + * @returns An object containing the inlined results for each requested locale. + */ +export async function inlineFileBatch( + request: InlineFileBatchRequest, +): Promise { + if (request.generation !== undefined && request.generation !== currentGeneration) { + currentGeneration = request.generation; + fileDataCache.clear(); + deserializedTranslations.clear(); + } + + if (request.activeLocales) { + const activeSet = new Set(request.activeLocales); + for (const locale of deserializedTranslations.keys()) { + if (!activeSet.has(locale)) { + deserializedTranslations.delete(locale); + } + } + } + + const { code, metadata } = await loadFileData(request.filename, request.code, !request.ephemeral); + + // Fast path: file has no $localize call sites or locale insert sites + if (metadata.callSites.length === 0 && metadata.localeInsertSites.length === 0) { + return { + file: request.filename, + unmodified: true, + messages: (metadata.diagnostics ?? []).map((message) => ({ + type: 'error' as const, + message, + })), + }; + } + + // Parse the sourcemap once for the entire batch if provided. + // It will naturally be garbage-collected after this batch action returns. + let map: SourceMapInput | undefined; + if (request.map) { + const rawMap = await request.map.text(); + map = rawMap ? (JSON.parse(rawMap) as SourceMapInput) : undefined; + } + + const results = []; + for (const [locale, translation] of request.locales) { + const result = await inlineLocalize( + code, + map, + metadata, + locale, + await loadTranslation(locale, translation), + request.filename, + request.missingTranslation, + ); + + results.push({ + locale, + code: result.code, + map: result.map, + messages: result.diagnostics, + }); + } + + return { + file: request.filename, + results, + }; +} + +/** + * Inlines the provided locale and translation into JavaScript code that contains `$localize` usage. + * This function is a secondary entry primarily for use with component HMR update modules. + * + * @param request An InlineRequest object representing the options for inlining + * @returns An object containing the inlined code. + */ +export async function inlineCode(request: InlineCodeRequest): Promise { + const metadata = extractLocalizeMetadata(request.filename, request.code); + const result = await inlineLocalize( + request.code, + undefined, + metadata, + request.locale, + await loadTranslation(request.locale, request.translation), + request.filename, + request.missingTranslation, + ); + + return { + output: result.code ?? request.code, + messages: result.diagnostics, + }; +} + +type DiagnosticMessage = { type: 'error' | 'warning'; message: string }; + +/** + * Translates a $localize message using @angular/localize low-level runtime functions. + * Handles missing translations and errors without requiring @angular/localize/tools. + */ +function translateMessage( + diagnostics: DiagnosticMessage[], + translations: Record | undefined, + messageParts: TemplateStringsArray, + substitutions: readonly number[], + missingTranslation: 'error' | 'warning' | 'ignore', +): [TemplateStringsArray, readonly number[]] { + // Fast path: untranslated locale (e.g. source locale without a translation dictionary). + // Directly parse the message parts to strip metadata and placeholder markers without + // throwing and catching a MissingTranslationError exception. + if (translations === undefined) { + const message = ɵparseMessage(messageParts, substitutions); + + return [ɵmakeTemplateObject(message.messageParts, message.messageParts), substitutions]; + } + + try { + return ɵtranslate(translations, messageParts, substitutions) as [ + TemplateStringsArray, + readonly number[], + ]; + } catch (error) { + if (ɵisMissingTranslationError(error)) { + if (missingTranslation !== 'ignore') { + diagnostics.push({ type: missingTranslation, message: error.message }); + } + + return [ + ɵmakeTemplateObject(error.parsedMessage.messageParts, error.parsedMessage.messageParts), + substitutions, + ]; + } else { + const message = error instanceof Error ? error.message : String(error); + diagnostics.push({ type: 'error', message }); + + return [messageParts, substitutions]; + } + } +} + +/** + * Metadata for a `$localize` tagged template expression extracted from the AST. + */ +interface LocalizeCallSite { + start: number; + end: number; + messageParts: TemplateStringsArray; + expressions: { start: number; end: number }[]; + expressionIndexes: number[]; +} + +/** + * Metadata extracted from a JavaScript file AST needed for localization inlining. + */ +interface FileLocalizeMetadata { + callSites: LocalizeCallSite[]; + localeInsertSites: { start: number; end: number }[]; + diagnostics?: string[]; +} + +/** + * Extracts localization call sites and locale insertion points from JavaScript code using OXC. + * + * @param filename The name of the file being processed. + * @param code The JavaScript source code. + * @returns The extracted localization metadata. + */ +function extractLocalizeMetadata(filename: string, code: string): FileLocalizeMetadata { + const { program } = parseSync(filename, code, { + sourceType: 'unambiguous', + }); + + if (!program) { + throw new Error(`Unknown error occurred parsing file "${filename}" with OXC.`); + } + + const callSites: LocalizeCallSite[] = []; + const localeInsertSites: { start: number; end: number }[] = []; + let diagnostics: string[] | undefined; + + traversePostOrder(program, (node) => { + if (node.type === 'Literal') { + if (typeof node.value === 'string' && node.value === '___NG_LOCALE_INSERT___') { + localeInsertSites.push({ start: node.start, end: node.end }); + } + } else if (node.type === 'TaggedTemplateExpression') { + if (node.tag.type === 'Identifier' && node.tag.name === '$localize') { + const cooked: string[] = []; + const raw: string[] = []; + let hasMalformedEscape = false; + + for (const q of node.quasi.quasis) { + if (q.value.cooked === null || q.value.cooked === undefined) { + hasMalformedEscape = true; + (diagnostics ??= []).push( + `Malformed escape sequence in $localize template literal in file "${filename}".`, + ); + break; + } + cooked.push(q.value.cooked); + raw.push(q.value.raw); + } + + if (!hasMalformedEscape) { + const messageParts = Object.assign(cooked, { raw }); + const expressions = node.quasi.expressions.map((expr) => ({ + start: expr.start, + end: expr.end, + })); + const expressionIndexes = expressions.map((_, index) => index); + + callSites.push({ + start: node.start, + end: node.end, + messageParts, + expressions, + expressionIndexes, + }); + } + } + } + }); + + return { callSites, localeInsertSites, diagnostics }; +} + +/** + * Escapes a template literal string part for insertion into an ES template literal (backticks). + * Uses JSON.stringify for base escaping of control characters and backslashes, then unescapes + * double quotes and escapes backticks and `${` expression delimiters in a single pass. + */ +function escapeTemplatePart(part: string): string { + return JSON.stringify(part) + .slice(1, -1) + .replace(/\\"|`|\$\{/g, (match) => (match === '\\"' ? '"' : '\\' + match)); +} + +/** + * Inlines translations into code using previously extracted localization metadata. + * + * @param code The source code to transform. + * @param map Optional source map for the source code. + * @param metadata Extracted localization metadata. + * @param locale The target locale identifier. + * @param translation The translation messages dictionary, or undefined for untranslated locale. + * @param filename The name of the file being transformed. + * @param missingTranslation How to handle missing translations. + * @returns The transformed code, optional remapped source map, and diagnostics. + */ +async function inlineLocalize( + code: string, + map: SourceMapInput | undefined, + metadata: FileLocalizeMetadata, + locale: string, + translation: Record | undefined, + filename: string, + missingTranslation: 'error' | 'warning' | 'ignore' = 'warning', +) { + const magicString = new MagicString(code); + const diagnostics: DiagnosticMessage[] = []; + + if (metadata.diagnostics) { + for (const message of metadata.diagnostics) { + diagnostics.push({ type: 'error', message }); + } + } + + if (metadata.localeInsertSites.length > 0) { + const localeData = await loadLocaleData(locale); + if (localeData.error) { + diagnostics.push({ type: 'error', message: localeData.error }); + } else if (localeData.warning) { + diagnostics.push({ type: 'warning', message: localeData.warning }); + } + let injected = false; + for (const site of metadata.localeInsertSites) { + magicString.overwrite( + site.start, + site.end, + JSON.stringify(locale) + (localeData.code && !injected ? `;\n${localeData.code}\n;` : ''), + ); + injected = true; + } + } + + for (const callSite of metadata.callSites) { + const [translatedParts, translatedSubstitutions] = translateMessage( + diagnostics, + translation, + callSite.messageParts, + callSite.expressionIndexes, + translation === undefined ? 'ignore' : missingTranslation, + ); + + // Reconstruct the new template/string literal replacement + let replacement: string; + if (translatedSubstitutions.length === 0) { + replacement = JSON.stringify(translatedParts[0]); + } else { + replacement = '`'; + for (let i = 0; i < translatedParts.length; i++) { + replacement += escapeTemplatePart(translatedParts[i]); + + if (i < translatedSubstitutions.length) { + const originalIndex = translatedSubstitutions[i]; + const expr = callSite.expressions[originalIndex]; + const exprCode = magicString.slice(expr.start, expr.end); + replacement += '${' + exprCode + '}'; + } + } + replacement += '`'; + } + + magicString.overwrite(callSite.start, callSite.end, replacement); + } + + if (!magicString.hasChanged()) { + return { + code: undefined, + map: undefined, + diagnostics, + }; + } + + const outputCode = magicString.toString(); + let outputMap; + if (map) { + // A decoded map is generated here rather than an encoded one because remapping decodes its + // inputs. Encoding the mappings only for remapping to immediately decode them again doubles + // the peak memory of the largest structure involved in inlining a file. + const rawMap = magicString.generateDecodedMap({ + source: filename, + includeContent: true, + hires: 'boundary', + }); + remapping ??= (await import('@ampproject/remapping')).default; + outputMap = remapping([{ ...rawMap, version: 3 } satisfies DecodedSourceMap, map], () => null); + } + + return { + code: outputCode, + map: outputMap && JSON.stringify(outputMap), + diagnostics, + }; +} diff --git a/packages/angular/build/src/tools/i18n/i18n-inliner.ts b/packages/angular/build/src/tools/i18n/i18n-inliner.ts new file mode 100644 index 000000000000..d4a4c4cd631f --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-inliner.ts @@ -0,0 +1,749 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵParsedTranslation } from '@angular/localize'; +import assert from 'node:assert'; +import { createRequire } from 'node:module'; +import { extname, join } from 'node:path'; +import { serialize } from 'node:v8'; +import { + type Cache, + type PersistentCacheStore, + createPersistentCacheStore, +} from '../../utils/cache'; +import { calculateHash, createContentHash, initializeHash } from '../../utils/hash'; +import { WorkerPool } from '../../utils/worker-pool'; +import { + type BuildOutputFile, + BuildOutputFileType, + createOutputFile, +} from '../esbuild/bundler-files'; +import type { + InlineCodeRequest, + InlineCodeResult, + InlineFileBatchRequest, + InlineFileBatchResult, +} from './i18n-inliner-worker'; +import { encodeTranslationToBuffer } from './i18n-translation-encoder'; + +// TODO: Convert to import.meta usage during ESM transition +const localRequire = createRequire(__filename); +const INLINER_WORKER_PATH = localRequire.resolve('./i18n-inliner-worker'); + +interface WorkerTaskMap { + inlineFileBatch: { + request: InlineFileBatchRequest; + result: InlineFileBatchResult; + }; + inlineCode: { + request: InlineCodeRequest; + result: InlineCodeResult; + }; +} + +/** + * A keyword used to indicate if a JavaScript file may require inlining of translations. + * This keyword is used to avoid processing files that would not otherwise need i18n processing. + */ +const LOCALIZE_KEYWORD = '$localize'; + +/** + * The baseline number of locales to process concurrently in a single sliding window. + * This caps peak worker memory on low-core machines while maintaining multi-locale batching throughput. + */ +const DEFAULT_LOCALE_WINDOW_SIZE = 8; + +/** + * Minimum byte size threshold for a file to be eligible for multi-batch sharding. + * Files below this threshold (< 100 KB) are processed in a single batch to minimize IPC overhead. + */ +const SMALL_FILE_FLOOR_BYTES = 100 * 1024; + +/** + * Ratio of the maximum file size in a window to consider a file "dominant". + * Files within 70% of the largest file are sharded across bounded workers for concurrency. + */ +const DOMINANT_FILE_RATIO = 0.7; + +/** + * Maximum number of worker threads to allocate concurrently across dominant files. + * Capping concurrency on dominant files (which hold large AST and sourcemap trees) + * prevents V8 heap and RSS explosion on machines with high CPU core counts. + */ +const MAX_DOMINANT_WORKERS = 4; + +/** + * Serializes the translation messages for a locale for transfer to an inliner Worker. + * + * A SharedArrayBuffer is preferred because it enables zero-copy shared memory access + * and on-demand string decoding across all worker threads. Falls back to a Blob when + * SharedArrayBuffer is unavailable. + * + * @param translation The translation messages for a locale, if the locale has any. + * @param translationIntegrity Optional content hash of the translation file for cache lookup. + * @param translationCache Optional Cache instance for binary translation buffers. + * @returns A SharedArrayBuffer or Blob containing the serialized messages, or undefined if none. + */ +async function serializeTranslation( + translation: Record | undefined, + translationIntegrity?: string, + translationCache?: Cache, +): Promise { + if (!translation) { + return undefined; + } + + if (typeof SharedArrayBuffer !== 'undefined') { + if (translationIntegrity && translationCache) { + // Look up or generate binary translation data in the persistent cache. + // A Uint8Array view is stored in the cache store to allow binary persistence. + const binaryData = await translationCache.getOrCreate(translationIntegrity, () => { + return new Uint8Array(encodeTranslationToBuffer(translation)); + }); + + // On a cache miss, getOrCreate returns the newly created Uint8Array backed by the + // original SharedArrayBuffer. Return it directly to avoid an unnecessary allocation and copy. + if ( + binaryData.buffer instanceof SharedArrayBuffer && + binaryData.byteOffset === 0 && + binaryData.byteLength === binaryData.buffer.byteLength + ) { + return binaryData.buffer; + } + + // On a warm cache hit, the restored data is backed by a standard ArrayBuffer from disk. + // Copy it into a SharedArrayBuffer so worker threads can access it via zero-copy shared memory. + const buffer = new SharedArrayBuffer(binaryData.byteLength); + new Uint8Array(buffer).set(binaryData); + + return buffer; + } + + // When persistent caching is not configured, encode directly into a SharedArrayBuffer. + return encodeTranslationToBuffer(translation); + } + + return new Blob([serialize(translation)]); +} + +/** + * Inlining options that should apply to all transformed code. + */ +export interface I18nInlinerOptions { + missingTranslation: 'error' | 'warning' | 'ignore'; + + /** + * The maximum number of concurrent translation inlining operations. + * When omitted, concurrency defaults to the available worker pool threads. + */ + maxConcurrency?: number; + persistentCachePath?: string; + localizeVersion?: string; +} + +/** + * Options for inlining a specific locale. + */ +export interface LocaleInlineOptions { + /** + * The locale specifier string. + */ + locale: string; + + /** + * The translation messages for the locale, or undefined for the source/untranslated locale. + */ + translation?: Record; + + /** + * An optional content integrity hash of the translation file(s) for fast cache key calculation. + */ + translationIntegrity?: string; +} + +/** + * Result of inlining for a specific locale. + */ +export interface LocaleInlineResult { + outputFiles: BuildOutputFile[]; + errors: string[]; + warnings: string[]; +} + +/** + * Transformation result for a single file and locale combination. + */ +interface TransformedFileResult { + file: string; + code?: string; + map?: string; + messages: { type: 'error' | 'warning'; message: string }[]; +} + +/** + * An uncached transformation request entry for a file within a specific locale. + */ +interface UncachedLocaleEntry { + locale: string; + cacheKey?: string; + translation?: Blob | SharedArrayBuffer; +} + +/** + * A class that performs i18n translation inlining of JavaScript code. + * A worker pool is used to distribute the transformation actions and allow + * parallel processing. Inlining is only performed on code that contains the + * localize function (`$localize`). + */ +export class I18nInliner { + #cacheInitFailed = false; + readonly #workerPool: WorkerPool; + readonly #ownsWorkerPool: boolean; + #cacheStore: PersistentCacheStore | undefined; + #transformedFileCache: Cache | undefined; + #translationCache: Cache | undefined; + #generation = 0; + + get #maxConcurrency(): number { + return this.options.maxConcurrency ?? (this.#workerPool.maxThreads || 1); + } + + constructor( + private readonly options: I18nInlinerOptions, + workerPool?: WorkerPool, + ) { + if ( + options.maxConcurrency !== undefined && + (!Number.isInteger(options.maxConcurrency) || options.maxConcurrency < 1) + ) { + throw new RangeError('options.maxConcurrency must be an integer greater than or equal to 1.'); + } + + this.#ownsWorkerPool = !workerPool; + // Piscina uses object spread against default options internally. Only define + // maxThreads when specified to avoid overwriting Piscina's default thread count + // with undefined. + this.#workerPool = + workerPool ?? + new WorkerPool({ + ...(options.maxConcurrency !== undefined && { maxThreads: options.maxConcurrency }), + }); + } + + #partitionFiles(files: Iterable): { + filenames: string[]; + localizeFiles: Map; + localizeMaps: Map; + unmodifiedFiles: BuildOutputFile[]; + } { + const filenames: string[] = []; + const localizeFiles = new Map(); + const localizeMaps = new Map(); + const unmodifiedFiles: BuildOutputFile[] = []; + + const pendingMaps: BuildOutputFile[] = []; + for (const file of files) { + if (file.type === BuildOutputFileType.Root || file.type === BuildOutputFileType.ServerRoot) { + // Skip also the server entry-point. + // Skip stats and similar files. + continue; + } + + const fileExtension = extname(file.path); + if (fileExtension === '.js' || fileExtension === '.mjs') { + // Check if localizations are present + const contentBuffer = Buffer.isBuffer(file.contents) + ? file.contents + : Buffer.from(file.contents.buffer, file.contents.byteOffset, file.contents.byteLength); + const hasLocalize = contentBuffer.includes(LOCALIZE_KEYWORD); + + if (hasLocalize) { + localizeFiles.set(file.path, file); + filenames.push(file.path); + + continue; + } + } else if (fileExtension === '.map') { + // The related JS file may not have been checked yet. To ensure that map files are not + // missed, store any pending map files and check them after all output files. + pendingMaps.push(file); + continue; + } + + unmodifiedFiles.push(file); + } + + // Check if any pending map files should be processed by checking if the parent JS file is present + for (const file of pendingMaps) { + const jsPath = file.path.slice(0, -4); + if (localizeFiles.has(jsPath)) { + localizeMaps.set(jsPath, file); + } else { + unmodifiedFiles.push(file); + } + } + + return { filenames, localizeFiles, localizeMaps, unmodifiedFiles }; + } + + /** + * Performs inlining of translations across multiple locales in parallel. + * + * An adaptive 2D task-partitioning algorithm distributes (files x locales) work units + * across all worker threads while caching AST metadata and sourcemaps in worker memory. + * + * @param files The build output files to transform. + * @param locales The locales and translations to inline. + * @returns A map of locale names to their inlined output files and diagnostics. + */ + async inlineAll( + files: Iterable, + locales: Iterable, + ): Promise> { + await this.initCache(); + + const generation = ++this.#generation; + const { missingTranslation, localizeVersion } = this.options; + const localeList = Array.from(locales); + + if (localeList.length === 0) { + return new Map(); + } + + const { filenames, localizeFiles, localizeMaps, unmodifiedFiles } = this.#partitionFiles(files); + + const fileResultsByLocale = new Map>(); + for (const { locale } of localeList) { + assert(!fileResultsByLocale.has(locale), 'Duplicate locale provided to inliner: ' + locale); + fileResultsByLocale.set(locale, new Map()); + } + + // Process locales in sliding windows to cap peak worker memory. + // Ensure the window has at least enough locales to saturate all available workers on high-core machines. + const windowSize = Math.max(DEFAULT_LOCALE_WINDOW_SIZE, this.#maxConcurrency); + for (let i = 0; i < localeList.length; i += windowSize) { + const windowLocales = localeList.slice(i, i + windowSize); + const activeLocales = windowLocales.map((item) => item.locale); + const isLastWindow = i + windowSize >= localeList.length; + + // Pre-calculate cache key bases and serialized Blobs for each locale in this window + const localeCacheBases = new Map(); + const localeBlobs = new Map(); + + await Promise.all( + windowLocales.map(async ({ locale, translation, translationIntegrity }) => { + const serialized = await serializeTranslation( + translation, + translationIntegrity, + this.#translationCache, + ); + localeBlobs.set(locale, serialized); + + if (this.#cacheStore) { + localeCacheBases.set( + locale, + calculateHash( + JSON.stringify({ + locale, + translation: translationIntegrity || translation, + missingTranslation, + localizeVersion, + }), + ), + ); + } + }), + ); + + const uncachedByFile = new Map(); + + if (this.#transformedFileCache) { + const cache = this.#transformedFileCache; + const cacheChecks: Promise[] = []; + + for (const filename of filenames) { + const file = localizeFiles.get(filename); + assert(file !== undefined, 'Localize file must exist: ' + filename); + + const fileEntriesPromises = windowLocales.map( + async ({ locale }): Promise => { + const fileCacheKeyBase = localeCacheBases.get(locale); + assert(fileCacheKeyBase !== undefined, 'Cache base must exist for locale: ' + locale); + + const hasher = createContentHash(); + hasher.update(file.hash); + hasher.update(filename); + hasher.update(fileCacheKeyBase); + const cacheKey = hasher.digest(); + + try { + const result = await cache.get(cacheKey); + if (result) { + fileResultsByLocale.get(locale)?.set(filename, result); + + return; + } + } catch {} + + return { + locale, + cacheKey, + translation: localeBlobs.get(locale), + }; + }, + ); + + cacheChecks.push( + Promise.all(fileEntriesPromises).then((entries) => { + const filtered = entries.filter((e): e is UncachedLocaleEntry => e !== undefined); + if (filtered.length > 0) { + uncachedByFile.set(filename, filtered); + } + }), + ); + } + + await Promise.all(cacheChecks); + } else { + for (const filename of filenames) { + uncachedByFile.set( + filename, + windowLocales.map(({ locale }) => ({ + locale, + translation: localeBlobs.get(locale), + })), + ); + } + } + + // Adaptive 2D Sharding for uncached tasks in this window + if (uncachedByFile.size > 0) { + await this.#processUncachedBatches( + localizeFiles, + localizeMaps, + uncachedByFile, + fileResultsByLocale, + activeLocales, + isLastWindow, + generation, + ); + } + } + + // Assemble final results in deterministic order per locale + const resultsByLocale = new Map(); + + for (const { locale } of localeList) { + const fileResults = fileResultsByLocale.get(locale); + const outputFiles: BuildOutputFile[] = []; + const errors: string[] = []; + const warnings: string[] = []; + + if (fileResults) { + for (const filename of filenames) { + const originalFile = localizeFiles.get(filename); + assert(originalFile !== undefined, 'Localize file must exist: ' + filename); + + const fileResult = fileResults.get(filename); + if (!fileResult) { + continue; + } + + const type = originalFile.type; + if (fileResult.code != undefined) { + outputFiles.push(createOutputFile(filename, fileResult.code, type)); + } else { + outputFiles.push(originalFile.clone()); + } + + const originalMap = localizeMaps.get(filename); + if (fileResult.map !== undefined) { + outputFiles.push(createOutputFile(filename + '.map', fileResult.map, type)); + } else if (originalMap !== undefined) { + outputFiles.push(originalMap.clone()); + } + + for (const message of fileResult.messages) { + if (message.type === 'error') { + errors.push(message.message); + } else { + warnings.push(message.message); + } + } + } + } + + // Include cloned unmodified files for every locale + outputFiles.push(...unmodifiedFiles.map((file) => file.clone())); + + resultsByLocale.set(locale, { + outputFiles, + errors, + warnings, + }); + } + + return resultsByLocale; + } + + async #processUncachedBatches( + localizeFiles: Map, + localizeMaps: Map, + uncachedByFile: Map, + fileResultsByLocale: Map>, + activeLocales?: string[], + isLastWindow = true, + generation?: number, + ): Promise { + const workerCount = this.#maxConcurrency; + + // Extract file data and identify the heaviest file size in a single pass + let maxFileSize = 0; + const sortedFiles = Array.from(uncachedByFile, ([filename, entries]) => { + const codeFile = localizeFiles.get(filename); + assert(codeFile !== undefined, 'Localize file must exist: ' + filename); + const fileSize = codeFile.contents.byteLength; + if (fileSize > maxFileSize) { + maxFileSize = fileSize; + } + + return { filename, entries, codeFile, fileSize }; + }); + + // Sort files descending by byte size (Longest Processing Time First / LPT). + // Heavy files (e.g. main.js) are queued first to saturate all worker threads immediately, + // while small files act as gap fillers near the window barrier to prevent tail stragglers. + sortedFiles.sort((a, b) => b.fileSize - a.fileSize); + + const dominantThreshold = Math.max(SMALL_FILE_FLOOR_BYTES, maxFileSize * DOMINANT_FILE_RATIO); + let dominantCount = 0; + for (const { fileSize } of sortedFiles) { + if (fileSize >= dominantThreshold) { + dominantCount++; + } else { + break; + } + } + const dominantTargetWorkers = + dominantCount > 0 + ? Math.max(1, Math.min(workerCount - 1, Math.floor(MAX_DOMINANT_WORKERS / dominantCount))) + : 1; + + const workerTasks: Promise[] = []; + + for (const { filename, entries, codeFile, fileSize } of sortedFiles) { + const mapFile = localizeMaps.get(filename); + const codeBlob = new Blob([codeFile.contents]); + const mapBlob = mapFile ? new Blob([mapFile.contents]) : undefined; + + let localesPerBatch: number; + if (uncachedByFile.size === 1) { + // Single file in window: shard across bounded workers to balance throughput and peak memory + const targetWorkers = Math.min(workerCount, MAX_DOMINANT_WORKERS); + localesPerBatch = Math.max(1, Math.ceil(entries.length / targetWorkers)); + } else if (fileSize < SMALL_FILE_FLOOR_BYTES) { + // Small chunks (< 100 KB): process all locales in 1 batch to eliminate IPC overhead + localesPerBatch = entries.length; + } else if (fileSize >= dominantThreshold) { + // Dominant file(s) with multiple files: shard across bounded workers while always reserving + // at least one worker to process smaller chunks in parallel without starvation. + localesPerBatch = Math.max(1, Math.ceil(entries.length / dominantTargetWorkers)); + } else if (uncachedByFile.size >= workerCount) { + // Worker pool is already saturated by file-level concurrency; + // process all locales in a single batch to avoid duplicate parsing and IPC overhead. + localesPerBatch = entries.length; + } else { + // Intermediate files with idle workers: moderate sharding + localesPerBatch = Math.max(1, Math.ceil(entries.length / 2)); + } + + const ephemeral = isLastWindow && entries.length <= localesPerBatch; + for (let i = 0; i < entries.length; i += localesPerBatch) { + const batchEntries = entries.slice(i, i + localesPerBatch); + const task = (async () => { + const batchResult = await this.#runWorkerTask('inlineFileBatch', { + filename, + code: codeBlob, + map: mapBlob, + locales: new Map(batchEntries.map((e) => [e.locale, e.translation])), + missingTranslation: this.options.missingTranslation, + ephemeral, + activeLocales, + generation, + }); + + if (batchResult.unmodified) { + const unmodifiedResult: TransformedFileResult = { + file: filename, + messages: batchResult.messages, + }; + + const cachePromises: Promise[] = []; + for (const { locale, cacheKey } of batchEntries) { + fileResultsByLocale.get(locale)?.set(filename, unmodifiedResult); + + if (this.#transformedFileCache && cacheKey) { + cachePromises.push(this.#transformedFileCache.put(cacheKey, unmodifiedResult)); + } + } + await Promise.allSettled(cachePromises); + } else { + const cachePromises: Promise[] = []; + for (const res of batchResult.results) { + const matchingEntry = batchEntries.find((e) => e.locale === res.locale); + const cacheKey = matchingEntry?.cacheKey; + const fileResult: TransformedFileResult = { + file: filename, + code: res.code, + map: res.map, + messages: res.messages, + }; + + if (this.#transformedFileCache && cacheKey) { + cachePromises.push(this.#transformedFileCache.put(cacheKey, fileResult)); + } + + fileResultsByLocale.get(res.locale)?.set(filename, fileResult); + } + await Promise.allSettled(cachePromises); + } + })(); + + workerTasks.push(task); + } + } + + await Promise.all(workerTasks); + } + + #runWorkerTask( + name: T, + request: WorkerTaskMap[T]['request'], + ): Promise { + return this.#workerPool.run(request, { + filename: INLINER_WORKER_PATH, + name, + }) as Promise; + } + + /** + * Performs inlining of translations for the provided locale and translations. + * + * @param files The build output files to transform. + * @param locale The string representing the locale to inline. + * @param translation The translation messages to use when inlining. + * @param translationIntegrity An optional integrity value for the translation messages to use for caching. + * @returns A promise that resolves to an array of OutputFiles representing a translated result. + */ + async inlineForLocale( + files: Iterable, + locale: string, + translation: Record | undefined, + translationIntegrity?: string, + ): Promise { + const results = await this.inlineAll(files, [{ locale, translation, translationIntegrity }]); + const result = results.get(locale); + assert(result !== undefined, `Result for locale '${locale}' should be present.`); + + return result; + } + + async inlineTemplateUpdate( + locale: string, + translation: Record | undefined, + templateCode: string, + templateId: string, + translationIntegrity?: string, + ): Promise<{ code: string; errors: string[]; warnings: string[] }> { + const hasLocalize = templateCode.includes(LOCALIZE_KEYWORD); + + if (!hasLocalize) { + return { + code: templateCode, + errors: [], + warnings: [], + }; + } + + const { output, messages } = await this.#runWorkerTask('inlineCode', { + code: templateCode, + filename: templateId, + locale, + missingTranslation: this.options.missingTranslation, + translation: await serializeTranslation( + translation, + translationIntegrity, + this.#translationCache, + ), + }); + + const errors: string[] = []; + const warnings: string[] = []; + for (const message of messages) { + if (message.type === 'error') { + errors.push(message.message); + } else { + warnings.push(message.message); + } + } + + return { + code: output, + errors, + warnings, + }; + } + + /** + * Stops all active transformation tasks and shuts down all workers. + * @returns A void promise that resolves when closing is complete. + */ + async close(): Promise { + await Promise.allSettled([ + this.#cacheStore?.close(), + this.#ownsWorkerPool ? this.#workerPool.destroy() : undefined, + ]); + } + + /** + * Initializes the cache for storing translated bundles. + * If the cache is already initialized, it does nothing. + * + * @returns A promise that resolves once the cache initialization process is complete. + */ + private async initCache(): Promise { + if (this.#cacheStore || this.#cacheInitFailed) { + return; + } + + const { persistentCachePath } = this.options; + // Webcontainers currently do not support this persistent cache store. + if (!persistentCachePath || process.versions.webcontainer) { + return; + } + + // Initialize a persistent cache for i18n transformations. + try { + const [, cacheStore] = await Promise.all([ + initializeHash(), + createPersistentCacheStore(join(persistentCachePath, 'angular-i18n')), + ]); + this.#cacheStore = cacheStore; + this.#transformedFileCache = cacheStore.createCache('transforms'); + this.#translationCache = cacheStore.createCache('translations'); + } catch { + this.#cacheInitFailed = true; + + // eslint-disable-next-line no-console + console.warn( + 'Unable to initialize JavaScript cache storage.\n' + + 'This will not affect the build output content but may result in slower builds.', + ); + } + } +} diff --git a/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts b/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts new file mode 100644 index 000000000000..2fbb6e02ce31 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts @@ -0,0 +1,1187 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵParsedTranslation } from '@angular/localize'; +import { transform } from 'esbuild'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { createPersistentCacheStore } from '../../utils/cache'; +import { initializeHash } from '../../utils/hash'; +import { WorkerPool } from '../../utils/worker-pool'; +import { + type BuildOutputFile, + BuildOutputFileType, + createOutputFile, +} from '../esbuild/bundler-files'; +import { I18nInliner, type I18nInlinerOptions } from './i18n-inliner'; + +/** + * A module that uses a `$localize` message with an explicit message identifier so that the + * translations for a test can be keyed by a known name. + */ +const GREETING_SOURCE = 'export const greeting = $localize`:@@greeting:Hello`;\n'; + +/** + * Creates the parsed translation form that `@angular/localize` expects. + */ +function parsedTranslation( + parts: string[], + placeholderNames: string[] = [], + text?: string, +): ɵParsedTranslation { + return { + messageParts: Object.assign([...parts], { raw: [...parts] }), + placeholderNames, + text: text ?? parts.join(''), + }; +} + +function translationFor(message: string): ɵParsedTranslation { + return parsedTranslation([message], [], message); +} + +function browserFile(path: string, contents: string): BuildOutputFile { + return createOutputFile(path, contents, BuildOutputFileType.Browser); +} + +function findFile(outputFiles: BuildOutputFile[], path: string): BuildOutputFile { + const file = outputFiles.find((output) => output.path === path); + if (!file) { + throw new Error(`Expected output files to contain '${path}'.`); + } + + return file; +} + +describe('I18nInliner', () => { + let inliner: I18nInliner | undefined; + + beforeAll(async () => { + await initializeHash(); + }); + + // A single thread is used throughout so that every file of every locale is inlined by the same + // Worker. Any translation state that a Worker retains between requests is then observable. + function createInliner(options?: Partial, maxConcurrency = 1): I18nInliner { + inliner = new I18nInliner({ missingTranslation: 'warning', maxConcurrency, ...options }); + + return inliner; + } + + afterEach(async () => { + await inliner?.close(); + inliner = undefined; + }); + + it('inlines the translations of a locale', async () => { + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'fr', + { greeting: translationFor('Bonjour') }, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(outputFiles, 'main.js').text).not.toContain('$localize'); + }); + + it('inlines the translations of each locale when several are inlined in sequence', async () => { + const files = [browserFile('main.js', GREETING_SOURCE)]; + const localeInliner = createInliner(); + + const french = await localeInliner.inlineForLocale(files, 'fr', { + greeting: translationFor('Bonjour'), + }); + const german = await localeInliner.inlineForLocale(files, 'de', { + greeting: translationFor('Hallo'), + }); + // Repeats the first locale to cover a locale being inlined again after another has been. + const frenchAgain = await localeInliner.inlineForLocale(files, 'fr', { + greeting: translationFor('Bonjour'), + }); + + expect(findFile(french.outputFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(german.outputFiles, 'main.js').text).toContain('"Hallo"'); + expect(findFile(frenchAgain.outputFiles, 'main.js').text).toContain('"Bonjour"'); + }); + + it('inlines the translations of a locale into every file that uses them', async () => { + const { outputFiles } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE), browserFile('chunk.js', GREETING_SOURCE)], + 'fr', + { greeting: translationFor('Bonjour') }, + ); + + expect(findFile(outputFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(outputFiles, 'chunk.js').text).toContain('"Bonjour"'); + }); + + it('retains the original messages for a locale without translations', async () => { + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'en-US', + undefined, + ); + + // A locale without translations is the source locale, so its messages are not missing. + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Hello"'); + }); + + it('retains the original messages with placeholders for a locale without translations', async () => { + const source = 'export const greeting = $localize`:@@greeting:Hello ${name}:NAME:!`;\n'; + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', source)], + 'en-US', + undefined, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('`Hello ${name}!`'); + expect(findFile(outputFiles, 'main.js').text).not.toContain('$localize'); + }); + + it('warns and retains the original message when a locale is missing a translation', async () => { + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'fr', + { unrelated: translationFor('Sans rapport') }, + ); + + expect(errors).toEqual([]); + expect(warnings.length).toBe(1); + expect(warnings[0]).toContain('greeting'); + expect(findFile(outputFiles, 'main.js').text).toContain('"Hello"'); + }); + + it('errors and retains the original message when missingTranslation is "error"', async () => { + const { outputFiles, errors, warnings } = await createInliner({ + missingTranslation: 'error', + }).inlineForLocale([browserFile('main.js', GREETING_SOURCE)], 'fr', { + unrelated: translationFor('Sans rapport'), + }); + + expect(errors.length).toBe(1); + expect(errors[0]).toContain('greeting'); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Hello"'); + }); + + it('ignores missing translations when missingTranslation is "ignore"', async () => { + const { outputFiles, errors, warnings } = await createInliner({ + missingTranslation: 'ignore', + }).inlineForLocale([browserFile('main.js', GREETING_SOURCE)], 'fr', { + unrelated: translationFor('Sans rapport'), + }); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Hello"'); + }); + + it('replaces the locale placeholder with the locale being inlined', async () => { + // The placeholder is only inlined for files that use `$localize`, which is where the build + // inserts it, so the message is present alongside it here. + const { outputFiles } = await createInliner().inlineForLocale( + [ + browserFile( + 'main.js', + `export const locale = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`, + ), + ], + 'fr', + { greeting: translationFor('Bonjour') }, + ); + + expect(findFile(outputFiles, 'main.js').text).toContain('"fr"'); + expect(findFile(outputFiles, 'main.js').text).not.toContain('___NG_LOCALE_INSERT___'); + }); + + it('remaps the source map of a file it modifies', async () => { + // esbuild provides a map from the emitted code back to an original file, matching what the + // inliner receives during a build. + const { code, map } = await transform(GREETING_SOURCE, { + sourcefile: 'greeting.ts', + loader: 'ts', + sourcemap: 'external', + }); + + const { outputFiles } = await createInliner().inlineForLocale( + [browserFile('main.js', code), browserFile('main.js.map', map)], + 'fr', + { greeting: translationFor('Bonjour') }, + ); + + const outputMap = JSON.parse(findFile(outputFiles, 'main.js.map').text) as { + version: number; + sources: string[]; + mappings: string; + }; + + expect(outputMap.version).toBe(3); + // The map must still resolve to the original file rather than to the inliner's input. + expect(outputMap.sources).toContain('greeting.ts'); + expect(outputMap.mappings.length).toBeGreaterThan(0); + }); + + describe('inlineTemplateUpdate', () => { + it('inlines the translations of a locale into a template update', async () => { + const { code, errors, warnings } = await createInliner().inlineTemplateUpdate( + 'fr', + { greeting: translationFor('Bonjour') }, + GREETING_SOURCE, + 'template-id', + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(code).toContain('"Bonjour"'); + expect(code).not.toContain('$localize'); + }); + + it('retains the original messages for a locale without translations', async () => { + const { code, errors, warnings } = await createInliner().inlineTemplateUpdate( + 'en-US', + undefined, + GREETING_SOURCE, + 'template-id', + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(code).toContain('"Hello"'); + }); + + it('returns the code untouched when it has no localize calls', async () => { + const source = 'export const answer = 42;\n'; + const { code } = await createInliner().inlineTemplateUpdate( + 'fr', + { greeting: translationFor('Bonjour') }, + source, + 'template-id', + ); + + expect(code).toBe(source); + }); + + it('inlines translations with translationIntegrity and persistent caching', async () => { + const cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'i18n-template-cache-test-')); + + try { + const inliner = new I18nInliner({ + missingTranslation: 'error', + persistentCachePath: cacheDir, + }); + + const translationIntegrity = 'hash-template-integrity-123'; + const { code, errors, warnings } = await inliner.inlineTemplateUpdate( + 'fr', + { greeting: translationFor('Bonjour') }, + GREETING_SOURCE, + 'template-id', + translationIntegrity, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(code).toContain('"Bonjour"'); + await inliner.close(); + } finally { + await fs.rm(cacheDir, { recursive: true, force: true }); + } + }); + }); + + it('safely inlines translations containing special characters, quotes, and newlines', async () => { + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'fr', + { + greeting: translationFor('Bonjour "mon ami" \\ \' \n '), + }, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toBe( + 'export const greeting = "Bonjour \\"mon ami\\" \\\\ \' \\n ";\n', + ); + }); + + it('inlines translations containing placeholders', async () => { + const source = 'export const welcome = (name) => $localize`:@@welcome:Hello ${name}!`;\n'; + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', source)], + 'fr', + { + welcome: parsedTranslation(['Bonjour ', ' !'], ['PH'], 'Bonjour {$PH} !'), + }, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toBe( + 'export const welcome = (name) => `Bonjour ${name} !`;\n', + ); + }); + + it('inlines multiple localize calls within the same file', async () => { + const source = + 'export const a = $localize`:@@greeting:Hello`;\nexport const b = $localize`:@@farewell:Goodbye`;\n'; + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', source)], + 'fr', + { + greeting: translationFor('Bonjour'), + farewell: translationFor('Au revoir'), + }, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toBe( + 'export const a = "Bonjour";\nexport const b = "Au revoir";\n', + ); + }); + + it('inlines translations across multiple files using multiple worker threads in parallel', async () => { + const files = [ + browserFile('main.js', GREETING_SOURCE), + browserFile('chunk1.js', GREETING_SOURCE), + browserFile('chunk2.js', GREETING_SOURCE), + browserFile('chunk3.js', GREETING_SOURCE), + ]; + inliner = new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: 4, + }); + + const { outputFiles, errors, warnings } = await inliner.inlineForLocale(files, 'fr', { + greeting: translationFor('Bonjour'), + }); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + for (const name of ['main.js', 'chunk1.js', 'chunk2.js', 'chunk3.js']) { + expect(findFile(outputFiles, name).text).toBe('export const greeting = "Bonjour";\n'); + } + }); + + it('leaves files without localize calls unmodified', async () => { + const { outputFiles } = await createInliner().inlineForLocale( + [ + browserFile('main.js', GREETING_SOURCE), + browserFile('other.js', 'export const answer = 42;\n'), + ], + 'fr', + { greeting: translationFor('Bonjour') }, + ); + + expect(findFile(outputFiles, 'other.js').text).toBe('export const answer = 42;\n'); + }); + + it('inlines nested $localize calls in post-order', async () => { + const source = + 'export const msg = $localize`:@@outer:You selected ${$localize`:@@inner:Apple`} for delivery.`;\n'; + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', source)], + 'fr', + { + inner: translationFor('Pomme'), + outer: parsedTranslation( + ['Vous avez sélectionné ', ' pour la livraison.'], + ['PH'], + 'Vous avez sélectionné {$PH} pour la livraison.', + ), + }, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toBe( + 'export const msg = `Vous avez sélectionné ${"Pomme"} pour la livraison.`;\n', + ); + }); + + it('reports an error diagnostic when a $localize template has a malformed escape sequence', async () => { + const source = 'export const msg = $localize`:@@id:\\unicode:`;\n'; + const { errors } = await createInliner().inlineForLocale( + [browserFile('main.js', source)], + 'fr', + {}, + ); + + expect(errors).toEqual([ + 'Malformed escape sequence in $localize template literal in file "main.js".', + ]); + }); + + it('inlines the translations of a locale when translationIntegrity is provided', async () => { + const { outputFiles, errors, warnings } = await createInliner().inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'fr', + { greeting: translationFor('Bonjour') }, + 'sha256-test-integrity', + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(outputFiles, 'main.js').text).not.toContain('$localize'); + }); + + it('inlines the translations of a locale when localizeVersion is configured in options', async () => { + inliner = new I18nInliner({ + missingTranslation: 'warning', + localizeVersion: '20.2.0', + maxConcurrency: 1, + }); + + const { outputFiles, errors, warnings } = await inliner.inlineForLocale( + [browserFile('main.js', GREETING_SOURCE)], + 'fr', + { greeting: translationFor('Bonjour') }, + 'sha256-test-integrity', + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(findFile(outputFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(outputFiles, 'main.js').text).not.toContain('$localize'); + }); + + it('inlines multiple locales in parallel via inlineAll', async () => { + const files = [ + browserFile('main.js', GREETING_SOURCE), + browserFile('chunk.js', GREETING_SOURCE), + browserFile('other.js', 'export const answer = 42;\n'), + ]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + { locale: 'de', translation: { greeting: translationFor('Hallo') } }, + { locale: 'es', translation: { greeting: translationFor('Hola') } }, + { locale: 'en-US', translation: undefined }, + ]); + + expect(results.size).toBe(4); + + const fr = results.get('fr'); + expect(fr).toBeDefined(); + expect(fr?.errors).toEqual([]); + expect(fr?.warnings).toEqual([]); + expect(findFile(fr?.outputFiles ?? [], 'main.js').text).toContain('"Bonjour"'); + expect(findFile(fr?.outputFiles ?? [], 'chunk.js').text).toContain('"Bonjour"'); + expect(findFile(fr?.outputFiles ?? [], 'other.js').text).toBe('export const answer = 42;\n'); + + const de = results.get('de'); + expect(de).toBeDefined(); + expect(de?.errors).toEqual([]); + expect(findFile(de?.outputFiles ?? [], 'main.js').text).toContain('"Hallo"'); + + const es = results.get('es'); + expect(es).toBeDefined(); + expect(es?.errors).toEqual([]); + expect(findFile(es?.outputFiles ?? [], 'main.js').text).toContain('"Hola"'); + + const en = results.get('en-US'); + expect(en).toBeDefined(); + expect(en?.errors).toEqual([]); + expect(findFile(en?.outputFiles ?? [], 'main.js').text).toContain('"Hello"'); + }); + + it('inlines multiple locales with sourcemaps in parallel via inlineAll', async () => { + const { code, map } = await transform(GREETING_SOURCE, { + sourcefile: 'greeting.ts', + loader: 'ts', + sourcemap: 'external', + }); + + const files = [ + browserFile('main.js', code), + browserFile('main.js.map', map), + browserFile('other.js', 'export const answer = 42;\n'), + ]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + { locale: 'de', translation: { greeting: translationFor('Hallo') } }, + { locale: 'en-US', translation: undefined }, + ]); + + expect(results.size).toBe(3); + + for (const [locale, greeting] of [ + ['fr', 'Bonjour'], + ['de', 'Hallo'], + ['en-US', 'Hello'], + ] as const) { + const localeResult = results.get(locale); + expect(localeResult).toBeDefined(); + expect(localeResult?.errors).toEqual([]); + expect(localeResult?.warnings).toEqual([]); + + const mainJs = findFile(localeResult?.outputFiles ?? [], 'main.js'); + expect(mainJs.text).toContain(`"${greeting}"`); + + const mainMap = findFile(localeResult?.outputFiles ?? [], 'main.js.map'); + const outputMap = JSON.parse(mainMap.text) as { + version: number; + sources: string[]; + mappings: string; + }; + expect(outputMap.version).toBe(3); + expect(outputMap.sources).toContain('greeting.ts'); + expect(outputMap.mappings.length).toBeGreaterThan(0); + + const otherJs = findFile(localeResult?.outputFiles ?? [], 'other.js'); + expect(otherJs.text).toBe('export const answer = 42;\n'); + } + }); + + it('inlines multiple locales with partial cache hits and misses via inlineAll', async () => { + const cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'i18n-cache-test-')); + + try { + const files = [ + browserFile('main.js', GREETING_SOURCE), + browserFile('other.js', 'export const answer = 42;\n'), + ]; + const initialInliner = new I18nInliner({ + missingTranslation: 'warning', + persistentCachePath: cacheDir, + maxConcurrency: 2, + }); + + // Pre-populate cache for 'fr' + await initialInliner.inlineForLocale( + files, + 'fr', + { greeting: translationFor('Bonjour') }, + 'integrity-fr-1', + ); + await initialInliner.close(); + + // Create new inliner with same cache path, inlining cached 'fr' alongside uncached 'de' and 'es' + inliner = new I18nInliner({ + missingTranslation: 'warning', + persistentCachePath: cacheDir, + maxConcurrency: 2, + }); + + const results = await inliner.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + translationIntegrity: 'integrity-fr-1', + }, + { + locale: 'de', + translation: { greeting: translationFor('Hallo') }, + translationIntegrity: 'integrity-de-1', + }, + { + locale: 'es', + translation: { greeting: translationFor('Hola') }, + translationIntegrity: 'integrity-es-1', + }, + ]); + + expect(results.size).toBe(3); + + const fr = results.get('fr'); + expect(fr?.errors).toEqual([]); + expect(findFile(fr?.outputFiles ?? [], 'main.js').text).toContain('"Bonjour"'); + expect(findFile(fr?.outputFiles ?? [], 'other.js').text).toBe('export const answer = 42;\n'); + + const de = results.get('de'); + expect(de?.errors).toEqual([]); + expect(findFile(de?.outputFiles ?? [], 'main.js').text).toContain('"Hallo"'); + + const es = results.get('es'); + expect(es?.errors).toEqual([]); + expect(findFile(es?.outputFiles ?? [], 'main.js').text).toContain('"Hola"'); + + // Verify deterministic file order matching input order + for (const localeResult of results.values()) { + expect(localeResult.outputFiles.map((f) => f.path)).toEqual(['main.js', 'other.js']); + } + } finally { + await fs.rm(cacheDir, { recursive: true, force: true }); + } + }); + + it('inlines across sliding windows when locale count exceeds window size', async () => { + const locales = Array.from({ length: 20 }, (_, i) => ({ + locale: `locale-${i}`, + translation: { greeting: translationFor(`Hello ${i}`) }, + })); + + const files = [browserFile('main.js', GREETING_SOURCE)]; + inliner = new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: 2, + }); + + const results = await inliner.inlineAll(files, locales); + + expect(results.size).toBe(20); + for (let i = 0; i < 20; i++) { + const localeResult = results.get(`locale-${i}`); + expect(localeResult?.errors).toEqual([]); + expect(findFile(localeResult?.outputFiles ?? [], 'main.js').text).toContain(`"Hello ${i}"`); + } + }); + + it('injects locale data alongside ___NG_LOCALE_INSERT___ for non-English locales', async () => { + const source = `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`; + const files = [browserFile('polyfills.js', source)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + { locale: 'en-US', translation: undefined }, + ]); + + const fr = results.get('fr'); + expect(fr?.errors).toEqual([]); + const frPolyfills = findFile(fr?.outputFiles ?? [], 'polyfills.js').text; + expect(frPolyfills).toContain('(globalThis.$localize ??= {}).locale = "fr";'); + expect(frPolyfills).toContain('ng.common.locales'); + + const en = results.get('en-US'); + expect(en?.errors).toEqual([]); + const enPolyfills = findFile(en?.outputFiles ?? [], 'polyfills.js').text; + expect(enPolyfills).toContain('(globalThis.$localize ??= {}).locale = "en-US";'); + expect(enPolyfills).not.toContain('ng.common.locales'); + }); + + it('warns and uses parent locale data when a subtag locale is not directly available', async () => { + const source = `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`; + const files = [browserFile('polyfills.js', source)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr-ZZ', translation: { greeting: translationFor('Bonjour') } }, + ]); + + const frZZ = results.get('fr-ZZ'); + expect(frZZ?.errors).toEqual([]); + expect(frZZ?.warnings).toEqual([ + "Locale data for 'fr-ZZ' cannot be found. Using locale data for 'fr'.", + ]); + const polyfills = findFile(frZZ?.outputFiles ?? [], 'polyfills.js').text; + expect(polyfills).toContain('(globalThis.$localize ??= {}).locale = "fr-ZZ";'); + expect(polyfills).toContain('ng.common.locales'); + }); + + it('warns and includes no locale data when locale data cannot be found', async () => { + const source = `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`; + const files = [browserFile('polyfills.js', source)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'xx-YY', translation: { greeting: translationFor('Test') } }, + ]); + + const xxYY = results.get('xx-YY'); + expect(xxYY?.errors).toEqual([]); + expect(xxYY?.warnings).toEqual([ + "Locale data for 'xx-YY' cannot be found. No locale data will be included for this locale.", + ]); + const polyfills = findFile(xxYY?.outputFiles ?? [], 'polyfills.js').text; + expect(polyfills).toContain('(globalThis.$localize ??= {}).locale = "xx-YY";'); + expect(polyfills).not.toContain('ng.common.locales'); + }); + + it('reports an error diagnostic when an invalid or unsupported locale is provided', async () => { + const source = `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`; + const files = [browserFile('polyfills.js', source)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'invalid locale tag', translation: { greeting: translationFor('Test') } }, + ]); + + const invalid = results.get('invalid locale tag'); + expect(invalid?.errors).toEqual([ + 'Invalid or unsupported locale provided in configuration: "invalid locale tag"', + ]); + }); + + it('injects locale data script only once when multiple ___NG_LOCALE_INSERT___ sites are present', async () => { + const source = + `(globalThis.$localize ??= {}).locale = "___NG_LOCALE_INSERT___";\n` + + `const secondary = "___NG_LOCALE_INSERT___";\n${GREETING_SOURCE}`; + const files = [browserFile('polyfills.js', source)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + ]); + + const fr = results.get('fr'); + expect(fr?.errors).toEqual([]); + const frPolyfills = findFile(fr?.outputFiles ?? [], 'polyfills.js').text; + expect(frPolyfills).toContain('(globalThis.$localize ??= {}).locale = "fr";'); + expect(frPolyfills).toContain('const secondary = "fr";'); + + const iifeMatches = frPolyfills.match(/function\s*\(global/g); + expect(iifeMatches?.length).toBe(1); + }); + + it('preserves code and sourcemaps when a file contains the $localize keyword only in comments', async () => { + const source = '// $localize keyword in comment\nexport const message = "hello world";\n'; + const { code, map } = await transform(source, { + sourcefile: 'comment-only.ts', + loader: 'ts', + sourcemap: 'external', + }); + + const files = [browserFile('main.js', code), browserFile('main.js.map', map)]; + const localeInliner = createInliner(); + + const results = await localeInliner.inlineAll(files, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + { locale: 'de', translation: { greeting: translationFor('Hallo') } }, + ]); + + expect(results.size).toBe(2); + + for (const locale of ['fr', 'de'] as const) { + const localeResult = results.get(locale); + expect(localeResult).toBeDefined(); + expect(localeResult?.errors).toEqual([]); + expect(localeResult?.warnings).toEqual([]); + + const mainJs = findFile(localeResult?.outputFiles ?? [], 'main.js'); + expect(mainJs.text).toBe(code); + + const mainMap = findFile(localeResult?.outputFiles ?? [], 'main.js.map'); + expect(mainMap.text).toBe(map); + } + }); + + it('correctly handles persistent caching for unmodified files', async () => { + const cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'i18n-unmodified-cache-test-')); + const source = '// $localize comment only\nexport const value = 123;\n'; + + try { + const files = [browserFile('main.js', source)]; + const inliner1 = new I18nInliner({ + missingTranslation: 'error', + persistentCachePath: cacheDir, + }); + + const results1 = await inliner1.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + translationIntegrity: 'fr-1', + }, + ]); + + expect(results1.get('fr')?.errors).toEqual([]); + expect(findFile(results1.get('fr')?.outputFiles ?? [], 'main.js').text).toBe(source); + await inliner1.close(); + + const inliner2 = new I18nInliner({ + missingTranslation: 'error', + persistentCachePath: cacheDir, + }); + + const results2 = await inliner2.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + translationIntegrity: 'fr-1', + }, + ]); + + expect(results2.get('fr')?.errors).toEqual([]); + expect(findFile(results2.get('fr')?.outputFiles ?? [], 'main.js').text).toBe(source); + await inliner2.close(); + } finally { + await fs.rm(cacheDir, { recursive: true, force: true }); + } + }); + + it('caches binary translation buffer in persistent cache store when translationIntegrity is provided', async () => { + const cacheDir = await fs.mkdtemp(path.join(os.tmpdir(), 'i18n-inliner-trans-cache-test-')); + + try { + const files = [browserFile('main.js', GREETING_SOURCE)]; + const inliner1 = new I18nInliner({ + missingTranslation: 'error', + persistentCachePath: cacheDir, + }); + + const translationIntegrity = 'hash-test-integrity-12345'; + const results1 = await inliner1.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + translationIntegrity, + }, + ]); + + expect(results1.get('fr')?.errors).toEqual([]); + expect(findFile(results1.get('fr')?.outputFiles ?? [], 'main.js').text).toContain( + '"Bonjour"', + ); + await inliner1.close(); + + // Verify directly that the binary translation buffer was persisted on disk + const store = await createPersistentCacheStore(path.join(cacheDir, 'angular-i18n')); + try { + const translationCache = store.createCache('translations'); + const cachedData = await translationCache.get(translationIntegrity); + expect(cachedData).toBeInstanceOf(Uint8Array); + expect(cachedData?.byteLength).toBeGreaterThan(0); + } finally { + await store.close(); + } + + const inliner2 = new I18nInliner({ + missingTranslation: 'error', + persistentCachePath: cacheDir, + }); + + const results2 = await inliner2.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + translationIntegrity, + }, + ]); + + expect(results2.get('fr')?.errors).toEqual([]); + expect(findFile(results2.get('fr')?.outputFiles ?? [], 'main.js').text).toContain( + '"Bonjour"', + ); + await inliner2.close(); + } finally { + await fs.rm(cacheDir, { recursive: true, force: true }); + } + }); + + it('throws an error when duplicate locales are provided to inlineAll', async () => { + const localeInliner = createInliner(); + + await expectAsync( + localeInliner.inlineAll( + [browserFile('main.js', GREETING_SOURCE)], + [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + { locale: 'fr', translation: { greeting: translationFor('Salut') } }, + ], + ), + ).toBeRejectedWithError(/Duplicate locale provided to inliner: fr/); + }); + + it('correctly transforms files across multiple inlineAll runs on the same inliner instance', async () => { + const localeInliner = new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: 2, + }); + + try { + const files1 = [browserFile('main.js', GREETING_SOURCE)]; + // First generation + const results1 = await localeInliner.inlineAll(files1, [ + { locale: 'fr', translation: { greeting: translationFor('Bonjour') } }, + ]); + expect(findFile(results1.get('fr')?.outputFiles ?? [], 'main.js').text).toContain( + '"Bonjour"', + ); + + // Second generation (e.g. watch mode rebuild with updated translation) + const files2 = [browserFile('main.js', GREETING_SOURCE)]; + const results2 = await localeInliner.inlineAll(files2, [ + { locale: 'fr', translation: { greeting: translationFor('Salut') } }, + { locale: 'de', translation: { greeting: translationFor('Hallo') } }, + ]); + expect(findFile(results2.get('fr')?.outputFiles ?? [], 'main.js').text).toContain('"Salut"'); + expect(findFile(results2.get('de')?.outputFiles ?? [], 'main.js').text).toContain('"Hallo"'); + } finally { + await localeInliner.close(); + } + }); + + it('correctly escapes backticks, double quotes, and expression delimiters in translated template literals', async () => { + const source = 'export const msg = $localize`:@@msg:Hello ${name}:name:!`;\n'; + const inliner = createInliner(); + + const results = await inliner.inlineAll( + [browserFile('main.js', source)], + [ + { + locale: 'fr', + translation: { + msg: parsedTranslation(['Bonjour "', '` with ${injected} and \\backslash!'], ['name']), + }, + }, + ], + ); + + const outputText = findFile(results.get('fr')?.outputFiles ?? [], 'main.js').text; + expect(outputText).toContain('`Bonjour "${name}\\` with \\${injected} and \\\\backslash!`'); + }); + + it('correctly inlines when files have varying sizes across multiple workers', async () => { + // Create a large dominant bundle (> 120 KB) and a small chunk (< 10 KB) + const largePadding = '/* padding */ console.log(1);\n'.repeat(4000); + const largeSource = `${GREETING_SOURCE}\n${largePadding}`; + const smallSource = 'console.log($localize`:@@farewell:Goodbye`);'; + + const largeFile = browserFile('main.js', largeSource); + const smallFile = browserFile('chunk.js', smallSource); + const files = [largeFile, smallFile]; + + inliner = new I18nInliner({ missingTranslation: 'error', maxConcurrency: 2 }); + + const results = await inliner.inlineAll(files, [ + { + locale: 'fr', + translation: { + greeting: translationFor('Bonjour'), + farewell: translationFor('Au revoir'), + }, + }, + { + locale: 'de', + translation: { + greeting: translationFor('Guten Tag'), + farewell: translationFor('Auf Wiedersehen'), + }, + }, + { + locale: 'es', + translation: { + greeting: translationFor('Hola'), + farewell: translationFor('Adios'), + }, + }, + ]); + + expect(results.size).toBe(3); + + const frFiles = results.get('fr')?.outputFiles ?? []; + expect(findFile(frFiles, 'main.js').text).toContain('"Bonjour"'); + expect(findFile(frFiles, 'chunk.js').text).toContain('"Au revoir"'); + + const deFiles = results.get('de')?.outputFiles ?? []; + expect(findFile(deFiles, 'main.js').text).toContain('"Guten Tag"'); + expect(findFile(deFiles, 'chunk.js').text).toContain('"Auf Wiedersehen"'); + + const esFiles = results.get('es')?.outputFiles ?? []; + expect(findFile(esFiles, 'main.js').text).toContain('"Hola"'); + expect(findFile(esFiles, 'chunk.js').text).toContain('"Adios"'); + }); + + it('respects maxConcurrency when processing multiple locales and files', async () => { + const files = [ + browserFile('main.js', GREETING_SOURCE), + browserFile('chunk.js', 'console.log($localize`:@@farewell:Goodbye`);'), + ]; + + inliner = new I18nInliner({ + missingTranslation: 'error', + maxConcurrency: 1, + }); + + const results = await inliner.inlineAll(files, [ + { + locale: 'fr', + translation: { + greeting: translationFor('Bonjour'), + farewell: translationFor('Au revoir'), + }, + }, + { + locale: 'de', + translation: { + greeting: translationFor('Guten Tag'), + farewell: translationFor('Auf Wiedersehen'), + }, + }, + ]); + + expect(results.size).toBe(2); + expect(findFile(results.get('fr')?.outputFiles ?? [], 'main.js').text).toContain('"Bonjour"'); + expect(findFile(results.get('de')?.outputFiles ?? [], 'chunk.js').text).toContain( + '"Auf Wiedersehen"', + ); + }); + + describe('maxConcurrency validation', () => { + it('throws when maxConcurrency is less than 1', () => { + expect( + () => + new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: 0, + }), + ).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + + expect( + () => + new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: -1, + }), + ).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + }); + + it('throws when maxConcurrency is not an integer', () => { + expect( + () => + new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: 1.5, + }), + ).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + + expect( + () => + new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: NaN, + }), + ).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + + expect( + () => + new I18nInliner({ + missingTranslation: 'warning', + maxConcurrency: Infinity, + }), + ).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + }); + + it('defaults to worker pool concurrency when maxConcurrency is omitted', async () => { + const maxThreadsSpy = spyOnProperty( + WorkerPool.prototype, + 'maxThreads', + 'get', + ).and.callThrough(); + + inliner = new I18nInliner({ + missingTranslation: 'warning', + }); + + const files = [browserFile('main.js', GREETING_SOURCE)]; + const results = await inliner.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + }, + ]); + + expect(results.size).toBe(1); + expect(findFile(results.get('fr')?.outputFiles ?? [], 'main.js').text).toContain('"Bonjour"'); + expect(maxThreadsSpy).toHaveBeenCalled(); + expect(maxThreadsSpy.calls.mostRecent().returnValue).toBeGreaterThanOrEqual(1); + }); + }); + + describe('supplied workerPool', () => { + let externalPool: WorkerPool | undefined; + + afterEach(async () => { + await externalPool?.destroy(); + externalPool = undefined; + }); + + it('uses the supplied workerPool to execute transformation tasks', async () => { + externalPool = new WorkerPool({ maxThreads: 1 }); + const runSpy = spyOn(externalPool, 'run').and.callThrough(); + + inliner = new I18nInliner({ missingTranslation: 'warning' }, externalPool); + + const files = [browserFile('main.js', GREETING_SOURCE)]; + const results = await inliner.inlineAll(files, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + }, + ]); + + expect(results.size).toBe(1); + expect(findFile(results.get('fr')?.outputFiles ?? [], 'main.js').text).toContain('"Bonjour"'); + expect(runSpy).toHaveBeenCalled(); + }); + + it('does not destroy the supplied workerPool on close()', async () => { + externalPool = new WorkerPool({ maxThreads: 1 }); + const destroySpy = spyOn(externalPool, 'destroy').and.callThrough(); + + inliner = new I18nInliner({ missingTranslation: 'warning' }, externalPool); + await inliner.close(); + + expect(destroySpy).not.toHaveBeenCalled(); + }); + + it('destroys internally created workerPool on close()', async () => { + const destroySpy = spyOn(WorkerPool.prototype, 'destroy').and.callThrough(); + + inliner = new I18nInliner({ missingTranslation: 'warning', maxConcurrency: 1 }); + await inliner.close(); + + expect(destroySpy).toHaveBeenCalled(); + }); + + it('supports multiple sequential inlining passes with the same supplied workerPool', async () => { + externalPool = new WorkerPool({ maxThreads: 1 }); + + inliner = new I18nInliner({ missingTranslation: 'warning' }, externalPool); + + const files1 = [browserFile('main.js', GREETING_SOURCE)]; + const results1 = await inliner.inlineAll(files1, [ + { + locale: 'fr', + translation: { greeting: translationFor('Bonjour') }, + }, + ]); + expect(findFile(results1.get('fr')?.outputFiles ?? [], 'main.js').text).toContain( + '"Bonjour"', + ); + + // Second inlining pass on the same pool + const files2 = [browserFile('main.js', GREETING_SOURCE)]; + const results2 = await inliner.inlineAll(files2, [ + { + locale: 'es', + translation: { greeting: translationFor('Hola') }, + }, + ]); + expect(findFile(results2.get('es')?.outputFiles ?? [], 'main.js').text).toContain('"Hola"'); + }); + }); +}); diff --git a/packages/angular/build/src/tools/i18n/i18n-translation-encoder.ts b/packages/angular/build/src/tools/i18n/i18n-translation-encoder.ts new file mode 100644 index 000000000000..cc8f1ae50f31 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-translation-encoder.ts @@ -0,0 +1,113 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵParsedTranslation } from '@angular/localize'; + +/** + * Magic header identifier for i18n SharedArrayBuffer translation tables ('I18N'). + */ +export const I18N_MAGIC_ID = 0x4931384e; + +/** + * Encodes a JavaScript translation dictionary into a contiguous SharedArrayBuffer. + * The buffer contains a header, a sorted index table (by key for fast O(log N) binary search), + * and a UTF-8 string pool. + * + * @param translation The translation dictionary object. + * @returns A SharedArrayBuffer containing the binary encoded translation catalog. + */ +export function encodeTranslationToBuffer( + translation: Record, +): SharedArrayBuffer { + const encoder = new TextEncoder(); + const entries = Object.entries(translation); + const entryCount = entries.length; + + // Pre-encode string keys and JSON-serialized string values + const encodedEntries: { + keyBytes: Uint8Array; + valBytes: Uint8Array; + }[] = new Array(entryCount); + + let stringPoolByteSize = 0; + + for (let i = 0; i < entryCount; i++) { + const [key, val] = entries[i]; + const keyBytes = encoder.encode(key); + const valBytes = encoder.encode(JSON.stringify(val)); + + encodedEntries[i] = { keyBytes, valBytes }; + stringPoolByteSize += keyBytes.byteLength + valBytes.byteLength; + } + + // Sort entries lexicographically by UTF-8 byte comparison. + // Lexicographical byte comparison matches the binary search reader's byte comparison, + // ensuring deterministic and zero-allocation lookups across all runtimes regardless of UTF-16 surrogate pairs. + encodedEntries.sort((a, b) => { + const aBytes = a.keyBytes; + const bBytes = b.keyBytes; + const minLen = Math.min(aBytes.length, bBytes.length); + + for (let i = 0; i < minLen; i++) { + const diff = aBytes[i] - bBytes[i]; + if (diff !== 0) { + return diff; + } + } + + return aBytes.length - bBytes.length; + }); + + const indexByteSize = entryCount * 16; + const headerByteSize = 16; + const stringPoolOffset = headerByteSize + indexByteSize; + + const totalByteSize = stringPoolOffset + stringPoolByteSize; + const buffer = new SharedArrayBuffer(totalByteSize); + + // Set up views over the SharedArrayBuffer + const uint32Header = new Uint32Array(buffer, 0, 4); + const uint32Index = new Uint32Array(buffer, headerByteSize, entryCount * 4); + const uint8Pool = new Uint8Array(buffer, stringPoolOffset); + + // Write Header: Magic, EntryCount, IndexOffset, StringPoolOffset + uint32Header[0] = I18N_MAGIC_ID; + uint32Header[1] = entryCount; + uint32Header[2] = headerByteSize; + uint32Header[3] = stringPoolOffset; + + // Write Index Table and String Pool entries + let currentPoolOffset = 0; + + for (let i = 0; i < entryCount; i++) { + const { keyBytes, valBytes } = encodedEntries[i]; + + const keyOffset = currentPoolOffset; + const keyLen = keyBytes.byteLength; + uint8Pool.set(keyBytes, keyOffset); + currentPoolOffset += keyLen; + + const valOffset = currentPoolOffset; + const valLen = valBytes.byteLength; + uint8Pool.set(valBytes, valOffset); + currentPoolOffset += valLen; + + // Index entry format (4 uint32 words / 16 bytes): + // [0]: keyOffset (uint32) + // [1]: keyLength (uint32) + // [2]: valOffset (uint32) + // [3]: valLength (uint32) + const idx = i * 4; + uint32Index[idx] = keyOffset; + uint32Index[idx + 1] = keyLen; + uint32Index[idx + 2] = valOffset; + uint32Index[idx + 3] = valLen; + } + + return buffer; +} diff --git a/packages/angular/build/src/tools/i18n/i18n-translation-encoder_spec.ts b/packages/angular/build/src/tools/i18n/i18n-translation-encoder_spec.ts new file mode 100644 index 000000000000..dd660f9a4059 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-translation-encoder_spec.ts @@ -0,0 +1,168 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { encodeTranslationToBuffer } from './i18n-translation-encoder'; +import { + SharedTranslationDictionary, + createSharedTranslationProxy, +} from './i18n-translation-reader'; + +describe('SharedArrayBuffer Translation Encoder & Reader', () => { + it('encodes and reads simple key-value translations', () => { + const translation = { + greeting: 'Hello', + farewell: 'Goodbye', + numberKey: 42, + arrayKey: ['part1', 'part2'], + }; + + const buffer = encodeTranslationToBuffer(translation); + const dictionary = new SharedTranslationDictionary(buffer); + + expect(dictionary.get('greeting')).toEqual('Hello'); + expect(dictionary.get('farewell')).toEqual('Goodbye'); + expect(dictionary.get('numberKey')).toEqual(42); + expect(dictionary.get('arrayKey')).toEqual(['part1', 'part2']); + expect(dictionary.get('nonexistent')).toBeUndefined(); + }); + + it('works with Proxy wrapper and "in" operator', () => { + const translation = { + msg1: 'Message 1', + msg2: 'Message 2', + }; + + const buffer = encodeTranslationToBuffer(translation); + const proxy = createSharedTranslationProxy(buffer); + + expect(proxy['msg1']).toEqual('Message 1'); + expect(proxy['msg2']).toEqual('Message 2'); + expect(proxy['unknown']).toBeUndefined(); + expect('msg1' in proxy).toBeTrue(); + expect('msg2' in proxy).toBeTrue(); + expect('unknown' in proxy).toBeFalse(); + }); + + it('supports Object.prototype.hasOwnProperty and Object.getOwnPropertyDescriptor on Proxy', () => { + const translation = { + msg1: 'Message 1', + }; + + const buffer = encodeTranslationToBuffer(translation); + const proxy = createSharedTranslationProxy(buffer); + + expect(Object.prototype.hasOwnProperty.call(proxy, 'msg1')).toBeTrue(); + expect(Object.prototype.hasOwnProperty.call(proxy, 'unknown')).toBeFalse(); + + const desc = Object.getOwnPropertyDescriptor(proxy, 'msg1'); + expect(desc).toBeDefined(); + expect(desc?.value).toEqual('Message 1'); + expect(desc?.enumerable).toBeTrue(); + + const missingDesc = Object.getOwnPropertyDescriptor(proxy, 'unknown'); + expect(missingDesc).toBeUndefined(); + + // Verify standard Object.prototype methods work and don't throw + expect(typeof proxy.toString).toBe('function'); + expect(proxy.toString()).toEqual('[object Object]'); + expect(typeof proxy.valueOf).toBe('function'); + expect('toString' in proxy).toBeTrue(); + expect(String(proxy)).toEqual('[object Object]'); + }); + + it('handles non-BMP Unicode surrogate pairs and high BMP keys correctly', () => { + const translation = { + '😀': 'emoji message', + '\uE000': 'uE000 message', + 'abc': 'abc message', + }; + + const buffer = encodeTranslationToBuffer(translation); + const dictionary = new SharedTranslationDictionary(buffer); + + expect(dictionary.get('😀')).toEqual('emoji message'); + expect(dictionary.get('\uE000')).toEqual('uE000 message'); + expect(dictionary.get('abc')).toEqual('abc message'); + }); + + it('handles empty translation dictionaries', () => { + const buffer = encodeTranslationToBuffer({}); + const dictionary = new SharedTranslationDictionary(buffer); + + expect(dictionary.get('anyKey')).toBeUndefined(); + }); + + it('caches missing translation lookups efficiently', () => { + const translation = { + msg1: 'Message 1', + }; + + const buffer = encodeTranslationToBuffer(translation); + const dictionary = new SharedTranslationDictionary(buffer); + + // First lookup for missing key + expect(dictionary.get('missingKey')).toBeUndefined(); + // Second lookup for missing key (should hit lazyCache NOT_FOUND sentinel) + expect(dictionary.get('missingKey')).toBeUndefined(); + }); + + it('validates header size and offsets on initialization', () => { + // Buffer too small + const smallSab = new SharedArrayBuffer(8); + expect(() => new SharedTranslationDictionary(smallSab)).toThrowError( + 'Invalid SharedArrayBuffer translation header: buffer too small.', + ); + + // Invalid magic header + const badMagicSab = new SharedArrayBuffer(16); + expect(() => new SharedTranslationDictionary(badMagicSab)).toThrowError( + 'Invalid SharedArrayBuffer translation header magic identifier.', + ); + + // Out-of-bounds offset values + const invalidOffsetsSab = new SharedArrayBuffer(16); + const view = new Uint32Array(invalidOffsetsSab); + view[0] = 0x4931384e; // I18N_MAGIC_ID + view[1] = 100; // entryCount = 100 entries requiring 1600 bytes + view[2] = 16; + view[3] = 16; + expect(() => new SharedTranslationDictionary(invalidOffsetsSab)).toThrowError( + 'Invalid SharedArrayBuffer translation header offsets.', + ); + + // Unaligned header size + const unalignedHeaderSab = new SharedArrayBuffer(32); + const unalignedView = new Uint32Array(unalignedHeaderSab); + unalignedView[0] = 0x4931384e; + unalignedView[1] = 0; + unalignedView[2] = 17; // unaligned header byte size + unalignedView[3] = 17; + expect(() => new SharedTranslationDictionary(unalignedHeaderSab)).toThrowError( + 'Invalid SharedArrayBuffer translation header offsets.', + ); + }); + + it('safely handles corrupted index offsets within a valid header', () => { + // 1 entry: header (16 bytes) + index (16 bytes) + pool (10 bytes) = 42 bytes + const buffer = new SharedArrayBuffer(48); + const uint32 = new Uint32Array(buffer); + uint32[0] = 0x4931384e; // Magic + uint32[1] = 1; // 1 entry + uint32[2] = 16; // header size + uint32[3] = 32; // string pool offset + + // Corrupted entry: keyOffset points past pool length + uint32[4] = 100; // keyOffset = 100 + uint32[5] = 5; // keyLen = 5 + uint32[6] = 0; // valOffset = 0 + uint32[7] = 5; // valLen = 5 + + const dictionary = new SharedTranslationDictionary(buffer); + expect(dictionary.get('testKey')).toBeUndefined(); + }); +}); diff --git a/packages/angular/build/src/tools/i18n/i18n-translation-reader.ts b/packages/angular/build/src/tools/i18n/i18n-translation-reader.ts new file mode 100644 index 000000000000..c332b47f1941 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-translation-reader.ts @@ -0,0 +1,196 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵParsedTranslation } from '@angular/localize'; +import { I18N_MAGIC_ID } from './i18n-translation-encoder'; + +/** + * Sentinel value used to cache non-existent message key lookups in lazyCache. + */ +const NOT_FOUND = Symbol('NOT_FOUND'); + +/** + * Compares a target key's UTF-8 byte array against a byte sequence in the string pool. + * Lexicographical byte comparison of UTF-8 sequences matches UTF-16 code-unit string comparison + * used when encoding the sorted index table. + */ +function compareBytes( + target: Uint8Array, + pool: Uint8Array, + poolOffset: number, + keyLen: number, +): number { + if (poolOffset < 0 || poolOffset + keyLen > pool.length) { + return 1; + } + + const minLen = Math.min(target.length, keyLen); + for (let i = 0; i < minLen; i++) { + const diff = target[i] - pool[poolOffset + i]; + if (diff !== 0) { + return diff; + } + } + + return target.length - keyLen; +} + +/** + * A zero-copy reader that queries translation messages directly from a SharedArrayBuffer + * using binary search over a sorted key index. + */ +export class SharedTranslationDictionary { + private readonly entryCount: number; + private readonly uint32Index: Uint32Array; + private readonly uint8Pool: Uint8Array; + private readonly decoder = new TextDecoder(); + private readonly encoder = new TextEncoder(); + private readonly lazyCache = new Map(); + + constructor(buffer: SharedArrayBuffer) { + if (buffer.byteLength < 16) { + throw new Error('Invalid SharedArrayBuffer translation header: buffer too small.'); + } + + const uint32Header = new Uint32Array(buffer, 0, 4); + if (uint32Header[0] !== I18N_MAGIC_ID) { + throw new Error('Invalid SharedArrayBuffer translation header magic identifier.'); + } + + this.entryCount = uint32Header[1]; + const headerByteSize = uint32Header[2]; + const stringPoolOffset = uint32Header[3]; + + if ( + headerByteSize < 16 || + headerByteSize % 4 !== 0 || + headerByteSize + this.entryCount * 16 > buffer.byteLength || + stringPoolOffset < headerByteSize + this.entryCount * 16 || + stringPoolOffset > buffer.byteLength + ) { + throw new Error('Invalid SharedArrayBuffer translation header offsets.'); + } + + this.uint32Index = new Uint32Array(buffer, headerByteSize, this.entryCount * 4); + this.uint8Pool = new Uint8Array(buffer, stringPoolOffset); + } + + /** + * Looks up a translation message by key. + * Performs a binary search over the index table if not previously cached in the lazy cache. + * + * @param targetKey The message key ID to search for. + * @returns The parsed translation message, or undefined if not found. + */ + get(targetKey: string): T | undefined { + const cached = this.lazyCache.get(targetKey); + if (cached !== undefined) { + return cached === NOT_FOUND ? undefined : cached; + } + + const targetBytes = this.encoder.encode(targetKey); + let low = 0; + let high = this.entryCount - 1; + + while (low <= high) { + const mid = (low + high) >>> 1; + const idx = mid * 4; + + const keyOffset = this.uint32Index[idx]; + const keyLen = this.uint32Index[idx + 1]; + + const cmp = compareBytes(targetBytes, this.uint8Pool, keyOffset, keyLen); + if (cmp === 0) { + const valOffset = this.uint32Index[idx + 2]; + const valLen = this.uint32Index[idx + 3]; + if (valOffset < 0 || valOffset + valLen > this.uint8Pool.length) { + this.lazyCache.set(targetKey, NOT_FOUND); + + return undefined; + } + + const valBytes = this.uint8Pool.subarray(valOffset, valOffset + valLen); + const valJson = this.decoder.decode(valBytes); + + try { + const val = JSON.parse(valJson) as T; + this.lazyCache.set(targetKey, val); + + return val; + } catch { + this.lazyCache.set(targetKey, NOT_FOUND); + + return undefined; + } + } else if (cmp < 0) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + this.lazyCache.set(targetKey, NOT_FOUND); + + return undefined; + } +} + +/** + * Creates a JavaScript object Proxy wrapping a SharedTranslationDictionary so it can be passed + * directly to `@angular/localize` inliner functions as a standard translation Record. + * + * Traps `get`, `has`, and `getOwnPropertyDescriptor` to fulfill all `@angular/localize` `translate()` + * lookup requirements (`translations[id]`, `translations[legacyId]`, `Object.hasOwn(translations, id)`). + * The `ownKeys` trap is intentionally omitted so keys are not eagerly decoded upfront upon reflection. + * + * @param buffer The SharedArrayBuffer containing binary encoded translation catalog. + * @returns A Proxy object that intercepts property reads and queries the SharedTranslationDictionary. + */ +export function createSharedTranslationProxy( + buffer: SharedArrayBuffer, +): Record { + const dictionary = new SharedTranslationDictionary(buffer); + + return new Proxy( + {}, + { + get(target, prop: string | symbol) { + if (typeof prop === 'string') { + const value = dictionary.get(prop); + if (value !== undefined) { + return value; + } + } + + return Reflect.get(target, prop); + }, + has(target, prop: string | symbol) { + if (typeof prop === 'string' && dictionary.get(prop) !== undefined) { + return true; + } + + return Reflect.has(target, prop); + }, + getOwnPropertyDescriptor(target, prop: string | symbol) { + if (typeof prop === 'string') { + const val = dictionary.get(prop); + if (val !== undefined) { + return { + enumerable: true, + configurable: true, + writable: false, + value: val, + }; + } + } + + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + }, + ); +} diff --git a/packages/angular/build/src/tools/i18n/index.ts b/packages/angular/build/src/tools/i18n/index.ts new file mode 100644 index 000000000000..a2f8cdd2d8f3 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/index.ts @@ -0,0 +1,12 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './i18n-inliner'; +export * from './i18n-translation-encoder'; +export * from './i18n-translation-reader'; +export * from './locale-data'; diff --git a/packages/angular/build/src/tools/i18n/locale-data.ts b/packages/angular/build/src/tools/i18n/locale-data.ts new file mode 100644 index 000000000000..0418830b69a8 --- /dev/null +++ b/packages/angular/build/src/tools/i18n/locale-data.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { createProjectResolver } from '../../utils/resolve-project'; + +/** + * The internal namespace used by generated locale import statements and Angular locale data plugin. + */ +export const LOCALE_DATA_NAMESPACE = 'angular:locale/data'; + +/** + * The base module location used to search for locale specific data. + */ +export const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; + +/** + * Result of resolving locale data for a given locale tag. + */ +export interface LocaleDataResolution { + path?: string; + warning?: string; + error?: string; +} + +/** + * Result of loading locale data for a given locale tag. + */ +export interface LoadedLocaleData { + code?: string; + warning?: string; + error?: string; +} + +const localeDataCache = new Map>(); + +/** + * Resolves the path to the Angular locale data file for a given locale tag. + * + * @param rawLocaleTag The raw locale identifier (e.g. "fr-CA", "de", "en-US"). + * @param projectResolve A function that attempts to resolve a path string to an absolute file path. + * @returns Resolution result with file path, or warning/error diagnostics if applicable. + */ +export function resolveLocaleDataPath( + rawLocaleTag: string, + projectResolve: (potentialPath: string) => string | undefined, +): LocaleDataResolution { + let partialLocaleTag: string; + try { + const locale = new Intl.Locale(rawLocaleTag); + partialLocaleTag = locale.baseName; + } catch { + return { + error: `Invalid or unsupported locale provided in configuration: "${rawLocaleTag}"`, + }; + } + + let exact = true; + while (partialLocaleTag) { + // Angular embeds the `en`/`en-US` locale into the framework and it does not need to be included again here. + if (partialLocaleTag === 'en' || partialLocaleTag === 'en-US') { + return {}; + } + + const potentialPath = `${LOCALE_DATA_BASE_MODULE}/${partialLocaleTag}`; + try { + const resolvedPath = projectResolve(potentialPath); + if (resolvedPath) { + return { + path: resolvedPath, + warning: exact + ? undefined + : `Locale data for '${rawLocaleTag}' cannot be found. Using locale data for '${partialLocaleTag}'.`, + }; + } + } catch {} + + // Remove the last subtag and try again with a less specific locale. + const parts = partialLocaleTag.split('-'); + partialLocaleTag = parts.slice(0, -1).join('-'); + exact = false; + } + + return { + warning: `Locale data for '${rawLocaleTag}' cannot be found. No locale data will be included for this locale.`, + }; +} + +/** + * Loads the Angular global locale data script for a specified locale tag. + * + * @param rawLocaleTag The raw locale identifier (e.g. "fr-CA", "de", "en-US"). + * @param projectRoot Optional project root for module resolution. + * @returns A promise resolving to the loaded locale data script code and any diagnostic warnings. + */ +export function loadLocaleData( + rawLocaleTag: string, + projectRoot?: string, +): Promise { + let cached = localeDataCache.get(rawLocaleTag); + if (!cached) { + cached = (async () => { + const projectResolve = createProjectResolver(projectRoot ?? process.cwd()); + const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) => { + try { + return projectResolve(potentialPath); + } catch { + return undefined; + } + }); + + if (resolution.error) { + return { error: resolution.error }; + } + + if (resolution.path) { + try { + const code = await readFile(resolution.path, 'utf8'); + + return { code, warning: resolution.warning }; + } catch (e) { + return { error: `Failed to read locale data file: ${(e as Error).message}` }; + } + } + + return { warning: resolution.warning }; + })(); + + localeDataCache.set(rawLocaleTag, cached); + } + + return cached; +} diff --git a/packages/angular/build/src/tools/javascript-transformer/index.ts b/packages/angular/build/src/tools/javascript-transformer/index.ts new file mode 100644 index 000000000000..399eea87e644 --- /dev/null +++ b/packages/angular/build/src/tools/javascript-transformer/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './javascript-transformer'; diff --git a/packages/angular/build/src/tools/javascript-transformer/javascript-transformer-worker.ts b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer-worker.ts new file mode 100644 index 000000000000..040eedaa4179 --- /dev/null +++ b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer-worker.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { DecodedSourceMap, EncodedSourceMap } from '@ampproject/remapping'; +import type { PluginItem } from '@babel/core'; +import { createRequire } from 'node:module'; +import { workerData } from 'node:worker_threads'; +import Piscina from 'piscina'; +import { useBabelLinker } from '../../utils/environment-options.js'; +import { + findTrailingSourceMapComment, + isTrailingSourceMapComment, + loadInputSourceMap, + loadInputSourceMapFromUrl, + removeSourceMappingURL, +} from '../../utils/source-map'; +import { transform as transformWithOxc } from '../oxc/oxc-transform.js'; +import type { JavaScriptTransformerOptions } from './javascript-transformer'; + +interface JavaScriptTransformRequest { + filename: string; + data: string | Uint8Array; + skipLinker?: boolean; + sideEffects?: boolean; + instrumentForCoverage?: boolean; +} + +interface TransformOptions extends Omit { + inputSourceMap?: EncodedSourceMap; + isAlreadyStripped?: boolean; +} + +const { + sourcemap = false, + thirdPartySourcemaps = false, + advancedOptimizations = false, + jit = false, +} = (workerData || {}) as Partial; + +let babelLinkerDeps: + | Promise< + [ + typeof import('@angular/compiler-cli/linker/babel'), + typeof import('@angular/compiler-cli'), + typeof import('@babel/core'), + ] + > + | undefined; + +let remapping: typeof import('@ampproject/remapping').default | undefined; + +const textDecoder = new TextDecoder(); +const textEncoder = new TextEncoder(); + +async function instrumentCoverage( + filename: string, + data: string, + useInputSourcemap: boolean, +): Promise<{ code: string; map?: EncodedSourceMap }> { + try { + let resolvedPath = 'istanbul-lib-instrument'; + try { + const requireFn = createRequire(filename); + resolvedPath = requireFn.resolve('istanbul-lib-instrument'); + } catch { + // Fallback to pool worker import traversal + } + + const { createInstrumenter } = (await import( + resolvedPath + )) as typeof import('istanbul-lib-instrument'); + const instrumenter = createInstrumenter({ + produceSourceMap: useInputSourcemap, + esModules: true, + }); + + const inputSourceMap = useInputSourcemap ? loadInputSourceMap(filename, data) : undefined; + const instrumentedCode = instrumenter.instrumentSync( + data, + filename, + inputSourceMap as Parameters[2], + ); + const lastMap = useInputSourcemap + ? (instrumenter.lastSourceMap() as EncodedSourceMap) + : undefined; + + return { + code: instrumentedCode, + map: lastMap ?? undefined, + }; + } catch (error) { + throw new Error( + `The 'istanbul-lib-instrument' package is required for code coverage but was not found. Please install the package.`, + { cause: error }, + ); + } +} + +export default async function transformJavaScript( + request: JavaScriptTransformRequest, +): Promise { + const { filename, data, ...options } = request; + + const useInputSourcemap = + sourcemap && (!!thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename)); + + let textData: string; + let inputSourceMap: EncodedSourceMap | undefined; + let isAlreadyStripped = false; + + if (typeof data !== 'string') { + const trailing = findTrailingSourceMapComment(data); + if (trailing === null) { + // 0 comments: fast path, no sourcemap to load or strip + textData = textDecoder.decode(data); + isAlreadyStripped = true; + } else if (trailing !== undefined) { + if (useInputSourcemap) { + inputSourceMap = loadInputSourceMapFromUrl(filename, trailing.urlLine); + if (inputSourceMap !== undefined) { + // Valid trailing sourcemap comment confirmed: safe to slice code buffer for transformation passes. + // Note: If no passes modify the code, the untouched original `data` buffer is returned below. + textData = textDecoder.decode(trailing.code); + isAlreadyStripped = true; + } else { + // Not a valid trailing sourcemap (e.g. inside template literal): fallback to full decode + textData = textDecoder.decode(data); + } + } else if (isTrailingSourceMapComment(trailing.urlLine)) { + // Valid trailing sourcemap comment confirmed: safe to slice code buffer + textData = textDecoder.decode(trailing.code); + isAlreadyStripped = true; + } else { + // Not a valid trailing sourcemap: fall back to full decode and oxc comment stripping + textData = textDecoder.decode(data); + } + } else { + // Multiple comments or comment not at line start: fall back to full decode and oxc comment stripping + textData = textDecoder.decode(data); + } + } else { + textData = data; + } + + const transformedData = await transformJavaScriptImpl(filename, textData, { + ...options, + inputSourceMap, + isAlreadyStripped, + }); + + // If no transformations modified the code, return the original untouched data buffer via `move`. + // This preserves any original trailing sourcemap comment and avoids re-encoding. + if (transformedData === textData && typeof data !== 'string') { + return Piscina.move(data); + } + + return Piscina.move(textEncoder.encode(transformedData)); +} + +async function transformJavaScriptImpl( + filename: string, + data: string, + options: TransformOptions, +): Promise { + const shouldLink = !options.skipLinker; + const useInputSourcemap = + sourcemap && (!!thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename)); + + let code = data; + const maps: (DecodedSourceMap | EncodedSourceMap)[] = []; + let coverageMap: EncodedSourceMap | undefined; + + if (options.instrumentForCoverage) { + const result = await instrumentCoverage(filename, code, useInputSourcemap); + code = result.code; + coverageMap = result.map; + } + + if (shouldLink && useBabelLinker) { + babelLinkerDeps ??= Promise.all([ + import('@angular/compiler-cli/linker/babel'), + import('@angular/compiler-cli'), + import('@babel/core'), + ]); + const [{ createEs2015LinkerPlugin }, { ConsoleLogger, LogLevel }, { transformAsync }] = + await babelLinkerDeps; + + const result = await transformAsync(code, { + filename, + inputSourceMap: false, + sourceMaps: !!useInputSourcemap, + compact: false, + configFile: false, + babelrc: false, + browserslistConfigFile: false, + plugins: [ + createEs2015LinkerPlugin({ + fileSystem: { + exists: () => false, + readFile: () => '', + resolve: (...paths: string[]) => paths.join('/'), + dirname: (path: string) => path.split('/').slice(0, -1).join('/'), + relative: (_from: string, to: string) => to, + } as never, + logger: new ConsoleLogger(LogLevel.info), + linkerJitMode: jit, + // This is a workaround until https://github.com/angular/angular/issues/42769 is fixed. + sourceMapping: false, + }) as PluginItem, + ], + }); + + code = result?.code ?? code; + if (result?.map) { + maps.push(result.map as EncodedSourceMap); + } + } + + // Run Oxc linking and/or advanced optimizations in a single unified AST traversal pass + const oxcLink = shouldLink && !useBabelLinker; + if (oxcLink || advancedOptimizations) { + const sideEffectFree = options.sideEffects === false; + const safeAngularPackage = + sideEffectFree && /[\\/]node_modules[\\/]@angular[\\/]/.test(filename); + const topLevelSafeMode = !safeAngularPackage; + + const result = transformWithOxc(filename, code, { + link: oxcLink, + jit, + advancedOptimizations, + sourcemap: useInputSourcemap, + sideEffects: options.sideEffects, + topLevelSafeMode, + }); + code = result.code; + if (result.map) { + maps.push(result.map); + } + } + + if (useInputSourcemap) { + const baseMap = coverageMap ?? options.inputSourceMap ?? loadInputSourceMap(filename, data); + if (maps.length > 0 || coverageMap) { + if (!options.isAlreadyStripped) { + code = removeSourceMappingURL(code); + } + const remappingChain: (DecodedSourceMap | EncodedSourceMap)[] = maps.reverse(); + if (baseMap) { + remappingChain.push(baseMap); + } + + if (remappingChain.length > 0) { + remapping ??= (await import('@ampproject/remapping')).default; + const finalMap = remapping(remappingChain, () => null).toString(); + const base64Map = Buffer.from(finalMap).toString('base64'); + code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`; + } + } + + return code; + } + + // Strip sourcemaps if they should not be used + return options.isAlreadyStripped ? code : removeSourceMappingURL(code); +} diff --git a/packages/angular/build/src/tools/javascript-transformer/javascript-transformer.ts b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer.ts new file mode 100644 index 000000000000..56a7b4eb6ed9 --- /dev/null +++ b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer.ts @@ -0,0 +1,393 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { Cache } from '../../utils/cache'; +import { createContentHash } from '../../utils/hash'; +import { IMPORT_EXEC_ARGV } from '../../utils/server-rendering/esm-in-memory-loader/utils'; +import { removeSourceMappingURL } from '../../utils/source-map'; +import { WorkerPool, WorkerPoolOptions } from '../../utils/worker-pool'; + +const LINKER_DECLARATION_PREFIX = 'ɵɵngDeclare'; +const LINKER_DECLARATION_PREFIX_BYTES = Buffer.from(LINKER_DECLARATION_PREFIX, 'utf-8'); + +const ADVANCED_OPTIMIZATION_TOKENS = [ + 'ɵ', + 'InjectionToken', + 'INJECTOR_KEY', + 'ctorParameters', + 'decorators', + 'propDecorators', +] as const; + +const ADVANCED_OPTIMIZATION_TOKEN_BYTES = ADVANCED_OPTIMIZATION_TOKENS.map((token) => + Buffer.from(token, 'utf-8'), +); + +const DECORATOR_TOKENS = ['__decorate', '__esDecorate'] as const; +const DECORATOR_TOKEN_BYTES = DECORATOR_TOKENS.map((token) => Buffer.from(token, 'utf-8')); + +const ADVANCED_OPTIMIZATION_REGEX = new RegExp(ADVANCED_OPTIMIZATION_TOKENS.join('|')); +const DECORATOR_REGEX = new RegExp(DECORATOR_TOKENS.join('|')); + +/** + * Determines whether JavaScript code contains potential candidate constructs for advanced optimizations. + * When false, advanced optimizations can be bypassed without worker dispatch or AST parsing. + * + * @param filename The full path to the file. + * @param data The data (string or Buffer) of the file. + * @param sideEffects An optional lazy resolver callback that returns whether the file is considered side-effect free. + * @returns True if the code may contain constructs that advanced optimizations can mutate. + */ +async function hasAdvancedOptimizationCandidates( + filename: string, + data: string | Uint8Array, + sideEffects?: () => Promise, +): Promise { + // Side-effect-free @angular/ packages undergo top-level pure function annotations + if (/[\\/]node_modules[\\/]@angular[\\/]/.test(filename) && (await sideEffects?.()) === false) { + return true; + } + + if (typeof data === 'string') { + const hasDecorators = DECORATOR_REGEX.test(data); + if (hasDecorators && (await sideEffects?.()) === false) { + return true; + } + + return ADVANCED_OPTIMIZATION_REGEX.test(data); + } + + const dataBuffer = Buffer.isBuffer(data) + ? data + : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + + for (const tokenBytes of DECORATOR_TOKEN_BYTES) { + if (dataBuffer.includes(tokenBytes)) { + if ((await sideEffects?.()) === false) { + return true; + } + break; + } + } + + for (const tokenBytes of ADVANCED_OPTIMIZATION_TOKEN_BYTES) { + if (dataBuffer.includes(tokenBytes)) { + return true; + } + } + + return false; +} + +/** + * Determines whether JavaScript code requires Angular linker processing. + * + * @param path The full path to the file. + * @param data The data (string or Buffer) of the file. + * @returns True if the code contains an Angular partial declaration; otherwise false. + */ +function requiresLinking(path: string, data: string | Uint8Array): boolean { + // @angular/core and @angular/compiler will cause false positives + // Also, TypeScript files do not require linking + if (/[\\/]@angular[\\/](?:compiler|core)[\\/]|\.[cm]?tsx?$/.test(path)) { + return false; + } + + if (typeof data === 'string') { + return data.includes(LINKER_DECLARATION_PREFIX); + } + + const dataBuffer = Buffer.isBuffer(data) + ? data + : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + + return dataBuffer.includes(LINKER_DECLARATION_PREFIX_BYTES); +} + +/** + * Transformation options that should apply to all transformed files and data. + */ +export interface JavaScriptTransformerOptions { + sourcemap: boolean; + thirdPartySourcemaps?: boolean; + advancedOptimizations?: boolean; + jit?: boolean; + + /** + * The maximum number of concurrent transformation operations. + * When omitted, concurrency defaults to the available worker pool threads. + */ + maxConcurrency?: number; +} + +/** + * Transformation options for an individual file or data transform request. + */ +export interface TransformOptions { + /** If true, bypass all Angular linker processing; if false, attempt linking. */ + skipLinker?: boolean; + + /** + * An optional lazy resolver callback that returns whether the file has side-effects. + * If it resolves to false, top-level pure function annotations and decorator wrapping may be applied. + */ + sideEffects?: () => Promise; + + /** If true, instrument the code for test coverage. */ + instrumentForCoverage?: boolean; +} + +/** + * A class that performs transformation of JavaScript files and raw data. + * A worker pool is used to distribute the transformation actions and allow + * parallel processing. Transformation behavior is based on the filename and + * data. Transformations may include: async downleveling, Angular linking, + * and advanced optimizations. + */ +export class JavaScriptTransformer { + #workerPool: WorkerPool | undefined; + #commonOptions: Required>; + #fileCacheKeyBase: Uint8Array; + + /** Queue of pending transformation tasks waiting for an active concurrency slot. */ + #pendingTasks: { resolve: () => void; reject: (reason: Error) => void }[] = []; + + /** Current count of actively executing transformation tasks. */ + #activeTasks = 0; + + get #maxConcurrency(): number { + return this.options.maxConcurrency ?? (this.#workerPool?.maxThreads || 1); + } + + constructor( + private readonly options: JavaScriptTransformerOptions, + private readonly cache?: Cache, + ) { + if ( + options.maxConcurrency !== undefined && + (!Number.isInteger(options.maxConcurrency) || options.maxConcurrency < 1) + ) { + throw new RangeError('options.maxConcurrency must be an integer greater than or equal to 1.'); + } + + // Extract options to ensure only the named options are serialized and sent to the worker + const { + sourcemap, + thirdPartySourcemaps = false, + advancedOptimizations = false, + jit = false, + } = options; + this.#commonOptions = { + sourcemap, + thirdPartySourcemaps, + advancedOptimizations, + jit, + }; + this.#fileCacheKeyBase = Buffer.from(JSON.stringify(this.#commonOptions), 'utf-8'); + this.#workerPool = this.#ensureWorkerPool(); + } + + /** + * Executes a transformation action using a semaphore-based backpressure throttle. + * Prevents libuv thread pool saturation and excessive V8 heap accumulation. + * @param action A callback that produces a promise for the transformation result. + * @returns A promise resolving to the transformation result. + */ + async #runWithThrottle(action: () => Promise): Promise { + if (this.#activeTasks >= this.#maxConcurrency) { + await new Promise((resolve, reject) => { + this.#pendingTasks.push({ resolve, reject }); + }); + } else { + this.#activeTasks++; + } + + try { + return await action(); + } finally { + const next = this.#pendingTasks.shift(); + if (next) { + next.resolve(); + } else { + this.#activeTasks--; + } + } + } + + #ensureWorkerPool(): WorkerPool { + if (this.#workerPool) { + return this.#workerPool; + } + + const workerPoolOptions: WorkerPoolOptions = { + filename: require.resolve('./javascript-transformer-worker'), + workerData: this.#commonOptions, + ...(this.options.maxConcurrency !== undefined && { + minThreads: this.options.maxConcurrency, + maxThreads: this.options.maxConcurrency, + }), + }; + + // Prevent passing SSR `--import` (loader-hooks) from parent to child worker. + const filteredExecArgv = process.execArgv.filter((v) => v !== IMPORT_EXEC_ARGV); + if (process.execArgv.length !== filteredExecArgv.length) { + workerPoolOptions.execArgv = filteredExecArgv; + } + + this.#workerPool = new WorkerPool(workerPoolOptions); + + return this.#workerPool; + } + + /** + * Performs JavaScript transformations on a file from the filesystem. + * If no transformations are required, the data for the original file will be returned. + * @param filename The full path to the file. + * @param options Transformation options specific to this file. + * @returns A promise that resolves to a UTF-8 encoded Uint8Array containing the result. + */ + async transformFile(filename: string, options?: TransformOptions): Promise { + return this.#runWithThrottle(async () => { + const data = await readFile(filename); + + return this.#transform(filename, data, options); + }); + } + + /** + * Performs JavaScript transformations on the provided data of a file. The file does not need + * to exist on the filesystem. + * @param filename The full path of the file represented by the data. + * @param data The data of the file that should be transformed. + * @param options Transformation options specific to this file data. + * @returns A promise that resolves to a UTF-8 encoded Uint8Array containing the result. + */ + async transformData( + filename: string, + data: string | Uint8Array, + options?: TransformOptions, + ): Promise { + return this.#runWithThrottle(() => this.#transform(filename, data, options)); + } + + async #transform( + filename: string, + data: string | Uint8Array, + options?: TransformOptions, + ): Promise { + let resolvedSideEffects: boolean | undefined; + let sideEffectsQueried = false; + + const sideEffectsGetter = options?.sideEffects + ? async () => { + if (!sideEffectsQueried) { + sideEffectsQueried = true; + resolvedSideEffects = await options.sideEffects?.(); + } + + return resolvedSideEffects; + } + : undefined; + + const shouldLink = !options?.skipLinker && requiresLinking(filename, data); + const shouldOptimize = + this.#commonOptions.advancedOptimizations && + (await hasAdvancedOptimizationCandidates(filename, data, sideEffectsGetter)); + + // Perform a quick test to determine if the data needs any transformations. + // This allows directly returning the data without the worker communication overhead. + if (!shouldLink && !shouldOptimize && !options?.instrumentForCoverage) { + const keepSourcemap = + this.#commonOptions.sourcemap && + (!!this.#commonOptions.thirdPartySourcemaps || !/[\\/]node_modules[\\/]/.test(filename)); + + if (typeof data === 'string') { + return Buffer.from(keepSourcemap ? data : removeSourceMappingURL(data), 'utf-8'); + } + + return keepSourcemap ? data : removeSourceMappingURL(data); + } + + let cacheKey: string | undefined; + if (this.cache) { + // Create a cache key from the file data and options that affect the output. + // NOTE: If additional options are added, this may need to be updated. + const hasher = createContentHash(); + hasher.update( + `${!options?.skipLinker}--${resolvedSideEffects === false}--${!!options?.instrumentForCoverage}`, + ); + hasher.update(data); + hasher.update(this.#fileCacheKeyBase); + cacheKey = hasher.digest(); + + try { + const cached = await this.cache.get(cacheKey); + if (cached !== undefined) { + return cached; + } + } catch { + // Failure to get the value should not fail the transform + } + } + + // Only standalone (non-pooled) ArrayBuffers can be transferred across worker threads. + // Node.js shares an internal 8KB ArrayBuffer pool for small buffers, and transferring + // a pooled buffer will throw a DataCloneError because detaching it invalidates other slices. + // In addition, SharedArrayBuffers cannot be transferred, and Yarn PnP has deserialization issues. + const isTransferable = + typeof data !== 'string' && + data.buffer instanceof ArrayBuffer && + data.byteOffset === 0 && + data.byteLength === data.buffer.byteLength && + !process.versions.pnp; + + const result = (await this.#ensureWorkerPool().run( + { + filename, + data, + skipLinker: !shouldLink, + sideEffects: resolvedSideEffects, + instrumentForCoverage: options?.instrumentForCoverage, + }, + { + transferList: isTransferable ? [data.buffer] : undefined, + }, + )) as Uint8Array; + + if (this.cache && cacheKey) { + try { + await this.cache.put(cacheKey, result); + } catch { + // Failure to store the value in the cache should not fail the transform + } + } + + return result; + } + + /** + * Stops all active transformation tasks and shuts down all workers. + * @returns A void promise that resolves when closing is complete. + */ + async close(): Promise { + const pending = this.#pendingTasks; + this.#pendingTasks = []; + for (const task of pending) { + task.reject(new Error('JavaScriptTransformer closed.')); + } + + if (this.#workerPool) { + try { + await this.#workerPool.destroy(); + } finally { + this.#workerPool = undefined; + } + } + } +} diff --git a/packages/angular/build/src/tools/javascript-transformer/javascript-transformer_spec.ts b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer_spec.ts new file mode 100644 index 000000000000..94d671ef2a72 --- /dev/null +++ b/packages/angular/build/src/tools/javascript-transformer/javascript-transformer_spec.ts @@ -0,0 +1,662 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { JavaScriptTransformer } from './javascript-transformer'; + +describe('JavaScriptTransformer sourcemaps', () => { + let transformer: JavaScriptTransformer; + + afterEach(async () => { + await transformer?.close(); + }); + + function extractSourcemap(code: string): Record | null { + const match = code.match( + /\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,(.+)/, + ); + if (!match) { + return null; + } + + return JSON.parse(Buffer.from(match[1], 'base64').toString('utf-8')); + } + + it('should remap correctly when only advanced optimizations are applied', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputMap = { + version: 3, + sources: ['src/app.ts'], + sourcesContent: ['export class MyClass { static ɵprov = 42; }'], + mappings: 'AAAA', + names: [], + }; + const base64Map = Buffer.from(JSON.stringify(inputMap)).toString('base64'); + const input = `export class MyClass { static ɵprov = 42; }\n//# sourceMappingURL=data:application/json;base64,${base64Map}`; + + const result = await transformer.transformData('src/app.js', input, { skipLinker: true }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('src/app.ts'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should remap correctly when only linking is applied', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + thirdPartySourcemaps: true, + maxConcurrency: 1, + }); + + const inputMap = { + version: 3, + sources: ['node_modules/my-lib/directive.ts'], + sourcesContent: ['export class MyDirective {}'], + mappings: 'AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA', + names: [], + }; + const base64Map = Buffer.from(JSON.stringify(inputMap)).toString('base64'); + const input = ` + import * as i0 from "@angular/core"; + export class MyDirective {} + MyDirective.ɵdir = i0.ɵɵngDeclareDirective({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyDirective, + selector: "[my-dir]" + }); + //# sourceMappingURL=data:application/json;base64,${base64Map} + `; + + const result = await transformer.transformData('node_modules/my-lib/directive.js', input, { + skipLinker: false, + }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('node_modules/my-lib/directive.ts'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should defer and chain remapping when both linking and advanced optimizations are applied', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + thirdPartySourcemaps: true, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputMap = { + version: 3, + sources: ['node_modules/my-lib/component.ts'], + sourcesContent: ['export class MyComponent {}'], + mappings: 'AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA', + names: [], + }; + const base64Map = Buffer.from(JSON.stringify(inputMap)).toString('base64'); + const input = ` + import * as i0 from "@angular/core"; + export class MyComponent {} + MyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyComponent, + selector: "my-cmp", + template: "
" + }); + //# sourceMappingURL=data:application/json;base64,${base64Map} + `; + + const result = await transformer.transformData('node_modules/my-lib/component.js', input, { + skipLinker: false, + }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('node_modules/my-lib/component.ts'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should produce a valid sourcemap when no input sourcemap is present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const input = 'export class MyClass { static ɵprov = 42; }'; + const result = await transformer.transformData('src/app.js', input, { skipLinker: true }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('src/app.js'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should remap correctly when coverage instrumentation is applied with an input sourcemap', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + maxConcurrency: 1, + }); + + const inputMap = { + version: 3, + sources: ['src/counter.ts'], + sourcesContent: ['export function add(a: number, b: number) { return a + b; }'], + mappings: 'AAAA', + names: [], + }; + const base64Map = Buffer.from(JSON.stringify(inputMap)).toString('base64'); + const input = `export function add(a, b) { return a + b; }\n//# sourceMappingURL=data:application/json;base64,${base64Map}`; + + const result = await transformer.transformData('src/counter.js', input, { + skipLinker: true, + instrumentForCoverage: true, + }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('src/counter.ts'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should defer and chain remapping when coverage instrumentation and advanced optimizations are applied', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputMap = { + version: 3, + sources: ['src/app.ts'], + sourcesContent: ['const x = new SomeClass();'], + mappings: 'AAAA', + names: [], + }; + const base64Map = Buffer.from(JSON.stringify(inputMap)).toString('base64'); + const input = `var x = new SomeClass();\n//# sourceMappingURL=data:application/json;base64,${base64Map}`; + + const result = await transformer.transformData('src/app.js', input, { + skipLinker: true, + instrumentForCoverage: true, + }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('src/app.ts'); + expect(typeof map?.['mappings']).toBe('string'); + expect((map?.['mappings'] as string).length).toBeGreaterThan(0); + }); + + it('should accept a Uint8Array input in transformData', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: true, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('export class MyClass { static ɵprov = 42; }', 'utf-8'); + const result = await transformer.transformData('src/app.js', inputBuffer, { skipLinker: true }); + const text = Buffer.from(result).toString('utf-8'); + const map = extractSourcemap(text); + + expect(map).toBeDefined(); + expect(map?.['version']).toBe(3); + expect(map?.['sources']).toContain('src/app.js'); + expect(typeof map?.['mappings']).toBe('string'); + }); + + it('should strip trailing sourcemap comments from Uint8Array input on fast-path', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from( + 'console.log("hello");\n//# sourceMappingURL=app.js.map', + 'utf-8', + ); + const result = await transformer.transformData('node_modules/my-lib/lib.js', inputBuffer, { + skipLinker: true, + }); + const text = Buffer.from(result).toString('utf-8'); + + expect(text).toBe('console.log("hello");\n'); + }); + + it('should return Uint8Array input untouched on fast-path when no sourcemap comment is present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('console.log("hello");\nconst x = 1;', 'utf-8'); + const result = await transformer.transformData('node_modules/my-lib/lib.js', inputBuffer, { + skipLinker: true, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should return Uint8Array untouched when skipLinker is false but file contains no linker declarations', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('console.log("no linking required");\nconst x = 1;', 'utf-8'); + const result = await transformer.transformData('node_modules/my-lib/lib.js', inputBuffer, { + skipLinker: false, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should bypass worker and skip linking for @angular/core and @angular/compiler paths', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('export const ɵɵngDeclareDirective = () => {};', 'utf-8'); + const result = await transformer.transformData( + 'node_modules/@angular/core/fesm2022/core.mjs', + inputBuffer, + { skipLinker: false }, + ); + + expect(result).toBe(inputBuffer); + }); + + it('should bypass worker and skip linking for TypeScript file extensions (.ts, .tsx, .mts, .cts)', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('export const ɵɵngDeclareDirective = () => {};', 'utf-8'); + + for (const ext of ['.ts', '.tsx', '.mts', '.cts']) { + const result = await transformer.transformData(`src/app/directive${ext}`, inputBuffer, { + skipLinker: false, + }); + + expect(result).toBe(inputBuffer); + } + }); + + it('should not exclude packages with similar prefixes such as @angular/compiler-cli', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + maxConcurrency: 1, + }); + + const input = ` + import * as i0 from "@angular/core"; + export class MyDirective {} + MyDirective.ɵdir = i0.ɵɵngDeclareDirective({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyDirective, + selector: "[my-dir]" + }); + `; + + const result = await transformer.transformData( + 'node_modules/@angular/compiler-cli/test.js', + input, + { skipLinker: false }, + ); + const text = Buffer.from(result).toString('utf-8'); + + expect(text).not.toContain('i0.ɵɵngDeclareDirective'); + }); + + describe('advanced optimizations fast-path pre-filter', () => { + it('should bypass worker and return input buffer directly when no candidate tokens are present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from( + 'function add(a, b) { return a + b; }\nconst result = add(1, 2);', + 'utf-8', + ); + const result = await transformer.transformData('src/math.js', inputBuffer, { + skipLinker: true, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should bypass worker for standard classes without static properties', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from( + `export class UserService { + constructor(http) { this.http = http; } + getUser(id) { return this.http.get('/users/' + id); } + }`, + 'utf-8', + ); + const result = await transformer.transformData('src/user.service.js', inputBuffer, { + skipLinker: true, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should bypass worker for default exports without static properties or Angular metadata', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from( + `export default class UserService { + constructor(http) { this.http = http; } + getUser(id) { return this.http.get('/users/' + id); } + }`, + 'utf-8', + ); + const result = await transformer.transformData('src/user.service.js', inputBuffer, { + skipLinker: true, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should bypass worker for classes with static members when no Angular metadata is present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('export class MyComponent { static prop = 42; }', 'utf-8'); + const result = await transformer.transformData('src/component.js', inputBuffer, { + skipLinker: true, + }); + + expect(result).toBe(inputBuffer); + }); + + it('should dispatch to worker when Angular tokens are present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const input = 'export class MyService { static ɵprov = true; }'; + const result = await transformer.transformData('src/service.js', input, { skipLinker: true }); + const text = Buffer.from(result).toString('utf-8'); + + expect(text).toContain('let MyService = /*#__PURE__*/ (() => {'); + }); + + it('should dispatch to worker when decorator tokens are present and sideEffects is false', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputBuffer = Buffer.from('const MyClass = __decorate([], class {});', 'utf-8'); + const result = await transformer.transformData('src/class.js', inputBuffer, { + skipLinker: true, + sideEffects: async () => false, + }); + + expect(result).not.toBe(inputBuffer); + }); + + it('should bypass worker and return converted buffer when no candidate tokens are present in string input', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputString = 'function multiply(a, b) { return a * b; }'; + const result = await transformer.transformData('src/math.js', inputString, { + skipLinker: true, + }); + + expect(Buffer.from(result).toString('utf-8')).toBe(inputString); + }); + + it('should dispatch to worker when candidate tokens are present in string input', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + const inputString = 'export class MyService { static ɵprov = true; }'; + const result = await transformer.transformData('src/service.js', inputString, { + skipLinker: true, + }); + const text = Buffer.from(result).toString('utf-8'); + + expect(text).toContain('let MyService = /*#__PURE__*/ (() => {'); + }); + + it('should not query sideEffects when no candidate tokens are present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queried = false; + const inputBuffer = Buffer.from('function add(a, b) { return a + b; }', 'utf-8'); + await transformer.transformData('src/math.js', inputBuffer, { + skipLinker: true, + sideEffects: async () => { + queried = true; + + return false; + }, + }); + + expect(queried).toBeFalse(); + }); + + it('should not query sideEffects when primary tokens are present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queried = false; + const input = 'export class MyService { static ɵprov = true; }'; + await transformer.transformData('src/service.js', input, { + skipLinker: true, + sideEffects: async () => { + queried = true; + + return false; + }, + }); + + expect(queried).toBeFalse(); + }); + + it('should query sideEffects for @angular/ packages and dispatch to worker when sideEffects is false', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queryCount = 0; + const inputBuffer = Buffer.from('export const foo = someCall();', 'utf-8'); + const result = await transformer.transformData( + '/node_modules/@angular/core/fesm2022/index.mjs', + inputBuffer, + { + skipLinker: true, + sideEffects: async () => { + queryCount++; + + return false; + }, + }, + ); + + expect(queryCount).toBe(1); + expect(result).not.toBe(inputBuffer); + }); + + it('should query sideEffects for decorator tokens and evaluate at most once', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queryCount = 0; + const inputBuffer = Buffer.from('const MyClass = __decorate([], class {});', 'utf-8'); + const result = await transformer.transformData('src/class.js', inputBuffer, { + skipLinker: true, + sideEffects: async () => { + queryCount++; + + return false; + }, + }); + + expect(queryCount).toBe(1); + expect(result).not.toBe(inputBuffer); + }); + + it('should query sideEffects and wrap decorators when both primary and decorator tokens are present', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queryCount = 0; + const input = ` + let MyService = class MyService { static ɵprov = true; }; + MyService = __decorate([], MyService); + `; + const result = await transformer.transformData('src/service.js', input, { + skipLinker: true, + sideEffects: async () => { + queryCount++; + + return false; + }, + }); + + expect(queryCount).toBe(1); + const text = Buffer.from(result).toString('utf-8'); + expect(text).toContain('let MyService = /*#__PURE__*/ (() => {'); + expect(text).toContain('__decorate'); + }); + + it('should query sideEffects when both primary and decorator tokens are present in Buffer', async () => { + transformer = new JavaScriptTransformer({ + sourcemap: false, + advancedOptimizations: true, + maxConcurrency: 1, + }); + + let queryCount = 0; + const inputBuffer = Buffer.from( + 'let MyService = class MyService { static ɵprov = true; };\nMyService = __decorate([], MyService);', + 'utf-8', + ); + const result = await transformer.transformData('src/service.js', inputBuffer, { + skipLinker: true, + sideEffects: async () => { + queryCount++; + + return false; + }, + }); + + expect(queryCount).toBe(1); + const text = Buffer.from(result).toString('utf-8'); + expect(text).toContain('let MyService = /*#__PURE__*/ (() => {'); + expect(text).toContain('__decorate'); + }); + }); + + describe('maxConcurrency', () => { + it('should throw RangeError if maxConcurrency is less than 1', () => { + expect(() => { + new JavaScriptTransformer({ sourcemap: false, maxConcurrency: 0 }); + }).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + + expect(() => { + new JavaScriptTransformer({ sourcemap: false, maxConcurrency: -1 }); + }).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + }); + + it('should throw RangeError if maxConcurrency is not an integer', () => { + expect(() => { + new JavaScriptTransformer({ sourcemap: false, maxConcurrency: 1.5 }); + }).toThrowError( + RangeError, + 'options.maxConcurrency must be an integer greater than or equal to 1.', + ); + }); + + it('should allow omitting maxConcurrency', async () => { + transformer = new JavaScriptTransformer({ sourcemap: false }); + const result = await transformer.transformData('src/app.js', 'const x = 1;', { + skipLinker: true, + }); + expect(result).toBeDefined(); + }); + }); +}); diff --git a/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts b/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts new file mode 100644 index 000000000000..7fe8c68030fc --- /dev/null +++ b/packages/angular/build/src/tools/oxc/adjust-static-class-members_oxc_spec.ts @@ -0,0 +1,1103 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { transform } from './oxc-transform'; + +const NO_CHANGE = Symbol('NO_CHANGE'); + +function cleanCode(code: string): string { + return code.replace(/\s+/g, '').replace(/,([}\])])/g, '$1'); +} + +function testCase({ + input, + expected, + options, +}: { + input: string; + expected: string | typeof NO_CHANGE; + options?: { wrapDecorators?: boolean }; +}): jasmine.ImplementationCallback { + return async () => { + const result = transform('test.js', input, { + sourcemap: false, + sideEffects: options?.wrapDecorators ? false : true, + pureAnnotate: false, + }); + if (!result?.code) { + fail('Expected oxc-transform to return a transform result.'); + } else { + const actualClean = cleanCode(result.code); + const expectedClean = cleanCode(expected === NO_CHANGE ? input : expected); + expect(actualClean).toEqual(expectedClean); + } + }; +} + +describe('adjust-static-class-members oxc-transform implementation', () => { + it( + 'elides empty ctorParameters function expression static field', + testCase({ + input: ` + export class SomeClass {} + SomeClass.ctorParameters = function () { return []; }; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'elides non-empty ctorParameters function expression static field', + testCase({ + input: ` + export class SomeClass {} + SomeClass.ctorParameters = function () { return [{type: Injector}]; }; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'elides empty ctorParameters arrow expression static field', + testCase({ + input: ` + export class SomeClass {} + SomeClass.ctorParameters = () => []; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'elides non-empty ctorParameters arrow expression static field', + testCase({ + input: ` + export class SomeClass {} + SomeClass.ctorParameters = () => [{type: Injector}]; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'keeps ctorParameters static field without arrow/function expression', + testCase({ + input: ` + export class SomeClass {} + SomeClass.ctorParameters = 42; + `, + expected: ` + export let SomeClass = /*#__PURE__*/ (() => { + class SomeClass {} + SomeClass.ctorParameters = 42; + return SomeClass; + })(); + `, + }), + ); + + it( + 'elides empty decorators static field with array literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.decorators = []; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'elides non-empty decorators static field with array literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.decorators = [{ type: Injectable }]; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'keeps decorators static field without array literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.decorators = 42; + `, + expected: ` + export let SomeClass = /*#__PURE__*/ (() => { + class SomeClass {} + SomeClass.decorators = 42; + return SomeClass; + })(); + `, + }), + ); + + it( + 'elides empty propDecorators static field with object literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.propDecorators = {}; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'elides non-empty propDecorators static field with object literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.propDecorators = { 'ngIf': [{ type: Input }] }; + `, + expected: 'export class SomeClass {}', + }), + ); + + it( + 'keeps propDecorators static field without object literal', + testCase({ + input: ` + export class SomeClass {} + SomeClass.propDecorators = 42; + `, + expected: ` + export let SomeClass = /*#__PURE__*/ (() => { + class SomeClass {} + SomeClass.propDecorators = 42; + return SomeClass; + })(); + `, + }), + ); + + it( + 'does not wrap default exported class with no connected siblings', + testCase({ + // NOTE: This could technically have no changes but the default export splitting detection + // does not perform class property analysis currently. + input: ` + export default class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + export { CustomComponentEffects as default }; + `, + }), + ); + + it( + 'does wrap not default exported class with only side effect fields', + testCase({ + input: ` + export default class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with only side effect fields', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with only side effect native fields', + testCase({ + input: ` + class CustomComponentEffects { + static someFieldWithSideEffects = console.log('foo'); + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with only instance native fields', + testCase({ + input: ` + class CustomComponentEffects { + someFieldWithSideEffects = console.log('foo'); + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: NO_CHANGE, + }), + ); + + it( + 'wraps class with pure annotated side effect fields (#__PURE__)', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with pure annotated side effect native fields (#__PURE__)', + testCase({ + input: ` + class CustomComponentEffects { + static someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + static someFieldWithSideEffects = /*#__PURE__*/ console.log('foo'); + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with pure annotated side effect fields (@__PURE__)', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /*@__PURE__*/ console.log('foo'); + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /*@__PURE__*/ console.log('foo'); + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with pure annotated side effect fields (@pureOrBreakMyCode)', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /**@pureOrBreakMyCode*/ console.log('foo'); + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = + /**@pureOrBreakMyCode*/ console.log('foo'); + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with closure pure annotated side effect fields', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = /* @pureOrBreakMyCode */ console.log('foo'); + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = + /* @pureOrBreakMyCode */ console.log('foo'); + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps exported class with a pure static field', + testCase({ + input: ` + export class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + `, + expected: ` + export let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps exported class with a pure native static field', + testCase({ + input: ` + export class CustomComponentEffects { + static someField = 42; + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: ` + export let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + static someField = 42; + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with a basic literal static field', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + return CustomComponentEffects; + })(); + `, + }), + ); + + it( + 'wraps class with a pure static field', + testCase({ + input: ` + const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; + const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; + class TemplateRef {} + TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; + `, + expected: ` + const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; + const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; + let TemplateRef = /*#__PURE__*/ (() => { + class TemplateRef {} + TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; + return TemplateRef; + })(); + `, + }), + ); + + it( + 'wraps class with multiple pure static field', + testCase({ + input: ` + const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; + const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; + class TemplateRef {} + TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; + TemplateRef.someField = 42; + `, + expected: ` + const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef; + const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__POST_R3__; + let TemplateRef = /*#__PURE__*/ (() => { + class TemplateRef {} + TemplateRef.__NG_ELEMENT_ID__ = SWITCH_TEMPLATE_REF_FACTORY; + TemplateRef.someField = 42; + return TemplateRef; + })(); + `, + }), + ); + + it( + 'does not wrap class with only some pure static fields', + testCase({ + input: ` + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with only pure native static fields and some side effect static fields', + testCase({ + input: ` + class CustomComponentEffects { + static someField = 42; + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someFieldWithSideEffects = console.log('foo'); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with only some pure native static fields', + testCase({ + input: ` + class CustomComponentEffects { + static someField = 42; + static someFieldWithSideEffects = console.log('foo'); + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap class with class decorators when wrapDecorators is false', + testCase({ + input: ` + let SomeClass = class SomeClass { + }; + SomeClass = __decorate([ + Dec() + ], SomeClass); + `, + expected: NO_CHANGE, + options: { wrapDecorators: false }, + }), + ); + + it( + 'wraps class with Angular ɵfac static field (esbuild)', + testCase({ + input: ` + var Comp2Component = class _Comp2Component { + static { + this.ɵfac = function Comp2Component_Factory(t) { + return new (t || _Comp2Component)(); + }; + } + }; + `, + expected: ` + var Comp2Component = /*#__PURE__*/ (() => { + let Comp2Component = class _Comp2Component { + static { + this.ɵfac = function Comp2Component_Factory(t) { + return new (t || _Comp2Component)(); + }; + } + }; + return Comp2Component; + })(); + `, + }), + ); + + it( + 'wraps class with class decorators when wrapDecorators is true (esbuild output)', + testCase({ + input: ` + var ExampleClass = class { + method() { + } + }; + __decorate([ + SomeDecorator() + ], ExampleClass.prototype, "method", null); + `, + expected: ` + var ExampleClass = /*#__PURE__*/ (() => { + let ExampleClass = class { + method() {} + }; + __decorate([SomeDecorator()], ExampleClass.prototype, "method", null); + return ExampleClass; + })(); + `, + options: { wrapDecorators: true }, + }), + ); + + it( + 'wraps class with class decorators when wrapDecorators is true', + testCase({ + input: ` + let SomeClass = class SomeClass { + }; + SomeClass = __decorate([ + SomeDecorator() + ], SomeClass); + `, + expected: ` + let SomeClass = /*#__PURE__*/ (() => { + let SomeClass = class SomeClass { + }; + SomeClass = __decorate([ + SomeDecorator() + ], SomeClass); + return SomeClass; + })(); + `, + options: { wrapDecorators: true }, + }), + ); + + it( + 'does not wrap class with constructor decorators when wrapDecorators is false', + testCase({ + input: ` + let SomeClass = class SomeClass { + constructor(foo) { } + }; + SomeClass = __decorate([ + __param(0, SomeDecorator) + ], SomeClass); + `, + expected: NO_CHANGE, + options: { wrapDecorators: false }, + }), + ); + + it( + 'wraps class with constructor decorators when wrapDecorators is true', + testCase({ + input: ` + let SomeClass = class SomeClass { + constructor(foo) { } + }; + SomeClass = __decorate([ + __param(0, SomeDecorator) + ], SomeClass); + `, + expected: ` + let SomeClass = /*#__PURE__*/ (() => { + let SomeClass = class SomeClass { + constructor(foo) { } + }; + SomeClass = __decorate([ + __param(0, SomeDecorator) + ], SomeClass); + return SomeClass; + })(); + `, + options: { wrapDecorators: true }, + }), + ); + + it( + 'does not wrap class with field decorators when wrapDecorators is false', + testCase({ + input: ` + class SomeClass { + constructor() { + this.foo = 42; + } + } + __decorate([ + SomeDecorator + ], SomeClass.prototype, "foo", void 0); + `, + expected: NO_CHANGE, + options: { wrapDecorators: false }, + }), + ); + + it( + 'wraps class with field decorators when wrapDecorators is true', + testCase({ + input: ` + class SomeClass { + constructor() { + this.foo = 42; + } + } + __decorate([ + SomeDecorator + ], SomeClass.prototype, "foo", void 0); + `, + expected: ` + let SomeClass = /*#__PURE__*/ (() => { + class SomeClass { + constructor() { + this.foo = 42; + } + } + __decorate([ + SomeDecorator + ], SomeClass.prototype, "foo", void 0); + return SomeClass; + })(); + `, + options: { wrapDecorators: true }, + }), + ); + + it( + 'wraps class with Angular ɵfac static field', + testCase({ + input: ` + class CommonModule { + } + CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + } + CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; + return CommonModule; + })(); + `, + }), + ); + + it( + 'wraps class with Angular ɵfac static block (ES2022 + useDefineForClassFields: false)', + testCase({ + input: ` + class CommonModule { + static { this.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; } + static { this.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); } + } + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + static { + this.ɵfac = function CommonModule_Factory(t) { + return new (t || CommonModule)(); + }; + } + static { + this.ɵmod = ɵngcc0.ɵɵdefineNgModule({ + type: CommonModule, + }); + } + } + return CommonModule; + })(); + `, + }), + ); + + it( + 'does not wrap class with side effect full static block (ES2022 + useDefineForClassFields: false)', + testCase({ + input: ` + class CommonModule { + static { globalThis.bar = 1 } + } + `, + expected: NO_CHANGE, + }), + ); + + it( + 'wraps class with Angular ɵmod static field', + testCase({ + input: ` + class CommonModule { + } + CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + } + CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); + return CommonModule; + })(); + `, + }), + ); + + it( + 'wraps class with Angular ɵinj static field', + testCase({ + input: ` + class CommonModule { + } + CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ + { provide: NgLocalization, useClass: NgLocaleLocalization }, + ] }); + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + } + CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ + { + provide: NgLocalization, + useClass: NgLocaleLocalization + }, + ] }); + return CommonModule; + })(); + `, + }), + ); + + it( + 'wraps class with multiple Angular static fields', + testCase({ + input: ` + class CommonModule { + } + CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; + CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); + CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ + { provide: NgLocalization, useClass: NgLocaleLocalization }, + ] }); + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + } + CommonModule.ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; + CommonModule.ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); + CommonModule.ɵinj = /*@__PURE__*/ ɵngcc0.ɵɵdefineInjector({ providers: [ + { + provide: NgLocalization, + useClass: NgLocaleLocalization + }, + ]}); + return CommonModule; + })(); + `, + }), + ); + + it( + 'wraps class with multiple Angular native static fields', + testCase({ + input: ` + class CommonModule { + static ɵfac = function CommonModule_Factory(t) { return new (t || CommonModule)(); }; + static ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ type: CommonModule }); + static ɵinj = ɵngcc0.ɵɵdefineInjector({ providers: [ + { provide: NgLocalization, useClass: NgLocaleLocalization }, + ] }); + } + `, + expected: ` + let CommonModule = /*#__PURE__*/ (() => { + class CommonModule { + static ɵfac = function CommonModule_Factory(t) { + return new (t || CommonModule)(); + }; + static ɵmod = /*@__PURE__*/ ɵngcc0.ɵɵdefineNgModule({ + type: CommonModule, + }); + static ɵinj = ɵngcc0.ɵɵdefineInjector({ + providers: [ + { + provide: NgLocalization, + useClass: NgLocaleLocalization, + }, + ], + }); + } + return CommonModule; + })(); + `, + }), + ); + + it( + 'wraps default exported class with pure static fields', + testCase({ + input: ` + export default class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + `, + expected: ` + let CustomComponentEffects = /*#__PURE__*/ (() => { + class CustomComponentEffects { + constructor(_actions) { + this._actions = _actions; + this.doThis = this._actions; + } + } + CustomComponentEffects.someField = 42; + return CustomComponentEffects; + })(); + export { CustomComponentEffects as default }; + `, + }), + ); + it( + 'supports class with empty static block and wraps pure static properties', + testCase({ + input: ` + class MyClass { + static {} + static ɵprov = 42; + } + `, + expected: ` + let MyClass = /*#__PURE__*/ (() => { + class MyClass { + static {} + static ɵprov = 42; + } + return MyClass; + })(); + `, + }), + ); + + it( + 'does not wrap class with non-empty static block', + testCase({ + input: ` + class MyClass { + static { console.log(1); } + static ɵprov = 42; + } + `, + expected: ` + class MyClass { + static { console.log(1); } + static ɵprov = 42; + } + `, + }), + ); + + it( + 'wraps adjacent class declarations without interleaving', + testCase({ + input: 'class A{static s=[1]}class B{static s=[2]}', + expected: ` + let A = /*#__PURE__*/ (() => { + class A { + static s = [1] + } + return A; + })(); + let B = /*#__PURE__*/ (() => { + class B { + static s = [2] + } + return B; + })(); + `, + }), + ); + + it( + 'wraps adjacent exported class declarations without interleaving', + testCase({ + input: 'export class A{static s=[1]}export class B{static s=[2]}', + expected: ` + export let A = /*#__PURE__*/ (() => { + class A { + static s = [1] + } + return A; + })(); + export let B = /*#__PURE__*/ (() => { + class B { + static s = [2] + } + return B; + })(); + `, + }), + ); + + it( + 'wraps adjacent default export and class declarations without interleaving', + testCase({ + input: 'export default class A{static s=[1]}class B{static s=[2]}', + expected: ` + let A = /*#__PURE__*/ (() => { + class A { + static s = [1] + } + return A; + })(); + export { A as default }; + let B = /*#__PURE__*/ (() => { + class B { + static s = [2] + } + return B; + })(); + `, + }), + ); + + it( + 'splits default export without interleaving with adjacent class declaration', + testCase({ + input: 'export default class A{}class B{static s=[2]}', + expected: ` + class A {} + export { A as default }; + let B = /*#__PURE__*/ (() => { + class B { + static s = [2] + } + return B; + })(); + `, + }), + ); + + it( + 'wraps adjacent variable class declarations without interleaving', + testCase({ + input: 'let A=class A{static s=[1]};class B{static s=[2]}', + expected: ` + let A = /*#__PURE__*/ (() => { + let A = class A { + static s = [1] + }; + return A; + })(); + let B = /*#__PURE__*/ (() => { + class B { + static s = [2] + } + return B; + })(); + `, + }), + ); +}); diff --git a/packages/angular/build/src/tools/oxc/adjust-typescript-enums_oxc_spec.ts b/packages/angular/build/src/tools/oxc/adjust-typescript-enums_oxc_spec.ts new file mode 100644 index 000000000000..82877cb3b2e3 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/adjust-typescript-enums_oxc_spec.ts @@ -0,0 +1,382 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { format } from 'prettier'; +import { transform } from './oxc-transform'; + +const NO_CHANGE = Symbol('NO_CHANGE'); + +function testCase({ + input, + expected, +}: { + input: string; + expected: string | typeof NO_CHANGE; +}): jasmine.ImplementationCallback { + return async () => { + const result = transform('test.js', input, { + sourcemap: false, + pureAnnotate: false, + }); + if (!result?.code) { + fail('Expected oxc-transform to return a transform result.'); + } else { + expect(await format(result.code, { parser: 'babel' })).toEqual( + await format(expected === NO_CHANGE ? input : expected, { parser: 'babel' }), + ); + } + }; +} + +describe('adjust-typescript-enums oxc-transform implementation', () => { + it( + 'wraps unexported TypeScript enums', + testCase({ + input: ` + var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); + `, + expected: ` + var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || {}); + `, + }), + ); + + it( + 'wraps exported TypeScript enums', + testCase({ + input: ` + export var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); + `, + expected: ` + export var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || {}); + `, + }), + ); + + it( + 'does not wrap exported TypeScript enums from CommonJS (<5.1)', + testCase({ + input: ` + var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy = exports.ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = {})); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'wraps exported TypeScript enums from CommonJS (5.1+)', + testCase({ + input: ` + var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = ChangeDetectionStrategy = {})); + `, + expected: ` + var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = ChangeDetectionStrategy = {})); + `, + }), + ); + + it( + 'wraps TypeScript enums with custom numbering', + testCase({ + input: ` + export var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 5] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 8] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); + `, + expected: ` + export var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 5)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 8)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || {}); + `, + }), + ); + + it( + 'wraps string-based TypeScript enums', + testCase({ + input: ` + var NotificationKind; + (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; + })(NotificationKind || (NotificationKind = {})); + `, + expected: ` + var NotificationKind = /*#__PURE__*/ (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; + return NotificationKind; + })(NotificationKind || {}); + `, + }), + ); + + it( + 'wraps enums that were renamed due to scope hoisting', + testCase({ + input: ` + var NotificationKind$1; + (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; + })(NotificationKind$1 || (NotificationKind$1 = {})); + `, + expected: ` + var NotificationKind$1 = /*#__PURE__*/ (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; + return NotificationKind; + })(NotificationKind$1 || {}); + `, + }), + ); + + it( + 'maintains multi-line comments', + testCase({ + input: ` + /** + * Supported http methods. + * @deprecated use @angular/common/http instead + */ + var RequestMethod; + (function (RequestMethod) { + RequestMethod[RequestMethod["Get"] = 0] = "Get"; + RequestMethod[RequestMethod["Post"] = 1] = "Post"; + RequestMethod[RequestMethod["Put"] = 2] = "Put"; + RequestMethod[RequestMethod["Delete"] = 3] = "Delete"; + RequestMethod[RequestMethod["Options"] = 4] = "Options"; + RequestMethod[RequestMethod["Head"] = 5] = "Head"; + RequestMethod[RequestMethod["Patch"] = 6] = "Patch"; + })(RequestMethod || (RequestMethod = {})); + `, + expected: ` + /** + * Supported http methods. + * @deprecated use @angular/common/http instead + */ + var RequestMethod = /*#__PURE__*/ (function (RequestMethod) { + RequestMethod[(RequestMethod["Get"] = 0)] = "Get"; + RequestMethod[(RequestMethod["Post"] = 1)] = "Post"; + RequestMethod[(RequestMethod["Put"] = 2)] = "Put"; + RequestMethod[(RequestMethod["Delete"] = 3)] = "Delete"; + RequestMethod[(RequestMethod["Options"] = 4)] = "Options"; + RequestMethod[(RequestMethod["Head"] = 5)] = "Head"; + RequestMethod[(RequestMethod["Patch"] = 6)] = "Patch"; + return RequestMethod; + })(RequestMethod || {}); + `, + }), + ); + + it( + 'does not wrap TypeScript enums with side effect values', + testCase({ + input: ` + export var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = console.log('foo'); + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); + `, + expected: NO_CHANGE, + }), + ); + + it( + 'does not wrap object literals similar to TypeScript enums', + testCase({ + input: ` + const RendererStyleFlags3 = { + Important: 1, + DashCase: 2, + }; + if (typeof RendererStyleFlags3 === 'object') { + RendererStyleFlags3[RendererStyleFlags3.Important] = 'DashCase'; + } + RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important'; + `, + expected: NO_CHANGE, + }), + ); + + it( + 'wraps TypeScript enums', + testCase({ + input: ` + var ChangeDetectionStrategy; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); + `, + expected: ` + var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || {}); + `, + }), + ); + + it( + 'should wrap TypeScript enums if the declaration identifier has been renamed to avoid collisions', + testCase({ + input: ` + var ChangeDetectionStrategy$1; + (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy$1 || (ChangeDetectionStrategy$1 = {})); + `, + expected: ` + var ChangeDetectionStrategy$1 = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy$1 || {}); + `, + }), + ); + + it( + 'handles TypeScript enums with chained exports assignment (angular-split / shared-docs pattern)', + testCase({ + input: ` + var Area; + (function (a1) { + a1[a1["areaAfter"] = 0] = "areaAfter"; + a1[a1["preserveOtherCategoryOrder"] = 1] = "preserveOtherCategoryOrder"; + })(Area || (Area = exports.Area = {})); + `, + expected: ` + var Area = /*#__PURE__*/ (function (a1) { + a1[(a1["areaAfter"] = 0)] = "areaAfter"; + a1[(a1["preserveOtherCategoryOrder"] = 1)] = "preserveOtherCategoryOrder"; + return a1; + })(Area || (exports.Area = {})); + `, + }), + ); + + it( + 'handles TypeScript enums wrapped in parentheses', + testCase({ + input: ` + var ChangeDetectionStrategy; + ((function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; + })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}))); + `, + expected: ` + var ChangeDetectionStrategy = /*#__PURE__*/ (function (ChangeDetectionStrategy) { + ChangeDetectionStrategy[(ChangeDetectionStrategy["OnPush"] = 0)] = "OnPush"; + ChangeDetectionStrategy[(ChangeDetectionStrategy["Default"] = 1)] = "Default"; + return ChangeDetectionStrategy; + })(ChangeDetectionStrategy || {}); + `, + }), + ); + + it( + 'wraps Crockford-style TypeScript enum IIFE without leaving dangling parentheses', + testCase({ + input: ` + var HDirection; + (function (HDirection) { + HDirection[HDirection['Backwards'] = -1] = 'Backwards'; + HDirection[HDirection['Forwards'] = 1] = 'Forwards'; + }(HDirection || (HDirection = {}))); + const nextStatement = true; + `, + expected: ` + var HDirection = /*#__PURE__*/ (function (HDirection) { + HDirection[(HDirection['Backwards'] = -1)] = 'Backwards'; + HDirection[(HDirection['Forwards'] = 1)] = 'Forwards'; + return HDirection; + }(HDirection || {})); + + const nextStatement = true; + `, + }), + ); + + it( + 'wraps TypeScript enum IIFE with multiple nested parentheses', + testCase({ + input: ` + var Foo; + (((function (Foo) { + Foo[Foo['A'] = 0] = 'A'; + }(Foo || (Foo = {}))))); + `, + expected: ` + var Foo = /*#__PURE__*/ (function (Foo) { + Foo[(Foo['A'] = 0)] = 'A'; + return Foo; + }(Foo || {})); + `, + }), + ); + + it( + 'wraps Crockford-style TypeScript enum IIFE with chained export assignments', + testCase({ + input: ` + var Foo; + (function (Foo) { + Foo[Foo['A'] = 0] = 'A'; + }(Foo || (Foo = exports.Foo = {}))); + `, + expected: ` + var Foo = /*#__PURE__*/ (function (Foo) { + Foo[(Foo['A'] = 0)] = 'A'; + return Foo; + }(Foo || (exports.Foo = {}))); + `, + }), + ); +}); diff --git a/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts b/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts new file mode 100644 index 000000000000..f4d6c09b6c19 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/elide-angular-metadata_oxc_spec.ts @@ -0,0 +1,213 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { transform } from './oxc-transform'; + +function cleanCode(code: string): string { + return code + .replace(/\s+/g, '') + .replace(/"/g, "'") + .replace(/;}/g, '}') + .replace(/,([}\])])/g, '$1'); +} + +function testCase({ + input, + expected, +}: { + input: string; + expected: string; +}): jasmine.ImplementationCallback { + return async () => { + const result = transform('test.js', input, { + sourcemap: false, + pureAnnotate: false, + }); + if (!result?.code) { + fail('Expected oxc-transform to return a transform result.'); + } else { + const actualClean = cleanCode(result.code); + const expectedClean = cleanCode(expected); + expect(actualClean).toEqual(expectedClean); + } + }; +} + +describe('elide-angular-metadata oxc-transform implementation', () => { + it( + 'elides pure annotated ɵsetClassMetadata', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (function () { i0.ɵsetClassMetadata(Clazz, [{ + type: Component, + args: [{ + selector: 'app-lazy', + template: 'very lazy', + styles: [] + }] + }], null, null); })(); + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (function () { void 0 })(); + `, + }), + ); + + it( + 'elides JIT mode protected ɵsetClassMetadata', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadata(SomeClass, [{ + type: Component, + args: [{ + selector: 'app-lazy', + template: 'very lazy', + styles: [] + }] + }], null, null); })();`, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + (function () { (typeof ngJitMode === "undefined" || ngJitMode) && void 0 })();`, + }), + ); + + it( + 'elides ɵsetClassMetadata inside an arrow-function-based IIFE', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (() => { i0.ɵsetClassMetadata(Clazz, [{ + type: Component, + args: [{ + selector: 'app-lazy', + template: 'very lazy', + styles: [] + }] + }], null, null); })(); + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (() => { void 0 })(); + `, + }), + ); + + it( + 'elides pure annotated ɵsetClassMetadataAsync', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (function () { + i0.ɵsetClassMetadataAsync(SomeClass, + function () { return [import("./cmp-a").then(function (m) { return m.CmpA; })]; }, + function (CmpA) { i0.ɵsetClassMetadata(SomeClass, [{ + type: Component, + args: [{ + selector: 'test-cmp', + standalone: true, + imports: [CmpA, LocalDep], + template: '{#defer}{/defer}', + }] + }], null, null); }); + })(); + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (function () { void 0 })(); + `, + }), + ); + + it( + 'elides JIT mode protected ɵsetClassMetadataAsync', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + (function () { + (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵsetClassMetadataAsync(SomeClass, + function () { return [import("./cmp-a").then(function (m) { return m.CmpA; })]; }, + function (CmpA) { i0.ɵsetClassMetadata(SomeClass, [{ + type: Component, + args: [{ + selector: 'test-cmp', + standalone: true, + imports: [CmpA, LocalDep], + template: '{#defer}{/defer}', + }] + }], null, null); }); + })(); + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + (function () { (typeof ngJitMode === "undefined" || ngJitMode) && void 0 })(); + `, + }), + ); + + it( + 'elides arrow-function-based ɵsetClassMetadataAsync', + testCase({ + input: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (() => { + i0.ɵsetClassMetadataAsync(SomeClass, + () => [import("./cmp-a").then(m => m.CmpA)], + (CmpA) => { i0.ɵsetClassMetadata(SomeClass, [{ + type: Component, + args: [{ + selector: 'test-cmp', + standalone: true, + imports: [CmpA, LocalDep], + template: '{#defer}{/defer}', + }] + }], null, null); }); + })(); + `, + expected: ` + import { Component } from '@angular/core'; + export class SomeClass {} + /*@__PURE__*/ (() => { void 0 })(); + `, + }), + ); + + it( + 'elides ɵsetClassDebugInfo', + testCase({ + input: ` + import { Component } from '@angular/core'; + class SomeClass {} + (() => { + (typeof ngDevMode === 'undefined' || ngDevMode) && + i0.ɵsetClassDebugInfo(SomeClass, { className: 'SomeClass' }); + })(); + `, + expected: ` + import { Component } from "@angular/core"; + class SomeClass {} + (() => { + (typeof ngDevMode === "undefined" || ngDevMode) && void 0; + })(); + `, + }), + ); +}); diff --git a/packages/angular/build/src/tools/oxc/oxc-transform.ts b/packages/angular/build/src/tools/oxc/oxc-transform.ts new file mode 100644 index 000000000000..e0d6ba26a252 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/oxc-transform.ts @@ -0,0 +1,748 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { DecodedSourceMap } from '@ampproject/remapping'; +import { needsLinking } from '@angular/compiler-cli/linker'; +import type { BindingIdentifier, Class, Node } from '@oxc-project/types'; +import { MagicString } from 'magic-string'; +import { parseSync } from 'oxc-parser'; +import { OxcLinker } from '../angular/linker/oxc-linker'; +import { traversePostOrder } from './traversal'; + +export interface OxcTransformOptions { + sourcemap?: boolean; + sideEffects?: boolean; + topLevelSafeMode?: boolean; + pureAnnotate?: boolean; + link?: boolean; + jit?: boolean; + advancedOptimizations?: boolean; +} + +/** + * A set of constructor names that are considered to be side-effect free. + */ +const sideEffectFreeConstructors = new Set(['InjectionToken']); + +/** + * A set of TypeScript helper function names used by the helper name matcher utility function. + */ +const tslibHelpers = new Set([ + '__extends', + '__assign', + '__rest', + '__decorate', + '__param', + '__esDecorate', + '__runInitializers', + '__propKey', + '__setFunctionName', + '__metadata', + '__awaiter', + '__generator', + '__exportStar', + '__values', + '__read', + '__privateGet', + '__privateSet', + '__privateMethod', + '__addDisposableResource', + '__disposeResources', +]); + +/** + * Determines whether an identifier name matches one of the TypeScript helper function names. + * + * @param name The identifier name to check. + * @returns True if the name matches a TypeScript helper name; otherwise, false. + */ +function isTslibHelperName(name: string): boolean { + const nameParts = name.split('$'); + const originalName = nameParts[0]; + + if (nameParts.length > 2 || (nameParts.length === 2 && !/^\d+$/.test(nameParts[1]))) { + return false; + } + + return tslibHelpers.has(originalName); +} + +/** + * A set of Babel helper function names that are intended to cause side effects. + */ +const babelHelpers = new Set(['_defineProperty']); + +/** + * Determines whether an identifier name matches one of the Babel helper function names. + * + * @param name The identifier name to check. + * @returns True if the name matches a Babel helper name; otherwise, false. + */ +function isBabelHelperName(name: string): boolean { + return babelHelpers.has(name); +} + +/** + * A set of Angular static properties that should be wrapped in pure IIFE statements. + */ +const angularStaticsToWrap = new Set([ + 'ɵcmp', + 'ɵdir', + 'ɵfac', + 'ɵinj', + 'ɵmod', + 'ɵpipe', + 'ɵprov', + 'INJECTOR_KEY', +]); + +/** + * A set of Angular metadata decorator functions that can be elided. + */ +const angularMetadataFunctions = new Set([ + 'ɵsetClassMetadata', + 'ɵsetClassMetadataAsync', + 'ɵsetClassDebugInfo', +]); + +/** + * A map of static properties and their matcher predicate functions to check if they + * can be safely elided from class declarations. + */ +const angularStaticsToElide: Record boolean> = { + 'ctorParameters'(node) { + return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + }, + 'decorators'(node) { + return node.type === 'ArrayExpression'; + }, + 'propDecorators'(node) { + return node.type === 'ObjectExpression'; + }, +}; + +/** + * Determines whether an AST node is considered safe for pure evaluation (side-effect free). + * + * @param node The AST node to check. + * @returns True if the node is side-effect free; otherwise, false. + */ +function isPure(node: Node): boolean { + switch (node.type) { + case 'Identifier': + case 'Literal': + return true; + case 'BinaryExpression': + case 'LogicalExpression': + return isPure(node.left) && isPure(node.right); + case 'UnaryExpression': + return isPure(node.argument); + case 'MemberExpression': + return isPure(node.object) && (!node.computed || isPure(node.property)); + case 'ObjectExpression': + return node.properties.every((p) => p.type === 'Property' && isPure(p.value)); + case 'ArrayExpression': + return node.elements.every((e) => !e || isPure(e)); + case 'ParenthesizedExpression': + return isPure(node.expression); + default: + return false; + } +} + +/** + * Recursively unwraps any ParenthesizedExpression wrapper nodes to get the inner expression. + * + * @param node The potentially parenthesized AST node. + * @returns The inner non-parenthesized AST node. + */ +function unwrapParentheses(node: Node): Node { + while (node && node.type === 'ParenthesizedExpression') { + node = node.expression; + } + + return node; +} + +/** + * Determines whether a class static property assignment is safe to be wrapped in a pure IIFE. + * + * @param propertyName The name of the property. + * @param assignmentValue The AST node representing the value assigned. + * @param code The source code of the file. + * @returns True if the property can be wrapped safely; otherwise, false. + */ +function canWrapProperty(propertyName: string, assignmentValue: Node, code: string): boolean { + if (angularStaticsToWrap.has(propertyName)) { + return true; + } + + const prefix = code.substring(Math.max(0, assignmentValue.start - 100), assignmentValue.start); + if (/(\/\*[\s\S]*?(?:@__PURE__|#__PURE__|@pureOrBreakMyCode)[\s\S]*?\*\/)\s*$/.test(prefix)) { + return true; + } + + return isPure(assignmentValue); +} + +/** + * Analyzes static properties inside a class body to determine if the class has any + * side-effecting static property initializers. + * + * @param classNode The Class AST node. + * @param code The source code of the file. + * @returns True if the class static properties are pure and can be wrapped; otherwise, false. + */ +function analyzeClassStaticProperties(classNode: Node, code: string): boolean { + let shouldWrap = false; + const body = (classNode as Class).body.body; + for (const element of body) { + if (element.type === 'PropertyDefinition') { + if (!element.static) { + continue; + } + + const key = element.key; + const value = element.value; + if (key.type === 'Identifier' && (!value || canWrapProperty(key.name, value, code))) { + shouldWrap = true; + } else { + shouldWrap = false; + break; + } + } else if (element.type === 'StaticBlock') { + const blockBody = element.body; + if (blockBody.length === 0) { + continue; + } + if (blockBody.length > 1) { + shouldWrap = false; + break; + } + const expressionStatement = blockBody[0]; + if (expressionStatement && expressionStatement.type === 'ExpressionStatement') { + const assignment = expressionStatement.expression; + if ( + assignment && + assignment.type === 'AssignmentExpression' && + assignment.left.type === 'MemberExpression' + ) { + const left = assignment.left; + if (left.object.type === 'ThisExpression' && left.property.type === 'Identifier') { + if (canWrapProperty(left.property.name, assignment.right, code)) { + shouldWrap = true; + continue; + } + } + } + } + shouldWrap = false; + break; + } + } + + return shouldWrap; +} + +/** + * Executes a single-pass optimized transformation using oxc-parser and magic-string. + * Performs typescript enum wrapping, static class members elision/wrapping, angular metadata elision, + * and top-level pure function annotations. + * + * @param filename The absolute path of the file being transformed. + * @param code The string source content of the file. + * @param options Configuration options specifying which optimization steps to run. + * @returns The transformed code string and an optional source map. + */ +// eslint-disable-next-line max-lines-per-function +export function transform(filename: string, code: string, options: OxcTransformOptions) { + const { program } = parseSync(filename, code, { range: true }); + const source = new MagicString(code); + + const shouldLink = options.link && needsLinking(filename, code); + const linker = shouldLink ? new OxcLinker(filename, code, options.jit) : undefined; + + const advancedOptimizations = options.advancedOptimizations ?? true; + const sideEffectFree = options.sideEffects === false; + const topLevelSafeMode = options.topLevelSafeMode ?? false; + const wrapDecorators = sideEffectFree; + const pureAnnotate = options.pureAnnotate ?? true; + + /** + * Scans backwards from the specified start index to check if a pure comment (e.g. `/*@__PURE__*\/`) + * already precedes the node. + * + * @param start The index where the node starts. + * @returns True if a pure comment is already present; otherwise, false. + */ + function hasPureComment(start: number): boolean { + let i = start - 1; + while (i >= 0 && /\s/.test(code[i])) { + i--; + } + if (i < 1 || code[i] !== '/' || code[i - 1] !== '*') { + return false; + } + const commentEnd = i + 1; + const commentStart = code.lastIndexOf('/*', commentEnd); + if (commentStart === -1) { + return false; + } + const commentContent = code.substring(commentStart + 2, commentEnd - 2); + + return commentContent.includes('@__PURE__') || commentContent.includes('#__PURE__'); + } + + const editedRanges: { start: number; end: number }[] = []; + + /** + * Records a range in the source code that has been modified, preventing subsequent nested mutations. + * + * @param start The start index of the modified range. + * @param end The end index of the modified range. + */ + function markEdited(start: number, end: number) { + editedRanges.push({ start, end }); + } + + /** + * Checks if the specified range falls inside an already modified section of code. + * + * @param start The start index of the range. + * @param end The end index of the range. + * @returns True if the range is already edited; otherwise, false. + */ + function isAlreadyEdited(start: number, end: number): boolean { + return editedRanges.some((r) => start >= r.start && end <= r.end); + } + + /** + * Scans and rewrites TypeScript emitted enum declarations in the statement block. + * Wraps enum statements inside a pure IIFE assignable directly to the enum variable. + * + * @param body The array of statement AST nodes to process. + */ + function adjustTypeScriptEnumsInStatements(body: Node[]) { + for (let i = 0; i < body.length - 1; i++) { + const statement = body[i]; + let declStatement = statement; + if ( + statement.type === 'ExportNamedDeclaration' && + statement.declaration?.type === 'VariableDeclaration' + ) { + declStatement = statement.declaration; + } + + if ( + declStatement.type !== 'VariableDeclaration' || + declStatement.kind !== 'var' || + declStatement.declarations.length !== 1 + ) { + continue; + } + const decl = declStatement.declarations[0]; + if (decl.init || decl.id.type !== 'Identifier') { + continue; + } + + const nextStatement = body[i + 1]; + if (nextStatement.type !== 'ExpressionStatement') { + continue; + } + + const nextExpr = unwrapParentheses(nextStatement.expression); + if (nextExpr.type !== 'CallExpression' || nextExpr.arguments.length !== 1) { + continue; + } + + const arg = unwrapParentheses(nextExpr.arguments[0]); + if (arg.type !== 'LogicalExpression' || arg.operator !== '||') { + continue; + } + + const argLeft = unwrapParentheses(arg.left); + if (argLeft.type !== 'Identifier' || argLeft.name !== decl.id.name) { + continue; + } + + const rightCallArgument = unwrapParentheses(arg.right); + if (rightCallArgument.type !== 'AssignmentExpression') { + continue; + } + + const callee = unwrapParentheses(nextExpr.callee); + if ( + callee.type !== 'FunctionExpression' || + callee.params.length !== 1 || + !callee.body || + callee.body.type !== 'BlockStatement' + ) { + continue; + } + + const param = callee.params[0]; + if (param.type !== 'Identifier') { + continue; + } + const paramName = (param as BindingIdentifier).name; + + // Check if all statements in body are pure assignments + let hasElements = false; + let allPure = true; + for (const enumStatement of callee.body.body) { + if (enumStatement.type !== 'ExpressionStatement') { + allPure = false; + break; + } + + const enumValueAssignment = unwrapParentheses(enumStatement.expression); + if ( + enumValueAssignment.type !== 'AssignmentExpression' || + !isPure(enumValueAssignment.right) + ) { + allPure = false; + break; + } + + hasElements = true; + } + + if (!allPure || !hasElements) { + continue; + } + + // 1. Remove leading/trailing characters/parentheses of the expression statement + source.remove(nextStatement.start, nextExpr.start); + source.remove(nextExpr.end, nextStatement.end); + markEdited(nextStatement.start, nextStatement.end); + + // 2. Add return statement inside IIFE body + source.appendRight(callee.body.end - 1, `; return ${paramName};`); + + // 3. Remove `Name = ` assignment in arguments if it's a simple identifier + if (rightCallArgument.left.type === 'Identifier') { + let replacement = code.substring( + rightCallArgument.right.start, + rightCallArgument.right.end, + ); + if (unwrapParentheses(rightCallArgument.right).type === 'AssignmentExpression') { + replacement = `(${replacement})`; + } + source.overwrite(arg.right.start, arg.right.end, replacement); + markEdited(arg.right.start, arg.right.end); + } + + // 4. Move IIFE to the var initializer + source.move(nextExpr.start, nextExpr.end, decl.id.end); + source.appendLeft(decl.id.end, ' = /*#__PURE__*/ '); + } + } + + /** + * Scans and rewrites static class member initializers in the statement block. + * Groups externalized class static assignments into pure wrappers or elides them when safe. + * + * @param body The array of statement AST nodes to process. + */ + function adjustStaticMembersInStatements(body: Node[]) { + for (let i = 0; i < body.length; i++) { + const statement = body[i]; + let classNode: Node | null = null; + let isExportDefault = false; + let isExportNamed = false; + let isVariableClass = false; + let classIdName = ''; + if (statement.type === 'ClassDeclaration') { + classNode = statement; + classIdName = classNode.id?.name || ''; + } else if ( + statement.type === 'ExportNamedDeclaration' && + statement.declaration?.type === 'ClassDeclaration' + ) { + classNode = statement.declaration; + classIdName = classNode.id?.name || ''; + isExportNamed = true; + } else if ( + statement.type === 'ExportDefaultDeclaration' && + statement.declaration?.type === 'ClassDeclaration' + ) { + classNode = statement.declaration; + classIdName = classNode.id?.name || ''; + isExportDefault = true; + } else if (statement.type === 'VariableDeclaration' && statement.declarations.length === 1) { + const decl = statement.declarations[0]; + if (decl.init && decl.init.type === 'ClassExpression' && decl.id.type === 'Identifier') { + classNode = decl.init; + classIdName = decl.id.name; + isVariableClass = true; + } + } + + if (!classNode || !classIdName) { + continue; + } + + const wrapStatementPaths: { statement: Node; type: 'wrap' | 'decorate' | 'elide' }[] = []; + let hasPotentialSideEffects = false; + + for (let j = i + 1; j < body.length; j++) { + const nextStatement = body[j]; + if (nextStatement.type !== 'ExpressionStatement') { + break; + } + + const nextExpression = nextStatement.expression; + + // Case 1: __decorate(...) + if (nextExpression.type === 'CallExpression') { + if ( + nextExpression.callee.type !== 'Identifier' || + nextExpression.callee.name !== '__decorate' + ) { + break; + } + + if (wrapDecorators) { + wrapStatementPaths.push({ statement: nextStatement, type: 'decorate' }); + } else { + hasPotentialSideEffects = true; + } + continue; + } + + // Case 2: AssignmentExpression + if (nextExpression.type !== 'AssignmentExpression') { + break; + } + + const left = nextExpression.left; + + if (left.type === 'Identifier') { + if ( + left.name !== classIdName || + nextExpression.right.type !== 'CallExpression' || + nextExpression.right.callee.type !== 'Identifier' || + nextExpression.right.callee.name !== '__decorate' + ) { + break; + } + + if (wrapDecorators) { + wrapStatementPaths.push({ statement: nextStatement, type: 'decorate' }); + } else { + hasPotentialSideEffects = true; + } + continue; + } + + if ( + left.type !== 'MemberExpression' || + left.object.type !== 'Identifier' || + left.object.name !== classIdName || + left.property.type !== 'Identifier' + ) { + break; + } + + const propertyName = left.property.name; + const assignmentValue = nextExpression.right; + + if (angularStaticsToElide[propertyName]?.(assignmentValue)) { + wrapStatementPaths.push({ statement: nextStatement, type: 'elide' }); + } else if (canWrapProperty(propertyName, assignmentValue, code)) { + wrapStatementPaths.push({ statement: nextStatement, type: 'wrap' }); + } else { + hasPotentialSideEffects = true; + } + } + + // Check class body static properties + const shouldWrapClassStaticProperties = analyzeClassStaticProperties(classNode, code); + + // Perform elisions immediately + for (const item of wrapStatementPaths) { + if (item.type === 'elide') { + source.remove(item.statement.start, item.statement.end); + markEdited(item.statement.start, item.statement.end); + } + } + + const activeWrapPaths = wrapStatementPaths.filter( + (p) => p.type === 'wrap' || p.type === 'decorate', + ); + + if ( + !hasPotentialSideEffects && + (activeWrapPaths.length > 0 || shouldWrapClassStaticProperties) + ) { + const lastStatement = + activeWrapPaths.length > 0 + ? activeWrapPaths[activeWrapPaths.length - 1].statement + : classNode; + + if (isExportDefault) { + // 1. Remove `export default ` + source.overwrite(statement.start, classNode.start, ''); + // 2. Wrap in IIFE + source.appendRight(classNode.start, `let ${classIdName} = /*#__PURE__*/ (() => {\n`); + source.appendLeft( + lastStatement.end, + `\nreturn ${classIdName};\n})();\nexport { ${classIdName} as default };`, + ); + } else if (isExportNamed) { + // 1. Export is kept, turn `class` into `let ClassName = IIFE` + source.appendRight(classNode.start, `let ${classIdName} = /*#__PURE__*/ (() => {\n`); + source.appendLeft(lastStatement.end, `\nreturn ${classIdName};\n})();`); + } else if (isVariableClass) { + // 2. Wrap class inside init: `(() => { let ClassName = class ClassName {}; return ClassName; })()` + source.appendRight(classNode.start, `/*#__PURE__*/ (() => {\nlet ${classIdName} = `); + const terminator = activeWrapPaths.length === 0 ? ';' : ''; + const iifeClosing = activeWrapPaths.length === 0 ? '})()' : '})();'; + source.appendLeft( + lastStatement.end, + `${terminator}\nreturn ${classIdName};\n${iifeClosing}`, + ); + } else { + // Standard ClassDeclaration + source.appendRight(classNode.start, `let ${classIdName} = /*#__PURE__*/ (() => {\n`); + source.appendLeft(lastStatement.end, `\nreturn ${classIdName};\n})();`); + } + + markEdited(statement.start, lastStatement.end); + + // Fast-forward outer loop index to skip the statements we wrapped + i += wrapStatementPaths.length; + } else if (isExportDefault && !hasPotentialSideEffects) { + // Splitting default export even when not wrapped + source.overwrite(statement.start, classNode.start, ''); + source.appendLeft(classNode.end, `\nexport { ${classIdName} as default };`); + markEdited(statement.start, classNode.end); + } + } + } + + traversePostOrder(program, (node, { functionDepth, classDepth, parentFunc }) => { + switch (node.type) { + case 'Program': + case 'BlockStatement': + if (advancedOptimizations) { + adjustTypeScriptEnumsInStatements(node.body); + adjustStaticMembersInStatements(node.body); + } + break; + + case 'CallExpression': { + if (isAlreadyEdited(node.start, node.end)) { + return; + } + + if (linker) { + const linkedCode = linker.linkCallExpression(node); + if (linkedCode !== undefined) { + source.overwrite(node.start, node.end, linkedCode); + markEdited(node.start, node.end); + + return; + } + } + + if (!advancedOptimizations) { + return; + } + + // 1. Elide Angular Metadata check + let calleeName: string | undefined; + if (node.callee.type === 'Identifier') { + calleeName = node.callee.name; + } else if ( + node.callee.type === 'MemberExpression' && + node.callee.property.type === 'Identifier' + ) { + calleeName = node.callee.property.name; + } + + if (calleeName && angularMetadataFunctions.has(calleeName)) { + if ( + parentFunc && + (parentFunc.type === 'FunctionExpression' || + parentFunc.type === 'ArrowFunctionExpression') + ) { + source.overwrite(node.start, node.end, 'void 0'); + markEdited(node.start, node.end); + + return; + } + } + + // 2. Mark Top-Level Pure Functions check + if (!pureAnnotate || functionDepth > 0 || classDepth > 0 || topLevelSafeMode) { + return; + } + + const callee = unwrapParentheses(node.callee); + if ( + (callee.type === 'FunctionExpression' || callee.type === 'ArrowFunctionExpression') && + node.arguments.length !== 0 + ) { + return; + } + + if ( + callee.type === 'Identifier' && + (isTslibHelperName(callee.name) || isBabelHelperName(callee.name)) + ) { + return; + } + + if (!hasPureComment(node.start)) { + source.appendLeft(node.start, '/*#__PURE__*/ '); + } + break; + } + + case 'NewExpression': { + if ( + !advancedOptimizations || + !pureAnnotate || + functionDepth > 0 || + classDepth > 0 || + isAlreadyEdited(node.start, node.end) + ) { + return; + } + + if (!topLevelSafeMode) { + if (!hasPureComment(node.start)) { + source.appendLeft(node.start, '/*#__PURE__*/ '); + } + + return; + } + + const newCallee = node.callee; + if (newCallee.type === 'Identifier' && sideEffectFreeConstructors.has(newCallee.name)) { + if (!hasPureComment(node.start)) { + source.appendLeft(node.start, '/*#__PURE__*/ '); + } + } + break; + } + } + }); + + let map: DecodedSourceMap | undefined; + if (options.sourcemap) { + const rawMap = source.generateDecodedMap({ hires: 'boundary', source: filename }); + map = { ...rawMap, version: 3 }; + } + + return { + code: source.toString(), + map, + }; +} diff --git a/packages/angular/build/src/tools/oxc/oxc-transform_spec.ts b/packages/angular/build/src/tools/oxc/oxc-transform_spec.ts new file mode 100644 index 000000000000..d1b02f6a1bdc --- /dev/null +++ b/packages/angular/build/src/tools/oxc/oxc-transform_spec.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { transform } from './oxc-transform'; + +describe('oxc-transform', () => { + describe('sourcemaps', () => { + it('should generate a decoded sourcemap when sourcemap option is enabled', () => { + const input = 'var result = new SomeClass();'; + const result = transform('test.js', input, { sourcemap: true }); + + expect(result.map).toBeDefined(); + expect(result.map?.version).toBe(3); + expect(result.map?.sources).toContain('test.js'); + expect(result.map?.mappings.length).toBeGreaterThan(0); + }); + }); + + describe('linking and unified passes', () => { + const componentInput = ` + import * as i0 from "@angular/core"; + export class MyComponent {} + MyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyComponent, + isStandalone: true, + selector: "my-cmp", + template: "Hello" + }); + `; + + it('should link partial component declarations when link option is enabled', () => { + const result = transform('test.js', componentInput, { link: true }); + expect(result.code).toContain('i0.ɵɵdefineComponent'); + expect(result.code).not.toContain('i0.ɵɵngDeclareComponent'); + }); + + it('should not link partial component declarations when link option is disabled', () => { + const result = transform('test.js', componentInput, { link: false }); + expect(result.code).not.toContain('i0.ɵɵdefineComponent'); + expect(result.code).toContain('i0.ɵɵngDeclareComponent'); + }); + + it('should perform linking and advanced optimizations simultaneously in a single pass', () => { + const input = ` + import * as i0 from "@angular/core"; + export class MyComponent { + static create() { + return new MyComponent(); + } + } + MyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ + minVersion: "12.0.0", + version: "14.0.0", + ngImport: i0, + type: MyComponent, + isStandalone: true, + selector: "my-cmp", + template: "Hello" + }); + `; + + const result = transform('test.js', input, { + link: true, + advancedOptimizations: true, + topLevelSafeMode: true, + }); + expect(result.code).toContain('i0.ɵɵdefineComponent'); + expect(result.code).not.toContain('i0.ɵɵngDeclareComponent'); + expect(result.code).toContain('let MyComponent = /*#__PURE__*/ (() => {'); + }); + }); +}); diff --git a/packages/angular/build/src/tools/oxc/pure-toplevel-functions_oxc_spec.ts b/packages/angular/build/src/tools/oxc/pure-toplevel-functions_oxc_spec.ts new file mode 100644 index 000000000000..0b91cc98aa45 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/pure-toplevel-functions_oxc_spec.ts @@ -0,0 +1,202 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { transform } from './oxc-transform'; + +function cleanCode(code: string): string { + return code + .replace(/\s+/g, '') + .replace(/"/g, "'") + .replace(/;}/g, '}') + .replace(/,([}\])])/g, '$1'); +} + +function testCase({ + input, + expected, + options, +}: { + input: string; + expected: string; + options?: { topLevelSafeMode: boolean }; +}): jasmine.ImplementationCallback { + return async () => { + const result = transform('test.js', input, { + sourcemap: false, + topLevelSafeMode: options?.topLevelSafeMode, + }); + if (!result?.code) { + fail('Expected oxc-transform to return a transform result.'); + } else { + const actualClean = cleanCode(result.code); + const expectedClean = cleanCode(expected); + expect(actualClean).toEqual(expectedClean); + } + }; +} + +function testCaseNoChange(input: string): jasmine.ImplementationCallback { + return testCase({ input, expected: input }); +} + +describe('pure-toplevel-functions oxc-transform implementation', () => { + it( + 'annotates top-level new expressions', + testCase({ + input: 'var result = new SomeClass();', + expected: 'var result = /*#__PURE__*/ new SomeClass();', + }), + ); + + it( + 'annotates top-level function calls', + testCase({ + input: 'var result = someCall();', + expected: 'var result = /*#__PURE__*/ someCall();', + }), + ); + + it( + 'annotates top-level IIFE assignments with no arguments', + testCase({ + input: 'var SomeClass = (function () { function SomeClass() { } return SomeClass; })();', + expected: + 'var SomeClass = /*#__PURE__*/(function () { function SomeClass() { } return SomeClass; })();', + }), + ); + + it( + 'annotates top-level arrow-function-based IIFE assignments with no arguments', + testCase({ + input: 'var SomeClass = (() => { function SomeClass() { } return SomeClass; })();', + expected: + 'var SomeClass = /*#__PURE__*/(() => { function SomeClass() { } return SomeClass; })();', + }), + ); + + it( + 'does not annotate top-level IIFE assignments with arguments', + testCaseNoChange( + 'var SomeClass = (function () { function SomeClass() { } return SomeClass; })(abc);', + ), + ); + + it( + 'does not annotate top-level arrow-function-based IIFE assignments with arguments', + testCaseNoChange( + 'var SomeClass = (() => { function SomeClass() { } return SomeClass; })(abc);', + ), + ); + + it( + 'does not annotate call expressions inside function declarations', + testCaseNoChange('function funcDecl() { const result = someFunction(); }'), + ); + + it( + 'does not annotate call expressions inside function expressions', + testCaseNoChange('const foo = function funcDecl() { const result = someFunction(); }'), + ); + + it( + 'does not annotate call expressions inside arrow functions', + testCaseNoChange('const foo = () => { const result = someFunction(); }'), + ); + + it( + 'does not annotate new expressions inside function declarations', + testCaseNoChange('function funcDecl() { const result = new SomeClass(); }'), + ); + + it( + 'does not annotate new expressions inside function expressions', + testCaseNoChange('const foo = function funcDecl() { const result = new SomeClass(); }'), + ); + + it( + 'does not annotate new expressions inside arrow functions', + testCaseNoChange('const foo = () => { const result = new SomeClass(); }'), + ); + + it( + 'does not annotate TypeScript helper functions (tslib)', + testCaseNoChange(` + class LanguageState {} + __decorate([ + __metadata("design:type", Function), + __metadata("design:paramtypes", [Object]), + __metadata("design:returntype", void 0) + ], LanguageState.prototype, "checkLanguage", null); + `), + ); + + it( + 'does not annotate _defineProperty function', + testCaseNoChange(` + class LanguageState {} + _defineProperty( + LanguageState, + 'property', + 'value' + ); + `), + ); + + it( + 'does not annotate object literal methods', + testCaseNoChange(` + const literal = { + method() { + var newClazz = new Clazz(); + } + }; + `), + ); + + it( + 'annotates helper functions with non-numeric suffixes', + testCase({ + input: 'var result = __decorate$foo();', + expected: 'var result = /*#__PURE__*/ __decorate$foo();', + }), + ); + + it( + 'does not annotate helper functions with numeric suffixes', + testCaseNoChange('var result = __decorate$1();'), + ); + + describe('topLevelSafeMode: true', () => { + it( + 'annotates top-level `new InjectionToken` expressions', + testCase({ + input: `const result = new InjectionToken('abc');`, + expected: `const result = /*#__PURE__*/ new InjectionToken('abc');`, + options: { topLevelSafeMode: true }, + }), + ); + + it( + 'does not annotate other top-level `new` expressions', + testCase({ + input: 'const result = new SomeClass();', + expected: 'const result = new SomeClass();', + options: { topLevelSafeMode: true }, + }), + ); + + it( + 'does not annotate top-level function calls', + testCase({ + input: 'const result = someCall();', + expected: 'const result = someCall();', + options: { topLevelSafeMode: true }, + }), + ); + }); +}); diff --git a/packages/angular/build/src/tools/oxc/traversal.ts b/packages/angular/build/src/tools/oxc/traversal.ts new file mode 100644 index 000000000000..f25f4bc78664 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/traversal.ts @@ -0,0 +1,354 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Node } from '@oxc-project/types'; +import { visitorKeys } from 'oxc-parser'; + +/** + * Contextual scope information provided to AST visitor callbacks during traversal. + */ +export interface TraversalContext { + /** + * The current function nesting depth. Top-level code has depth 0. + */ + functionDepth: number; + + /** + * The current class nesting depth. Top-level code has depth 0. + */ + classDepth: number; + + /** + * The immediate enclosing function AST node, if currently inside a function. + */ + parentFunc?: Node; +} + +/** + * A set of TypeScript AST node types that contain executable code or runtime declarations. + */ +const executableTypeScriptNodes = new Set([ + 'TSEnumDeclaration', + 'TSEnumBody', + 'TSEnumMember', + 'TSModuleDeclaration', + 'TSModuleBlock', + 'TSParameterProperty', + 'TSImportEqualsDeclaration', + 'TSExternalModuleReference', +]); + +/** + * Determines whether the given AST node type represents a function declaration or expression. + * + * @param type The AST node type to check. + * @returns True if the type is a function; otherwise, false. + */ +function isFunction(type: Node['type']): boolean { + return ( + type === 'FunctionDeclaration' || + type === 'FunctionExpression' || + type === 'ArrowFunctionExpression' + ); +} + +/** + * Determines whether the given AST node type represents a class declaration or expression. + * + * @param type The AST node type to check. + * @returns True if the type is a class; otherwise, false. + */ +function isClass(type: Node['type']): boolean { + return type === 'ClassDeclaration' || type === 'ClassExpression'; +} + +/** + * Determines whether the given AST node type represents a non-executable TypeScript type-only node. + * Executable TypeScript nodes (e.g. enums, namespaces, parameter properties) return false. + * + * @param type The AST node type to check. + * @returns True if the type is a TypeScript type construct that can be safely pruned; otherwise, false. + */ +function isTypeOnlyTypeScriptNode(type: Node['type']): boolean { + return type.startsWith('TS') && !executableTypeScriptNodes.has(type); +} + +/** + * Pushes an array of AST nodes onto the traversal stack in reverse order. + * + * @param nodes The array of child AST nodes to push. + * @param stack The traversal stack. + */ +function pushNodesReverse( + nodes: readonly (Node | null | undefined)[] | undefined, + stack: (Node | null)[], +): void { + if (nodes) { + for (let i = nodes.length - 1; i >= 0; i--) { + const item = nodes[i]; + if (item) { + stack.push(item); + } + } + } +} + +/** + * Pushes child AST nodes of the specified node onto the traversal stack in reverse order + * so they are visited in source order. + * + * Explicit cases are provided for the most common AST node types (~95%+ of AST nodes) to: + * 1. Fast-path leaf nodes and frequent expressions/statements by avoiding dynamic `visitorKeys` + * dictionary lookups, string indexing, and dynamic array iteration. + * 2. Prune non-executable TypeScript type subtrees (e.g. `typeAnnotation`, `typeParameters`, + * `returnType`, `implements`) so traversal only processes executable JavaScript expressions. + * + * All other less frequent node types fall back to the `visitorKeys` lookup in `default:`. + * + * @param node The parent AST node whose children to push. + * @param stack The traversal stack. + */ +function pushChildNodes(node: Node, stack: (Node | null)[]): void { + switch (node.type) { + // High-frequency leaf nodes (~50% of AST) + case 'Identifier': + case 'PrivateIdentifier': + case 'Literal': + case 'ThisExpression': + break; + + case 'Program': + case 'BlockStatement': + case 'ClassBody': + case 'StaticBlock': + pushNodesReverse(node.body, stack); + break; + + case 'ExpressionStatement': + case 'ParenthesizedExpression': + case 'ChainExpression': + case 'TSNonNullExpression': + case 'TSAsExpression': + case 'TSTypeAssertion': + case 'TSSatisfiesExpression': + case 'TSInstantiationExpression': + case 'TSExportAssignment': + if (node.expression) { + stack.push(node.expression); + } + break; + + case 'CallExpression': + case 'NewExpression': + pushNodesReverse(node.arguments, stack); + if (node.callee) { + stack.push(node.callee); + } + break; + + case 'MemberExpression': + if (node.property) { + stack.push(node.property); + } + if (node.object) { + stack.push(node.object); + } + break; + + case 'BinaryExpression': + case 'LogicalExpression': + case 'AssignmentExpression': + if (node.right) { + stack.push(node.right); + } + if (node.left) { + stack.push(node.left); + } + break; + + case 'UnaryExpression': + case 'UpdateExpression': + case 'AwaitExpression': + case 'YieldExpression': + case 'ReturnStatement': + case 'ThrowStatement': + if (node.argument) { + stack.push(node.argument); + } + break; + + case 'IfStatement': + case 'ConditionalExpression': + if (node.alternate) { + stack.push(node.alternate); + } + if (node.consequent) { + stack.push(node.consequent); + } + if (node.test) { + stack.push(node.test); + } + break; + + case 'VariableDeclaration': + pushNodesReverse(node.declarations, stack); + break; + + case 'VariableDeclarator': + if (node.init) { + stack.push(node.init); + } + if (node.id) { + stack.push(node.id); + } + break; + + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + if (node.body) { + stack.push(node.body); + } + pushNodesReverse(node.params, stack); + if (node.id) { + stack.push(node.id); + } + break; + + case 'ClassDeclaration': + case 'ClassExpression': + if (node.body) { + stack.push(node.body); + } + if (node.superClass) { + stack.push(node.superClass); + } + if (node.id) { + stack.push(node.id); + } + pushNodesReverse(node.decorators, stack); + break; + + case 'Property': + case 'PropertyDefinition': + case 'MethodDefinition': + if (node.value) { + stack.push(node.value); + } + if (node.key) { + stack.push(node.key); + } + if (node.type !== 'Property') { + pushNodesReverse(node.decorators, stack); + } + break; + + case 'ObjectExpression': + pushNodesReverse(node.properties, stack); + break; + + case 'ArrayExpression': + pushNodesReverse(node.elements, stack); + break; + + case 'TemplateLiteral': + pushNodesReverse(node.expressions, stack); + break; + + case 'TaggedTemplateExpression': + if (node.quasi) { + stack.push(node.quasi); + } + if (node.tag) { + stack.push(node.tag); + } + break; + + default: { + // Prune non-executable TypeScript type-only AST nodes (e.g. TSTypeAnnotation, TSTypeReference, etc.) + if (isTypeOnlyTypeScriptNode(node.type)) { + break; + } + + const keys = visitorKeys[node.type]; + if (!keys) { + break; + } + + for (let i = keys.length - 1; i >= 0; i--) { + const child = ( + node as unknown as Record + )[keys[i]]; + if (!child) { + continue; + } + + if (Array.isArray(child)) { + pushNodesReverse(child, stack); + } else { + stack.push(child); + } + } + break; + } + } +} + +/** + * Traverses ESTree AST nodes in post-order (bottom-up) without recursion. + * + * @param root The root AST node to traverse. + * @param visit Callback invoked on each AST node in post-order. + */ +export function traversePostOrder( + root: Node, + visit: (node: Node, context: TraversalContext) => void, +): void { + const stack: (Node | null)[] = [root]; + let functionDepth = 0; + let classDepth = 0; + const functionStack: Node[] = []; + + while (stack.length > 0) { + const current = stack.pop(); + if (current === undefined) { + break; + } + if (current === null) { + const node = stack.pop(); + if (!node) { + continue; + } + const type = node.type; + if (isFunction(type)) { + functionDepth--; + functionStack.pop(); + } else if (isClass(type)) { + classDepth--; + } + visit(node, { + functionDepth, + classDepth, + parentFunc: functionStack[functionStack.length - 1], + }); + continue; + } + + stack.push(current); + stack.push(null); + const type = current.type; + if (isFunction(type)) { + functionDepth++; + functionStack.push(current); + } else if (isClass(type)) { + classDepth++; + } + + pushChildNodes(current, stack); + } +} diff --git a/packages/angular/build/src/tools/oxc/types.d.ts b/packages/angular/build/src/tools/oxc/types.d.ts new file mode 100644 index 000000000000..aa1f40580491 --- /dev/null +++ b/packages/angular/build/src/tools/oxc/types.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +declare module 'istanbul-lib-instrument' { + export interface Instrumenter { + instrumentSync(code: string, filename: string, inputSourceMap?: object): string; + lastSourceMap(): object | undefined; + } + + export function createInstrumenter(options?: { + produceSourceMap?: boolean; + esModules?: boolean; + coverageVariable?: string; + }): Instrumenter; +} diff --git a/packages/angular/build/src/tools/sass/lexer.ts b/packages/angular/build/src/tools/sass/lexer.ts new file mode 100644 index 000000000000..0fc4f7d1e543 --- /dev/null +++ b/packages/angular/build/src/tools/sass/lexer.ts @@ -0,0 +1,182 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +// TODO: Combine everything into a single pass lexer + +/** + * Determines if a unicode code point is a CSS whitespace character. + * @param code The unicode code point to test. + * @returns true, if the code point is CSS whitespace; false, otherwise. + */ +function isWhitespace(code: number): boolean { + // Based on https://www.w3.org/TR/css-syntax-3/#whitespace + switch (code) { + case 0x0009: // tab + case 0x0020: // space + case 0x000a: // line feed + case 0x000c: // form feed + case 0x000d: // carriage return + return true; + default: + return false; + } +} + +/** + * Scans a CSS or Sass file and locates all valid url function values as defined by the + * syntax specification. + * @param contents A string containing a CSS or Sass file to scan. + * @returns An iterable that yields each CSS url function value found. + */ +export function* findUrls( + contents: string, +): Iterable<{ start: number; end: number; value: string }> { + let pos = 0; + let width = 1; + let current = -1; + const next = () => { + pos += width; + current = contents.codePointAt(pos) ?? -1; + width = current > 0xffff ? 2 : 1; + + return current; + }; + + // Based on https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token + while ((pos = contents.indexOf('url(', pos)) !== -1) { + width = 1; + + // Ensure whitespace, comma, or colon before `url(` + if (pos > 0) { + pos -= 2; + next(); + if (!isWhitespace(current) && current !== 0x002c && current !== 0x003a) { + // Skip - not a url token + pos += 3; + continue; + } + pos += 1; + } + + // Set to position of the ( + pos += 3; + + // Consume all leading whitespace + while (isWhitespace(next())) { + /* empty */ + } + + // Initialize URL state + const url = { start: pos, end: -1, value: '' }; + let complete = false; + + // If " or ', then consume the value as a string + if (current === 0x0022 || current === 0x0027) { + const ending = current; + // Based on https://www.w3.org/TR/css-syntax-3/#consume-string-token + while (!complete) { + switch (next()) { + case -1: // EOF + return; + case 0x000a: // line feed + case 0x000c: // form feed + case 0x000d: // carriage return + // Invalid + complete = true; + break; + case 0x005c: // \ -- character escape + // If not EOF or newline, add the character after the escape + switch (next()) { + case -1: + return; + case 0x000a: // line feed + case 0x000c: // form feed + case 0x000d: // carriage return + // Skip when inside a string + break; + default: + // TODO: Handle hex escape codes + url.value += String.fromCodePoint(current); + break; + } + break; + case ending: + // Full string position should include the quotes for replacement + url.end = pos + 1; + complete = true; + yield url; + break; + default: + url.value += String.fromCodePoint(current); + break; + } + } + + next(); + continue; + } + + // Based on https://www.w3.org/TR/css-syntax-3/#consume-url-token + while (!complete) { + switch (current) { + case -1: // EOF + return; + case 0x0022: // " + case 0x0027: // ' + case 0x0028: // ( + // Invalid + complete = true; + break; + case 0x0029: // ) + // URL is valid and complete + url.end = pos; + complete = true; + break; + case 0x005c: // \ -- character escape + // If not EOF or newline, add the character after the escape + switch (next()) { + case -1: // EOF + return; + case 0x000a: // line feed + case 0x000c: // form feed + case 0x000d: // carriage return + // Invalid + complete = true; + break; + default: + // TODO: Handle hex escape codes + url.value += String.fromCodePoint(current); + break; + } + break; + default: + if (isWhitespace(current)) { + while (isWhitespace(next())) { + /* empty */ + } + // Unescaped whitespace is only valid before the closing ) + if (current === 0x0029) { + // URL is valid + url.end = pos; + } + complete = true; + } else { + // Add the character to the url value + url.value += String.fromCodePoint(current); + } + break; + } + next(); + } + + // An end position indicates a URL was found + if (url.end !== -1) { + yield url; + } + } +} diff --git a/packages/angular/build/src/tools/sass/lexer_spec.ts b/packages/angular/build/src/tools/sass/lexer_spec.ts new file mode 100644 index 000000000000..151077af4c7f --- /dev/null +++ b/packages/angular/build/src/tools/sass/lexer_spec.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { findUrls } from './lexer'; + +describe('Sass URL lexer', () => { + it('should find url immediately after a colon, comma, or whitespace', () => { + const input = `.c{property:url("first"),url("second"), url("third");}`; + + const result = [...findUrls(input)]; + + expect(result).toEqual([ + { start: 16, end: 23, value: 'first' }, + { start: 29, end: 37, value: 'second' }, + { start: 44, end: 51, value: 'third' }, + ]); + }); + + it('should find full url with string containing url function', () => { + const input = `.c{property:url("url('abc')");}`; + + const result = [...findUrls(input)]; + + expect(result).toEqual([{ start: 16, end: 28, value: `url('abc')` }]); + }); +}); diff --git a/packages/angular/build/src/tools/sass/rebasing-importer.ts b/packages/angular/build/src/tools/sass/rebasing-importer.ts new file mode 100644 index 000000000000..ccc5fa3c4664 --- /dev/null +++ b/packages/angular/build/src/tools/sass/rebasing-importer.ts @@ -0,0 +1,396 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { DecodedSourceMap } from '@ampproject/remapping'; +import { MagicString } from 'magic-string'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { basename, dirname, extname, join, relative } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import type { CanonicalizeContext, Importer, ImporterResult, Syntax } from 'sass-embedded'; +import { assertIsError } from '../../utils/error'; +import { toPosixPath } from '../../utils/path'; +import { findUrls } from './lexer'; + +/** + * A preprocessed cache entry for the files and directories within a previously searched + * directory when performing Sass import resolution. + */ +export interface DirectoryEntry { + files: Set; + directories: Set; +} + +/** + * A Sass Importer base class that provides the load logic to rebase all `url()` functions + * within a stylesheet. The rebasing will ensure that the URLs in the output of the Sass compiler + * reflect the final filesystem location of the output CSS file. + * + * This class provides the core of the rebasing functionality. To ensure that each file is processed + * by this importer's load implementation, the Sass compiler requires the importer's canonicalize + * function to return a non-null value with the resolved location of the requested stylesheet. + * Concrete implementations of this class must provide this canonicalize functionality for rebasing + * to be effective. + */ +abstract class UrlRebasingImporter implements Importer<'sync'> { + /** + * @param entryDirectory The directory of the entry stylesheet that was passed to the Sass compiler. + * @param rebaseSourceMaps When provided, rebased files will have an intermediate sourcemap added to the Map + * which can be used to generate a final sourcemap that contains original sources. + */ + constructor( + private entryDirectory: string, + private rebaseSourceMaps?: Map, + ) { + this.load = this.load.bind(this); + } + + abstract canonicalize(url: string, options: { fromImport: boolean }): URL | null; + + load(canonicalUrl: URL): ImporterResult | null { + const stylesheetPath = fileURLToPath(canonicalUrl); + const stylesheetDirectory = dirname(stylesheetPath); + let contents = readFileSync(stylesheetPath, 'utf-8'); + + // Rebase any URLs that are found + let updatedContents; + for (const { start, end, value } of findUrls(contents)) { + // Skip if value is empty or Webpack-specific prefix + if (value.length === 0 || value[0] === '~' || value[0] === '^') { + continue; + } + + // Skip if root-relative, absolute or protocol relative url + if (/^((?:\w+:)?\/\/|data:|chrome:|\/)/.test(value)) { + continue; + } + + // Skip if a fragment identifier but not a Sass interpolation + if (value[0] === '#' && value[1] !== '{') { + continue; + } + + // Skip if value is value contains a function call + if (/#\{.+\(.+\)\}/.test(value)) { + continue; + } + + // Sass variable usage either starts with a `$` or contains a namespace and a `.$` + const valueNormalized = + value[0] === '$' || /^\w[\w_-]*\.\$/.test(value) ? `#{${value}}` : value; + const rebasedPath = relative(this.entryDirectory, stylesheetDirectory); + + // Normalize path separators and escape characters + // https://developer.mozilla.org/en-US/docs/Web/CSS/url#syntax + const rebasedUrl = toPosixPath(rebasedPath).replace(/[()\s'"]/g, '\\$&'); + + updatedContents ??= new MagicString(contents); + // Always quote the URL to avoid potential downstream parsing problems + updatedContents.update(start, end, `"${rebasedUrl}||file:${valueNormalized}"`); + } + + if (updatedContents) { + contents = updatedContents.toString(); + if (this.rebaseSourceMaps) { + // Generate an intermediate source map for the rebasing changes + const map = updatedContents.generateDecodedMap({ + hires: 'boundary', + includeContent: true, + source: canonicalUrl.href, + }); + this.rebaseSourceMaps.set(canonicalUrl.href, { + ...map, + version: 3, + } satisfies DecodedSourceMap); + } + } + + let syntax: Syntax | undefined; + switch (extname(stylesheetPath).toLowerCase()) { + case '.css': + syntax = 'css'; + break; + case '.sass': + syntax = 'indented'; + break; + default: + syntax = 'scss'; + break; + } + + return { + contents, + syntax, + sourceMapUrl: canonicalUrl, + }; + } +} + +/** + * Provides the Sass importer logic to resolve relative stylesheet imports via both import and use rules + * and also rebase any `url()` function usage within those stylesheets. The rebasing will ensure that + * the URLs in the output of the Sass compiler reflect the final filesystem location of the output CSS file. + */ +export class RelativeUrlRebasingImporter extends UrlRebasingImporter { + constructor( + entryDirectory: string, + private directoryCache = new Map(), + rebaseSourceMaps?: Map, + ) { + super(entryDirectory, rebaseSourceMaps); + this.canonicalize = this.canonicalize.bind(this); + } + + canonicalize(url: string, options: { fromImport: boolean }): URL | null { + return this.resolveImport(url, options.fromImport, true); + } + + /** + * Attempts to resolve a provided URL to a stylesheet file using the Sass compiler's resolution algorithm. + * Based on https://github.com/sass/dart-sass/blob/44d6bb6ac72fe6b93f5bfec371a1fffb18e6b76d/lib/src/importer/utils.dart + * @param url The file protocol URL to resolve. + * @param fromImport If true, URL was from an import rule; otherwise from a use rule. + * @param checkDirectory If true, try checking for a directory with the base name containing an index file. + * @returns A full resolved URL of the stylesheet file or `null` if not found. + */ + private resolveImport(url: string, fromImport: boolean, checkDirectory: boolean): URL | null { + let stylesheetPath; + try { + stylesheetPath = fileURLToPath(url); + } catch { + // Only file protocol URLs are supported by this importer + return null; + } + + const directory = dirname(stylesheetPath); + const extension = extname(stylesheetPath); + const hasStyleExtension = + extension === '.scss' || extension === '.sass' || extension === '.css'; + // Remove the style extension if present to allow adding the `.import` suffix + const filename = basename(stylesheetPath, hasStyleExtension ? extension : undefined); + + const importPotentials = new Set(); + const defaultPotentials = new Set(); + + if (hasStyleExtension) { + if (fromImport) { + importPotentials.add(filename + '.import' + extension); + importPotentials.add('_' + filename + '.import' + extension); + } + defaultPotentials.add(filename + extension); + defaultPotentials.add('_' + filename + extension); + } else { + if (fromImport) { + importPotentials.add(filename + '.import.scss'); + importPotentials.add(filename + '.import.sass'); + importPotentials.add(filename + '.import.css'); + importPotentials.add('_' + filename + '.import.scss'); + importPotentials.add('_' + filename + '.import.sass'); + importPotentials.add('_' + filename + '.import.css'); + } + defaultPotentials.add(filename + '.scss'); + defaultPotentials.add(filename + '.sass'); + defaultPotentials.add(filename + '.css'); + defaultPotentials.add('_' + filename + '.scss'); + defaultPotentials.add('_' + filename + '.sass'); + defaultPotentials.add('_' + filename + '.css'); + } + + let foundDefaults; + let foundImports; + let hasPotentialIndex = false; + + let cachedEntries = this.directoryCache.get(directory); + if (cachedEntries) { + // If there is a preprocessed cache of the directory, perform an intersection of the potentials + // and the directory files. + const { files, directories } = cachedEntries; + foundDefaults = [...defaultPotentials.intersection(files)]; + foundImports = [...importPotentials.intersection(files)]; + hasPotentialIndex = checkDirectory && !hasStyleExtension && directories.has(filename); + } else { + // If no preprocessed cache exists, get the entries from the file system and, while searching, + // generate the cache for later requests. + let entries; + try { + entries = readdirSync(directory, { withFileTypes: true }); + } catch (error) { + assertIsError(error); + // If the containing directory does not exist return null to indicate it cannot be resolved + if (error.code === 'ENOENT') { + return null; + } + + throw new Error(`Error reading directory ["${directory}"] while resolving Sass import`, { + cause: error, + }); + } + + foundDefaults = []; + foundImports = []; + cachedEntries = { files: new Set(), directories: new Set() }; + for (const entry of entries) { + let isDirectory: boolean; + let isFile: boolean; + + if (entry.isSymbolicLink()) { + const stats = statSync(join(directory, entry.name)); + isDirectory = stats.isDirectory(); + isFile = stats.isFile(); + } else { + isDirectory = entry.isDirectory(); + isFile = entry.isFile(); + } + + if (isDirectory) { + cachedEntries.directories.add(entry.name); + + // Record if the name should be checked as a directory with an index file + if (checkDirectory && !hasStyleExtension && entry.name === filename) { + hasPotentialIndex = true; + } + } + + if (!isFile) { + continue; + } + + cachedEntries.files.add(entry.name); + + if (importPotentials.has(entry.name)) { + foundImports.push(entry.name); + } + + if (defaultPotentials.has(entry.name)) { + foundDefaults.push(entry.name); + } + } + + this.directoryCache.set(directory, cachedEntries); + } + + // `foundImports` will only contain elements if `options.fromImport` is true + const result = this.checkFound(foundImports) ?? this.checkFound(foundDefaults); + if (result !== null) { + return pathToFileURL(join(directory, result)); + } + + if (hasPotentialIndex) { + // Check for index files using filename as a directory + return this.resolveImport(url + '/index', fromImport, false); + } + + return null; + } + + /** + * Checks an array of potential stylesheet files to determine if there is a valid + * stylesheet file. More than one discovered file may indicate an error. + * @param found An array of discovered stylesheet files. + * @returns A fully resolved path for a stylesheet file or `null` if not found. + * @throws If there are ambiguous files discovered. + */ + private checkFound(found: string[]): string | null { + if (found.length === 0) { + // Not found + return null; + } + + // More than one found file may be an error + if (found.length > 1) { + // Presence of CSS files alongside a Sass file does not cause an error + const foundWithoutCss = found.filter((element) => extname(element) !== '.css'); + // If the length is zero then there are two or more css files + // If the length is more than one than there are two or more sass/scss files + if (foundWithoutCss.length !== 1) { + throw new Error('Ambiguous import detected.'); + } + + // Return the non-CSS file (sass/scss files have priority) + // https://github.com/sass/dart-sass/blob/44d6bb6ac72fe6b93f5bfec371a1fffb18e6b76d/lib/src/importer/utils.dart#L44-L47 + return foundWithoutCss[0]; + } + + return found[0]; + } +} + +/** + * Provides the Sass importer logic to resolve module (npm package) stylesheet imports asynchronously + * and also rebase any `url()` function usage within those stylesheets. + */ +export class AsyncModuleUrlRebasingImporter implements Importer<'async'> { + private relativeImporter: RelativeUrlRebasingImporter; + + constructor( + entryDirectory: string, + directoryCache: Map, + rebaseSourceMaps: Map | undefined, + private finder: ( + specifier: string, + options: CanonicalizeContext, + ) => Promise | URL | null, + ) { + this.relativeImporter = new RelativeUrlRebasingImporter( + entryDirectory, + directoryCache, + rebaseSourceMaps, + ); + this.canonicalize = this.canonicalize.bind(this); + this.load = this.load.bind(this); + } + + canonicalize(url: string, options: CanonicalizeContext): Promise | URL | null { + if (url.startsWith('file://')) { + return this.relativeImporter.canonicalize(url, options); + } + + // Use `Promise.resolve` instead of an `async` method so the returned promise is an + // instance of the current `globalThis.Promise` (e.g., `ZoneAwarePromise` when Zone.js + // is loaded during SSR). `sass-embedded` checks `result instanceof Promise`, which fails + // for native `async` function return values when `globalThis.Promise` has been replaced. + return Promise.resolve(this.finder(url, options)).then((result) => + result ? this.relativeImporter.canonicalize(result.href, options) : null, + ); + } + + load(canonicalUrl: URL): ImporterResult | null { + return this.relativeImporter.load(canonicalUrl); + } +} + +/** + * Provides the Sass importer logic to resolve load paths located stylesheet imports via both import and + * use rules and also rebase any `url()` function usage within those stylesheets. The rebasing will ensure that + * the URLs in the output of the Sass compiler reflect the final filesystem location of the output CSS file. + */ +export class LoadPathsUrlRebasingImporter extends RelativeUrlRebasingImporter { + constructor( + entryDirectory: string, + directoryCache: Map, + rebaseSourceMaps: Map | undefined, + private loadPaths: Iterable, + ) { + super(entryDirectory, directoryCache, rebaseSourceMaps); + } + + override canonicalize(url: string, options: { fromImport: boolean }): URL | null { + if (url.startsWith('file://')) { + return super.canonicalize(url, options); + } + + let result = null; + for (const loadPath of this.loadPaths) { + result = super.canonicalize(pathToFileURL(join(loadPath, url)).href, options); + if (result !== null) { + break; + } + } + + return result; + } +} diff --git a/packages/angular/build/src/tools/sass/sass-service.ts b/packages/angular/build/src/tools/sass/sass-service.ts new file mode 100644 index 000000000000..8ce65dd7e2f2 --- /dev/null +++ b/packages/angular/build/src/tools/sass/sass-service.ts @@ -0,0 +1,219 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 mergeSourceMaps, { type DecodedSourceMap, type RawSourceMap } from '@ampproject/remapping'; +import { dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { + AsyncCompiler, + CanonicalizeContext, + CompileResult, + FileImporter, + Importer, + NodePackageImporter, + StringOptions, +} from 'sass-embedded'; +import { useSassEmbedded } from '../../utils/environment-options'; +import { + AsyncModuleUrlRebasingImporter, + DirectoryEntry, + LoadPathsUrlRebasingImporter, + RelativeUrlRebasingImporter, +} from './rebasing-importer'; + +type Importers = + | Importer<'sync'> + | Importer<'async'> + | FileImporter<'sync'> + | FileImporter<'async'> + | NodePackageImporter; + +function isFileImporter(value: Importers): value is FileImporter { + return 'findFileUrl' in value; +} + +/** + * A Sass renderer implementation that uses the persistent Dart Sass embedded compiler + * daemon (`sass-embedded`) communicating over standard input/output with protocol buffers, + * or falls back to the pure-JS Dart Sass async compiler (`sass.initAsyncCompiler()`). + */ +export class SassCompiler { + #asyncCompiler: AsyncCompiler | undefined; + #asyncCompilerPromise: Promise | undefined; + readonly #directoryCache = new Map(); + + constructor(private readonly rebase = false) {} + + async #createAsyncCompiler(): Promise { + if (useSassEmbedded) { + const { initAsyncCompiler } = await import('sass-embedded'); + + return initAsyncCompiler(); + } + + const { initAsyncCompiler } = await import('sass'); + + return initAsyncCompiler() as unknown as Promise; + } + + async #ensureAsyncCompiler(): Promise { + if (this.#asyncCompiler) { + return this.#asyncCompiler; + } + + this.#asyncCompilerPromise ??= this.#createAsyncCompiler(); + + try { + this.#asyncCompiler = await this.#asyncCompilerPromise; + } finally { + this.#asyncCompilerPromise = undefined; + } + + return this.#asyncCompiler; + } + + /** + * Provides information about the Sass implementation. + * This mimics enough of the `sass-embedded` or `sass` value to be used with the `sass-loader`. + */ + get info(): string { + return useSassEmbedded ? 'sass-embedded\tasync-compiler' : 'dart-sass\tasync-compiler'; + } + + /** + * The synchronous render function is not used by the `sass-loader`. + */ + compileString(): never { + throw new Error('Sass compileString is not supported.'); + } + + /** + * Asynchronously request a Sass stylesheet to be rendered using the native embedded compiler + * or the pure-JS async compiler fallback. + * + * @param source The contents to compile. + * @param options The `sass` / `sass-embedded` options to use when rendering the stylesheet. + */ + async compileStringAsync( + source: string, + options: StringOptions<'async'>, + ): Promise { + // The CLI's configuration does not use or expose the ability to define custom Sass functions + if (options.functions && Object.keys(options.functions).length > 0) { + throw new Error('Sass custom functions are not supported.'); + } + + const compiler = await this.#ensureAsyncCompiler(); + + if (!this.rebase) { + return compiler.compileStringAsync(source, options); + } + + const { functions, importers, importer, url, logger, ...serializableOptions } = options; + + let finalImporters: + (Importer<'async'> | FileImporter<'async'> | NodePackageImporter)[] | undefined; + let loadPaths = options.loadPaths; + const entryDirectory = url ? dirname(fileURLToPath(url)) : process.cwd(); + const directoryCache = this.#directoryCache; + const rebaseSourceMaps = options.sourceMap ? new Map() : undefined; + + if (importers?.length) { + if (importers.some((i) => !isFileImporter(i))) { + throw new Error('Only File Importers are supported.'); + } + + finalImporters = [ + new AsyncModuleUrlRebasingImporter( + entryDirectory, + directoryCache, + rebaseSourceMaps, + async (specifier: string, options: CanonicalizeContext): Promise => { + for (const importer of importers) { + const result = await (importer as FileImporter<'async'>).findFileUrl( + specifier, + options, + ); + if (result) { + return result; + } + } + + return null; + }, + ), + ]; + } + + if (loadPaths?.length) { + finalImporters ??= []; + finalImporters.push( + new LoadPathsUrlRebasingImporter( + entryDirectory, + directoryCache, + rebaseSourceMaps, + loadPaths, + ), + ); + loadPaths = undefined; + } + + const relativeImporter = new RelativeUrlRebasingImporter( + entryDirectory, + directoryCache, + rebaseSourceMaps, + ); + + const result = await compiler.compileStringAsync(source, { + ...serializableOptions, + url, + loadPaths, + importers: finalImporters, + importer: relativeImporter, + logger, + }); + + if (result.sourceMap && rebaseSourceMaps?.size) { + result.sourceMap = mergeSourceMaps( + result.sourceMap as unknown as RawSourceMap, + (file, context) => (file !== context.importer ? rebaseSourceMaps.get(file) : null), + ) as unknown as typeof result.sourceMap; + } + + return result; + } + + /** + * Clear the directory cache. + */ + clearCache(): void { + this.#directoryCache.clear(); + } + + /** + * Shutdown the Sass compiler. + * @returns A void promise that resolves when closing is complete. + */ + async close(): Promise { + this.clearCache(); + + if (this.#asyncCompilerPromise) { + try { + await this.#ensureAsyncCompiler(); + } catch { + // Ignore compiler initialization failures on shutdown + } + } + + if (this.#asyncCompiler) { + const compiler = this.#asyncCompiler; + this.#asyncCompiler = undefined; + await compiler.dispose(); + } + } +} diff --git a/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts new file mode 100644 index 000000000000..04093e520448 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts @@ -0,0 +1,262 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { lookup as lookupMimeType } from 'mrmime'; +import { readFileSync } from 'node:fs'; +import type { ServerResponse } from 'node:http'; +import { extname } from 'node:path'; +import type { Connect, ViteDevServer } from 'vite' with { + 'resolution-mode': 'import', +}; +import { ResultFile } from '../../../builders/application/results'; +import { calculateHash } from '../../../utils/hash'; +import { AngularMemoryOutputFiles, AngularOutputAssets, pathnameWithoutBasePath } from '../utils'; + +export interface ComponentStyleRecord { + rawContent: Uint8Array; + used?: Set; + reload?: boolean; +} + +const CSS_PREPROCESSOR_REGEXP = /\.(?:s[ac]ss|less|css)$/; +const JS_TS_REGEXP = /\.[cm]?[tj]sx?$/; + +export function createAngularAssetsMiddleware( + server: ViteDevServer, + assets: AngularOutputAssets, + outputFiles: AngularMemoryOutputFiles, + componentStyles: Map, + encapsulateStyle: (style: Uint8Array, componentId: string) => string, +): Connect.NextHandleFunction { + return function angularAssetsMiddleware(req, res, next) { + if (req.url === undefined || res.writableEnded) { + return; + } + + // Parse the incoming request. + // The base of the URL is unused but required to parse the URL. + const pathname = pathnameWithoutBasePath(req.url, server.config.base); + const extension = extname(pathname); + const pathnameHasTrailingSlash = pathname.at(-1) === '/'; + + // Rewrite all build assets to a vite raw fs URL + const asset = assets.get(pathname); + if (asset) { + // This is a workaround to serve extensionless, CSS, JS and TS files without Vite transformations. + if (!extension || JS_TS_REGEXP.test(extension) || CSS_PREPROCESSOR_REGEXP.test(extension)) { + const contents = readFileSync(asset.source); + const etag = `W/"${calculateHash(contents)}"`; + if (checkAndHandleEtag(req, res, etag)) { + return; + } + + const mimeType = lookupMimeType(extension); + if (mimeType) { + res.setHeader('Content-Type', mimeType); + } + + res.setHeader('ETag', etag); + res.setHeader('Cache-Control', 'no-cache'); + res.end(contents); + } else { + // The encoding needs to match what happens in the vite static middleware. + // ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163 + req.url = `${server.config.base}@fs/${encodeURI(asset.source)}`; + next(); + } + + return; + } + + // HTML fallbacking + // This matches what happens in the vite html fallback middleware. + // ref: https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/htmlFallback.ts#L9 + const htmlAssetSourcePath = pathnameHasTrailingSlash + ? // Trailing slash check for `index.html`. + assets.get(pathname + 'index.html') + : // Non-trailing slash check for fallback `.html` + assets.get(pathname + '.html'); + + if (htmlAssetSourcePath) { + req.url = `${server.config.base}@fs/${encodeURI(htmlAssetSourcePath.source)}`; + next(); + + return; + } + + // Support HTTP HEAD requests for the virtual output files from the Angular build + if (req.method === 'HEAD' && outputFiles.get(pathname)?.servable) { + // While a GET will also generate content, the rest of the response is equivalent + req.method = 'GET'; + } + + // Resource files are handled directly. + // Global stylesheets (CSS files) are currently considered resources to workaround + // dev server sourcemap issues with stylesheets. + if (extension !== '.js' && pathname !== '/index.html' && pathname !== '/index.csr.html') { + const outputFile = outputFiles.get(pathname); + if (outputFile?.servable) { + let data: Uint8Array | string = outputFile.contents; + const componentStyle = componentStyles.get(pathname); + if (componentStyle) { + // Inject component ID for view encapsulation if requested + const searchParams = new URL(req.url, 'http://localhost').searchParams; + const componentId = searchParams.get('ngcomp'); + if (componentId !== null) { + // Track if the component uses ShadowDOM encapsulation (3 = ViewEncapsulation.ShadowDom) + // Shadow DOM components currently require a full reload. + // Vite's CSS hot replacement does not support shadow root searching. + if (searchParams.get('e') === '3') { + componentStyle.reload = true; + } + + // Record the component style usage for HMR updates + if (componentStyle.used === undefined) { + componentStyle.used = new Set([componentId]); + } else { + componentStyle.used.add(componentId); + } + + const etag = `W/"${outputFile.contents.byteLength}-${outputFile.hash}-${componentId}"`; + if (checkAndHandleEtag(req, res, etag)) { + return; + } + + // Shim the stylesheet if a component ID is provided + if (componentId.length > 0) { + // Validate component ID + if (!/^[_.\-\p{Letter}\d]+-c\d+$/u.test(componentId)) { + const message = 'Invalid component stylesheet ID request: ' + componentId; + // eslint-disable-next-line no-console + console.error(message); + res.statusCode = 400; + res.end(message); + + return; + } + + data = encapsulateStyle(data, componentId); + } + + res.setHeader('Content-Type', 'text/css'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('ETag', etag); + res.end(data); + + return; + } + } + + const etag = `W/"${outputFile.contents.byteLength}-${outputFile.hash}"`; + if (checkAndHandleEtag(req, res, etag)) { + return; + } + + const mimeType = lookupMimeType(extension); + if (mimeType) { + res.setHeader('Content-Type', mimeType); + } + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('ETag', etag); + res.end(data); + + return; + } + } + + // If the path has no trailing slash and it matches a servable directory redirect to the same path with slash. + // This matches the default express static behaviour. + // See: https://github.com/expressjs/serve-static/blob/89fc94567fae632718a2157206c52654680e9d01/index.js#L182 + if (!pathnameHasTrailingSlash) { + for (const assetPath of assets.keys()) { + if (pathname === assetPath.substring(0, assetPath.lastIndexOf('/'))) { + const { pathname, search, hash } = new URL(req.url, 'http://localhost'); + const location = [pathname, '/', search, hash].join(''); + + res.statusCode = 301; + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Location', location); + res.end(` + + + + + Redirecting + + +
Redirecting to ${location}
+ + + `); + + return; + } + } + } + + next(); + }; +} + +function checkAndHandleEtag( + req: Connect.IncomingMessage, + res: ServerResponse, + etag: string, +): boolean { + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304; + res.end(); + + return true; + } + + return false; +} + +export function createBuildAssetsMiddleware( + basePath: string, + buildResultFiles: ReadonlyMap, + readHandler: (path: string) => Buffer = readFileSync, +): Connect.NextHandleFunction { + return function buildAssetsMiddleware(req, res, next) { + if (req.url === undefined || res.writableEnded) { + return; + } + + // Parse the incoming request. + // The base of the URL is unused but required to parse the URL. + const pathname = pathnameWithoutBasePath(req.url, basePath); + const extension = extname(pathname); + if (extension && !/\.[mc]?[jt]s(?:\.map)?$/.test(extension)) { + const outputFile = buildResultFiles.get(pathname.slice(1)); + if (outputFile) { + const contents = + outputFile.origin === 'memory' ? outputFile.contents : readHandler(outputFile.source); + const hash = outputFile.origin === 'memory' ? outputFile.hash : calculateHash(contents); + + const etag = `W/"${hash}"`; + if (checkAndHandleEtag(req, res, etag)) { + return; + } + + const mimeType = lookupMimeType(extension); + if (mimeType) { + res.setHeader('Content-Type', mimeType); + } + + res.setHeader('ETag', etag); + res.setHeader('Cache-Control', 'no-cache'); + res.end(contents); + + return; + } + } + + next(); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/assets-middleware_spec.ts b/packages/angular/build/src/tools/vite/middlewares/assets-middleware_spec.ts new file mode 100644 index 000000000000..f8bf6e94584e --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/assets-middleware_spec.ts @@ -0,0 +1,162 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { ResultFile } from '../../../builders/application/results'; +import { calculateHash, initializeHash } from '../../../utils/hash'; +import { BuildOutputFileType } from '../../esbuild/bundler-files'; +import { createBuildAssetsMiddleware } from './assets-middleware'; + +describe('createBuildAssetsMiddleware', () => { + beforeAll(async () => { + await initializeHash(); + }); + + function createMockReqRes( + url: string, + headers: Record = {}, + ): { + req: IncomingMessage; + res: ServerResponse & { setHeader: jasmine.Spy; end: jasmine.Spy }; + } { + const req = { + url, + method: 'GET', + headers, + } as unknown as IncomingMessage; + + const res = { + statusCode: 200, + writableEnded: false, + setHeader: jasmine.createSpy('setHeader'), + end: jasmine.createSpy('end'), + } as unknown as ServerResponse & { setHeader: jasmine.Spy; end: jasmine.Spy }; + + return { req, res }; + } + + it('uses precomputed outputFile.hash for memory files instead of recalculating hash', () => { + const contents = new TextEncoder().encode('body { color: red; }'); + const precomputedHash = 'precomputed-memory-hash'; + const buildResultFiles = new Map([ + [ + 'styles.css', + { + origin: 'memory', + path: 'styles.css', + contents, + hash: precomputedHash, + type: BuildOutputFileType.Browser, + }, + ], + ]); + + const readHandler = jasmine.createSpy('readHandler'); + const middleware = createBuildAssetsMiddleware('/', buildResultFiles, readHandler); + const { req, res } = createMockReqRes('/styles.css'); + const next = jasmine.createSpy('next'); + + middleware(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(readHandler).not.toHaveBeenCalled(); + expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'text/css'); + expect(res.setHeader).toHaveBeenCalledWith('ETag', `W/"${precomputedHash}"`); + expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'no-cache'); + expect(res.end).toHaveBeenCalledWith(contents); + }); + + it('returns 304 for memory files when If-None-Match matches precomputed outputFile.hash', () => { + const contents = new TextEncoder().encode('body { color: red; }'); + const precomputedHash = 'precomputed-memory-hash'; + const buildResultFiles = new Map([ + [ + 'styles.css', + { + origin: 'memory', + path: 'styles.css', + contents, + hash: precomputedHash, + type: BuildOutputFileType.Browser, + }, + ], + ]); + + const middleware = createBuildAssetsMiddleware('/', buildResultFiles); + const { req, res } = createMockReqRes('/styles.css', { + 'if-none-match': `W/"${precomputedHash}"`, + }); + const next = jasmine.createSpy('next'); + + middleware(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.statusCode).toBe(304); + expect(res.end).toHaveBeenCalledWith(); + }); + + it('calculates hash from disk contents when outputFile.origin is disk', () => { + const diskBuffer = Buffer.from('console.log("asset");', 'utf-8'); + const expectedHash = calculateHash(diskBuffer); + const buildResultFiles = new Map([ + [ + 'assets/data.json', + { + origin: 'disk', + path: 'assets/data.json', + source: '/workspace/src/assets/data.json', + type: BuildOutputFileType.Browser, + }, + ], + ]); + + const readHandler = jasmine.createSpy('readHandler').and.returnValue(diskBuffer); + const middleware = createBuildAssetsMiddleware('/', buildResultFiles, readHandler); + const { req, res } = createMockReqRes('/assets/data.json'); + const next = jasmine.createSpy('next'); + + middleware(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(readHandler).toHaveBeenCalledOnceWith('/workspace/src/assets/data.json'); + expect(res.setHeader).toHaveBeenCalledWith('Content-Type', 'application/json'); + expect(res.setHeader).toHaveBeenCalledWith('ETag', `W/"${expectedHash}"`); + expect(res.setHeader).toHaveBeenCalledWith('Cache-Control', 'no-cache'); + expect(res.end).toHaveBeenCalledWith(diskBuffer); + }); + + it('returns 304 for disk files when If-None-Match matches calculated hash', () => { + const diskBuffer = Buffer.from('{"ok":true}', 'utf-8'); + const expectedHash = calculateHash(diskBuffer); + const buildResultFiles = new Map([ + [ + 'assets/data.json', + { + origin: 'disk', + path: 'assets/data.json', + source: '/workspace/src/assets/data.json', + type: BuildOutputFileType.Browser, + }, + ], + ]); + + const readHandler = jasmine.createSpy('readHandler').and.returnValue(diskBuffer); + const middleware = createBuildAssetsMiddleware('/', buildResultFiles, readHandler); + const { req, res } = createMockReqRes('/assets/data.json', { + 'if-none-match': `W/"${expectedHash}"`, + }); + const next = jasmine.createSpy('next'); + + middleware(req, res, next); + + expect(next).not.toHaveBeenCalled(); + expect(readHandler).toHaveBeenCalledOnceWith('/workspace/src/assets/data.json'); + expect(res.statusCode).toBe(304); + expect(res.end).toHaveBeenCalledWith(); + }); +}); diff --git a/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts new file mode 100644 index 000000000000..a9df78fd2981 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Connect } from 'vite' with { + 'resolution-mode': 'import', +}; +import { addLeadingSlash } from '../../../utils/url'; + +/** + * Patches the Vite base middleware to correctly handle the Angular application's base href. + * This is necessary because Vite's default base middleware might not align with Angular's + * expected path handling when using SSR, especially when a base href is configured. + * + * @param middlewares The Connect server instance containing the middleware stack. + * @param base The base URL path to be handled by the middleware. + */ +export function patchBaseMiddleware(middlewares: Connect.Server, base: string): void { + const entry = middlewares.stack.find( + ({ handle }) => typeof handle === 'function' && handle.name.startsWith('viteBaseMiddleware'), + ); + + if (typeof entry?.handle !== 'function') { + return; + } + + entry.handle = function angularBaseMiddleware( + req: IncomingMessage, + res: ServerResponse, + next: (err?: unknown) => void, + ) { + const url = req.url || '/'; + if (url.startsWith(base)) { + // Rewrite the URL to remove the base prefix before passing it to the next middleware. + // If the URL is exactly the base, it becomes '/'. + // Otherwise, we slice off the base and ensure there's a leading slash. + // See: https://github.com/vitejs/vite/blob/e81c183f8c8ccaf7774ef0d0ee125bf63dbf30b4/packages/vite/src/node/server/middlewares/base.ts#L12 + req.url = url === base ? '/' : addLeadingSlash(url.slice(base.length - 1)); + + return next(); + } + + const { pathname, hash, search } = new URL(url, 'http://localhost'); + if (pathname === '/' || pathname === '/index.html') { + res.writeHead(302, { Location: `${base}${search}${hash}` }); + res.end(); + + return; + } + + next(); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/chrome-devtools-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/chrome-devtools-middleware.ts new file mode 100644 index 000000000000..fdeff2eec705 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/chrome-devtools-middleware.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { randomUUID } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { Connect } from 'vite' with { + 'resolution-mode': 'import', +}; + +type DevToolsJson = { + workspace: { + root: string; + uuid: string; + }; +}; + +const CHROME_DEVTOOLS_ROUTE = '/.well-known/appspecific/com.chrome.devtools.json'; + +export function createChromeDevtoolsMiddleware( + cacheDir: string, + projectRoot: string, +): Connect.NextHandleFunction { + let devtoolsConfig: string | undefined; + const devtoolsConfigPath = join(cacheDir, 'com.chrome.devtools.json'); + + return function chromeDevtoolsMiddleware(req, res, next) { + if (req.url !== CHROME_DEVTOOLS_ROUTE) { + next(); + + return; + } + + if (!devtoolsConfig) { + // We store the UUID and re-use it to ensure Chrome does not repeatedly ask for permissions when restarting the dev server. + try { + devtoolsConfig = readFileSync(devtoolsConfigPath, 'utf-8'); + + const devtoolsConfigJson: DevToolsJson = JSON.parse(devtoolsConfig); + assert.equal(projectRoot, devtoolsConfigJson?.workspace.root); + } catch { + const devtoolsConfigJson: DevToolsJson = { + workspace: { + root: projectRoot, + uuid: randomUUID(), + }, + }; + + devtoolsConfig = JSON.stringify(devtoolsConfigJson, undefined, 2); + + try { + mkdirSync(cacheDir, { recursive: true }); + writeFileSync(devtoolsConfigPath, devtoolsConfig); + } catch {} + } + } + + res.setHeader('Content-Type', 'application/json'); + res.end(devtoolsConfig); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/component-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/component-middleware.ts new file mode 100644 index 000000000000..29360d78af55 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/component-middleware.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Connect, ViteDevServer } from 'vite' with { + 'resolution-mode': 'import', +}; +import { pathnameWithoutBasePath } from '../utils'; + +const ANGULAR_COMPONENT_PREFIX = '/@ng/component'; + +export function createAngularComponentMiddleware( + server: ViteDevServer, + templateUpdates: ReadonlyMap, +): Connect.NextHandleFunction { + return function angularComponentMiddleware(req, res, next) { + if (req.url === undefined || res.writableEnded) { + return; + } + + const pathname = pathnameWithoutBasePath(req.url, server.config.base); + if (!pathname.includes(ANGULAR_COMPONENT_PREFIX)) { + next(); + + return; + } + + const requestUrl = new URL(req.url, 'http://localhost'); + const componentId = requestUrl.searchParams.get('c'); + if (!componentId) { + res.statusCode = 400; + res.end(); + + return; + } + + const updateCode = templateUpdates.get(encodeURIComponent(componentId)) ?? ''; + + res.setHeader('Content-Type', 'text/javascript'); + res.setHeader('Cache-Control', 'no-cache'); + res.end(updateCode); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/headers-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/headers-middleware.ts new file mode 100644 index 000000000000..c7f9408cec4a --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/headers-middleware.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ServerResponse } from 'node:http'; +import type { Connect, ViteDevServer } from 'vite' with { + 'resolution-mode': 'import', +}; + +/** + * Creates a middleware for adding custom headers. + * + * This middleware is responsible for setting HTTP headers as configured in the Vite server options. + * If headers are defined in the server configuration, they are applied to the server response. + * + * @param server - The instance of `ViteDevServer` containing the configuration, including custom headers. + * @returns A middleware function that processes the incoming request, sets headers if available, + * and passes control to the next middleware in the chain. + */ +export function createAngularHeadersMiddleware(server: ViteDevServer): Connect.NextHandleFunction { + return function angularHeadersMiddleware( + _req: Connect.IncomingMessage, + res: ServerResponse, + next: Connect.NextFunction, + ) { + const headers = server.config.server.headers; + if (!headers) { + return next(); + } + + for (const [name, value] of Object.entries(headers)) { + if (value !== undefined) { + res.setHeader(name, value); + } + } + + next(); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts new file mode 100644 index 000000000000..a4d49f4a9eeb --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Connect } from 'vite' with { + 'resolution-mode': 'import', +}; + +export function patchHostValidationMiddleware(middlewares: Connect.Server): void { + const entry = middlewares.stack.find( + ({ handle }) => + typeof handle === 'function' && handle.name.startsWith('hostValidationMiddleware'), + ); + + if (typeof entry?.handle !== 'function') { + return; + } + + const originalHandle = entry.handle as Connect.NextHandleFunction; + + entry.handle = function angularHostValidationMiddleware( + req: IncomingMessage, + res: ServerResponse, + next: (err?: unknown) => void, + ) { + originalHandle( + req, + { + writeHead: (code) => { + res.writeHead(code, { 'content-type': 'text/html' }); + }, + end: () => { + const hostname = req.headers.host?.toLowerCase().split(':')[0] ?? ''; + res.end(html403(hostname)); + }, + } as ServerResponse, + next, + ); + }; +} + +function html403(hostname: string): string { + return ` + + + + + Blocked request + + + +
+

Blocked request. This host ("${hostname}") is not allowed.

+

To allow this host, add it to allowedHosts under the serve target in angular.json.

+
{
+  "serve": {
+    "options": {
+      "allowedHosts": ["${hostname}"]
+    }
+  }
+}
+
+ + `; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/html-fallback-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/html-fallback-middleware.ts new file mode 100644 index 000000000000..dbef050ac4c0 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/html-fallback-middleware.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ServerResponse } from 'node:http'; +import type { Connect } from 'vite' with { + 'resolution-mode': 'import', +}; +import { lookupMimeTypeFromRequest } from '../utils'; + +const ALLOWED_FALLBACK_METHODS = Object.freeze(['GET', 'HEAD']); + +export function angularHtmlFallbackMiddleware( + req: Connect.IncomingMessage, + _res: ServerResponse, + next: Connect.NextFunction, +): void { + // Similar to how it is handled in vite + // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/middlewares/htmlFallback.ts#L15C19-L15C45 + if (!req.method || !ALLOWED_FALLBACK_METHODS.includes(req.method)) { + // No fallback for unsupported request methods + next(); + + return; + } + + if (req.url) { + const mimeType = lookupMimeTypeFromRequest(req.url); + if ( + (mimeType === 'text/html' || mimeType === 'application/xhtml+xml') && + !/^\/index\.(?:csr\.)?html/.test(req.url) + ) { + // eslint-disable-next-line no-console + console.warn( + `Request for HTML file "${req.url}" was received but no asset found. Asset may be missing from build.`, + ); + } else if (mimeType) { + // No fallback for request of asset-like files + next(); + + return; + } + } + + if ( + !req.headers.accept || + req.headers.accept.includes('text/html') || + req.headers.accept.includes('text/*') || + req.headers.accept.includes('*/*') + ) { + req.url = '/index.html'; + } + + next(); +} diff --git a/packages/angular/build/src/tools/vite/middlewares/index-html-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/index-html-middleware.ts new file mode 100644 index 000000000000..7767d970ee42 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/index-html-middleware.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { extname } from 'node:path'; +import type { Connect, ViteDevServer } from 'vite' with { + 'resolution-mode': 'import', +}; +import { AngularMemoryOutputFiles, pathnameWithoutBasePath } from '../utils'; + +export function createAngularIndexHtmlMiddleware( + server: ViteDevServer, + outputFiles: AngularMemoryOutputFiles, + resetComponentUpdates: () => void, + indexHtmlTransformer: ((content: string) => Promise) | undefined, +): Connect.NextHandleFunction { + return function angularIndexHtmlMiddleware(req, res, next) { + if (!req.url) { + next(); + + return; + } + + // Parse the incoming request. + // The base of the URL is unused but required to parse the URL. + const pathname = pathnameWithoutBasePath(req.url, server.config.base); + const extension = extname(pathname); + if (extension !== '.html') { + next(); + + return; + } + + const rawHtml = outputFiles.get(pathname)?.contents; + if (!rawHtml) { + next(); + + return; + } + + // A request for the index indicates a full page reload request. + resetComponentUpdates(); + + server + .transformIndexHtml(req.url, Buffer.from(rawHtml).toString('utf-8')) + .then(async (processedHtml) => { + if (indexHtmlTransformer) { + processedHtml = await indexHtmlTransformer(processedHtml); + } + + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Cache-Control', 'no-cache'); + res.end(processedHtml); + }) + .catch((error) => next(error)); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/index.ts b/packages/angular/build/src/tools/vite/middlewares/index.ts new file mode 100644 index 000000000000..807e739eed59 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/index.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export { type ComponentStyleRecord, createAngularAssetsMiddleware } from './assets-middleware'; +export { angularHtmlFallbackMiddleware } from './html-fallback-middleware'; +export { createAngularIndexHtmlMiddleware } from './index-html-middleware'; +export { + createAngularSsrExternalMiddleware, + createAngularSsrInternalMiddleware, +} from './ssr-middleware'; +export { createAngularHeadersMiddleware } from './headers-middleware'; +export { createAngularComponentMiddleware } from './component-middleware'; +export { createChromeDevtoolsMiddleware } from './chrome-devtools-middleware'; +export { patchHostValidationMiddleware } from './host-check-middleware'; +export { patchBaseMiddleware } from './base-middleware'; diff --git a/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts new file mode 100644 index 000000000000..c75c63e992bb --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts @@ -0,0 +1,162 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { + AngularAppEngine as SSRAngularAppEngine, + ɵgetOrCreateAngularServerApp as getOrCreateAngularServerApp, +} from '@angular/ssr'; +import type { ServerResponse } from 'node:http'; +import type { Connect, ViteDevServer } from 'vite' with { + 'resolution-mode': 'import', +}; +import { + isSsrNodeRequestHandler, + isSsrRequestHandler, +} from '../../../utils/server-rendering/utils'; + +export function createAngularSsrInternalMiddleware( + server: ViteDevServer, + resetComponentUpdates: () => void, + indexHtmlTransformer?: (content: string) => Promise, +): Connect.NextHandleFunction { + let cachedAngularServerApp: ReturnType | undefined; + + return function angularSsrMiddleware( + req: Connect.IncomingMessage, + res: ServerResponse, + next: Connect.NextFunction, + ) { + if (req.url === undefined) { + return next(); + } + + (async () => { + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + const { writeResponseToNodeResponse, createWebRequestFromNodeRequest } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); + + const { ɵgetOrCreateAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as { + ɵgetOrCreateAngularServerApp: typeof getOrCreateAngularServerApp; + }; + + const angularServerApp = ɵgetOrCreateAngularServerApp({ + allowStaticRouteRender: true, + }); + + // Only Add the transform hook only if it's a different instance. + if (cachedAngularServerApp !== angularServerApp) { + angularServerApp.hooks.on('html:transform:pre', async ({ html, url }) => { + resetComponentUpdates(); + const processedHtml = await server.transformIndexHtml(url.pathname, html); + + return indexHtmlTransformer?.(processedHtml) ?? processedHtml; + }); + + cachedAngularServerApp = angularServerApp; + } + + const webReq = new Request(createWebRequestFromNodeRequest(req), { + signal: AbortSignal.timeout(30_000), + }); + const webRes = await angularServerApp.handle(webReq); + if (!webRes) { + return next(); + } + + return writeResponseToNodeResponse(webRes, res); + })().catch(next); + }; +} + +export async function createAngularSsrExternalMiddleware( + server: ViteDevServer, + resetComponentUpdates: () => void, + indexHtmlTransformer?: (content: string) => Promise, +): Promise { + let fallbackWarningShown = false; + let cachedAngularAppEngine: typeof SSRAngularAppEngine | undefined; + let angularSsrInternalMiddleware: + ReturnType | undefined; + + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + + const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); + + // Disable host check if allowed hosts is true meaning allow all hosts. + const { allowedHosts } = server.config.server; + const disableAllowedHostsCheck = allowedHosts === true; + + return function angularSsrExternalMiddleware( + req: Connect.IncomingMessage, + res: ServerResponse, + next: Connect.NextFunction, + ) { + (async () => { + const { reqHandler, AngularAppEngine } = (await server.ssrLoadModule('./server.mjs')) as { + reqHandler?: unknown; + AngularAppEngine: typeof SSRAngularAppEngine; + }; + + if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) { + if (!fallbackWarningShown) { + // eslint-disable-next-line no-console + console.warn( + `The 'reqHandler' export in 'server.ts' is either undefined or does not provide a recognized request handler. ` + + 'Using the internal SSR middleware instead.', + ); + + fallbackWarningShown = true; + } + + angularSsrInternalMiddleware ??= createAngularSsrInternalMiddleware( + server, + resetComponentUpdates, + indexHtmlTransformer, + ); + + angularSsrInternalMiddleware(req, res, next); + + return; + } + + if (cachedAngularAppEngine !== AngularAppEngine) { + AngularAppEngine.ɵdisableAllowedHostsCheck = disableAllowedHostsCheck; + AngularAppEngine.ɵallowStaticRouteRender = true; + AngularAppEngine.ɵhooks.on('html:transform:pre', async ({ html, url }) => { + resetComponentUpdates(); + const processedHtml = await server.transformIndexHtml(url.pathname, html); + + return indexHtmlTransformer?.(processedHtml) ?? processedHtml; + }); + + cachedAngularAppEngine = AngularAppEngine; + } + + // Forward the request to the middleware in server.ts + if (isSsrNodeRequestHandler(reqHandler)) { + await reqHandler(req, res, next); + } else { + const webRes = await reqHandler(createWebRequestFromNodeRequest(req)); + if (!webRes) { + next(); + + return; + } + + await writeResponseToNodeResponse(webRes, res); + } + })().catch(next); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/ssr-middleware_spec.ts b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware_spec.ts new file mode 100644 index 000000000000..a61011043a43 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware_spec.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { + createAngularSsrExternalMiddleware, + createAngularSsrInternalMiddleware, +} from './ssr-middleware'; + +type ViteDevServer = Parameters[0]; + +describe('SSR dev-server middleware', () => { + function createMockReqRes(): { req: IncomingMessage; res: ServerResponse } { + const req = { + url: '/', + method: 'GET', + headers: { host: 'localhost' }, + } as unknown as IncomingMessage; + + const res = { + statusCode: 200, + setHeader: jasmine.createSpy('setHeader'), + writeHead: jasmine.createSpy('writeHead'), + end: jasmine.createSpy('end'), + } as unknown as ServerResponse; + + return { req, res }; + } + + it('resets component updates when html:transform:pre executes in internal SSR middleware', async () => { + let hookCallback: ((args: { html: string; url: URL }) => Promise) | undefined; + const resetComponentUpdates = jasmine.createSpy('resetComponentUpdates'); + let resolveHookRegistered!: () => void; + const hookRegistered = new Promise((resolve) => { + resolveHookRegistered = resolve; + }); + + const fakeAngularServerApp = { + hooks: { + on: (_name: string, cb: typeof hookCallback) => { + hookCallback = cb; + resolveHookRegistered(); + }, + }, + handle: jasmine.createSpy('handle').and.resolveTo(new Response('rendered')), + }; + + const server = { + config: { server: { allowedHosts: true }, base: '/' }, + ssrLoadModule: jasmine.createSpy('ssrLoadModule').and.resolveTo({ + ɵgetOrCreateAngularServerApp: () => fakeAngularServerApp, + }), + transformIndexHtml: jasmine + .createSpy('transformIndexHtml') + .and.callFake(async (_path: string, html: string) => html), + } as unknown as ViteDevServer; + + const middleware = createAngularSsrInternalMiddleware( + server, + resetComponentUpdates, + async (html) => html + '', + ); + + const { req, res } = createMockReqRes(); + middleware(req, res, () => {}); + + await hookRegistered; + + expect(resetComponentUpdates).not.toHaveBeenCalled(); + expect(hookCallback).toBeDefined(); + const result = await hookCallback?.({ + html: '
test
', + url: new URL('http://localhost/'), + }); + expect(resetComponentUpdates).toHaveBeenCalledTimes(1); + expect(result).toBe('
test
'); + }); + + it('resets component updates when html:transform:pre executes in external SSR middleware', async () => { + let hookCallback: ((args: { html: string; url: URL }) => Promise) | undefined; + const resetComponentUpdates = jasmine.createSpy('resetComponentUpdates'); + let resolveHookRegistered!: () => void; + const hookRegistered = new Promise((resolve) => { + resolveHookRegistered = resolve; + }); + + class FakeAngularAppEngine { + static ɵhooks = { + on: (_name: string, cb: typeof hookCallback) => { + hookCallback = cb; + resolveHookRegistered(); + }, + }; + static ɵdisableAllowedHostsCheck: boolean; + static ɵallowStaticRouteRender: boolean; + } + + const server = { + config: { server: { allowedHosts: true }, base: '/' }, + ssrLoadModule: jasmine.createSpy('ssrLoadModule').and.resolveTo({ + reqHandler: Object.assign(() => new Response('ok'), { __ng_request_handler__: true }), + AngularAppEngine: FakeAngularAppEngine, + }), + transformIndexHtml: jasmine + .createSpy('transformIndexHtml') + .and.callFake(async (_path: string, html: string) => html + ''), + } as unknown as ViteDevServer; + + const middleware = await createAngularSsrExternalMiddleware(server, resetComponentUpdates); + + const { req, res } = createMockReqRes(); + middleware(req, res, () => {}); + + await hookRegistered; + + expect(resetComponentUpdates).not.toHaveBeenCalled(); + expect(hookCallback).toBeDefined(); + const result = await hookCallback?.({ + html: '
test
', + url: new URL('http://localhost/'), + }); + expect(resetComponentUpdates).toHaveBeenCalledTimes(1); + expect(result).toBe('
test
'); + }); +}); diff --git a/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts b/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts new file mode 100644 index 000000000000..c30365bbf142 --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts @@ -0,0 +1,165 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import { dirname, join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type * as Vite from 'vite' with { + 'resolution-mode': 'import', +}; +import { removeSourceMappingURL } from '../../../utils/source-map'; +import { AngularMemoryOutputFiles } from '../utils'; + +interface AngularMemoryPluginOptions { + virtualProjectRoot: string; + outputFiles: AngularMemoryOutputFiles; + templateUpdates?: ReadonlyMap; + external?: string[]; + disableViteTransport?: boolean; +} + +const ANGULAR_PREFIX = '/@ng/'; +const VITE_FS_PREFIX = '/@fs/'; +const FILE_PROTOCOL = 'file:'; + +export async function createAngularMemoryPlugin( + options: AngularMemoryPluginOptions, +): Promise { + const { virtualProjectRoot, outputFiles, external } = options; + const { normalizePath } = (await import('vite' as string)) as typeof Vite; + + return { + name: 'vite:angular-memory', + // Ensures plugin hooks run before built-in Vite hooks + enforce: 'pre', + async resolveId(source, importer, { ssr }) { + if (source.startsWith(VITE_FS_PREFIX)) { + return; + } + + // For SSR with component HMR, pass through as a virtual module + if (ssr && source.startsWith(FILE_PROTOCOL) && source.includes(ANGULAR_PREFIX)) { + // Vite will resolve these these files example: + // `file:///@ng/component?c=src%2Fapp%2Fapp.component.ts%40AppComponent&t=1737017253850` + const sourcePath = fileURLToPath(source); + const sourceWithoutRoot = normalizePath('/' + relative(virtualProjectRoot, sourcePath)); + + if (sourceWithoutRoot.startsWith(ANGULAR_PREFIX)) { + const [, query] = source.split('?', 2); + + return `\0${sourceWithoutRoot}?${query}`; + } + } + + // Prevent vite from resolving an explicit external dependency (`externalDependencies` option) + if (external?.includes(source)) { + // This is still not ideal since Vite will still transform the import specifier to + // `/@id/${source}` but is currently closer to a raw external than a resolved file path. + return source; + } + + if (importer && source[0] === '.') { + const normalizedImporter = normalizePath(importer); + if (normalizedImporter.startsWith(virtualProjectRoot)) { + // Remove query if present + const [importerFile] = normalizedImporter.split('?', 1); + source = '/' + join(dirname(relative(virtualProjectRoot, importerFile)), source); + } + } + + const [file] = source.split('?', 1); + if (outputFiles.has(normalizePath(file))) { + return join(virtualProjectRoot, source); + } + }, + load(id, loadOptions) { + // For SSR component updates, return the component update module or empty if none + if (loadOptions?.ssr && id.startsWith(`\0${ANGULAR_PREFIX}`)) { + // Extract component identifier (first character is rollup virtual module null) + const requestUrl = new URL(id.slice(1), 'http://localhost'); + const componentId = requestUrl.searchParams.get('c'); + + return (componentId && options.templateUpdates?.get(encodeURIComponent(componentId))) ?? ''; + } + + const [file] = id.split('?', 1); + const relativeFile = '/' + normalizePath(relative(virtualProjectRoot, file)); + const codeContents = outputFiles.get(relativeFile)?.contents; + if (codeContents === undefined) { + if (relativeFile.endsWith('/node_modules/vite/dist/client/client.mjs')) { + return loadViteClientCode(file, options.disableViteTransport); + } + + return undefined; + } + + const mapContents = outputFiles.get(relativeFile + '.map')?.contents; + const strippedContents = mapContents ? removeSourceMappingURL(codeContents) : codeContents; + + return { + // Remove source map URL comments from the code if a sourcemap is present. + // Vite will inline and add an additional sourcemap URL for the sourcemap. + code: decodeUtf8(strippedContents), + map: mapContents && decodeUtf8(mapContents), + }; + }, + }; +} + +/** + * Decodes UTF-8 bytes into a string without copying the underlying memory. + */ +function decodeUtf8(data: Uint8Array): string { + const buffer = Buffer.isBuffer(data) + ? data + : Buffer.from(data.buffer, data.byteOffset, data.byteLength); + + return buffer.toString('utf-8'); +} + +/** + * Reads the resolved Vite client code from disk and updates the content to remove + * an unactionable suggestion to update the Vite configuration file to disable the + * error overlay. The Vite configuration file is not present when used in the Angular + * CLI. + * @param file The absolute path to the Vite client code. + * @returns + */ +async function loadViteClientCode(file: string, disableViteTransport = false): Promise { + const originalContents = await readFile(file, 'utf-8'); + let updatedContents = originalContents.replace( + '"You can also disable this overlay by setting ", ' + + 'h("code", { part: "config-option-name" }, "server.hmr.overlay"), ' + + '" to ", ' + + 'h("code", { part: "config-option-value" }, "false"), ' + + '" in ", ' + + 'h("code", { part: "config-file-name" }, hmrConfigName), ' + + '"."', + '', + ); + + assert(originalContents !== updatedContents, 'Failed to update Vite client error overlay text.'); + + if (disableViteTransport) { + const previousUpdatedContents = updatedContents; + + updatedContents = updatedContents.replace( + 'transport.connect(createHMRHandler(handleMessage));', + '', + ); + assert( + previousUpdatedContents !== updatedContents, + 'Failed to update Vite client WebSocket disable.', + ); + + updatedContents = updatedContents.replace('console.debug("[vite] connecting...")', ''); + } + + return updatedContents; +} diff --git a/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin.ts b/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin.ts new file mode 100644 index 000000000000..74cd03179a7e --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Plugin } from 'vite' with { + 'resolution-mode': 'import', +}; + +// NOTE: the implementation for this Vite plugin is roughly based on: +// https://github.com/MilanKovacic/vite-plugin-externalize-dependencies + +const VITE_ID_PREFIX = '@id/'; + +const escapeRegexSpecialChars = (inputString: string): string => { + return inputString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string +}; + +export function createRemoveIdPrefixPlugin(externals: string[]): Plugin { + return { + name: 'angular-plugin-remove-id-prefix', + apply: 'serve', + configResolved: (resolvedConfig) => { + // don't do anything when the list of externals is empty + if (externals.length === 0) { + return; + } + + const transformFn = createTransformer(resolvedConfig.base, externals); + + // @ts-expect-error: Property 'push' does not exist on type 'readonly Plugin[]' + // Reasoning: + // since the /@id/ prefix is added by Vite's import-analysis plugin, + // we must add our actual plugin dynamically, to ensure that it will run + // AFTER the import-analysis. + resolvedConfig.plugins.push({ + name: 'angular-plugin-remove-id-prefix-transform', + transform: transformFn, + }); + }, + }; +} + +/** + * Creates a transform function that removes the Vite ID prefix from externals. + * @param base The base path of the application. + * @param externals The external package names. + * @returns A function that transforms code by removing the Vite ID prefix. + */ +export function createTransformer(base: string, externals: string[]): (code: string) => string { + // The path suffix is bounded so that a match can never extend past the end of an + // import specifier string literal. With a greedy `.+`, minified (single-line) code + // would let the first match consume the remainder of the line, leaving all later + // `/@id/` occurrences on that line unstripped. + const escapedExternals = externals.map((e) => escapeRegexSpecialChars(e) + '(?:/[^\'"`\\s]+)?'); + + const prefixedExternalRegex = new RegExp( + `${base}${VITE_ID_PREFIX}(${escapedExternals.join('|')})`, + 'g', + ); + + return (code: string) => { + return code.includes(VITE_ID_PREFIX) + ? code.replace(prefixedExternalRegex, (_, externalName) => externalName) + : // don't do anything when code does not contain the Vite prefix + code; + }; +} diff --git a/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin_spec.ts b/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin_spec.ts new file mode 100644 index 000000000000..37d1bdf61fe6 --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/id-prefix-plugin_spec.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createTransformer } from './id-prefix-plugin'; + +describe('createTransformer', () => { + it('should strip the prefix from every occurrence on a single (minified) line', () => { + const transform = createTransformer('/', [ + '@angular/common', + '@angular/common/http', + '@angular/core', + '@angular/router', + ]); + + const minified = + 'import{a}from"/@id/@angular/common/http";' + + 'import{b}from"/@id/@angular/router";' + + 'import{c}from"/@id/@angular/core";'; + + expect(transform(minified)).toBe( + 'import{a}from"@angular/common/http";' + + 'import{b}from"@angular/router";' + + 'import{c}from"@angular/core";', + ); + }); + + it('should strip the prefix from an external with a deep import path', () => { + const transform = createTransformer('/', ['@angular/common']); + + expect(transform('import{h}from"/@id/@angular/common/http";')).toBe( + 'import{h}from"@angular/common/http";', + ); + }); + + it('should strip the prefix when a non-root base is configured', () => { + const transform = createTransformer('/app/', ['@angular/router']); + + expect(transform('import{r}from"/app/@id/@angular/router";')).toBe( + 'import{r}from"@angular/router";', + ); + }); + + it('should strip the prefix from multi-line (unminified) code', () => { + const transform = createTransformer('/', ['@angular/common', '@angular/router']); + + const code = + 'import { CommonModule } from "/@id/@angular/common";\n' + + 'import { Router } from "/@id/@angular/router";\n'; + + expect(transform(code)).toBe( + 'import { CommonModule } from "@angular/common";\n' + + 'import { Router } from "@angular/router";\n', + ); + }); + + it('should not modify imports that are not configured externals', () => { + const transform = createTransformer('/', ['@angular/router']); + + const code = 'import{x}from"/@id/some-other-package";'; + expect(transform(code)).toBe(code); + }); +}); diff --git a/packages/angular/build/src/tools/vite/plugins/index.ts b/packages/angular/build/src/tools/vite/plugins/index.ts new file mode 100644 index 000000000000..6c4cdd4496e4 --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/index.ts @@ -0,0 +1,13 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createAngularMemoryPlugin } from './angular-memory-plugin'; +export { createRemoveIdPrefixPlugin } from './id-prefix-plugin'; +export { createAngularSetupMiddlewaresPlugin, ServerSsrMode } from './setup-middlewares-plugin'; +export { createAngularSsrTransformPlugin } from './ssr-transform-plugin'; +export { createAngularServerSideSSLPlugin } from './ssr-ssl-plugin'; diff --git a/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts b/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts new file mode 100644 index 000000000000..34b0704f4091 --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts @@ -0,0 +1,149 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Connect, Plugin } from 'vite' with { + 'resolution-mode': 'import', +}; +import { + ComponentStyleRecord, + angularHtmlFallbackMiddleware, + createAngularAssetsMiddleware, + createAngularComponentMiddleware, + createAngularHeadersMiddleware, + createAngularIndexHtmlMiddleware, + createAngularSsrExternalMiddleware, + createAngularSsrInternalMiddleware, + createChromeDevtoolsMiddleware, + patchBaseMiddleware, + patchHostValidationMiddleware, +} from '../middlewares'; +import { AngularMemoryOutputFiles, AngularOutputAssets } from '../utils'; + +export enum ServerSsrMode { + /** + * No SSR + */ + NoSsr, + + /** + * Internal server-side rendering (SSR) is handled through the built-in middleware. + * + * In this mode, the SSR process is managed internally by the dev-server's middleware. + * The server automatically renders pages on the server without requiring external + * middleware or additional configuration from the developer. + */ + InternalSsrMiddleware, + + /** + * External server-side rendering (SSR) is handled by a custom middleware defined in server.ts. + * + * This mode allows developers to define custom SSR behavior by providing a middleware in the + * `server.ts` file. It gives more flexibility for handling SSR, such as integrating with other + * frameworks or customizing the rendering pipeline. + */ + ExternalSsrMiddleware, +} + +interface AngularSetupMiddlewaresPluginOptions { + outputFiles: AngularMemoryOutputFiles; + assets: AngularOutputAssets; + extensionMiddleware?: Connect.NextHandleFunction[]; + indexHtmlTransformer?: (content: string) => Promise; + componentStyles: Map; + templateUpdates: Map; + ssrMode: ServerSsrMode; + resetComponentUpdates: () => void; + projectRoot: string; +} + +async function createEncapsulateStyle(): Promise< + (style: Uint8Array, componentId: string) => string +> { + const { encapsulateStyle } = await import('@angular/compiler'); + const decoder = new TextDecoder('utf-8'); + + return (style, componentId) => { + return encapsulateStyle(decoder.decode(style), componentId); + }; +} + +export function createAngularSetupMiddlewaresPlugin( + options: AngularSetupMiddlewaresPluginOptions, +): Plugin { + return { + name: 'vite:angular-setup-middlewares', + enforce: 'pre', + async configureServer(server) { + const { + indexHtmlTransformer, + outputFiles, + extensionMiddleware, + assets, + componentStyles, + templateUpdates, + ssrMode, + resetComponentUpdates, + } = options; + + const middlewares = server.middlewares; + + // Headers, assets and resources get handled first + middlewares.use(createAngularHeadersMiddleware(server)); + middlewares.use(createAngularComponentMiddleware(server, templateUpdates)); + middlewares.use( + createAngularAssetsMiddleware( + server, + assets, + outputFiles, + componentStyles, + await createEncapsulateStyle(), + ), + ); + + middlewares.use(createChromeDevtoolsMiddleware(server.config.cacheDir, options.projectRoot)); + + extensionMiddleware?.forEach((middleware) => middlewares.use(middleware)); + + // Returning a function, installs middleware after the main transform middleware but + // before the built-in HTML middleware + // eslint-disable-next-line @typescript-eslint/no-misused-promises + return async () => { + patchHostValidationMiddleware(server.middlewares); + + if (ssrMode === ServerSsrMode.ExternalSsrMiddleware) { + patchBaseMiddleware(server.middlewares, server.config.base); + middlewares.use( + await createAngularSsrExternalMiddleware( + server, + resetComponentUpdates, + indexHtmlTransformer, + ), + ); + + return; + } + + if (ssrMode === ServerSsrMode.InternalSsrMiddleware) { + middlewares.use( + createAngularSsrInternalMiddleware(server, resetComponentUpdates, indexHtmlTransformer), + ); + } + + middlewares.use(angularHtmlFallbackMiddleware); + middlewares.use( + createAngularIndexHtmlMiddleware( + server, + outputFiles, + resetComponentUpdates, + indexHtmlTransformer, + ), + ); + }; + }, + }; +} diff --git a/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts b/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts new file mode 100644 index 000000000000..ceb1f9630b7f --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { getCACertificates, setDefaultCACertificates } from 'node:tls'; +import type { Plugin } from 'vite' with { + 'resolution-mode': 'import', +}; + +export function createAngularServerSideSSLPlugin(): Plugin { + return { + name: 'angular-ssr-ssl-plugin', + apply: 'serve', + async configureServer({ config, httpServer }) { + const { + ssr, + server: { https }, + } = config; + + if (!ssr || !https?.cert) { + return; + } + + if (httpServer && 'ALPNProtocols' in httpServer) { + // Force Vite to use HTTP/1.1 when SSR and SSL are enabled. + // This is required because the Express server used for SSR does not support HTTP/2. + // See: https://github.com/vitejs/vite/blob/46d3077f2b63771cc50230bc907c48f5773c00fb/packages/vite/src/node/http.ts#L126 + + // We directly set the `ALPNProtocols` on the HTTP server to override the default behavior. + // Passing `ALPNProtocols` in the TLS options would cause Node.js to automatically include `h2`. + // Additionally, using `ALPNCallback` is not an option as it is mutually exclusive with `ALPNProtocols`. + // See: https://github.com/nodejs/node/blob/b8b4350ed3b73d225eb9e628d69151df56eaf298/lib/internal/http2/core.js#L3351 + httpServer.ALPNProtocols = ['http/1.1']; + } + + const { cert } = https; + const additionalCerts = Array.isArray(cert) ? cert : [cert]; + + const currentCerts = getCACertificates('default'); + setDefaultCACertificates([...currentCerts, ...additionalCerts]); + }, + }; +} diff --git a/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts b/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts new file mode 100644 index 000000000000..b857cc3cde74 --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 remapping, { SourceMapInput } from '@ampproject/remapping'; +import type * as Vite from 'vite' with { + 'resolution-mode': 'import', +}; + +export async function createAngularSsrTransformPlugin(workspaceRoot: string): Promise { + const { normalizePath } = (await import('vite' as string)) as typeof Vite; + + return { + name: 'vite:angular-ssr-transform', + enforce: 'post', + transform(code, _id, { ssr, inMap }: { ssr?: boolean; inMap?: SourceMapInput } = {}) { + if (!ssr || !inMap) { + return null; + } + + const remappedMap = remapping([inMap], () => null); + // Set the sourcemap root to the workspace root. This is needed since we set a virtual path as root. + remappedMap.sourceRoot = normalizePath(workspaceRoot) + '/'; + + return { + code, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + map: remappedMap as any, + }; + }, + }; +} diff --git a/packages/angular/build/src/tools/vite/utils.ts b/packages/angular/build/src/tools/vite/utils.ts new file mode 100644 index 000000000000..fa833066f8ed --- /dev/null +++ b/packages/angular/build/src/tools/vite/utils.ts @@ -0,0 +1,164 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { lookup as lookupMimeType } from 'mrmime'; +import { builtinModules, isBuiltin } from 'node:module'; +import { extname } from 'node:path'; +import type { DepOptimizationConfig } from 'vite' with { + 'resolution-mode': 'import', +}; +import type { ExternalResultMetadata } from '../esbuild/bundler-execution-result'; +import { JavaScriptTransformer } from '../javascript-transformer'; + +export type AngularMemoryOutputFiles = Map< + string, + { contents: Uint8Array; hash: string; servable: boolean } +>; + +export type AngularOutputAssets = Map; + +export function pathnameWithoutBasePath(url: string, basePath: string): string { + const parsedUrl = new URL(url, 'http://localhost'); + const pathname = decodeURIComponent(parsedUrl.pathname); + + // slice(basePath.length - 1) to retain the trailing slash + return basePath !== '/' && pathname.startsWith(basePath) + ? pathname.slice(basePath.length - 1) + : pathname; +} + +export function lookupMimeTypeFromRequest(url: string): string | undefined { + const extension = extname(url.split('?')[0]); + + if (extension === '.ico') { + return 'image/x-icon'; + } + + return extension && lookupMimeType(extension); +} + +export type RolldownLoaderOption = Exclude< + DepOptimizationConfig['rolldownOptions'], + undefined +>['moduleTypes']; + +export function getDepOptimizationConfig({ + target, + disabled, + exclude, + include, + prebundleTransformer, + loader, + thirdPartySourcemaps, + define = {}, +}: { + target: string[]; + disabled: boolean; + exclude: string[]; + include: string[]; + prebundleTransformer: JavaScriptTransformer; + loader?: RolldownLoaderOption; + thirdPartySourcemaps: boolean; + define: Record | undefined; +}): DepOptimizationConfig { + const config: DepOptimizationConfig = { + // Exclude any explicitly defined dependencies (currently build defined externals) + exclude, + // NB: to disable the deps optimizer, set optimizeDeps.noDiscovery to true and optimizeDeps.include as undefined. + // Include all implict dependencies from the external packages internal option + include: disabled ? undefined : include, + noDiscovery: disabled, + rolldownOptions: { + transform: { + target, + define, + }, + moduleTypes: loader, + resolve: { + extensions: ['.mjs', '.js', '.cjs'], + }, + plugins: [ + { + name: `angular-vite-optimize-deps${thirdPartySourcemaps ? '-vendor-sourcemap' : ''}`, + load: { + filter: { id: /\.[cm]?js$/ }, + async handler(id: string) { + const code = await prebundleTransformer.transformFile(id); + + return { code: Buffer.from(code).toString('utf-8') }; + }, + }, + }, + ], + }, + }; + + return config; +} + +export interface DevServerExternalResultMetadata { + implicitBrowser: string[]; + implicitServer: string[]; + explicitBrowser: string[]; + explicitServer: string[]; +} + +export function isAbsoluteUrl(url: string): boolean { + try { + new URL(url); + + return true; + } catch { + return false; + } +} + +export function updateExternalMetadata( + result: { detail?: { externalMetadata?: ExternalResultMetadata } }, + externalMetadata: DevServerExternalResultMetadata, + externalDependencies: string[] | undefined, + explicitPackagesOnly: boolean = false, +): void { + if (!result.detail?.['externalMetadata']) { + return; + } + + const { implicitBrowser, implicitServer, explicit } = result.detail['externalMetadata']; + const implicitServerFiltered = implicitServer.filter( + (m) => !isBuiltin(m) && !isAbsoluteUrl(m) && !m.endsWith('.json'), + ); + const implicitBrowserFiltered = implicitBrowser.filter( + (m) => !isAbsoluteUrl(m) && !m.endsWith('.json'), + ); + const explicitBrowserFiltered = explicitPackagesOnly + ? explicit.filter((m) => !isAbsoluteUrl(m)) + : explicit; + + // Empty Arrays to avoid growing unlimited with every re-build. + externalMetadata.explicitBrowser.length = 0; + externalMetadata.explicitServer.length = 0; + externalMetadata.implicitServer.length = 0; + externalMetadata.implicitBrowser.length = 0; + + const externalDeps = externalDependencies ?? []; + externalMetadata.explicitBrowser.push(...explicitBrowserFiltered, ...externalDeps); + externalMetadata.explicitServer.push( + ...explicitBrowserFiltered, + ...externalDeps, + ...builtinModules, + ); + externalMetadata.implicitServer.push(...implicitServerFiltered); + externalMetadata.implicitBrowser.push(...implicitBrowserFiltered); + + // The below needs to be sorted as Vite uses these options as part of the hashing invalidation algorithm. + // See: https://github.com/vitejs/vite/blob/0873bae0cfe0f0718ad2f5743dd34a17e4ab563d/packages/vite/src/node/optimizer/index.ts#L1203-L1239 + externalMetadata.explicitBrowser.sort(); + externalMetadata.explicitServer.sort(); + externalMetadata.implicitServer.sort(); + externalMetadata.implicitBrowser.sort(); +} diff --git a/packages/angular/build/src/utils/bundle-calculator.ts b/packages/angular/build/src/utils/bundle-calculator.ts new file mode 100644 index 000000000000..2ef1c8385ef6 --- /dev/null +++ b/packages/angular/build/src/utils/bundle-calculator.ts @@ -0,0 +1,399 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Budget as BudgetEntry, Type as BudgetType } from '../builders/application/schema'; +import { formatSize } from './format-bytes'; + +// Re-export to avoid direct schema importing throughout code +export { type BudgetEntry, BudgetType }; + +export const BYTES_IN_KILOBYTE = 1000; + +interface Size { + size: number; + label?: string; +} + +export interface Threshold { + limit: number; + type: ThresholdType; + severity: ThresholdSeverity; +} + +enum ThresholdType { + Max = 'maximum', + Min = 'minimum', +} + +export enum ThresholdSeverity { + Warning = 'warning', + Error = 'error', +} + +export interface BudgetCalculatorResult { + severity: ThresholdSeverity; + message: string; + label?: string; +} + +export interface BudgetChunk { + files?: string[]; + names?: string[]; + initial?: boolean; +} + +export interface BudgetAsset { + name: string; + size: number; + componentStyle?: boolean; +} + +export interface BudgetStats { + chunks?: BudgetChunk[]; + assets?: BudgetAsset[]; +} + +function* calculateThresholds(budget: BudgetEntry): IterableIterator { + if (budget.maximumWarning) { + yield { + limit: calculateBytes(budget.maximumWarning, budget.baseline, 1), + type: ThresholdType.Max, + severity: ThresholdSeverity.Warning, + }; + } + + if (budget.maximumError) { + yield { + limit: calculateBytes(budget.maximumError, budget.baseline, 1), + type: ThresholdType.Max, + severity: ThresholdSeverity.Error, + }; + } + + if (budget.minimumWarning) { + yield { + limit: calculateBytes(budget.minimumWarning, budget.baseline, -1), + type: ThresholdType.Min, + severity: ThresholdSeverity.Warning, + }; + } + + if (budget.minimumError) { + yield { + limit: calculateBytes(budget.minimumError, budget.baseline, -1), + type: ThresholdType.Min, + severity: ThresholdSeverity.Error, + }; + } + + if (budget.warning) { + yield { + limit: calculateBytes(budget.warning, budget.baseline, -1), + type: ThresholdType.Min, + severity: ThresholdSeverity.Warning, + }; + + yield { + limit: calculateBytes(budget.warning, budget.baseline, 1), + type: ThresholdType.Max, + severity: ThresholdSeverity.Warning, + }; + } + + if (budget.error) { + yield { + limit: calculateBytes(budget.error, budget.baseline, -1), + type: ThresholdType.Min, + severity: ThresholdSeverity.Error, + }; + + yield { + limit: calculateBytes(budget.error, budget.baseline, 1), + type: ThresholdType.Max, + severity: ThresholdSeverity.Error, + }; + } +} + +/** + * Calculates the sizes for bundles in the budget type provided. + */ +function calculateSizes(budget: BudgetEntry, stats: BudgetStats): Size[] { + type CalculatorTypes = { + new (budget: BudgetEntry, chunks: BudgetChunk[], assets: BudgetAsset[]): Calculator; + }; + const calculatorMap: Record = { + all: AllCalculator, + allScript: AllScriptCalculator, + any: AnyCalculator, + anyScript: AnyScriptCalculator, + anyComponentStyle: AnyComponentStyleCalculator, + bundle: BundleCalculator, + initial: InitialCalculator, + }; + + const ctor = calculatorMap[budget.type]; + const { chunks, assets } = stats; + if (!chunks) { + throw new Error('Webpack stats output did not include chunk information.'); + } + if (!assets) { + throw new Error('Webpack stats output did not include asset information.'); + } + + const calculator = new ctor(budget, chunks, assets); + + return calculator.calculate(); +} + +abstract class Calculator { + private assetMap?: ReadonlyMap; + + constructor( + protected budget: BudgetEntry, + protected chunks: BudgetChunk[], + protected assets: BudgetAsset[], + ) {} + + abstract calculate(): Size[]; + + /** Calculates the size of the given chunk for the provided build type. */ + protected calculateChunkSize(chunk: BudgetChunk): number { + // No differential builds, get the chunk size by summing its assets. + if (!chunk.files) { + return 0; + } + + if (!this.assetMap) { + const map = new Map(); + for (const asset of this.assets) { + map.set(asset.name, asset.size); + } + this.assetMap = map; + } + const assetMap = this.assetMap; + + return chunk.files + .filter((file) => !file.endsWith('.map')) + .map((file) => { + const assetSize = assetMap.get(file); + if (assetSize === undefined) { + throw new Error(`Could not find asset for file: ${file}`); + } + + return assetSize; + }) + .reduce((l, r) => l + r, 0); + } + + protected getAssetSize(asset: BudgetAsset): number { + return asset.size; + } +} + +/** + * A named bundle. + */ +class BundleCalculator extends Calculator { + calculate() { + const budgetName = this.budget.name; + if (!budgetName) { + return []; + } + + const size = this.chunks + .filter((chunk) => chunk?.names?.includes(budgetName)) + .map((chunk) => this.calculateChunkSize(chunk)) + .reduce((l, r) => l + r, 0); + + return [{ size, label: this.budget.name }]; + } +} + +/** + * The sum of all initial chunks (marked as initial). + */ +class InitialCalculator extends Calculator { + calculate() { + return [ + { + label: `bundle initial`, + size: this.chunks + .filter((chunk) => chunk.initial) + .map((chunk) => this.calculateChunkSize(chunk)) + .reduce((l, r) => l + r, 0), + }, + ]; + } +} + +/** + * The sum of all the scripts portions. + */ +class AllScriptCalculator extends Calculator { + calculate() { + const size = this.assets + .filter((asset) => asset.name.endsWith('.js')) + .map((asset) => this.getAssetSize(asset)) + .reduce((total: number, size: number) => total + size, 0); + + return [{ size, label: 'total scripts' }]; + } +} + +/** + * All scripts and assets added together. + */ +class AllCalculator extends Calculator { + calculate() { + const size = this.assets + .filter((asset) => !asset.name.endsWith('.map') && !asset.componentStyle) + .map((asset) => this.getAssetSize(asset)) + .reduce((total: number, size: number) => total + size, 0); + + return [{ size, label: 'total' }]; + } +} + +/** + * Any script, individually. + */ +class AnyScriptCalculator extends Calculator { + calculate() { + return this.assets + .filter((asset) => asset.name.endsWith('.js')) + .map((asset) => ({ + size: this.getAssetSize(asset), + label: asset.name, + })); + } +} + +/** + * Any script or asset (images, css, etc). + */ +class AnyCalculator extends Calculator { + calculate() { + return this.assets + .filter((asset) => !asset.name.endsWith('.map') && !asset.componentStyle) + .map((asset) => ({ + size: this.getAssetSize(asset), + label: asset.name, + })); + } +} + +/** + * Any compoonent stylesheet + */ +class AnyComponentStyleCalculator extends Calculator { + calculate() { + return this.assets + .filter((asset) => asset.componentStyle) + .map((asset) => ({ + size: this.getAssetSize(asset), + label: asset.name, + })); + } +} + +/** + * Calculate the bytes given a string value. + */ +function calculateBytes(input: string, baseline?: string, factor: 1 | -1 = 1): number { + const matches = input.trim().match(/^(\d+(?:\.\d+)?)[ \t]*(%|[kmg]?b)?$/i); + if (!matches) { + return NaN; + } + + const baselineBytes = (baseline && calculateBytes(baseline)) || 0; + + let value = Number(matches[1]); + switch (matches[2] && matches[2].toLowerCase()) { + case '%': + value = (baselineBytes * value) / 100; + break; + case 'kb': + value *= BYTES_IN_KILOBYTE; + break; + case 'mb': + value *= BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE; + break; + case 'gb': + value *= BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE; + break; + } + + if (baselineBytes === 0) { + return value; + } + + return baselineBytes + value * factor; +} + +export function* checkBudgets( + budgets: BudgetEntry[], + stats: BudgetStats, + checkComponentStyles?: boolean, +): IterableIterator { + // Ignore AnyComponentStyle budgets as these are handled in `AnyComponentStyleBudgetChecker` unless requested + const computableBudgets = checkComponentStyles + ? budgets + : budgets.filter((budget) => budget.type !== BudgetType.AnyComponentStyle); + + for (const budget of computableBudgets) { + const sizes = calculateSizes(budget, stats); + for (const { size, label } of sizes) { + yield* checkThresholds(calculateThresholds(budget), size, label); + } + } +} + +function* checkThresholds( + thresholds: Iterable, + size: number, + label?: string, +): IterableIterator { + for (const threshold of thresholds) { + switch (threshold.type) { + case ThresholdType.Max: { + if (size <= threshold.limit) { + continue; + } + + const sizeDifference = formatSize(size - threshold.limit); + yield { + severity: threshold.severity, + label, + message: `${label} exceeded maximum budget. Budget ${formatSize( + threshold.limit, + )} was not met by ${sizeDifference} with a total of ${formatSize(size)}.`, + }; + break; + } + case ThresholdType.Min: { + if (size >= threshold.limit) { + continue; + } + + const sizeDifference = formatSize(threshold.limit - size); + yield { + severity: threshold.severity, + label, + message: `${label} failed to meet minimum budget. Budget ${formatSize( + threshold.limit, + )} was not met by ${sizeDifference} with a total of ${formatSize(size)}.`, + }; + break; + } + default: { + throw new Error(`Unexpected threshold type: ${ThresholdType[threshold.type]}`); + } + } + } +} diff --git a/packages/angular/build/src/utils/bundle-calculator_spec.ts b/packages/angular/build/src/utils/bundle-calculator_spec.ts new file mode 100644 index 000000000000..9bb44394496b --- /dev/null +++ b/packages/angular/build/src/utils/bundle-calculator_spec.ts @@ -0,0 +1,379 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + BYTES_IN_KILOBYTE, + BudgetEntry, + BudgetType, + ThresholdSeverity, + checkBudgets, +} from './bundle-calculator'; + +describe('bundle-calculator', () => { + describe('checkBudgets()', () => { + it('yields maximum budgets exceeded', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Any, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [], + assets: [ + { + name: 'foo.js', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'foo.js', + message: jasmine.stringMatching('foo.js exceeded maximum budget.'), + }); + }); + + it('yields minimum budgets exceeded', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Any, + minimumError: '1kb', + }, + ]; + const stats = { + chunks: [], + assets: [ + { + name: 'foo.js', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'bar.js', + message: jasmine.stringMatching('bar.js failed to meet minimum budget.'), + }); + }); + + it('yields exceeded bundle budgets', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Bundle, + name: 'foo', + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + names: ['foo'], + files: ['foo.js', 'bar.js'], + }, + ], + assets: [ + { + name: 'foo.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'foo', + message: jasmine.stringMatching('foo exceeded maximum budget.'), + }); + }); + + it('yields exceeded initial budget', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Initial, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.js', 'bar.js'], + }, + ], + assets: [ + { + name: 'foo.js', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'bundle initial', + message: jasmine.stringMatching('initial exceeded maximum budget.'), + }); + }); + + it('yields exceeded total scripts budget', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.AllScript, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.js', 'bar.js'], + }, + ], + assets: [ + { + name: 'foo.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + { + name: 'baz.css', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'total scripts', + message: jasmine.stringMatching('total scripts exceeded maximum budget.'), + }); + }); + + it('yields exceeded total budget', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.All, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.js', 'bar.css'], + }, + ], + assets: [ + { + name: 'foo.js', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.css', + size: 0.75 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'total', + message: jasmine.stringMatching('total exceeded maximum budget.'), + }); + }); + + it('skips component style budgets', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.AnyComponentStyle, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.css', 'bar.js'], + }, + ], + assets: [ + { + name: 'foo.css', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(0); + }); + + it('yields exceeded individual script budget', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.AnyScript, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.js', 'bar.js'], + }, + ], + assets: [ + { + name: 'foo.js', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.js', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'foo.js', + message: jasmine.stringMatching('foo.js exceeded maximum budget.'), + }); + }); + + it('yields exceeded individual file budget', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Any, + maximumError: '1kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['foo'], + files: ['foo.ext', 'bar.ext'], + }, + ], + assets: [ + { + name: 'foo.ext', + size: 1.5 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.ext', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures.length).toBe(1); + expect(failures).toContain({ + severity: ThresholdSeverity.Error, + label: 'foo.ext', + message: jasmine.stringMatching('foo.ext exceeded maximum budget.'), + }); + }); + + it('does not exceed the individual file budget limit', () => { + const budgets: BudgetEntry[] = [ + { + type: BudgetType.Bundle, + maximumError: '1000kb', + }, + ]; + const stats = { + chunks: [ + { + id: 0, + initial: true, + names: ['main'], + files: ['main.ext', 'bar.ext'], + }, + ], + assets: [ + { + name: 'main.ext', + size: 1 * BYTES_IN_KILOBYTE, + }, + { + name: 'bar.ext', + size: 0.5 * BYTES_IN_KILOBYTE, + }, + ], + }; + + const failures = Array.from(checkBudgets(budgets, stats)); + + expect(failures).toHaveSize(0); + }); + }); +}); diff --git a/packages/angular/build/src/utils/cache/cache.ts b/packages/angular/build/src/utils/cache/cache.ts new file mode 100644 index 000000000000..1773caca71ea --- /dev/null +++ b/packages/angular/build/src/utils/cache/cache.ts @@ -0,0 +1,337 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * Provides infrastructure for common caching functionality within the build system. + */ + +import { persistentCacheStoreSetting } from '../environment-options'; +import { assertIsError } from '../error'; + +/** + * A backing data store for one or more Cache instances. + * The interface is intentionally designed to support using a JavaScript + * Map instance as a potential cache store. + */ +export interface CacheStore { + /** + * Returns the specified value from the cache store or `undefined` if not found. + * @param key The key to retrieve from the store. + */ + get(key: string): V | undefined | Promise; + + /** + * Returns whether the provided key is present in the cache store. + * @param key The key to check from the store. + */ + has(key: string): boolean | Promise; + + /** + * Adds a new value to the cache store if the key is not present. + * Updates the value for the key if already present. + * @param key The key to associate with the value in the cache store. + * @param value The value to add to the cache store. + */ + set(key: string, value: V): this | Promise; +} + +/** + * A persistent backing data store that supports namespace partitioning + * and manual lifecycle close operations. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface PersistentCacheStore extends CacheStore { + createCache(namespace: string): Cache; + close(): void | Promise; +} + +/** + * A backing data store wrapper that namespaces all keys using length-prefix framing. + * Prevents key collisions between namespaces regardless of characters (such as colons) + * in the namespace or key. + */ +export class NamespacedCacheStore implements CacheStore { + readonly #prefix: string; + + constructor( + private readonly store: CacheStore, + readonly namespace: string, + ) { + this.#prefix = `${namespace.length}:${namespace}:`; + } + + get(key: string): V | undefined | Promise { + return this.store.get(this.#prefix + key); + } + + has(key: string): boolean | Promise { + return this.store.has(this.#prefix + key); + } + + set(key: string, value: V): this | Promise { + const result = this.store.set(this.#prefix + key, value); + if (result instanceof Promise) { + return result.then(() => this); + } + + return this; + } +} + +/** + * A cache object that allows accessing and storing key/value pairs in + * an underlying CacheStore. This class is the primary method for consumers + * to use a cache. + */ +export class Cache = CacheStore> { + // In-flight creator promises to deduplicate concurrent requests for the same key. + readonly #requests = new Map>(); + // Track how many writes occurred for a key to detect mutations during await gaps. + readonly #writeCounts = new Map(); + // Count the number of active, pending getOrCreate operations per key to avoid memory leaks. + readonly #pendingGets = new Map(); + + constructor(protected readonly store: S) {} + + #incrementWrite(key: string) { + // Only track write counts if there is a pending getOrCreate operation active for the key. + // This ensures that write counts are not leaked when no concurrent gets are running. + if (this.#pendingGets.has(key)) { + this.#writeCounts.set(key, (this.#writeCounts.get(key) || 0) + 1); + } + } + + /** + * Gets the value associated with a provided key if available. + * Otherwise, creates a value using the factory creator function, puts the value + * in the cache, and returns the new value. + * @param key A key associated with the value. + * @param creator A factory function for the value if no value is present. + * @returns A value associated with the provided key. + */ + async getOrCreate(key: string, creator: () => V | Promise): Promise { + // 1. If another call is already running the creator for this key, share its promise. + let activeRequest = this.#requests.get(key); + if (activeRequest !== undefined) { + return activeRequest; + } + + // Increment pending gets count to enable write-tracking for this key. + const currentPending = this.#pendingGets.get(key) || 0; + this.#pendingGets.set(key, currentPending + 1); + + try { + const startWriteCount = this.#writeCounts.get(key) || 0; + + // 2. Query the backing store. Since store.get can be async, we yield to the event loop. + const value = await this.store.get(key); + + // If a write (e.g. put) occurred during the store.get await gap, we must abort + // the current execution and restart to ensure we return the newly written value. + if ((this.#writeCounts.get(key) || 0) !== startWriteCount) { + return this.getOrCreate(key, creator); + } + + if (value !== undefined) { + return value; + } + + // 3. Recheck active request after the await gap in case another concurrent call + // initiated a creator during the store.get wait. + activeRequest = this.#requests.get(key); + if (activeRequest !== undefined) { + return activeRequest; + } + + // 4. Run the creator to produce the new value, and store its promise in #requests. + activeRequest = Promise.resolve(creator()).then( + async (newValue) => { + // Ensure this request is still the active one before writing back to the store + // (prevents overwriting newer data if put() was called before resolution). + if (this.#requests.get(key) === activeRequest) { + this.#incrementWrite(key); + await this.store.set(key, newValue); + this.#requests.delete(key); + } + + return newValue; + }, + (error) => { + // Clean up the active request if the creator fails. + if (this.#requests.get(key) === activeRequest) { + this.#requests.delete(key); + } + throw error; + }, + ); + + this.#requests.set(key, activeRequest); + + return activeRequest; + } finally { + // Clean up write counts and pending gets once all concurrent gets for this key finish. + const current = this.#pendingGets.get(key) || 0; + if (current <= 1) { + this.#pendingGets.delete(key); + this.#writeCounts.delete(key); + } else { + this.#pendingGets.set(key, current - 1); + } + } + } + + /** + * Gets the value associated with a provided key if available. + * @param key A key associated with the value. + * @returns A value associated with the provided key if present. Otherwise, `undefined`. + */ + async get(key: string): Promise { + const value = await this.store.get(key); + + return value; + } + + /** + * Puts a value in the cache and associates it with the provided key. + * If the key is already present, the value is updated instead. + * @param key A key associated with the value. + * @param value A value to put in the cache. + */ + async put(key: string, value: V): Promise { + this.#requests.delete(key); + this.#incrementWrite(key); + await this.store.set(key, value); + } + + /** + * Clears internal state for a specific key (requests, write counts, and pending gets). + */ + protected deleteInternal(key: string): void { + this.#requests.delete(key); + this.#writeCounts.delete(key); + this.#pendingGets.delete(key); + } + + /** + * Clears the base class internal state (requests, write counts, and pending gets). + */ + protected clearInternal(): void { + this.#requests.clear(); + this.#writeCounts.clear(); + this.#pendingGets.clear(); + } +} + +/** + * A lightweight in-memory cache implementation based on a JavaScript Map object. + */ +export class MemoryCache extends Cache> { + constructor() { + super(new Map()); + } + + /** + * Removes the specified key from the cache instance. + * @param key The key to remove. + * @returns True if an element in the Map existed and has been removed, or false if the element does not exist. + */ + delete(key: string): boolean { + this.deleteInternal(key); + + return this.store.delete(key); + } + + /** + * Removes all entries from the cache instance. + */ + clear() { + this.clearInternal(); + this.store.clear(); + } + + /** + * Provides all the values currently present in the cache instance. + * @returns An iterable of all values in the cache. + */ + values() { + return this.store.values(); + } + + /** + * Provides all the keys/values currently present in the cache instance. + * @returns An iterable of all key/value pairs in the cache. + */ + entries() { + return this.store.entries(); + } +} + +/** + * Creates and returns a persistent cache store. + * Attempts to use the native LMDB store first, and falls back to the built-in SQLite store + * if LMDB fails to initialize. + * + * @param baseCachePath The base path of the cache file/directory without suffix/extension. + * @returns A promise resolving to a PersistentCacheStore instance. + */ +export async function createPersistentCacheStore( + baseCachePath: string, +): Promise { + if (persistentCacheStoreSetting === 'sqlite') { + try { + const { SqliteCacheStore } = await import('./sqlite-cache-store'); + + return new SqliteCacheStore(baseCachePath + '-sqlite.db'); + } catch (err) { + assertIsError(err); + + throw new Error( + 'Unable to initialize JavaScript cache storage.\n' + `SQLite error: ${err.message}`, + { cause: err }, + ); + } + } + + if (persistentCacheStoreSetting === 'lmdb') { + try { + const { LmdbCacheStore } = await import('./lmdb-cache-store'); + + return new LmdbCacheStore(baseCachePath + '.db'); + } catch (err) { + assertIsError(err); + + throw new Error( + 'Unable to initialize JavaScript cache storage.\n' + `LMDB error: ${err.message}`, + { cause: err }, + ); + } + } + + try { + const { LmdbCacheStore } = await import('./lmdb-cache-store'); + + return new LmdbCacheStore(baseCachePath + '.db'); + } catch (lmdbError) { + try { + const { SqliteCacheStore } = await import('./sqlite-cache-store'); + + return new SqliteCacheStore(baseCachePath + '-sqlite.db'); + } catch (sqliteError) { + assertIsError(lmdbError); + assertIsError(sqliteError); + + throw new Error( + 'Unable to initialize JavaScript cache storage.\n' + + `LMDB error: ${lmdbError.message.split('\n')[0]}\n` + + `SQLite error: ${sqliteError.message.split('\n')[0]}`, + { cause: sqliteError }, + ); + } + } +} diff --git a/packages/angular/build/src/utils/cache/cache_spec.ts b/packages/angular/build/src/utils/cache/cache_spec.ts new file mode 100644 index 000000000000..c5c0b18f6a49 --- /dev/null +++ b/packages/angular/build/src/utils/cache/cache_spec.ts @@ -0,0 +1,267 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Cache, CacheStore, MemoryCache, NamespacedCacheStore } from './cache'; + +describe('MemoryCache', () => { + let cache: MemoryCache; + + beforeEach(() => { + cache = new MemoryCache(); + }); + + it('should return cached value on subsequent getOrCreate calls', async () => { + let callCount = 0; + const creator = () => { + callCount++; + + return 'value'; + }; + + const val1 = await cache.getOrCreate('key', creator); + const val2 = await cache.getOrCreate('key', creator); + + expect(val1).toBe('value'); + expect(val2).toBe('value'); + expect(callCount).toBe(1); + }); + + it('should call creator only once for concurrent getOrCreate calls with the same key', async () => { + let callCount = 0; + let resolveCreator!: (value: string) => void; + const promise = new Promise((resolve) => { + resolveCreator = resolve; + }); + + const creator = () => { + callCount++; + + return promise; + }; + + const p1 = cache.getOrCreate('key', creator); + const p2 = cache.getOrCreate('key', creator); + + resolveCreator('concurrent-value'); + + const [val1, val2] = await Promise.all([p1, p2]); + + expect(val1).toBe('concurrent-value'); + expect(val2).toBe('concurrent-value'); + expect(callCount).toBe(1); + }); + + it('should call creator multiple times for concurrent getOrCreate calls with different keys', async () => { + let callCount = 0; + const creator = (val: string) => { + callCount++; + + return Promise.resolve(val); + }; + + const p1 = cache.getOrCreate('key1', () => creator('value1')); + const p2 = cache.getOrCreate('key2', () => creator('value2')); + + const [val1, val2] = await Promise.all([p1, p2]); + + expect(val1).toBe('value1'); + expect(val2).toBe('value2'); + expect(callCount).toBe(2); + }); + + it('should clean up active request if creator throws/rejects', async () => { + let callCount = 0; + let rejectCreator!: (err: Error) => void; + const promise = new Promise((_, reject) => { + rejectCreator = reject; + }); + + const creator = () => { + callCount++; + + return promise; + }; + + const p1 = cache.getOrCreate('key', creator); + const p2 = cache.getOrCreate('key', creator); + + rejectCreator(new Error('creator error')); + + await expectAsync(p1).toBeRejectedWithError('creator error'); + await expectAsync(p2).toBeRejectedWithError('creator error'); + + // Subsequent call should trigger the creator again + const p3 = cache.getOrCreate('key', () => { + callCount++; + + return Promise.resolve('new-value'); + }); + const val3 = await p3; + expect(val3).toBe('new-value'); + expect(callCount).toBe(2); + }); + + it('should override/clear active requests when put is called', async () => { + let resolveCreator!: (value: string) => void; + const promise = new Promise((resolve) => { + resolveCreator = resolve; + }); + + let creatorStarted!: (value: void) => void; + const creatorStartedPromise = new Promise((resolve) => { + creatorStarted = resolve; + }); + + const creator = () => { + creatorStarted(); + + return promise; + }; + + const p1 = cache.getOrCreate('key', creator); + + // Wait for the creator to be called so that the active request is created + await creatorStartedPromise; + + // Call put before the creator promise resolves + await cache.put('key', 'override-value'); + + resolveCreator('original-value'); + + const val1 = await p1; + // p1 was already returned, so it resolves to original-value + expect(val1).toBe('original-value'); + + // Subsequent getOrCreate should return the put/overridden value, not the resolved original-value + const val2 = await cache.getOrCreate('key', () => 'should-not-run'); + expect(val2).toBe('override-value'); + }); + + it('should delete a cached key and allow creating a new value', async () => { + await cache.put('key', 'value-1'); + expect(await cache.get('key')).toBe('value-1'); + + const deleted = cache.delete('key'); + expect(deleted).toBeTrue(); + expect(await cache.get('key')).toBeUndefined(); + + // Subsequent getOrCreate should call creator + const newValue = await cache.getOrCreate('key', () => 'value-2'); + expect(newValue).toBe('value-2'); + }); + + it('should return false when deleting a non-existent key', () => { + expect(cache.delete('non-existent')).toBeFalse(); + }); + + it('should return unencoded keys in entries() and allow deletion', async () => { + await cache.put('component/style.scss', 'content'); + + const entries = Array.from(cache.entries()); + expect(entries).toEqual([['component/style.scss', 'content']]); + + expect(cache.delete(entries[0][0])).toBeTrue(); + expect(await cache.get('component/style.scss')).toBeUndefined(); + }); +}); + +describe('NamespacedCacheStore', () => { + class TestStore implements CacheStore { + readonly map = new Map(); + + get(key: string): string | undefined { + return this.map.get(key); + } + + has(key: string): boolean { + return this.map.has(key); + } + + set(key: string, value: string): this { + this.map.set(key, value); + + return this; + } + } + + let store: TestStore; + + beforeEach(() => { + store = new TestStore(); + }); + + it('should encode namespaced keys with ::', async () => { + const namespacedStore = new NamespacedCacheStore(store, 'test-ns'); + const cache = new Cache(namespacedStore); + await cache.put('my-key', 'my-val'); + + expect(store.map.has('7:test-ns:my-key')).toBeTrue(); + expect(await cache.get('my-key')).toBe('my-val'); + }); + + it('should prevent collisions between namespaces containing colons', async () => { + const cacheA = new Cache(new NamespacedCacheStore(store, 'a')); + const cacheB = new Cache(new NamespacedCacheStore(store, 'a:b')); + + await cacheA.put('b:c', 'val-a'); + await cacheB.put('c', 'val-b'); + + expect(await cacheA.get('b:c')).toBe('val-a'); + expect(await cacheB.get('c')).toBe('val-b'); + expect(store.map.get('1:a:b:c')).toBe('val-a'); + expect(store.map.get('3:a:b:c')).toBe('val-b'); + }); + + it('should encode empty string namespace as 0::', async () => { + const namespacedStore = new NamespacedCacheStore(store, ''); + const cache = new Cache(namespacedStore); + await cache.put('key', 'val'); + + expect(store.map.has('0::key')).toBeTrue(); + expect(await cache.get('key')).toBe('val'); + }); + + it('should forward get, has, and set calls with the namespaced prefix', async () => { + const namespacedStore = new NamespacedCacheStore(store, 'custom'); + await namespacedStore.set('hello', 'world'); + + expect(store.map.has('6:custom:hello')).toBeTrue(); + expect(await namespacedStore.has('hello')).toBeTrue(); + expect(await namespacedStore.get('hello')).toBe('world'); + }); + + it('should return this when the underlying store set is asynchronous', async () => { + class AsyncStore implements CacheStore { + readonly map = new Map(); + + get(key: string): Promise { + return Promise.resolve(this.map.get(key)); + } + + has(key: string): Promise { + return Promise.resolve(this.map.has(key)); + } + + async set(key: string, value: string): Promise { + this.map.set(key, value); + + return this; + } + } + + const asyncStore = new AsyncStore(); + const namespacedStore = new NamespacedCacheStore(asyncStore, 'async-ns'); + const setPromise = namespacedStore.set('foo', 'bar'); + + expect(setPromise instanceof Promise).toBeTrue(); + expect(await setPromise).toBe(namespacedStore); + expect(asyncStore.map.get('8:async-ns:foo')).toBe('bar'); + expect(await namespacedStore.get('foo')).toBe('bar'); + expect(await namespacedStore.has('foo')).toBeTrue(); + }); +}); diff --git a/packages/angular/build/src/utils/cache/index.ts b/packages/angular/build/src/utils/cache/index.ts new file mode 100644 index 000000000000..417d13326f50 --- /dev/null +++ b/packages/angular/build/src/utils/cache/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './cache'; diff --git a/packages/angular/build/src/utils/cache/lmdb-cache-store.ts b/packages/angular/build/src/utils/cache/lmdb-cache-store.ts new file mode 100644 index 000000000000..d7ac3fed49db --- /dev/null +++ b/packages/angular/build/src/utils/cache/lmdb-cache-store.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { RootDatabase, open } from 'lmdb'; +import { Cache, NamespacedCacheStore, PersistentCacheStore } from './cache'; + +export class LmdbCacheStore implements PersistentCacheStore { + readonly #cacheFileUrl; + #db: RootDatabase | undefined; + + constructor(readonly cachePath: string) { + this.#cacheFileUrl = cachePath; + } + + #ensureCacheFile(): RootDatabase { + this.#db ??= open({ + path: this.#cacheFileUrl, + compression: true, + }); + + return this.#db; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async get(key: string): Promise { + const db = this.#ensureCacheFile(); + const value = db.get(key); + + return value; + } + + has(key: string): boolean { + return this.#ensureCacheFile().doesExist(key); + } + + async set(key: string, value: unknown): Promise { + const db = this.#ensureCacheFile(); + await db.put(key, value); + + return this; + } + + createCache(namespace: string): Cache { + return new Cache(new NamespacedCacheStore(this, namespace)); + } + + async close() { + try { + await this.#db?.close(); + } catch { + // Failure to close should not be fatal + } + } +} diff --git a/packages/angular/build/src/utils/cache/sqlite-cache-store.ts b/packages/angular/build/src/utils/cache/sqlite-cache-store.ts new file mode 100644 index 000000000000..d9273f5816e7 --- /dev/null +++ b/packages/angular/build/src/utils/cache/sqlite-cache-store.ts @@ -0,0 +1,384 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { mkdirSync, rmSync } from 'node:fs'; +import { dirname } from 'node:path'; +import { DatabaseSync, StatementSync } from 'node:sqlite'; +import { promisify } from 'node:util'; +import { deserialize, serialize } from 'node:v8'; +import { deflateRaw, inflateRawSync } from 'node:zlib'; +import { Cache, NamespacedCacheStore, PersistentCacheStore } from './cache'; + +const deflateRawAsync = promisify(deflateRaw); + +/** + * Minimum payload size (in bytes) required to attempt compression. + * Smaller payloads generally do not achieve meaningful compression ratios, while larger payloads + * (such as transformed JavaScript modules from node_modules) achieve 70-80% size reduction + * and drastically reduce SQLite overflow pages. + */ +const COMPRESSION_THRESHOLD = 32 * 1024; // 32 KB + +/** + * Storage format discriminator values for cache table entries. + */ +const enum CacheFormat { + V8 = 0, + V8Compressed = 1, + RawBinary = 2, + RawBinaryCompressed = 3, +} + +/** + * Common SQLite primary result codes. + * @see https://www.sqlite.org/rescode.html + */ +const enum SqliteResultCode { + Busy = 5, + Locked = 6, +} + +interface SqliteError extends Error { + code?: string; + errcode?: number; + errstr?: string; +} + +function isSqliteError(error: unknown): error is SqliteError { + return ( + error instanceof Error && + ('errcode' in error || + ('code' in error && (error as { code: unknown }).code === 'ERR_SQLITE_ERROR')) + ); +} + +/** + * A persistent cache store backed by SQLite. + * + * Values are persisted with the V8 structured clone serialization API instead of JSON. Cached + * values include binary data such as the `Uint8Array` output of the JavaScript transformer and + * the `contents` of an esbuild load result. A JSON round-trip converts those into plain objects + * (`{"0":105,"1":109,...}`), which breaks consumers on any build that reads them back from disk. + */ +export class SqliteCacheStore implements PersistentCacheStore { + #db: DatabaseSync | undefined; + #disabled = false; + #getStmt: StatementSync | undefined; + #hasStmt: StatementSync | undefined; + #setStmt: StatementSync | undefined; + #updateAccessedStmt: StatementSync | undefined; + readonly #pendingAccessedKeys = new Set(); + #flushTimeout: NodeJS.Timeout | undefined; + readonly #busyTimeoutMs: number; + + constructor( + readonly cachePath: string, + private readonly maxPayloadSize = 1024 * 1024 * 1024, + private readonly ttlDays = 14, + busyTimeoutMs = 5000, + ) { + this.#busyTimeoutMs = + Number.isSafeInteger(busyTimeoutMs) && busyTimeoutMs >= 0 ? busyTimeoutMs : 5000; + } + + #openDatabase(): DatabaseSync { + let db: DatabaseSync | undefined; + try { + if (this.cachePath === ':memory:') { + db = new DatabaseSync(this.cachePath); + } else { + // Optimistically attempt to open the database file first to avoid directory creation + // syscalls on warm builds where the parent directory already exists. + try { + db = new DatabaseSync(this.cachePath); + } catch { + mkdirSync(dirname(this.cachePath), { recursive: true }); + db = new DatabaseSync(this.cachePath); + } + } + + // Optimize SQLite for cache usage + db.exec(`PRAGMA busy_timeout = ${this.#busyTimeoutMs};`); + db.exec('PRAGMA auto_vacuum = FULL;'); + db.exec('PRAGMA journal_mode = WAL;'); + db.exec('PRAGMA synchronous = NORMAL;'); + db.exec('PRAGMA temp_store = MEMORY;'); + db.exec('PRAGMA mmap_size = 268435456;'); + db.exec( + 'CREATE TABLE IF NOT EXISTS cache (' + + 'key TEXT PRIMARY KEY, ' + + 'value BLOB, ' + + 'format INTEGER NOT NULL DEFAULT 0, ' + + 'last_accessed INTEGER NOT NULL' + + ') WITHOUT ROWID;', + ); + try { + db.exec('ALTER TABLE cache ADD COLUMN format INTEGER NOT NULL DEFAULT 0;'); + } catch { + // Ignore error if format column already exists + } + db.exec( + 'CREATE INDEX IF NOT EXISTS idx_cache_accessed ON cache (last_accessed DESC, key DESC);', + ); + + this.#getStmt = db.prepare('SELECT value, format FROM cache WHERE key = ?'); + this.#hasStmt = db.prepare('SELECT 1 FROM cache WHERE key = ?'); + this.#setStmt = db.prepare( + 'INSERT OR REPLACE INTO cache (key, value, format, last_accessed) VALUES (?, ?, ?, unixepoch())', + ); + this.#updateAccessedStmt = db.prepare( + 'UPDATE cache SET last_accessed = unixepoch() WHERE key = ?', + ); + + this.#db = db; + + return db; + } catch (error) { + try { + db?.close(); + } catch { + // Ignore close error on corrupted handle + } + this.#getStmt = undefined; + this.#hasStmt = undefined; + this.#setStmt = undefined; + this.#updateAccessedStmt = undefined; + throw error; + } + } + + #ensureDb(): DatabaseSync | undefined { + if (this.#disabled) { + return undefined; + } + + if (!this.#db) { + try { + return this.#openDatabase(); + } catch (error) { + // If the database is locked by another active process, + // do not attempt to delete the database files as that could corrupt the active process's database. + const isBusy = + isSqliteError(error) && + (error.errcode === SqliteResultCode.Busy || error.errcode === SqliteResultCode.Locked); + + // Attempt to recover from database corruption by deleting the corrupted files and recreating + if (!isBusy && this.cachePath !== ':memory:') { + try { + rmSync(this.cachePath, { force: true }); + rmSync(this.cachePath + '-wal', { force: true }); + rmSync(this.cachePath + '-shm', { force: true }); + rmSync(this.cachePath + '-journal', { force: true }); + + return this.#openDatabase(); + } catch { + // If recovery fails (e.g. read-only filesystem or permission denied), disable caching + } + } + + this.#disabled = true; + + return undefined; + } + } + + return this.#db; + } + + #queueAccessUpdate(key: string): void { + this.#pendingAccessedKeys.add(key); + + if (!this.#flushTimeout) { + this.#flushTimeout = setTimeout(() => this.#flushAccessUpdates(), 1000); + this.#flushTimeout.unref?.(); + } + } + + #flushAccessUpdates(): void { + if (this.#flushTimeout) { + clearTimeout(this.#flushTimeout); + this.#flushTimeout = undefined; + } + + if (this.#pendingAccessedKeys.size === 0) { + return; + } + + try { + if (this.#db && this.#updateAccessedStmt) { + this.#db.exec('BEGIN IMMEDIATE TRANSACTION;'); + for (const key of this.#pendingAccessedKeys) { + this.#updateAccessedStmt.run(key); + } + this.#db.exec('COMMIT;'); + } + } catch { + try { + this.#db?.exec('ROLLBACK;'); + } catch { + // Ignore rollback errors if transaction was not active + } + } finally { + this.#pendingAccessedKeys.clear(); + } + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async get(key: string): Promise { + if (!this.#ensureDb()) { + return undefined; + } + + try { + // SQLite column types are dynamic, so the stored value is only known at runtime. + const row = this.#getStmt?.get(key) as { value: unknown; format: CacheFormat } | undefined; + + if (row) { + this.#queueAccessUpdate(key); + + if (row.value instanceof Uint8Array) { + try { + switch (row.format) { + case CacheFormat.RawBinary: + return row.value; + case CacheFormat.RawBinaryCompressed: { + const decompressed = inflateRawSync(row.value); + + return new Uint8Array( + decompressed.buffer, + decompressed.byteOffset, + decompressed.byteLength, + ); + } + case CacheFormat.V8Compressed: + return deserialize(inflateRawSync(row.value)); + case CacheFormat.V8: + default: + return deserialize(row.value); + } + } catch { + // Treat corrupt or unparseable cached payloads as a cache miss. + } + } + } + } catch { + // Treat query errors (e.g. disk read failures) as a cache miss. + } + + return undefined; + } + + has(key: string): boolean { + if (!this.#ensureDb()) { + return false; + } + + try { + return !!this.#hasStmt?.get(key); + } catch { + return false; + } + } + + async set(key: string, value: unknown): Promise { + if (!this.#ensureDb()) { + return this; + } + + try { + this.#pendingAccessedKeys.delete(key); + + const isBinary = value instanceof Uint8Array; + const data = isBinary ? value : serialize(value); + let format = isBinary ? CacheFormat.RawBinary : CacheFormat.V8; + let payload: Uint8Array = data; + + if (data.byteLength >= COMPRESSION_THRESHOLD) { + const compressed = await deflateRawAsync(data, { level: 1 }); + if (compressed.byteLength < data.byteLength) { + payload = compressed; + format = isBinary ? CacheFormat.RawBinaryCompressed : CacheFormat.V8Compressed; + } + } + + this.#setStmt?.run(key, payload, format); + } catch { + // Writing to cache is non-fatal and should not fail the build. + } + + return this; + } + + createCache(namespace: string): Cache { + return new Cache(new NamespacedCacheStore(this, namespace)); + } + + close(): void { + this.#flushAccessUpdates(); + + if (this.#db) { + try { + this.#db.exec('BEGIN IMMEDIATE TRANSACTION;'); + try { + // 1. Delete items older than N days + this.#db + .prepare("DELETE FROM cache WHERE last_accessed < unixepoch('now', ?);") + .run(`-${this.ttlDays} days`); + + // 2. Prune oldest items if payload exceeds maxPayloadSize + // Skip the expensive window aggregate query if total database size is below maxPayloadSize + const sizeResult = this.#db + .prepare( + 'SELECT (page_count - freelist_count) * page_size AS total_size ' + + 'FROM pragma_page_count(), pragma_freelist_count(), pragma_page_size();', + ) + .get() as { total_size?: number } | undefined; + + if ((sizeResult?.total_size ?? 0) > this.maxPayloadSize) { + this.#db + .prepare( + `DELETE FROM cache WHERE key IN ( + SELECT key FROM ( + SELECT key, + sum(length(key) + length(value)) OVER (ORDER BY last_accessed DESC, key DESC) as running_size + FROM cache + ) WHERE running_size > ? + );`, + ) + .run(this.maxPayloadSize); + } + + this.#db.exec('COMMIT;'); + } catch (error) { + try { + this.#db.exec('ROLLBACK;'); + } catch { + // Ignore rollback errors if transaction was not active + } + throw error; + } + } catch { + // Pruning errors should not block build success + } finally { + this.#getStmt = undefined; + this.#hasStmt = undefined; + this.#setStmt = undefined; + this.#updateAccessedStmt = undefined; + + try { + this.#db.close(); + } catch { + // Failure to close should not block build success + } + this.#db = undefined; + } + } + + this.#disabled = false; + } +} diff --git a/packages/angular/build/src/utils/cache/sqlite-cache-store_spec.ts b/packages/angular/build/src/utils/cache/sqlite-cache-store_spec.ts new file mode 100644 index 000000000000..4eac21f3b34b --- /dev/null +++ b/packages/angular/build/src/utils/cache/sqlite-cache-store_spec.ts @@ -0,0 +1,630 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { promises as fs } from 'node:fs'; +import { join } from 'node:path'; +import { SqliteCacheStore } from './sqlite-cache-store'; + +describe('SqliteCacheStore', () => { + let tempDir: string; + let cachePath: string; + let store: SqliteCacheStore; + + beforeEach(async () => { + // Create a temporary directory in the workspace for testing + tempDir = join(__dirname, `sqlite-test-temp-${Date.now()}`); + await fs.mkdir(tempDir, { recursive: true }); + cachePath = join(tempDir, 'test-cache.db'); + store = new SqliteCacheStore(cachePath); + }); + + afterEach(async () => { + store.close(); + await fs.rm(tempDir, { recursive: true, force: true }); + }); + + it('should store and retrieve a value', async () => { + const data = { foo: 'bar', list: [1, 2, 3] }; + await store.set('test-key', data); + + const result = await store.get('test-key'); + expect(result).toEqual(data); + }); + + it('should preserve binary values', async () => { + const data = new TextEncoder().encode('export const value = 1;\n'); + await store.set('binary-key', data); + + const result = await store.get('binary-key'); + expect(result).toBeInstanceOf(Uint8Array); + expect(result).toEqual(data); + }); + + it('should preserve binary values nested within an object', async () => { + const data = { + contents: new TextEncoder().encode('export const value = 1;\n'), + loader: 'js', + watchFiles: ['/some/file.js'], + }; + await store.set('nested-binary-key', data); + + const result = await store.get('nested-binary-key'); + expect(result.contents).toBeInstanceOf(Uint8Array); + expect(result).toEqual(data); + }); + + it('should preserve binary values across store instances', async () => { + const data = new TextEncoder().encode('export const value = 1;\n'); + await store.set('persisted-binary-key', data); + store.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('persisted-binary-key'); + expect(result).toBeInstanceOf(Uint8Array); + expect(result).toEqual(data); + } finally { + reopenedStore.close(); + } + }); + + it('should treat a corrupt payload as a cache miss', async () => { + await store.set('corrupt-key', 'value'); + store.close(); + + // Simulate an entry with an invalid/corrupt payload that fails deserialization. + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + directDb + .prepare('UPDATE cache SET value = ? WHERE key = ?') + .run(new Uint8Array([0x00, 0x01, 0x02]), 'corrupt-key'); + directDb.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + expect(await reopenedStore.get('corrupt-key')).toBeUndefined(); + } finally { + reopenedStore.close(); + } + }); + + it('should automatically recover from a corrupted database file', async () => { + // Write corrupted header data to the database file + await fs.writeFile(cachePath, 'CORRUPTED_DATABASE_FILE_CONTENTS'); + + // The store should detect corruption, reset the database files, and operate normally + await store.set('recover-key', 'recovered-value'); + const result = await store.get('recover-key'); + expect(result).toBe('recovered-value'); + }); + + it('should automatically recover from a corrupted B-tree page', async () => { + // Initialize valid database + await store.set('initial-key', 'initial-val'); + store.close(); + + // Overwrite page data with garbage + const handle = await fs.open(cachePath, 'r+'); + await handle.write(Buffer.alloc(200, 0xff), 0, 200, 100); + await handle.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + await reopenedStore.set('new-key', 'new-val'); + expect(await reopenedStore.get('new-key')).toBe('new-val'); + } finally { + reopenedStore.close(); + } + }); + + it('should gracefully degrade when database path is permanently unwritable', async () => { + // A regular file in place of a directory path ensures unwritability across all platforms (ENOTDIR) + const blockingFile = join(tempDir, 'blocking-file'); + await fs.writeFile(blockingFile, 'cannot-be-a-directory'); + + const unwritableStore = new SqliteCacheStore(join(blockingFile, 'cannot-create.db')); + try { + expect(unwritableStore.has('any-key')).toBeFalse(); + expect(await unwritableStore.get('any-key')).toBeUndefined(); + await unwritableStore.set('any-key', 'any-val'); + expect(await unwritableStore.get('any-key')).toBeUndefined(); + expect(unwritableStore.has('any-key')).toBeFalse(); + } finally { + unwritableStore.close(); + } + }); + + it('should automatically recover from a corrupted journal file', async () => { + await store.set('key-before', 'val-before'); + store.close(); + + // Create a corrupt rollback journal file + await fs.writeFile(cachePath + '-journal', 'CORRUPTED_JOURNAL_FILE'); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + await reopenedStore.set('new-key', 'new-val'); + expect(await reopenedStore.get('new-key')).toBe('new-val'); + } finally { + reopenedStore.close(); + } + }); + + it('should not delete database files when database is locked by another process', async () => { + await store.set('persist-key', 'persist-val'); + store.close(); + + // Open direct connection with an exclusive transaction holding a write lock + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + directDb.exec('BEGIN EXCLUSIVE TRANSACTION;'); + + // Use a tiny busyTimeoutMs so the test fails fast instead of waiting 5s + const lockedStore = new SqliteCacheStore(cachePath, undefined, undefined, 10); + try { + expect(lockedStore.has('persist-key')).toBeFalse(); + expect(await lockedStore.get('persist-key')).toBeUndefined(); + } finally { + lockedStore.close(); + directDb.exec('COMMIT;'); + directDb.close(); + } + + // Verify the original database file and its data were not deleted + const verifyStore = new SqliteCacheStore(cachePath); + try { + expect(await verifyStore.get('persist-key')).toBe('persist-val'); + } finally { + verifyStore.close(); + } + }); + + it('should safely fall back to default timeout if invalid busyTimeoutMs is provided', async () => { + // Pass NaN as busyTimeoutMs + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const invalidStore = new SqliteCacheStore(cachePath, undefined, undefined, NaN as any); + try { + await invalidStore.set('valid-key', 'valid-value'); + expect(await invalidStore.get('valid-key')).toBe('valid-value'); + } finally { + invalidStore.close(); + } + }); + + it('should flush pending access updates on close', async () => { + await store.set('flush-key', 'flush-val'); + + // Manually backdate the entry's last_accessed timestamp to simulate elapsed time + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const pastTimestamp = Math.floor(Date.now() / 1000) - 3600; + directDb + .prepare('UPDATE cache SET last_accessed = ? WHERE key = ?') + .run(pastTimestamp, 'flush-key'); + directDb.close(); + + // Access the key via store.get() to queue an access update + await store.get('flush-key'); + + // Immediately close the store before the debounced 500ms timeout fires + store.close(); + + // Verify the timestamp in SQLite was updated upon close + const checkDb = new DatabaseSync(cachePath); + const row = checkDb + .prepare('SELECT last_accessed FROM cache WHERE key = ?') + .get('flush-key') as { last_accessed: number }; + checkDb.close(); + + expect(row.last_accessed).toBeGreaterThan(pastTimestamp); + }); + + it('should selectively compress entries that exceed the 32KB threshold', async () => { + const largeContent = + 'export const testFunction = () => { console.log("hello world"); };\n'.repeat(1000); + await store.set('large-key', largeContent); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const row = directDb + .prepare('SELECT value, format FROM cache WHERE key = ?') + .get('large-key') as { + value: Uint8Array; + format: number; + }; + directDb.close(); + + // Verify format flag is 1 (CacheFormat.V8Compressed) and compressed size is drastically smaller + expect(row.format).toBe(1); + expect(row.value.byteLength).toBeLessThan(largeContent.length / 5); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('large-key'); + expect(result).toBe(largeContent); + } finally { + reopenedStore.close(); + } + }); + + it('should not compress entries below the 32KB threshold', async () => { + const smallContent = 'export const small = true;'; + await store.set('small-key', smallContent); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const row = directDb + .prepare('SELECT value, format FROM cache WHERE key = ?') + .get('small-key') as { + value: Uint8Array; + format: number; + }; + directDb.close(); + + // Verify format flag is 0 (CacheFormat.V8) + expect(row.format).toBe(0); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('small-key'); + expect(result).toBe(smallContent); + } finally { + reopenedStore.close(); + } + }); + + it('should not compress entries exceeding the 32KB threshold if compression does not reduce size', async () => { + const { randomBytes } = await import('node:crypto'); + // High-entropy random bytes cannot be compressed by DEFLATE + const incompressibleData = new Uint8Array(randomBytes(48 * 1024)); + await store.set('incompressible-key', incompressibleData); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const row = directDb + .prepare('SELECT value, format FROM cache WHERE key = ?') + .get('incompressible-key') as { + value: Uint8Array; + format: number; + }; + directDb.close(); + + // Verify entry is stored uncompressed as raw binary (format 2 = CacheFormat.RawBinary) + expect(row.format).toBe(2); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('incompressible-key'); + expect(result).toEqual(incompressibleData); + } finally { + reopenedStore.close(); + } + }); + + it('should store raw Uint8Array directly with zero serialization', async () => { + const binaryData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + await store.set('binary-key', binaryData); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const row = directDb + .prepare('SELECT value, format FROM cache WHERE key = ?') + .get('binary-key') as { + value: Uint8Array; + format: number; + }; + directDb.close(); + + // Verify format is 2 (CacheFormat.RawBinary) and value is the exact raw bytes + expect(row.format).toBe(2); + expect(row.value).toEqual(binaryData); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('binary-key'); + expect(result).toEqual(binaryData); + } finally { + reopenedStore.close(); + } + }); + + it('should selectively compress large Uint8Array entries', async () => { + const largeBinary = new Uint8Array(Buffer.from('export const x = 1;\n'.repeat(2000))); + await store.set('large-binary-key', largeBinary); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + const row = directDb + .prepare('SELECT value, format FROM cache WHERE key = ?') + .get('large-binary-key') as { + value: Uint8Array; + format: number; + }; + directDb.close(); + + // Verify format is 3 (CacheFormat.RawBinaryCompressed) + expect(row.format).toBe(3); + expect(row.value.byteLength).toBeLessThan(largeBinary.byteLength / 5); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('large-binary-key'); + expect(result).toEqual(largeBinary); + } finally { + reopenedStore.close(); + } + }); + + it('should seamlessly read legacy entries from databases created without a format column', async () => { + const { serialize } = await import('node:v8'); + const { DatabaseSync } = await import('node:sqlite'); + + // Create a legacy database without a format column + const directDb = new DatabaseSync(cachePath); + directDb.exec( + 'CREATE TABLE cache (key TEXT PRIMARY KEY, value BLOB, last_accessed INTEGER NOT NULL) WITHOUT ROWID;', + ); + const legacyPayload = serialize('legacy-content'); + directDb + .prepare('INSERT INTO cache (key, value, last_accessed) VALUES (?, ?, unixepoch())') + .run('legacy-key', legacyPayload); + directDb.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + const result = await reopenedStore.get('legacy-key'); + expect(result).toBe('legacy-content'); + } finally { + reopenedStore.close(); + } + }); + + it('should treat a corrupted compressed payload as a cache miss', async () => { + // Initialize database + await store.set('init-key', 'init-val'); + store.close(); + + // Insert an entry with format = 1 (V8Compressed) followed by garbage + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + directDb + .prepare( + 'INSERT INTO cache (key, value, format, last_accessed) VALUES (?, ?, 1, unixepoch())', + ) + .run('corrupt-compressed-key', new Uint8Array([0xde, 0xad, 0xbe, 0xef])); + directDb.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + expect(await reopenedStore.get('corrupt-compressed-key')).toBeUndefined(); + } finally { + reopenedStore.close(); + } + }); + + it('should treat a non-binary payload as a cache miss', async () => { + await store.set('text-key', 'value'); + store.close(); + + // SQLite column types are dynamic, so a stored value is not guaranteed to be binary. + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + directDb.prepare('UPDATE cache SET value = ? WHERE key = ?').run('"value"', 'text-key'); + directDb.close(); + + const reopenedStore = new SqliteCacheStore(cachePath); + try { + expect(await reopenedStore.get('text-key')).toBeUndefined(); + } finally { + reopenedStore.close(); + } + }); + + it('should return undefined for non-existent key', async () => { + const result = await store.get('missing-key'); + expect(result).toBeUndefined(); + }); + + it('should correctly report existence of a key', async () => { + expect(store.has('exist-key')).toBeFalse(); + + await store.set('exist-key', 'value'); + expect(store.has('exist-key')).toBeTrue(); + }); + + it('should overwrite values for existing keys', async () => { + await store.set('overwrite-key', 'initial'); + await store.set('overwrite-key', 'updated'); + + const result = await store.get('overwrite-key'); + expect(result).toBe('updated'); + }); + + it('should prune items older than TTL on close', async () => { + // Write two items + await store.set('new-key', 'new-val'); + await store.set('old-key', 'old-val'); + + // Close the store so we can modify the DB safely + store.close(); + + // Directly open database to update timestamp of 'old-key' to 15 days ago + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + directDb + .prepare('UPDATE cache SET last_accessed = unixepoch() - 15 * 24 * 3600 WHERE key = ?') + .run('old-key'); + directDb.close(); + + // Reopen store with a 14-day TTL, access it to open connection, then close to trigger pruning + const pruneStore = new SqliteCacheStore(cachePath, undefined, 14); + expect(pruneStore.has('new-key')).toBeTrue(); + pruneStore.close(); + + // Verify 'old-key' is gone but 'new-key' remains + const checkStore = new SqliteCacheStore(cachePath); + expect(checkStore.has('old-key')).toBeFalse(); + expect(checkStore.has('new-key')).toBeTrue(); + checkStore.close(); + }); + + it('should prune oldest items when total payload size exceeds maximum on close', async () => { + // Close the default store so we can instantiate one with a small limit + store.close(); + + // Create a store with a tiny size limit (e.g. 25 bytes) + // Keys 'k1', 'k2', 'k3' are small (each is 12 bytes: 2 byte key + 10 byte serialized value). + // Total size of k1 + k2 + k3 is 36 bytes, which exceeds the 25 bytes limit. + const sizeStore = new SqliteCacheStore(cachePath, 25); + + // Set k1, then k2, then k3. + // Order of inserts: k1 (oldest), k2 (middle), k3 (newest) + await sizeStore.set('k1', 'value1'); + await sizeStore.set('k2', 'value2'); + await sizeStore.set('k3', 'value3'); + + // Close sizeStore to trigger pruning + sizeStore.close(); + + // Reopen to check which keys were kept + const checkStore = new SqliteCacheStore(cachePath); + // k3 (newest) and k2 (middle) should be kept (~20 bytes total) + // k1 (oldest) should be pruned to get under 25 bytes. + expect(checkStore.has('k3')).toBeTrue(); + expect(checkStore.has('k2')).toBeTrue(); + expect(checkStore.has('k1')).toBeFalse(); + checkStore.close(); + }); + + it('should not prune items when total database size is within maxPayloadSize on close', async () => { + store.close(); + + const sizeStore = new SqliteCacheStore(cachePath, 1024 * 1024); + await sizeStore.set('k1', 'value1'); + await sizeStore.set('k2', 'value2'); + sizeStore.close(); + + const checkStore = new SqliteCacheStore(cachePath); + expect(checkStore.has('k1')).toBeTrue(); + expect(checkStore.has('k2')).toBeTrue(); + checkStore.close(); + }); + + it('should create an index on last_accessed and key', async () => { + // Trigger db initialization + await store.set('test-key', 'test-value'); + store.close(); + + const { DatabaseSync } = await import('node:sqlite'); + const directDb = new DatabaseSync(cachePath); + try { + const indexRows = directDb + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'cache' AND name = 'idx_cache_accessed'", + ) + .all(); + expect(indexRows.length).toBe(1); + } finally { + directDb.close(); + } + }); + + it('should create parent directories if they do not exist', async () => { + const nestedDir = join(tempDir, 'nested', 'deeply', 'cache'); + const nestedCachePath = join(nestedDir, 'nested-cache.db'); + const nestedStore = new SqliteCacheStore(nestedCachePath); + + try { + await nestedStore.set('nested-key', 'nested-value'); + const result = await nestedStore.get('nested-key'); + expect(result).toBe('nested-value'); + } finally { + nestedStore.close(); + } + }); + + it('should support in-memory databases', async () => { + const memoryStore = new SqliteCacheStore(':memory:'); + try { + await memoryStore.set('mem-key', 'mem-value'); + const result = await memoryStore.get('mem-key'); + expect(result).toBe('mem-value'); + } finally { + memoryStore.close(); + } + }); + + describe('NG_BUILD_CACHE_STORE env variable option', () => { + it('should force SQLite when NG_BUILD_CACHE_STORE=sqlite', () => { + const code = ` + (async () => { + const { createPersistentCacheStore } = await import('./cache.js'); + const { SqliteCacheStore } = await import('./sqlite-cache-store.js'); + const store = await createPersistentCacheStore('dummy-sqlite-env'); + if (!(store instanceof SqliteCacheStore)) { + console.error('Expected SqliteCacheStore, got:', store.constructor.name); + process.exit(1); + } + })().catch(err => { + console.error(err); + process.exit(2); + }); + `; + const { execFileSync } = require('node:child_process'); + execFileSync(process.execPath, ['--input-type=module', '-e', code], { + cwd: __dirname, + env: { + ...process.env, + NG_BUILD_CACHE_STORE: 'sqlite', + }, + }); + }); + + it('should force LMDB when NG_BUILD_CACHE_STORE=lmdb', () => { + const code = ` + (async () => { + const { createPersistentCacheStore } = await import('./cache.js'); + const { LmdbCacheStore } = await import('./lmdb-cache-store.js'); + const store = await createPersistentCacheStore('dummy-lmdb-env'); + if (!(store instanceof LmdbCacheStore)) { + console.error('Expected LmdbCacheStore, got:', store.constructor.name); + process.exit(1); + } + })().catch(err => { + console.error(err); + process.exit(2); + }); + `; + const { execFileSync } = require('node:child_process'); + try { + execFileSync(process.execPath, ['--input-type=module', '-e', code], { + cwd: __dirname, + env: { + ...process.env, + NG_BUILD_CACHE_STORE: 'lmdb', + }, + }); + } catch (e) { + if (e && typeof e === 'object' && 'message' in e) { + const error = e as { message: string; stderr?: Buffer }; + const output = error.stderr?.toString() || error.message; + if (!output.includes('Unable to initialize JavaScript cache storage')) { + throw e; + } + } else { + throw e; + } + } + }); + }); +}); diff --git a/packages/angular/build/src/utils/check-port.ts b/packages/angular/build/src/utils/check-port.ts new file mode 100644 index 000000000000..7f68c3b266fd --- /dev/null +++ b/packages/angular/build/src/utils/check-port.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { createServer } from 'node:net'; +import { isTTY } from './tty'; + +function createInUseError(port: number): Error { + return new Error(`Port ${port} is already in use. Use '--port' to specify a different port.`); +} + +export async function checkPort(port: number, host: string): Promise { + // A port of 0 requests an OS-assigned ephemeral port. Vite now binds this correctly + // (https://github.com/vitejs/vite/pull/23158); webpack-dev-server always has. + if (port === 0) { + return 0; + } + + return new Promise((resolve, reject) => { + const server = createServer(); + + server + .once('error', (err: NodeJS.ErrnoException) => { + if (err.code !== 'EADDRINUSE') { + reject(err); + + return; + } + + if (!isTTY()) { + reject(createInUseError(port)); + + return; + } + + import('@inquirer/confirm') + .then(({ default: confirm }) => + confirm({ + message: `Port ${port} is already in use.\nWould you like to use a different port?`, + default: true, + theme: { prefix: '' }, + }), + ) + .then( + (answer) => (answer ? resolve(checkPort(0, host)) : reject(createInUseError(port))), + () => reject(createInUseError(port)), + ); + }) + .once('listening', () => { + // Get the actual address from the listening server instance + const address = server.address(); + assert( + address && typeof address !== 'string', + 'Port check server address should always be an object.', + ); + + server.close(); + resolve(address.port); + }) + .listen(port, host); + }); +} diff --git a/packages/angular/build/src/utils/color.ts b/packages/angular/build/src/utils/color.ts new file mode 100644 index 000000000000..3915d99ce248 --- /dev/null +++ b/packages/angular/build/src/utils/color.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { WriteStream } from 'node:tty'; + +export { color as colors, figures } from 'listr2'; + +export function supportColor(stream: NodeJS.WritableStream = process.stdout): boolean { + if (stream instanceof WriteStream) { + return stream.hasColors(); + } + + try { + // The hasColors function does not rely on any instance state and should ideally be static + return WriteStream.prototype.hasColors(); + } catch { + return process.env['FORCE_COLOR'] !== undefined && process.env['FORCE_COLOR'] !== '0'; + } +} diff --git a/packages/angular/build/src/utils/concurrency.ts b/packages/angular/build/src/utils/concurrency.ts new file mode 100644 index 000000000000..39f2b70c95df --- /dev/null +++ b/packages/angular/build/src/utils/concurrency.ts @@ -0,0 +1,98 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * Maximum number of concurrent file system read/stat operations to prevent OS file descriptor exhaustion. + */ +export const MAX_CONCURRENT_READS = 16; + +/** + * Executes an asynchronous function for each item in an array concurrently up to a specified limit. + * + * If any task fails, processing of subsequent items stops and the first encountered error is re-thrown + * after all currently in-flight tasks have settled. + * + * @param items Array of items to process. + * @param limit Maximum number of concurrent tasks in flight. + * @param fn Async task function. + */ +export async function runConcurrent( + items: readonly T[], + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + if (items.length === 0) { + return; + } + + let index = 0; + let firstError: unknown; + + const concurrency = Math.min(Math.max(1, Math.floor(limit) || 1), items.length); + const workers = Array.from({ length: concurrency }, async () => { + while (!firstError && index < items.length) { + const i = index++; + try { + await fn(items[i], i); + } catch (error) { + firstError ??= error; + } + } + }); + + await Promise.allSettled(workers); + + if (firstError) { + throw firstError; + } +} + +/** + * Maps an array asynchronously with a sliding worker pool up to a specified concurrency limit. + * + * If any task fails, processing of subsequent items stops and the first encountered error is re-thrown + * after all currently in-flight tasks have settled. + * + * @param items Array of items to map. + * @param limit Maximum number of concurrent tasks in flight. + * @param fn Async mapper function. + * @returns Array of mapped results in the original item order. + */ +export async function mapConcurrent( + items: readonly T[], + limit: number, + fn: (item: T, index: number) => Promise, +): Promise { + if (items.length === 0) { + return []; + } + + const results: R[] = new Array(items.length); + let index = 0; + let firstError: unknown; + + const concurrency = Math.min(Math.max(1, Math.floor(limit) || 1), items.length); + const workers = Array.from({ length: concurrency }, async () => { + while (!firstError && index < items.length) { + const i = index++; + try { + results[i] = await fn(items[i], i); + } catch (error) { + firstError ??= error; + } + } + }); + + await Promise.allSettled(workers); + + if (firstError) { + throw firstError; + } + + return results; +} diff --git a/packages/angular/build/src/utils/concurrency_spec.ts b/packages/angular/build/src/utils/concurrency_spec.ts new file mode 100644 index 000000000000..ab63054046c5 --- /dev/null +++ b/packages/angular/build/src/utils/concurrency_spec.ts @@ -0,0 +1,212 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { mapConcurrent, runConcurrent } from './concurrency'; + +describe('concurrency utilities', () => { + describe('runConcurrent', () => { + it('should process all items in an array', async () => { + const items = [1, 2, 3, 4, 5]; + const processed: number[] = []; + + await runConcurrent(items, 2, async (item) => { + processed.push(item); + }); + + expect(processed.sort((a, b) => a - b)).toEqual(items); + }); + + it('should respect the concurrency limit', async () => { + const items = [10, 20, 30, 40, 50, 60]; + const limit = 2; + let active = 0; + let maxActive = 0; + + await runConcurrent(items, limit, async () => { + active++; + maxActive = Math.max(maxActive, active); + await new Promise((resolve) => setTimeout(resolve, 10)); + active--; + }); + + expect(maxActive).toBeLessThanOrEqual(limit); + }); + + it('should handle non-integer and NaN limits', async () => { + const items = [1, 2, 3]; + const processed: number[] = []; + + await runConcurrent(items, 2.7, async (item) => { + processed.push(item); + }); + expect(processed).toEqual(items); + + const processedNaN: number[] = []; + await runConcurrent(items, NaN, async (item) => { + processedNaN.push(item); + }); + expect(processedNaN).toEqual(items); + }); + + it('should handle an empty array', async () => { + let called = false; + await runConcurrent([], 3, async () => { + called = true; + }); + + expect(called).toBe(false); + }); + + it('should pass item and index to callback', async () => { + const items = ['a', 'b', 'c']; + const passed: { item: string; index: number }[] = []; + + await runConcurrent(items, 2, async (item, index) => { + passed.push({ item, index }); + }); + + expect(passed.sort((a, b) => a.index - b.index)).toEqual([ + { item: 'a', index: 0 }, + { item: 'b', index: 1 }, + { item: 'c', index: 2 }, + ]); + }); + + it('should stop processing new items and rethrow the first error', async () => { + const items = [1, 2, 3, 4, 5, 6]; + const executed: number[] = []; + + await expectAsync( + runConcurrent(items, 1, async (item) => { + executed.push(item); + if (item === 2) { + throw new Error('Task failed'); + } + }), + ).toBeRejectedWithError('Task failed'); + + // Subsequent items should not have been executed + expect(executed).toEqual([1, 2]); + }); + + it('should wait for in-flight tasks to settle when an error occurs', async () => { + const items = [1, 2, 3, 4]; + let task2Finished = false; + + await expectAsync( + runConcurrent(items, 2, async (item) => { + if (item === 1) { + throw new Error('Task 1 failed'); + } + if (item === 2) { + await new Promise((resolve) => setTimeout(resolve, 20)); + task2Finished = true; + } + }), + ).toBeRejectedWithError('Task 1 failed'); + + expect(task2Finished).toBe(true); + }); + }); + + describe('mapConcurrent', () => { + it('should map items and return results in original order', async () => { + const items = [1, 2, 3, 4, 5]; + + const results = await mapConcurrent(items, 2, async (item) => { + // Add varying delay so tasks finish out of order + await new Promise((resolve) => setTimeout(resolve, (5 - item) * 5)); + + return item * 2; + }); + + expect(results).toEqual([2, 4, 6, 8, 10]); + }); + + it('should respect the concurrency limit', async () => { + const items = [1, 2, 3, 4, 5]; + const limit = 2; + let active = 0; + let maxActive = 0; + + await mapConcurrent(items, limit, async (item) => { + active++; + maxActive = Math.max(maxActive, active); + await new Promise((resolve) => setTimeout(resolve, 10)); + active--; + + return item; + }); + + expect(maxActive).toBeLessThanOrEqual(limit); + }); + + it('should handle non-integer and NaN limits', async () => { + const items = [1, 2, 3]; + + const results = await mapConcurrent(items, 2.7, async (item) => item * 2); + expect(results).toEqual([2, 4, 6]); + + const resultsNaN = await mapConcurrent(items, NaN, async (item) => item * 2); + expect(resultsNaN).toEqual([2, 4, 6]); + }); + + it('should handle an empty array', async () => { + const results = await mapConcurrent([], 3, async (item) => item); + + expect(results).toEqual([]); + }); + + it('should pass item and index to mapper function', async () => { + const items = ['x', 'y', 'z']; + + const results = await mapConcurrent(items, 2, async (item, index) => `${item}:${index}`); + + expect(results).toEqual(['x:0', 'y:1', 'z:2']); + }); + + it('should stop processing new items and rethrow the first error', async () => { + const items = [1, 2, 3, 4, 5, 6]; + const executed: number[] = []; + + await expectAsync( + mapConcurrent(items, 1, async (item) => { + executed.push(item); + if (item === 2) { + throw new Error('Map failed'); + } + + return item; + }), + ).toBeRejectedWithError('Map failed'); + + expect(executed).toEqual([1, 2]); + }); + + it('should wait for in-flight tasks to settle when an error occurs', async () => { + const items = [1, 2, 3, 4]; + let task2Finished = false; + + await expectAsync( + mapConcurrent(items, 2, async (item) => { + if (item === 1) { + throw new Error('Map 1 failed'); + } + if (item === 2) { + await new Promise((resolve) => setTimeout(resolve, 20)); + task2Finished = true; + } + + return item; + }), + ).toBeRejectedWithError('Map 1 failed'); + + expect(task2Finished).toBe(true); + }); + }); +}); diff --git a/packages/angular/build/src/utils/debug-id.ts b/packages/angular/build/src/utils/debug-id.ts new file mode 100644 index 000000000000..a03fd571ec72 --- /dev/null +++ b/packages/angular/build/src/utils/debug-id.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createHash } from 'node:crypto'; + +/** + * Fixed RFC 4122 namespace UUID used to derive deterministic UUIDv5 build/Debug IDs. + * Treated as 16 raw bytes when fed into the SHA-1 of `namespace || name`. + * + * The exact value is arbitrary but must remain stable across releases so that + * the same source map content always yields the same Debug ID. + */ +const ANGULAR_BUILD_NAMESPACE = Buffer.from('6f9619ff8b86d011b42d00cf4fc964ff', 'hex'); + +/** + * Generates a deterministic UUIDv5 (RFC 4122 §4.3) Debug ID from the given name bytes. + * + * Determinism is recommended by the ECMA-426 "Source Map Debug ID" proposal + * (https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md) so that the + * produced artifacts are stable across builds with the same source content. + * + * @param name Bytes that uniquely identify the artifact (typically the source map content). + * @returns A canonical UUIDv5 string (lowercase, hyphenated). + */ +export function generateDebugId(name: string | Uint8Array): string { + const sha = createHash('sha1').update(ANGULAR_BUILD_NAMESPACE).update(name).digest(); + + // Set version (5) in the high nibble of byte 6. + sha[6] = (sha[6] & 0x0f) | 0x50; + // Set RFC 4122 variant bits (10xx) in byte 8. + sha[8] = (sha[8] & 0x3f) | 0x80; + + const h = sha.toString('hex'); + + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`; +} + +/** Pattern matching an existing `//# debugId=` comment at the end of the file. */ +const DEBUG_ID_COMMENT = /(\n\/\/# debugId=[^\r\n]*)(\n\/\/# sourceMappingURL=[^\r\n]*)?(\s*)$/; + +/** Pattern matching the `//# sourceMappingURL=` comment, used to position the debug-id line. */ +const SOURCE_MAPPING_URL_COMMENT = /\n\/\/# sourceMappingURL=[^\r\n]*\s*$/; + +/** + * Inserts (or replaces) a `//# debugId=` comment in the given JavaScript text. + * + * Per ECMA-426, the comment must appear within the last 5 lines and SHOULD be + * placed immediately above any `//# sourceMappingURL=` comment so that existing + * tools that only consult the final line still find the source-map URL. + */ +export function injectDebugIdIntoJs(text: string, id: string): string { + const comment = `//# debugId=${id}`; + + // Replace any existing debugId comment to keep the operation idempotent. + if (DEBUG_ID_COMMENT.test(text)) { + return text.replace(DEBUG_ID_COMMENT, (_, p1, p2, p3) => `\n${comment}${p2 || ''}${p3 || ''}`); + } + + if (SOURCE_MAPPING_URL_COMMENT.test(text)) { + return text.replace(SOURCE_MAPPING_URL_COMMENT, (match) => `\n${comment}${match}`); + } + + // No source map reference; append at the very end on its own line. + return text.endsWith('\n') ? `${text}${comment}\n` : `${text}\n${comment}\n`; +} + +/** + * Sets the top-level `debugId` field on a JSON source map. + * + * Per ECMA-426, source maps embed the same Debug ID under a `debugId` key so + * that consumers can pair a generated file with its source map without relying + * on URL/path conventions. + */ +export function injectDebugIdIntoSourceMap(json: string, id: string): string { + let parsed: Record; + try { + parsed = JSON.parse(json) as Record; + } catch { + // Source map is malformed; do not corrupt it further. + return json; + } + + if (parsed['debugId'] === id) { + return json; + } + + parsed['debugId'] = id; + + // Preserve existing pretty-print indentation when the source map is formatted. + const indent = json.match(/^[^{]*{\r?\n([ \t]+)/)?.[1]; + + return JSON.stringify(parsed, null, indent); +} + +/** + * Strips any existing `debugId` field from the source map JSON string to restore + * the original JSON contents for deterministic/idempotent hashing. + */ +export function stripDebugIdFromSourceMap(json: string): string { + return json.replace(/,\s*"debugId"\s*:\s*"[^"]*"|\s*"debugId"\s*:\s*"[^"]*"\s*,?/g, ''); +} diff --git a/packages/angular/build/src/utils/debug-id_spec.ts b/packages/angular/build/src/utils/debug-id_spec.ts new file mode 100644 index 000000000000..f254e28f6eee --- /dev/null +++ b/packages/angular/build/src/utils/debug-id_spec.ts @@ -0,0 +1,137 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + generateDebugId, + injectDebugIdIntoJs, + injectDebugIdIntoSourceMap, + stripDebugIdFromSourceMap, +} from './debug-id'; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +describe('debug-id', () => { + describe('generateDebugId', () => { + it('produces a canonical UUIDv5 string', () => { + expect(generateDebugId('hello')).toMatch(UUID); + expect(generateDebugId(new TextEncoder().encode('hello'))).toMatch(UUID); + }); + + it('is deterministic for identical inputs', () => { + expect(generateDebugId('same content')).toBe(generateDebugId('same content')); + }); + + it('differs for different inputs', () => { + expect(generateDebugId('one')).not.toBe(generateDebugId('two')); + }); + }); + + describe('injectDebugIdIntoJs', () => { + const id = '11111111-2222-5333-9444-555555555555'; + + it('inserts the debugId comment immediately above sourceMappingURL', () => { + const text = 'console.log(1);\n//# sourceMappingURL=foo.js.map\n'; + const result = injectDebugIdIntoJs(text, id); + expect(result).toBe( + 'console.log(1);\n//# debugId=11111111-2222-5333-9444-555555555555\n//# sourceMappingURL=foo.js.map\n', + ); + }); + + it('appends the comment when no sourceMappingURL is present', () => { + const text = 'console.log(1);\n'; + const result = injectDebugIdIntoJs(text, id); + expect(result).toBe('console.log(1);\n//# debugId=11111111-2222-5333-9444-555555555555\n'); + }); + + it('appends a leading newline when input does not end with one', () => { + const text = 'console.log(1);'; + const result = injectDebugIdIntoJs(text, id); + expect(result).toBe('console.log(1);\n//# debugId=11111111-2222-5333-9444-555555555555\n'); + }); + + it('replaces an existing debugId comment (idempotent)', () => { + const original = + 'console.log(1);\n//# debugId=00000000-0000-5000-8000-000000000000\n//# sourceMappingURL=foo.js.map\n'; + const result = injectDebugIdIntoJs(original, id); + expect(result).toBe( + 'console.log(1);\n//# debugId=11111111-2222-5333-9444-555555555555\n//# sourceMappingURL=foo.js.map\n', + ); + // Re-running with the same id is a no-op. + expect(injectDebugIdIntoJs(result, id)).toBe(result); + }); + + it('does not replace a debugId comment that is inside a string or template literal', () => { + const text = + 'const t = `\n//# debugId=00000000-0000-5000-8000-000000000000\n`;\n//# sourceMappingURL=foo.js.map\n'; + const result = injectDebugIdIntoJs(text, id); + expect(result).toBe( + 'const t = `\n//# debugId=00000000-0000-5000-8000-000000000000\n`;\n' + + `//# debugId=${id}\n` + + '//# sourceMappingURL=foo.js.map\n', + ); + }); + }); + + describe('injectDebugIdIntoSourceMap', () => { + const id = '11111111-2222-5333-9444-555555555555'; + + it('adds a top-level debugId field', () => { + const map = JSON.stringify({ version: 3, sources: ['a.ts'], mappings: '' }); + const updated = JSON.parse(injectDebugIdIntoSourceMap(map, id)); + expect(updated.debugId).toBe(id); + expect(updated.version).toBe(3); + }); + + it('overwrites an existing debugId field', () => { + const map = JSON.stringify({ version: 3, debugId: 'old', mappings: '' }); + const updated = JSON.parse(injectDebugIdIntoSourceMap(map, id)); + expect(updated.debugId).toBe(id); + }); + + it('returns the original input when debugId already matches', () => { + const map = + '{\n "version": 3,\n "debugId": "11111111-2222-5333-9444-555555555555",\n "mappings": ""\n}'; + expect(injectDebugIdIntoSourceMap(map, id)).toBe(map); + }); + + it('preserves indentation when updating a pretty-printed source map', () => { + const map = '{\n\t"version": 3,\n\t"mappings": ""\n}'; + expect(injectDebugIdIntoSourceMap(map, id)).toBe( + '{\n\t"version": 3,\n\t"mappings": "",\n\t"debugId": "11111111-2222-5333-9444-555555555555"\n}', + ); + }); + + it('returns the original input when JSON is malformed', () => { + const malformed = '{ this is not json'; + expect(injectDebugIdIntoSourceMap(malformed, id)).toBe(malformed); + }); + }); + + describe('stripDebugIdFromSourceMap', () => { + it('removes the debugId field from pretty-printed source maps', () => { + const original = '{\n\t"version": 3,\n\t"mappings": ""\n}'; + const updated = + '{\n\t"version": 3,\n\t"mappings": "",\n\t"debugId": "11111111-2222-5333-9444-555555555555"\n}'; + expect(stripDebugIdFromSourceMap(updated)).toBe(original); + }); + + it('removes the debugId field from minified source maps', () => { + const original = '{"version":3,"mappings":""}'; + const updated = + '{"version":3,"mappings":"","debugId":"11111111-2222-5333-9444-555555555555"}'; + expect(stripDebugIdFromSourceMap(updated)).toBe(original); + }); + + it('removes the debugId field when it is the first property', () => { + const original = '{\n\t"version": 3,\n\t"mappings": ""\n}'; + const updated = + '{\n\t"debugId": "11111111-2222-5333-9444-555555555555",\n\t"version": 3,\n\t"mappings": ""\n}'; + expect(stripDebugIdFromSourceMap(updated)).toBe(original); + }); + }); +}); diff --git a/packages/angular/build/src/utils/delete-output-dir.ts b/packages/angular/build/src/utils/delete-output-dir.ts new file mode 100644 index 000000000000..1f676e77b759 --- /dev/null +++ b/packages/angular/build/src/utils/delete-output-dir.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readdir, rm } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; + +/** + * Delete an output directory, but error out if it's the root of the project. + */ +export async function deleteOutputDir( + root: string, + outputPath: string, + emptyOnlyDirectories?: string[], +): Promise { + const resolvedRoot = resolve(root); + const resolvedOutputPath = resolve(resolvedRoot, outputPath); + if (resolvedOutputPath === resolvedRoot) { + throw new Error('Output path MUST not be project root directory!'); + } + + const directoriesToEmpty = emptyOnlyDirectories + ? new Set(emptyOnlyDirectories.map((directory) => join(resolvedOutputPath, directory))) + : undefined; + + // Avoid removing the actual directory to avoid errors in cases where the output + // directory is mounted or symlinked. Instead the contents are removed. + let entries; + try { + entries = await readdir(resolvedOutputPath); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return; + } + throw error; + } + + for (const entry of entries) { + const fullEntry = join(resolvedOutputPath, entry); + + // Leave requested directories. This allows symlinks to continue to function. + if (directoriesToEmpty?.has(fullEntry)) { + await deleteOutputDir(resolvedOutputPath, fullEntry); + continue; + } + + await rm(fullEntry, { force: true, recursive: true, maxRetries: 3 }); + } +} diff --git a/packages/angular/build/src/utils/disk-files.ts b/packages/angular/build/src/utils/disk-files.ts new file mode 100644 index 000000000000..dbbe34ee919e --- /dev/null +++ b/packages/angular/build/src/utils/disk-files.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { constants, cp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { runConcurrent } from './concurrency'; + +/** + * Maximum number of concurrent file system write/copy operations to avoid open file descriptor exhaustion. + */ +const MAX_CONCURRENT_OPS = 64; + +/** + * Represents a file that can be emitted to disk from memory or copied from an existing path on disk. + */ +export type EmittableFile = + { origin: 'memory'; contents: string | Uint8Array } | { origin: 'disk'; source: string }; + +/** + * Writes or copies a collection of files to disk with bounded concurrency, + * ensuring parent directories are created once per invocation. + * + * @param files The collection of files to emit. + * @param resolveDestinationPath Callback returning the absolute destination path for a file, or `undefined` to skip it. + */ +export async function emitFilesToDisk( + files: readonly T[], + resolveDestinationPath: (file: T) => string | undefined, +): Promise { + if (files.length === 0) { + return; + } + + const directoryCreationPromises = new Map>(); + + await runConcurrent(files, MAX_CONCURRENT_OPS, async (file) => { + const fullFilePath = resolveDestinationPath(file); + if (!fullFilePath) { + return; + } + + // Ensure output subdirectories exist + const fileBasePath = dirname(fullFilePath); + if (fileBasePath) { + let mkdirPromise = directoryCreationPromises.get(fileBasePath); + if (!mkdirPromise) { + mkdirPromise = mkdir(fileBasePath, { recursive: true }); + directoryCreationPromises.set(fileBasePath, mkdirPromise); + } + await mkdirPromise; + } + + if (file.origin === 'memory') { + // Write file contents + await writeFile(fullFilePath, file.contents); + + return; + } + + // Copy file contents + await cp(file.source, fullFilePath, { + mode: constants.COPYFILE_FICLONE, + preserveTimestamps: true, + }); + }); +} + +/** + * Deletes a collection of files from disk with bounded concurrency. + * @param files The collection of files to delete. + */ +export async function deleteFilesFromDisk(files: readonly string[]): Promise { + if (files.length === 0) { + return; + } + + await runConcurrent(files, MAX_CONCURRENT_OPS, (file) => rm(file, { force: true })); +} diff --git a/packages/angular/build/src/utils/disk-files_spec.ts b/packages/angular/build/src/utils/disk-files_spec.ts new file mode 100644 index 000000000000..4a9422bd4373 --- /dev/null +++ b/packages/angular/build/src/utils/disk-files_spec.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { existsSync } from 'node:fs'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { type EmittableFile, deleteFilesFromDisk, emitFilesToDisk } from './disk-files'; + +describe('disk-files', () => { + let tempRoot: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-disk-files-test-')); + }); + + afterEach(async () => { + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }); + } + }); + + describe('emitFilesToDisk', () => { + it('should write memory files and copy disk files while creating nested directories', async () => { + const sourceFile = join(tempRoot, 'source-asset.txt'); + await writeFile(sourceFile, 'from-disk'); + + const files: (EmittableFile & { path: string })[] = [ + { + origin: 'memory', + path: 'nested/a/mem1.txt', + contents: new TextEncoder().encode('mem-1'), + }, + { origin: 'memory', path: 'nested/a/mem2.txt', contents: 'mem-2' }, + { origin: 'disk', path: 'nested/b/disk1.txt', source: sourceFile }, + { origin: 'disk', path: 'nested/c/disk2.txt', source: sourceFile }, + { origin: 'memory', path: 'skipped/file.txt', contents: 'should-not-exist' }, + ]; + + const outDir = join(tempRoot, 'out'); + await emitFilesToDisk(files, (file) => + file.path.startsWith('skipped/') ? undefined : join(outDir, file.path), + ); + + expect(await readFile(join(outDir, 'nested/a/mem1.txt'), 'utf-8')).toBe('mem-1'); + expect(await readFile(join(outDir, 'nested/a/mem2.txt'), 'utf-8')).toBe('mem-2'); + expect(await readFile(join(outDir, 'nested/b/disk1.txt'), 'utf-8')).toBe('from-disk'); + expect(await readFile(join(outDir, 'nested/c/disk2.txt'), 'utf-8')).toBe('from-disk'); + expect(existsSync(join(outDir, 'skipped/file.txt'))).toBeFalse(); + }); + }); + + describe('deleteFilesFromDisk', () => { + it('should delete existing files and ignore non-existent files', async () => { + const fileA = join(tempRoot, 'a.txt'); + const fileB = join(tempRoot, 'b.txt'); + const nonExistent = join(tempRoot, 'missing.txt'); + + await writeFile(fileA, 'a'); + await writeFile(fileB, 'b'); + + await deleteFilesFromDisk([fileA, nonExistent]); + + expect(existsSync(fileA)).toBeFalse(); + expect(existsSync(fileB)).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/utils/environment-options.ts b/packages/angular/build/src/utils/environment-options.ts new file mode 100644 index 000000000000..d87c104aba65 --- /dev/null +++ b/packages/angular/build/src/utils/environment-options.ts @@ -0,0 +1,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 + */ + +import { availableParallelism } from 'node:os'; + +/** A set of strings that are considered "truthy" when parsing environment variables. */ +const TRUTHY_VALUES = new Set(['1', 'true']); + +/** A set of strings that are considered "falsy" when parsing environment variables. */ +const FALSY_VALUES = new Set(['0', 'false']); + +/** + * Checks if an environment variable is present and has a non-empty value. + * @param variable The environment variable to check. + * @returns `true` if the variable is a non-empty string. + */ +function isPresent(variable: string | undefined): variable is string { + return typeof variable === 'string' && variable !== ''; +} + +/** + * Parses an environment variable into a boolean or undefined. + * @returns `true` if the variable is truthy ('1', 'true'). + * @returns `false` if the variable is falsy ('0', 'false'). + * @returns `undefined` if the variable is not present or has an unknown value. + */ +function parseTristate(variable: string | undefined): boolean | undefined { + if (!isPresent(variable)) { + return undefined; + } + + const value = variable.toLowerCase(); + if (TRUTHY_VALUES.has(value)) { + return true; + } + if (FALSY_VALUES.has(value)) { + return false; + } + + // TODO: Consider whether a warning is useful in this case of a malformed value + return undefined; +} + +// Optimization and mangling +const debugOptimizeVariable = process.env['NG_BUILD_DEBUG_OPTIMIZE']; +const debugOptimize = (() => { + if (!isPresent(debugOptimizeVariable) || parseTristate(debugOptimizeVariable) === false) { + return { + mangle: true, + minify: true, + beautify: false, + }; + } + + const debugValue = { + mangle: false, + minify: false, + beautify: true, + }; + + if (parseTristate(debugOptimizeVariable) === true) { + return debugValue; + } + + for (const part of debugOptimizeVariable.split(',')) { + switch (part.trim().toLowerCase()) { + case 'mangle': + debugValue.mangle = true; + break; + case 'minify': + debugValue.minify = true; + break; + case 'beautify': + debugValue.beautify = true; + break; + } + } + + return debugValue; +})(); + +/** + * Allows disabling of code mangling when the `NG_BUILD_MANGLE` environment variable is set to `0` or `false`. + * This is useful for debugging build output. + */ +export const allowMangle = parseTristate(process.env['NG_BUILD_MANGLE']) ?? debugOptimize.mangle; + +/** + * Allows beautification of build output when the `NG_BUILD_DEBUG_OPTIMIZE` environment variable is enabled. + * This is useful for debugging build output. + */ +export const shouldBeautify = debugOptimize.beautify; + +/** + * Allows disabling of code minification when the `NG_BUILD_DEBUG_OPTIMIZE` environment variable is enabled. + * This is useful for debugging build output. + */ +export const allowMinify = debugOptimize.minify; + +/** + * Allows using Rolldown for chunk optimization instead of Rollup. + * This is useful for debugging and testing scenarios. + */ +export const useRolldownChunks = parseTristate(process.env['NG_BUILD_CHUNKS_ROLLDOWN']) ?? true; + +const maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS']; + +let customMaxWorkers: number | undefined; +if (isPresent(maxWorkersVariable)) { + const parsed = +maxWorkersVariable; + if (Number.isInteger(parsed) && parsed >= 1) { + customMaxWorkers = parsed; + } +} + +/** + * Whether the maximum number of workers was explicitly configured via the + * `NG_BUILD_MAX_WORKERS` environment variable. + */ +export const hasCustomMaxWorkers = customMaxWorkers !== undefined; + +/** + * The maximum number of workers to use for parallel processing. + * This can be controlled by the `NG_BUILD_MAX_WORKERS` environment variable. + * When not set, defaults to available parallelism minus one to ensure the main thread is not starved. + */ +export const maxWorkers = customMaxWorkers ?? Math.max(availableParallelism() - 1, 1); + +/** + * The maximum number of workers to use for JavaScript transformations during bundling. + * Transformation tasks are short-lived, and esbuild concurrently utilizes all CPU cores + * for bundling. To prevent CPU starvation and thread startup overhead, concurrency is + * budgeted to a fraction of available cores, capped at 6, unless overridden by + * `NG_BUILD_MAX_WORKERS`. + */ +export const maxTransformWorkers = + customMaxWorkers ?? Math.max(1, Math.min(6, Math.floor(availableParallelism() / 4))); + +/** + * The maximum number of workers to use for i18n translation inlining. + * Translation inlining and sourcemap remapping are CPU- and memory-intensive operations. + * To prevent thread oversubscription, memory allocator lock contention, and high-core + * performance degradation, concurrency is capped at 8 unless overridden by + * `NG_BUILD_MAX_WORKERS`. + */ +export const maxInlinerWorkers = customMaxWorkers ?? Math.min(8, availableParallelism()); + +/** + * When `NG_BUILD_PARALLEL_TS` is set to `0` or `false`, parallel TypeScript compilation is disabled. + */ +export const useParallelTs = parseTristate(process.env['NG_BUILD_PARALLEL_TS']) !== false; + +/** + * When `NG_BUILD_DEBUG_PERF` is enabled, performance debugging information is printed. + */ +export const debugPerformance = parseTristate(process.env['NG_BUILD_DEBUG_PERF']) === true; + +/** + * When `NG_BUILD_WATCH_ROOT` is enabled, the build will watch the root directory for changes. + */ +export const shouldWatchRoot = parseTristate(process.env['NG_BUILD_WATCH_ROOT']) === true; + +/** + * When `NG_BUILD_TYPE_CHECK` is set to `0` or `false`, type checking is disabled. + */ +export const useTypeChecking = parseTristate(process.env['NG_BUILD_TYPE_CHECK']) !== false; + +/** + * When `NG_BUILD_LOGS_JSON` is enabled, build logs will be output in JSON format. + */ +export const useJSONBuildLogs = parseTristate(process.env['NG_BUILD_LOGS_JSON']) === true; + +/** + * When `NG_BUILD_OPTIMIZE_CHUNKS` is enabled, the build will optimize chunks. + */ +/** + * The threshold of lazy chunks required to enable the chunk optimization pass. + * Can be configured via the `NG_BUILD_OPTIMIZE_CHUNKS` environment variable. + * - `false` or `0` disables the feature. + * - `true` or `1` forces the feature on (threshold 0). + * - A number sets the specific threshold. + * - Default is 3. + */ +const optimizeChunksEnv = process.env['NG_BUILD_OPTIMIZE_CHUNKS']; +export const optimizeChunksThreshold = (() => { + if (optimizeChunksEnv === undefined) { + return 3; + } + if (optimizeChunksEnv === 'false' || optimizeChunksEnv === '0') { + return Infinity; + } + if (optimizeChunksEnv === 'true' || optimizeChunksEnv === '1') { + return 0; + } + const num = Number.parseInt(optimizeChunksEnv, 10); + + return Number.isNaN(num) || num < 0 ? 3 : num; +})(); + +/** + * When `NG_HMR_CSTYLES` is enabled, component styles will be hot-reloaded. + */ +export const useComponentStyleHmr = parseTristate(process.env['NG_HMR_CSTYLES']) === true; + +/** + * When `NG_HMR_TEMPLATES` is set to `0` or `false`, component templates will not be hot-reloaded. + */ +export const useComponentTemplateHmr = parseTristate(process.env['NG_HMR_TEMPLATES']) !== false; + +/** + * When `NG_BUILD_PARTIAL_SSR` is enabled, a partial server-side rendering build will be performed. + */ +export const usePartialSsrBuild = parseTristate(process.env['NG_BUILD_PARTIAL_SSR']) === true; + +/** + * When `NG_BUILD_BABEL_LINKER` is enabled (`1` or `true`), the Babel-based + * Angular Linker (`@angular/compiler-cli/linker/babel`) will be used instead of the + * default OXC in-place linker. + */ +export const useBabelLinker = parseTristate(process.env['NG_BUILD_BABEL_LINKER']) === true; + +/** + * When `NG_BUILD_SASS_EMBEDDED` is set to `0` or `false`, or when running within a + * WebContainer environment, the native embedded Sass compiler is disabled + * and the pure-JavaScript Sass compiler is used instead. + */ +export const useSassEmbedded = + !process.versions.webcontainer && parseTristate(process.env['NG_BUILD_SASS_EMBEDDED']) !== false; + +const bazelBinDirectory = process.env['BAZEL_BINDIR']; +const bazelExecRoot = process.env['JS_BINARY__EXECROOT']; + +export const bazelEsbuildPluginPath = + bazelBinDirectory && bazelExecRoot + ? process.env['NG_INTERNAL_ESBUILD_PLUGINS_DO_NOT_USE'] + : undefined; + +/** + * The persistent cache store configuration to use. + * Managed by the `NG_BUILD_CACHE_STORE` environment variable. + * - 'lmdb': Forces the use of LMDB. + * - 'sqlite': Forces the use of SQLite. + * - undefined / 'auto' / other: Automatically uses LMDB and falls back to SQLite. + */ +export const persistentCacheStoreSetting = (() => { + const env = process.env['NG_BUILD_CACHE_STORE']?.trim().toLowerCase(); + if (env === 'lmdb' || env === 'sqlite') { + return env; + } + + return undefined; +})(); diff --git a/packages/angular/build/src/utils/environment-options_spec.ts b/packages/angular/build/src/utils/environment-options_spec.ts new file mode 100644 index 000000000000..4ad098a24763 --- /dev/null +++ b/packages/angular/build/src/utils/environment-options_spec.ts @@ -0,0 +1,247 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { availableParallelism } from 'node:os'; + +describe('environment options - maxWorkers', () => { + const originalEnvValue = process.env['NG_BUILD_MAX_WORKERS']; + + function loadEnvironmentOptions(): typeof import('./environment-options') { + delete require.cache[require.resolve('./environment-options')]; + + return require('./environment-options'); + } + + afterEach(() => { + if (originalEnvValue !== undefined) { + process.env['NG_BUILD_MAX_WORKERS'] = originalEnvValue; + } else { + delete process.env['NG_BUILD_MAX_WORKERS']; + } + delete require.cache[require.resolve('./environment-options')]; + }); + + it('defaults maxWorkers to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is unset', () => { + delete process.env['NG_BUILD_MAX_WORKERS']; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('uses configured positive integer when NG_BUILD_MAX_WORKERS is set', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '8'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeTrue(); + expect(maxWorkers).toBe(8); + }); + + it('allows maxWorkers greater than 4 when explicitly configured', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '32'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeTrue(); + expect(maxWorkers).toBe(32); + }); + + it('supports maxWorkers set to 1', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '1'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeTrue(); + expect(maxWorkers).toBe(1); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is 0', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '0'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is negative', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '-4'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is not a number', () => { + process.env['NG_BUILD_MAX_WORKERS'] = 'invalid'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is a float', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '2.5'; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is an empty string', () => { + process.env['NG_BUILD_MAX_WORKERS'] = ''; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('falls back to availableParallelism - 1 when NG_BUILD_MAX_WORKERS is whitespace only', () => { + process.env['NG_BUILD_MAX_WORKERS'] = ' '; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeFalse(); + expect(maxWorkers).toBe(Math.max(availableParallelism() - 1, 1)); + }); + + it('parses positive integers with surrounding whitespace', () => { + process.env['NG_BUILD_MAX_WORKERS'] = ' 8 '; + const { maxWorkers, hasCustomMaxWorkers } = loadEnvironmentOptions(); + + expect(hasCustomMaxWorkers).toBeTrue(); + expect(maxWorkers).toBe(8); + }); +}); + +describe('environment options - maxTransformWorkers', () => { + const originalEnvValue = process.env['NG_BUILD_MAX_WORKERS']; + + function loadEnvironmentOptions(): typeof import('./environment-options') { + delete require.cache[require.resolve('./environment-options')]; + + return require('./environment-options'); + } + + afterEach(() => { + if (originalEnvValue !== undefined) { + process.env['NG_BUILD_MAX_WORKERS'] = originalEnvValue; + } else { + delete process.env['NG_BUILD_MAX_WORKERS']; + } + delete require.cache[require.resolve('./environment-options')]; + }); + + it('defaults maxTransformWorkers to availableParallelism / 4 (bounded between 1 and 6) when NG_BUILD_MAX_WORKERS is unset', () => { + delete process.env['NG_BUILD_MAX_WORKERS']; + const { maxTransformWorkers } = loadEnvironmentOptions(); + + const expected = Math.max(1, Math.min(6, Math.floor(availableParallelism() / 4))); + expect(maxTransformWorkers).toBe(expected); + }); + + it('uses configured positive integer when NG_BUILD_MAX_WORKERS is set', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '8'; + const { maxTransformWorkers } = loadEnvironmentOptions(); + + expect(maxTransformWorkers).toBe(8); + }); + + it('allows maxTransformWorkers greater than 6 when explicitly configured', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '32'; + const { maxTransformWorkers } = loadEnvironmentOptions(); + + expect(maxTransformWorkers).toBe(32); + }); + + it('supports maxTransformWorkers set to 1', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '1'; + const { maxTransformWorkers } = loadEnvironmentOptions(); + + expect(maxTransformWorkers).toBe(1); + }); + + it('falls back to default calculation when NG_BUILD_MAX_WORKERS is 0 or negative', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '0'; + const { maxTransformWorkers: zeroWorkers } = loadEnvironmentOptions(); + const expected = Math.max(1, Math.min(6, Math.floor(availableParallelism() / 4))); + expect(zeroWorkers).toBe(expected); + + process.env['NG_BUILD_MAX_WORKERS'] = '-4'; + const { maxTransformWorkers: negativeWorkers } = loadEnvironmentOptions(); + expect(negativeWorkers).toBe(expected); + }); + + it('falls back to default calculation when NG_BUILD_MAX_WORKERS is invalid', () => { + process.env['NG_BUILD_MAX_WORKERS'] = 'invalid'; + const { maxTransformWorkers } = loadEnvironmentOptions(); + const expected = Math.max(1, Math.min(6, Math.floor(availableParallelism() / 4))); + + expect(maxTransformWorkers).toBe(expected); + }); +}); + +describe('environment options - maxInlinerWorkers', () => { + const originalEnvValue = process.env['NG_BUILD_MAX_WORKERS']; + + function loadEnvironmentOptions(): typeof import('./environment-options') { + delete require.cache[require.resolve('./environment-options')]; + + return require('./environment-options'); + } + + afterEach(() => { + if (originalEnvValue !== undefined) { + process.env['NG_BUILD_MAX_WORKERS'] = originalEnvValue; + } else { + delete process.env['NG_BUILD_MAX_WORKERS']; + } + delete require.cache[require.resolve('./environment-options')]; + }); + + it('defaults maxInlinerWorkers to min(8, availableParallelism()) when NG_BUILD_MAX_WORKERS is unset', () => { + delete process.env['NG_BUILD_MAX_WORKERS']; + const { maxInlinerWorkers } = loadEnvironmentOptions(); + + expect(maxInlinerWorkers).toBe(Math.min(8, availableParallelism())); + }); + + it('uses configured positive integer when NG_BUILD_MAX_WORKERS is set', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '4'; + const { maxInlinerWorkers } = loadEnvironmentOptions(); + + expect(maxInlinerWorkers).toBe(4); + }); + + it('allows maxInlinerWorkers greater than 8 when explicitly configured', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '16'; + const { maxInlinerWorkers } = loadEnvironmentOptions(); + + expect(maxInlinerWorkers).toBe(16); + }); + + it('supports maxInlinerWorkers set to 1', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '1'; + const { maxInlinerWorkers } = loadEnvironmentOptions(); + + expect(maxInlinerWorkers).toBe(1); + }); + + it('falls back to min(8, availableParallelism()) when NG_BUILD_MAX_WORKERS is 0 or negative', () => { + process.env['NG_BUILD_MAX_WORKERS'] = '0'; + const { maxInlinerWorkers: zeroWorkers } = loadEnvironmentOptions(); + expect(zeroWorkers).toBe(Math.min(8, availableParallelism())); + + process.env['NG_BUILD_MAX_WORKERS'] = '-4'; + const { maxInlinerWorkers: negativeWorkers } = loadEnvironmentOptions(); + expect(negativeWorkers).toBe(Math.min(8, availableParallelism())); + }); + + it('falls back to min(8, availableParallelism()) when NG_BUILD_MAX_WORKERS is invalid', () => { + process.env['NG_BUILD_MAX_WORKERS'] = 'invalid'; + const { maxInlinerWorkers } = loadEnvironmentOptions(); + + expect(maxInlinerWorkers).toBe(Math.min(8, availableParallelism())); + }); +}); diff --git a/packages/angular/build/src/utils/error.ts b/packages/angular/build/src/utils/error.ts new file mode 100644 index 000000000000..0ca77c331d2d --- /dev/null +++ b/packages/angular/build/src/utils/error.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; + +export function assertIsError(value: unknown): asserts value is Error & { code?: string } { + const isError = + value instanceof Error || + // The following is needing to identify errors coming from RxJs. + (typeof value === 'object' && value && 'name' in value && 'message' in value); + assert(isError, 'catch clause variable is not an Error instance'); +} diff --git a/packages/angular/build/src/utils/format-bytes.ts b/packages/angular/build/src/utils/format-bytes.ts new file mode 100644 index 000000000000..5c9ecee6875a --- /dev/null +++ b/packages/angular/build/src/utils/format-bytes.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 function formatSize(size: number): string { + if (size <= 0) { + return '0 bytes'; + } + + const abbreviations = ['bytes', 'kB', 'MB', 'GB']; + const index = Math.floor(Math.log(size) / Math.log(1000)); + const roundedSize = size / Math.pow(1000, index); + // bytes don't have a fraction + const fractionDigits = index === 0 ? 0 : 2; + + return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`; +} diff --git a/packages/angular/build/src/utils/format-bytes_spec.ts b/packages/angular/build/src/utils/format-bytes_spec.ts new file mode 100644 index 000000000000..63cb3f761ecf --- /dev/null +++ b/packages/angular/build/src/utils/format-bytes_spec.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { formatSize } from './format-bytes'; + +describe('formatSize', () => { + it('1000 bytes to be 1kB', () => { + expect(formatSize(1000)).toBe('1.00 kB'); + }); + + it('1_000_000 bytes to be 1MB', () => { + expect(formatSize(1_000_000)).toBe('1.00 MB'); + }); + + it('1_500_000 bytes to be 1.5MB', () => { + expect(formatSize(1_500_000)).toBe('1.50 MB'); + }); + + it('1_000_000_000 bytes to be 1GB', () => { + expect(formatSize(1_000_000_000)).toBe('1.00 GB'); + }); +}); diff --git a/packages/angular/build/src/utils/hash.ts b/packages/angular/build/src/utils/hash.ts new file mode 100644 index 000000000000..fdc5565afbb1 --- /dev/null +++ b/packages/angular/build/src/utils/hash.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import type { XXHashAPI } from 'xxhash-wasm'; + +let xxhashInstance: XXHashAPI | undefined; +let xxhashPromise: Promise | undefined; + +/** + * Initializes the xxHash WASM instance early to ensure synchronous hashing uses xxHash. + */ +export async function initializeHash(): Promise { + if (xxhashInstance) { + return; + } + + xxhashPromise ??= import('xxhash-wasm').then((m) => m.default()); + xxhashInstance = await xxhashPromise; +} + +function getXxhash(): XXHashAPI { + assert( + xxhashInstance, + 'Hash utility must be initialized by awaiting `initializeHash()` before use.', + ); + + return xxhashInstance; +} + +/** + * Calculates a fast 64-bit non-cryptographic hash of the provided content. + * Suitable for cache keys, ETags, and change detection. + */ +export function calculateHash(data: string | Uint8Array): string { + const instance = getXxhash(); + + if (typeof data === 'string') { + return instance.h64ToString(data); + } + + return instance.h64Raw(data).toString(16).padStart(16, '0'); +} + +export interface ContentHasher { + update(data: string | Uint8Array): ContentHasher; + digest(): string; +} + +/** + * Creates a streaming 64-bit non-cryptographic content hasher. + */ +export function createContentHash(): ContentHasher { + const instance = getXxhash(); + const hasher = instance.create64(); + + const contentHasher: ContentHasher = { + update(data: string | Uint8Array): ContentHasher { + hasher.update(data); + + return contentHasher; + }, + digest(): string { + return hasher.digest().toString(16).padStart(16, '0'); + }, + }; + + return contentHasher; +} diff --git a/packages/angular/build/src/utils/hash_spec.ts b/packages/angular/build/src/utils/hash_spec.ts new file mode 100644 index 000000000000..77fcbc909403 --- /dev/null +++ b/packages/angular/build/src/utils/hash_spec.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { calculateHash, createContentHash, initializeHash } from './hash'; + +describe('hash utility', () => { + beforeAll(async () => { + await initializeHash(); + }); + + it('should calculate identical 64-bit hex hash for string and Buffer with same content', () => { + const text = 'export const message = "hello world";'; + const buffer = Buffer.from(text, 'utf-8'); + + const stringHash = calculateHash(text); + const bufferHash = calculateHash(buffer); + + expect(typeof stringHash).toBe('string'); + expect(stringHash.length).toBe(16); + expect(stringHash).toBe(bufferHash); + }); + + it('should calculate different hashes for different contents', () => { + const hash1 = calculateHash('const a = 1;'); + const hash2 = calculateHash('const a = 2;'); + + expect(hash1).not.toBe(hash2); + }); + + it('should support streaming multi-part hashing matching combined single-shot hash', () => { + const part1 = 'header: '; + const part2 = 'body content: '; + const part3 = 'footer'; + + const hasher = createContentHash(); + hasher.update(part1); + hasher.update(part2); + hasher.update(Buffer.from(part3, 'utf-8')); + const streamingHash = hasher.digest(); + + const singleShotHash = calculateHash(part1 + part2 + part3); + + expect(streamingHash.length).toBe(16); + expect(streamingHash).toBe(singleShotHash); + }); + + it('should handle Uint8Array chunks in streaming hasher', () => { + const hasher = createContentHash(); + hasher.update(new Uint8Array([1, 2, 3, 4])).update('some-string'); + const digest = hasher.digest(); + + expect(typeof digest).toBe('string'); + expect(digest.length).toBe(16); + }); +}); diff --git a/packages/angular/build/src/utils/i18n-options.ts b/packages/angular/build/src/utils/i18n-options.ts new file mode 100644 index 000000000000..9a55656e6798 --- /dev/null +++ b/packages/angular/build/src/utils/i18n-options.ts @@ -0,0 +1,295 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵParsedTranslation } from '@angular/localize'; +import path from 'node:path'; +import type { TranslationLoader } from './load-translations'; + +export interface LocaleDescription { + files: { + path: string; + integrity?: string; + format?: string; + }[]; + translation?: Record; + dataPath?: string; + baseHref?: string; + subPath: string; +} + +export interface I18nOptions { + inlineLocales: Set; + sourceLocale: string; + locales: Record; + flatOutput?: boolean; + readonly shouldInline: boolean; + hasDefinedSourceLocale?: boolean; + localizeVersion?: string; +} + +function normalizeTranslationFileOption( + option: unknown, + locale: string, + expectObjectInError: boolean, +): string[] { + if (typeof option === 'string') { + return [option]; + } + + if (Array.isArray(option) && option.every((element) => typeof element === 'string')) { + return option; + } + + let errorMessage = `Project i18n locales translation field value for '${locale}' is malformed. `; + if (expectObjectInError) { + errorMessage += 'Expected a string, array of strings, or object.'; + } else { + errorMessage += 'Expected a string or array of strings.'; + } + + throw new Error(errorMessage); +} + +function ensureObject(value: unknown, name: string): asserts value is Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`Project field '${name}' is malformed. Expected an object.`); + } +} + +function ensureString(value: unknown, name: string): asserts value is string { + if (typeof value !== 'string') { + throw new Error(`Project field '${name}' is malformed. Expected a string.`); + } +} + +function ensureValidSubPath(value: unknown, name: string): asserts value is string { + ensureString(value, name); + + if (!/^[\w-]*$/.test(value)) { + throw new Error( + `Project field '${name}' is invalid. It can only contain letters, numbers, hyphens, and underscores.`, + ); + } +} +export function createI18nOptions( + projectMetadata: { i18n?: unknown }, + inline?: boolean | string[], + logger?: { + warn(message: string): void; + }, + ssrEnabled?: boolean, +): I18nOptions { + const { i18n: metadata = {} } = projectMetadata; + + ensureObject(metadata, 'i18n'); + + const i18n: I18nOptions = { + inlineLocales: new Set(), + // en-US is the default locale added to Angular applications (https://angular.dev/guide/i18n/format-data-locale) + sourceLocale: 'en-US', + locales: {}, + get shouldInline() { + return this.inlineLocales.size > 0; + }, + }; + + let rawSourceLocale: string | undefined; + let rawSourceLocaleBaseHref: string | undefined; + let rawsubPath: string | undefined; + if (typeof metadata.sourceLocale === 'string') { + rawSourceLocale = metadata.sourceLocale; + } else if (metadata.sourceLocale !== undefined) { + ensureObject(metadata.sourceLocale, 'i18n.sourceLocale'); + + if (metadata.sourceLocale.code !== undefined) { + ensureString(metadata.sourceLocale.code, 'i18n.sourceLocale.code'); + rawSourceLocale = metadata.sourceLocale.code; + } + + if (metadata.sourceLocale.baseHref !== undefined) { + ensureString(metadata.sourceLocale.baseHref, 'i18n.sourceLocale.baseHref'); + if (ssrEnabled) { + logger?.warn( + `'baseHref' in 'i18n.sourceLocale' may lead to undefined behavior when used with SSR. ` + + `Consider using 'subPath' instead.\n\n` + + `Note: 'subPath' specifies the URL segment for the locale, serving as both the HTML base HREF ` + + `and the output directory name.\nBy default, if not explicitly set, 'subPath' defaults to the locale code.`, + ); + } + + rawSourceLocaleBaseHref = metadata.sourceLocale.baseHref; + } + + if (metadata.sourceLocale.subPath !== undefined) { + ensureValidSubPath(metadata.sourceLocale.subPath, 'i18n.sourceLocale.subPath'); + rawsubPath = metadata.sourceLocale.subPath; + } + + if (rawsubPath !== undefined && rawSourceLocaleBaseHref !== undefined) { + throw new Error( + `'i18n.sourceLocale.subPath' and 'i18n.sourceLocale.baseHref' cannot be used together.`, + ); + } + } + + if (rawSourceLocale !== undefined) { + i18n.sourceLocale = rawSourceLocale; + i18n.hasDefinedSourceLocale = true; + } + + i18n.locales[i18n.sourceLocale] = { + files: [], + baseHref: rawSourceLocaleBaseHref, + subPath: rawsubPath ?? i18n.sourceLocale, + }; + + if (metadata.locales !== undefined) { + ensureObject(metadata.locales, 'i18n locales'); + + for (const [locale, options] of Object.entries(metadata.locales)) { + let translationFiles: string[] | undefined; + let baseHref: string | undefined; + let subPath: string | undefined; + + if (options && typeof options === 'object' && 'translation' in options) { + translationFiles = normalizeTranslationFileOption(options.translation, locale, false); + + if ('baseHref' in options) { + ensureString(options.baseHref, `i18n.locales.${locale}.baseHref`); + + if (ssrEnabled) { + logger?.warn( + `'baseHref' in 'i18n.locales.${locale}' may lead to undefined behavior when used with SSR. ` + + `Consider using 'subPath' instead.\n\n` + + `Note: 'subPath' specifies the URL segment for the locale, serving as both the HTML base HREF ` + + `and the output directory name.\nBy default, if not explicitly set, 'subPath' defaults to the locale code.`, + ); + } + baseHref = options.baseHref; + } + + if ('subPath' in options) { + ensureValidSubPath(options.subPath, `i18n.locales.${locale}.subPath`); + subPath = options.subPath; + } + + if (subPath !== undefined && baseHref !== undefined) { + throw new Error( + `'i18n.locales.${locale}.subPath' and 'i18n.locales.${locale}.baseHref' cannot be used together.`, + ); + } + } else { + translationFiles = normalizeTranslationFileOption(options, locale, true); + } + + if (locale === i18n.sourceLocale) { + throw new Error( + `An i18n locale ('${locale}') cannot both be a source locale and provide a translation.`, + ); + } + + i18n.locales[locale] = { + files: translationFiles.map((file) => ({ path: file })), + baseHref, + subPath: subPath ?? locale, + }; + } + } + + if (inline === true) { + i18n.inlineLocales.add(i18n.sourceLocale); + Object.keys(i18n.locales).forEach((locale) => i18n.inlineLocales.add(locale)); + } else if (inline) { + for (const locale of inline) { + if (!i18n.locales[locale] && i18n.sourceLocale !== locale) { + throw new Error(`Requested locale '${locale}' is not defined for the project.`); + } + + i18n.inlineLocales.add(locale); + } + } + + // Check that subPaths are unique only the locales that we are inlining. + const localesData = Object.entries(i18n.locales).filter(([locale]) => + i18n.inlineLocales.has(locale), + ); + + for (let i = 0; i < localesData.length; i++) { + const [localeA, { subPath: subPathA }] = localesData[i]; + + for (let j = i + 1; j < localesData.length; j++) { + const [localeB, { subPath: subPathB }] = localesData[j]; + + if (subPathA === subPathB) { + throw new Error( + `Invalid i18n configuration: Locales '${localeA}' and '${localeB}' cannot have the same subPath: '${subPathB}'.`, + ); + } + } + } + + return i18n; +} + +export function loadTranslations( + locale: string, + desc: LocaleDescription, + workspaceRoot: string, + loader: TranslationLoader, + logger: { warn: (message: string) => void; error: (message: string) => void }, + usedFormats?: Set, + duplicateTranslation?: 'ignore' | 'error' | 'warning', +) { + let translations: Record | undefined = undefined; + for (const file of desc.files) { + const loadResult = loader(path.join(workspaceRoot, file.path)); + + for (const diagnostics of loadResult.diagnostics.messages) { + if (diagnostics.type === 'error') { + logger.error(`Error parsing translation file '${file.path}': ${diagnostics.message}`); + } else { + logger.warn(`WARNING [${file.path}]: ${diagnostics.message}`); + } + } + + if (loadResult.locale !== undefined && loadResult.locale !== locale) { + logger.warn( + `WARNING [${file.path}]: File target locale ('${loadResult.locale}') does not match configured locale ('${locale}')`, + ); + } + + usedFormats?.add(loadResult.format); + file.format = loadResult.format; + file.integrity = loadResult.integrity; + + if (translations) { + // Merge translations + for (const [id, message] of Object.entries(loadResult.translations)) { + if (translations[id] !== undefined) { + const duplicateTranslationMessage = `[${file.path}]: Duplicate translations for message '${id}' when merging.`; + switch (duplicateTranslation) { + case 'ignore': + break; + case 'error': + logger.error(`ERROR ${duplicateTranslationMessage}`); + break; + case 'warning': + default: + logger.warn(`WARNING ${duplicateTranslationMessage}`); + break; + } + } + translations[id] = message; + } + } else { + // First or only translation file + translations = loadResult.translations; + } + } + desc.translation = translations; +} diff --git a/packages/angular/build/src/utils/index-file/add-event-dispatch-contract.ts b/packages/angular/build/src/utils/index-file/add-event-dispatch-contract.ts new file mode 100644 index 000000000000..749a489f8a4a --- /dev/null +++ b/packages/angular/build/src/utils/index-file/add-event-dispatch-contract.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { htmlRewritingStream } from './html-rewriting-stream'; + +let jsActionContractScript: string; + +export async function addEventDispatchContract(html: string): Promise { + const { rewriter, transformedContent } = await htmlRewritingStream(html); + + jsActionContractScript ??= + ''; + + rewriter.on('startTag', (tag) => { + rewriter.emitStartTag(tag); + + if (tag.tagName === 'body') { + rewriter.emitRaw(jsActionContractScript); + } + }); + + return transformedContent(); +} diff --git a/packages/angular/build/src/utils/index-file/add-event-dispatch-contract_spec.ts b/packages/angular/build/src/utils/index-file/add-event-dispatch-contract_spec.ts new file mode 100644 index 000000000000..6c0747730c29 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/add-event-dispatch-contract_spec.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { addEventDispatchContract } from './add-event-dispatch-contract'; + +describe('addEventDispatchContract', () => { + it('should inline event dispatcher script', async () => { + const result = await addEventDispatchContract(` + + + +

Hello World!

+ + + `); + + expect(result).toMatch( + /\s*`); + } + + let subResourceIntegrityTag: string | undefined; + let headerLinkTags: string[] = []; + let bodyLinkTags: string[] = []; + + // Emit an integrity-only import map so the browser can validate lazy chunks + // resolved via dynamic `import()` (which otherwise carry no SRI metadata). + // The block is placed first inside `` so it precedes any module + // script, as required by the import-map spec. + if (sri && chunksIntegrity?.size) { + const integrity: Record = {}; + // Stable iteration order for reproducible builds. + const sortedEntries = [...chunksIntegrity.entries()].sort(([keyA], [keyB]) => + keyA.localeCompare(keyB), + ); + for (const [url, integrityHash] of sortedEntries) { + const resolvedUrl = generateUrl(url, deployUrl); + const key = RESOLVABLE_URL_REGEXP.test(resolvedUrl) ? resolvedUrl : `./${resolvedUrl}`; + integrity[key] = integrityHash; + } + const importMapJson = JSON.stringify({ integrity }).replace(/${importMapJson}`; + } + + for (const src of stylesheets) { + const attrs = [`rel="stylesheet"`, `href="${generateUrl(src, deployUrl)}"`]; + + if (crossOrigin !== 'none') { + attrs.push(`crossorigin="${crossOrigin}"`); + } + + if (sri) { + const content = await loadOutputFile(src); + attrs.push(generateSriAttributes(content)); + } + + headerLinkTags.push(``); + } + + if (params.hints?.length) { + for (const hint of params.hints) { + const attrs = [`rel="${hint.mode}"`, `href="${generateUrl(hint.url, deployUrl)}"`]; + + if (hint.mode !== 'modulepreload' && crossOrigin !== 'none') { + // Value is considered anonymous by the browser when not present or empty + attrs.push(crossOrigin === 'anonymous' ? 'crossorigin' : `crossorigin="${crossOrigin}"`); + } + + if (hint.mode === 'preload' || hint.mode === 'prefetch') { + switch (extname(hint.url)) { + case '.js': + attrs.push('as="script"'); + break; + case '.css': + attrs.push('as="style"'); + break; + default: + if (hint.as) { + attrs.push(`as="${hint.as}"`); + } + break; + } + } + + if ( + sri && + (hint.mode === 'preload' || hint.mode === 'prefetch' || hint.mode === 'modulepreload') + ) { + const content = await loadOutputFile(hint.url); + attrs.push(generateSriAttributes(content)); + } + + const tag = ``; + if (hint.mode === 'modulepreload') { + // Module preloads should be placed by the inserted script elements in the body since + // they are only useful in combination with the scripts. + bodyLinkTags.push(tag); + } else { + headerLinkTags.push(tag); + } + } + } + + const dir = lang ? await getLanguageDirection(lang, warnings) : undefined; + const { rewriter, transformedContent } = await htmlRewritingStream(html); + const baseTagExists = html.includes('(); + + rewriter + .on('startTag', (tag, rawTagHtml) => { + switch (tag.tagName) { + case 'html': + // Adjust document locale if specified + if (isString(lang)) { + updateAttribute(tag, 'lang', lang); + } + + if (dir) { + updateAttribute(tag, 'dir', dir); + } + break; + case 'head': + // Base href should be added before any link, meta tags + if (!baseTagExists && isString(baseHref)) { + rewriter.emitStartTag(tag); + rewriter.emitRaw(``); + if (subResourceIntegrityTag) { + rewriter.emitRaw(subResourceIntegrityTag); + } + + return; + } + break; + case 'base': + // Adjust base href if specified + if (isString(baseHref)) { + updateAttribute(tag, 'href', baseHref); + } + + if (subResourceIntegrityTag) { + rewriter.emitRaw(subResourceIntegrityTag); + } + + break; + case 'link': + if (readAttribute(tag, 'rel') === 'preconnect') { + const href = readAttribute(tag, 'href'); + if (href) { + foundPreconnects.add(href); + } + } + break; + default: + if (tag.selfClosing && !VALID_SELF_CLOSING_TAGS.has(tag.tagName)) { + errors.push(`Invalid self-closing element in index HTML file: '${rawTagHtml}'.`); + + return; + } + } + + rewriter.emitStartTag(tag); + }) + .on('endTag', (tag) => { + switch (tag.tagName) { + case 'head': + for (const linkTag of headerLinkTags) { + rewriter.emitRaw(linkTag); + } + if (imageDomains) { + for (const imageDomain of imageDomains) { + if (!foundPreconnects.has(imageDomain)) { + rewriter.emitRaw(``); + } + } + } + headerLinkTags = []; + break; + case 'body': + for (const linkTag of bodyLinkTags) { + rewriter.emitRaw(linkTag); + } + bodyLinkTags = []; + + // Add script tags + for (const scriptTag of scriptTags) { + rewriter.emitRaw(scriptTag); + } + + scriptTags = []; + break; + } + + rewriter.emitEndTag(tag); + }); + + const content = await transformedContent(); + + return { + content: + headerLinkTags.length || scriptTags.length + ? // In case no body/head tags are not present (dotnet partial templates) + headerLinkTags.join('') + scriptTags.join('') + content + : content, + warnings, + errors, + }; +} + +function generateSriAttributes(content: string): string { + const algo = 'sha384'; + const hash = createHash(algo).update(content, 'utf8').digest('base64'); + + return `integrity="${algo}-${hash}"`; +} + +function generateUrl(value: string, deployUrl: string | undefined): string { + if (!deployUrl) { + return value; + } + + // Skip if root-relative, absolute or protocol relative url + if (/^((?:\w+:)?\/\/|data:|chrome:|\/)/.test(value)) { + return value; + } + + return `${deployUrl}${value}`; +} + +function updateAttribute( + tag: { attrs: { name: string; value: string }[] }, + name: string, + value: string, +): void { + const index = tag.attrs.findIndex((a) => a.name === name); + const newValue = { name, value }; + + if (index === -1) { + tag.attrs.push(newValue); + } else { + tag.attrs[index] = newValue; + } +} + +function readAttribute( + tag: { attrs: { name: string; value: string }[] }, + name: string, +): string | undefined { + const targetAttr = tag.attrs.find((attr) => attr.name === name); + + return targetAttr ? targetAttr.value : undefined; +} + +function isString(value: unknown): value is string { + return typeof value === 'string'; +} + +async function getLanguageDirection( + locale: string, + warnings: string[], +): Promise { + const dir = await getLanguageDirectionFromLocales(locale); + + if (!dir) { + warnings.push( + `Locale data for '${locale}' cannot be found. 'dir' attribute will not be set for this locale.`, + ); + } + + return dir; +} + +async function getLanguageDirectionFromLocales(locale: string): Promise { + try { + const localeData = (await import(`@angular/common/locales/${locale}`)).default; + const dir = localeData[localeData.length - 2]; + + return isString(dir) ? dir : undefined; + } catch { + // In some cases certain locales might map to files which are named only with language id. + // Example: `en-US` -> `en`. + const [languageId] = locale.split('-', 1); + if (languageId !== locale) { + return getLanguageDirectionFromLocales(languageId); + } + } + + return undefined; +} diff --git a/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts b/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts new file mode 100644 index 000000000000..df292b8771a3 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts @@ -0,0 +1,592 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { AugmentIndexHtmlOptions, augmentIndexHtml } from './augment-index-html'; + +describe('augment-index-html', () => { + const indexGeneratorOptions: AugmentIndexHtmlOptions = { + html: '', + baseHref: '/', + sri: false, + files: [], + loadOutputFile: async (_fileName: string) => '', + entrypoints: [ + ['scripts', false], + ['polyfills', true], + ['main', true], + ['styles', false], + ], + }; + + const oneLineHtml = (html: TemplateStringsArray) => + `${html}`.replace(/(>\s+)/g, '>').replace(/\s+ { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + files: [ + { file: 'styles.css', extension: '.css', name: 'styles' }, + { file: 'runtime.js', extension: '.js', name: 'main' }, + { file: 'main.js', extension: '.js', name: 'main' }, + { file: 'runtime.js', extension: '.js', name: 'polyfills' }, + { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, + ], + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + + + + `); + }); + + it('should replace base href value', async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: '', + baseHref: '/Apps/', + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + `); + }); + + it('should add lang and dir LTR attribute for French (fr)', async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + lang: 'fr', + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + `); + }); + + it('should add lang and dir RTL attribute for Pashto (ps)', async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + lang: 'ps', + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + `); + }); + + it(`should fallback to use language ID to set the dir attribute (en-US)`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + lang: 'en-US', + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + `); + }); + + it(`should work when lang (locale) is not provided by '@angular/common'`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + lang: 'xx-XX', + }); + + expect(warnings).toEqual([ + `Locale data for 'xx-XX' cannot be found. 'dir' attribute will not be set for this locale.`, + ]); + expect(content).toEqual(oneLineHtml` + + + + + + + + `); + }); + + it(`should add script and link tags even when body and head element doesn't exist`, async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: ``, + files: [ + { file: 'styles.css', extension: '.css', name: 'styles' }, + { file: 'runtime.js', extension: '.js', name: 'main' }, + { file: 'main.js', extension: '.js', name: 'main' }, + { file: 'runtime.js', extension: '.js', name: 'polyfills' }, + { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, + ], + }); + + expect(content).toEqual(oneLineHtml` + + + + + + `); + }); + + it(`should add preconnect and dns-prefetch hints when provided with cross origin`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'preconnect', url: 'http://example.com' }, + { mode: 'dns-prefetch', url: 'http://example.com' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add preconnect and dns-prefetch hints when provided with "use-credentials" cross origin`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + crossOrigin: 'use-credentials', + hints: [ + { mode: 'preconnect', url: 'http://example.com' }, + { mode: 'dns-prefetch', url: 'http://example.com' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add preconnect and dns-prefetch hints when provided with "anonymous" cross origin`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + crossOrigin: 'anonymous', + hints: [ + { mode: 'preconnect', url: 'http://example.com' }, + { mode: 'dns-prefetch', url: 'http://example.com' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add preconnect and dns-prefetch hints when provided with "none" cross origin`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + crossOrigin: 'none', + hints: [ + { mode: 'preconnect', url: 'http://example.com' }, + { mode: 'dns-prefetch', url: 'http://example.com' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add preconnect and dns-prefetch hints when provided with no cross origin`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'preconnect', url: 'http://example.com' }, + { mode: 'dns-prefetch', url: 'http://example.com' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add modulepreload hint when provided`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'modulepreload', url: 'x.js' }, + { mode: 'modulepreload', url: 'y/z.js' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add modulepreload hint with no crossorigin attribute when provided with cross origin set`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + crossOrigin: 'anonymous', + hints: [ + { mode: 'modulepreload', url: 'x.js' }, + { mode: 'modulepreload', url: 'y/z.js' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add prefetch/preload hints with as=script when specified with a JS url`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'prefetch', url: 'x.js' }, + { mode: 'preload', url: 'y/z.js' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add prefetch/preload hints with as=style when specified with a CSS url`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'prefetch', url: 'x.css' }, + { mode: 'preload', url: 'y/z.css' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should add prefetch/preload hints with as=style when specified with a URL and an 'as' option`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + hints: [ + { mode: 'prefetch', url: 'https://example.com/x?a=1', as: 'style' }, + { mode: 'preload', url: 'http://example.com/y?b=2', as: 'style' }, + ], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it(`should not add deploy URL to hints with an absolute URL`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + deployUrl: 'https://localhost/', + hints: [{ mode: 'preload', url: 'http://example.com/y?b=2' }], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + `); + }); + + it(`should not add deploy URL to hints with a root-relative URL`, async () => { + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + deployUrl: 'https://example.com/', + hints: [{ mode: 'preload', url: '/y?b=2' }], + }); + + expect(warnings).toHaveSize(0); + expect(content).toEqual(oneLineHtml` + + + + + + + + + `); + }); + + it('should add `.mjs` script tags', async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + files: [{ file: 'main.mjs', extension: '.mjs', name: 'main' }], + entrypoints: [['main', true /* isModule */]], + }); + + expect(content).toContain(''); + }); + + it('should reject non-module `.mjs` scripts', async () => { + const options: AugmentIndexHtmlOptions = { + ...indexGeneratorOptions, + files: [{ file: 'main.mjs', extension: '.mjs', name: 'main' }], + entrypoints: [['main', false /* isModule */]], + }; + + await expectAsync(augmentIndexHtml(options)).toBeRejectedWithError( + '`.mjs` files *must* set `isModule` to `true`.', + ); + }); + + it('should escape `<` characters in inline importmap JSON', async () => { + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + sri: true, + chunksIntegrity: new Map([['lazy([^<]+)<\/script>/); + expect(match).withContext('importmap script tag missing').not.toBeNull(); + expect(match?.[1]).toContain('./lazy\\u003cchunk.js'); + expect(match?.[1]).not.toContain('./lazy { + const imageDomains = ['https://www.example.com', 'https://www.example2.com']; + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + imageDomains, + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it('should add no image preconnects if provided empty domain list', async () => { + const imageDomains: Array = []; + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + imageDomains, + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + `); + }); + + it('should not add duplicate preconnects', async () => { + const imageDomains = ['https://www.example1.com', 'https://www.example2.com']; + const { content, warnings } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: '', + imageDomains, + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + + + `); + }); + + it('should add image preconnects if it encounters preconnect elements for other resources', async () => { + const imageDomains = ['https://www.example2.com', 'https://www.example3.com']; + const { content } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: '', + imageDomains, + }); + + expect(content).toEqual(oneLineHtml` + + + + + + + + + + + `); + }); + + describe('self-closing tags', () => { + it('should return an error when used on a not supported element', async () => { + const { errors } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: ` + + + + + ' + `, + }); + + expect(errors.length).toEqual(1); + expect(errors).toEqual([`Invalid self-closing element in index HTML file: ''.`]); + }); + + it('should not return an error when used on a supported element', async () => { + const { errors } = await augmentIndexHtml({ + ...indexGeneratorOptions, + html: ` + + +
+ + + ' + `, + }); + + expect(errors.length).toEqual(0); + }); + }); +}); diff --git a/packages/angular/build/src/utils/index-file/auto-csp.ts b/packages/angular/build/src/utils/index-file/auto-csp.ts new file mode 100644 index 000000000000..cd07fb821640 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/auto-csp.ts @@ -0,0 +1,354 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 crypto from 'node:crypto'; +import { StartTag, htmlRewritingStream } from './html-rewriting-stream'; + +/** + * The hash function to use for hash directives to use in the CSP. + */ +const HASH_FUNCTION = 'sha256'; + +/** + * Store the appropriate attributes of a sourced script tag to generate the loader script. + */ +interface SrcScriptTag { + src: string; + type?: string; + async: boolean; + defer: boolean; + integrity?: string; + crossOrigin?: string; +} + +/** + * Get the specified attribute or return undefined if the tag doesn't have that attribute. + * + * @param tag StartTag of the `); + scriptContent = []; + } + + rewriter.on('startTag', (tag) => { + if (tag.tagName === 'script') { + openedScriptTag = tag; + const src = getScriptAttributeValue(tag, 'src'); + + if (src) { + // If there are any interesting attributes, note them down. + const scriptType = getScriptAttributeValue(tag, 'type'); + if (shouldDynamicallyLoadScriptTagBasedOnType(scriptType)) { + const crossOrigin = getScriptAttributeValue(tag, 'crossorigin'); + scriptContent.push({ + src: src, + type: scriptType, + async: getScriptAttributeValue(tag, 'async') !== undefined, + defer: getScriptAttributeValue(tag, 'defer') !== undefined, + integrity: getScriptAttributeValue(tag, 'integrity'), + crossOrigin: crossOrigin === '' ? 'anonymous' : crossOrigin, + }); + + return; // Skip writing my script tag until we've read it all. + } + } + } + // We are encountering the first start tag that's not tag if it's a part of the + // dynamic loader script. + if (src && shouldDynamicallyLoadScriptTagBasedOnType(scriptType)) { + return; + } + } + + if (tag.tagName === 'head' || tag.tagName === 'body' || tag.tagName === 'html') { + // Write the loader script if a string of +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(csps[0]).toContain(hashTextContent("console.log('foo');")); + }); + + it('should rewrite a single source script', async () => { + const result = await autoCsp(` + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain(`const scripts = [['./main.js', "", false, false, null, null]];`); + }); + + it('should rewrite a single source script in place', async () => { + const result = await autoCsp(` + + + + +
Some text
+ + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + // Our loader script appears after the HTML text content. + expect(result).toMatch( + /Some text<\/div>\s* + + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_TWO_HASHES_REGEX); + expect(result).toContain( + // eslint-disable-next-line max-len + `const scripts = [['./main1.js', "", false, false, null, null],['./main2.js', "", true, false, null, null],['./main3.js', "module", true, true, null, null]];`, + ); + // Head loader script is in the head. + expect(result).toContain(``); + // Only two loader scripts are created. + expect(Array.from(result.matchAll(/ + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + // & encodes correctly + expect(result).toContain(`'/foo&bar'`); + // Impossible to escape a string and create invalid loader JS with a ' + // (Quotes and backslashes work) + expect(result).toContain(`'/one\\'two%5C\\'three%5C%5C\\'four%5C%5C%5C\\'five'`); + // HTML entities work + expect(result).toContain(`'/one&two&three&four'`); + // Cannot escape JS context to HTML + expect(result).toContain(`'./%3C/script%3E'`); + }); + + it('should rewrite all script tags', async () => { + const result = await autoCsp(` + + + + + + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + // Exactly four hashes for the four scripts that remain (inline, loader, inline, loader). + expect(csps[0]).toMatch(CSP_FOUR_HASHES_REGEX); + expect(csps[0]).toContain(hashTextContent("console.log('foo');")); + expect(csps[0]).toContain(hashTextContent("console.log('bar');")); + // Loader script for main.js and main2.js appear after 'foo' and before 'bar'. + expect(result).toMatch( + // eslint-disable-next-line max-len + /console.log\('foo'\);<\/script>\s* + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + + expect(result).toContain( + // eslint-disable-next-line max-len + `document.lastElementChild.appendChild`, + ); + // Head loader script is in the head. + expect(result).toContain(``); + // Only one loader script is created. + expect(Array.from(result.matchAll(/ +
Some text
+ + \r\n + `); + + const csps = getCsps(result); + expect(result).not.toContain(`\r\n`); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(csps[0]).toContain(hashTextContent(`\r\nconsole.log('foo');\r\n`)); + }); + + it('should preserve integrity and crossorigin attributes in loader script', async () => { + const result = await autoCsp(` + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "module", false, false, "sha384-xyz123", "anonymous"]];`, + ); + }); + + it('should preserve only integrity attribute when crossorigin is omitted', async () => { + const result = await autoCsp(` + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "", false, false, "sha384-xyz123", null]];`, + ); + }); + + it('should map empty crossorigin attribute to anonymous', async () => { + const result = await autoCsp(` + + + + + +
Some text
+ + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "", false, false, null, "anonymous"]];`, + ); + }); + + it('should rewrite scripts with application/javascript type', async () => { + const result = await autoCsp(` + + + + + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "application/javascript", false, false, null, null]];`, + ); + }); + + it('should rewrite scripts with case-insensitive type and parameters with whitespace', async () => { + const result = await autoCsp(` + + + + + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "Text/JavaScript ; charset=utf-8", false, false, null, null]];`, + ); + }); + + it('should rewrite scripts with case-insensitive module type', async () => { + const result = await autoCsp(` + + + + + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + expect(result).toContain( + `const scripts = [['./main.js', "Module", false, false, null, null]];`, + ); + }); + + it('should not rewrite non-JavaScript script tags', async () => { + const result = await autoCsp(` + + + + + + + `); + + // No dynamic loader script is emitted because application/json is not JavaScript. + expect(result).toContain(''); + expect(result).not.toContain('const scripts ='); + }); + + it('should encode a script type that carries MIME parameters', async () => { + const result = await autoCsp(` + + + + + + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + // The type stays inside its string literal. + expect(result).toContain( + `const scripts = [['./main.js', "text/javascript;']];var x=1;var junk=[['a','b", false, false, null, null]];`, + ); + }); + + it('should encode a script type that contains a closing script tag', async () => { + const result = await autoCsp(` + + + + + + + + `); + + const csps = getCsps(result); + expect(csps).toHaveSize(1); + expect(csps[0]).toMatch(CSP_SINGLE_HASH_REGEX); + // Only the loader element is emitted. + expect(Array.from(result.matchAll(/ + + + + + `; + + const { content } = await inlineCriticalCss( + initialContent, + '/dist/', + undefined, + false, + readAsset, + ); + + expect(content).toContain(''); + }); + + it('should capture warnings from beasties', async () => { + const initialContent = ` + + + + + + `; + + const { warnings } = await inlineCriticalCss( + initialContent, + '/dist/', + undefined, + false, + readAsset, + ); + + expect(warnings.length).toBeGreaterThan(0); + expect(warnings[0]).toContain('missing.css'); + }); + + it('should retain nonce on stylesheet links and noscript fallback', async () => { + const initialContent = ` + + + + + + `; + + const { content, errors, warnings } = await inlineCriticalCss( + initialContent, + '/dist/', + undefined, + false, + readAsset, + ); + + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + expect(content).toContain( + '', + ); + expect(content).toContain( + '', + ); + }); +}); diff --git a/packages/angular/build/src/utils/index-file/inline-fonts.ts b/packages/angular/build/src/utils/index-file/inline-fonts.ts new file mode 100644 index 000000000000..387eb479cd60 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/inline-fonts.ts @@ -0,0 +1,317 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createHash } from 'node:crypto'; +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { type Agent, get as httpsGet } from 'node:https'; +import { join } from 'node:path'; +import { NormalizedCachedOptions } from '../normalize-cache'; +import { htmlRewritingStream } from './html-rewriting-stream'; + +interface FontProviderDetails { + preconnectUrl: string; +} + +export interface InlineFontsOptions { + minify?: boolean; + cache?: NormalizedCachedOptions; +} + +const SUPPORTED_PROVIDERS: Record = { + 'fonts.googleapis.com': { + preconnectUrl: 'https://fonts.gstatic.com', + }, + 'use.typekit.net': { + preconnectUrl: 'https://use.typekit.net', + }, +}; + +/** + * Hash algorithm used for cached files. + */ +const CONTENT_HASH_ALGORITHM = 'sha256'; + +/** + * String length of the SHA-256 content hash stored in cached files. + */ +const CONTENT_HASH_LENGTH = 64; + +export class InlineFontsProcessor { + private readonly cachePath: string | undefined; + constructor(private options: InlineFontsOptions) { + const { path: cacheDirectory, enabled } = this.options.cache || {}; + if (cacheDirectory && enabled) { + this.cachePath = join(cacheDirectory, 'angular-build-fonts'); + } + } + + async process(content: string): Promise { + const hrefList: string[] = []; + const existingPreconnect = new Set(); + + // Collector link tags with href + const { rewriter: collectorStream, transformedContent: initCollectorStream } = + await htmlRewritingStream(content); + + collectorStream.on('startTag', (tag) => { + const { tagName, attrs } = tag; + + if (tagName !== 'link') { + return; + } + + let hrefValue: string | undefined; + let relValue: string | undefined; + for (const { name, value } of attrs) { + switch (name) { + case 'rel': + relValue = value; + break; + + case 'href': + hrefValue = value; + break; + } + + if (hrefValue && relValue) { + switch (relValue) { + case 'stylesheet': + // + hrefList.push(hrefValue); + break; + + case 'preconnect': + // + existingPreconnect.add(hrefValue.replace(/\/$/, '')); + break; + } + + return; + } + } + }); + + void initCollectorStream().catch(() => { + // We don't really care about any errors here because it just initializes + // the rewriting stream, as we are waiting for `finish` below. + }); + + await new Promise((resolve) => collectorStream.on('finish', resolve)); + + // Download stylesheets + const hrefsContent = new Map(); + const newPreconnectUrls = new Set(); + + for (const hrefItem of hrefList) { + const url = this.createNormalizedUrl(hrefItem); + if (!url) { + continue; + } + + const content = await this.processURL(url); + if (content === undefined) { + continue; + } + + hrefsContent.set(hrefItem, content); + + // Add preconnect + const preconnectUrl = this.getFontProviderDetails(url)?.preconnectUrl; + if (preconnectUrl && !existingPreconnect.has(preconnectUrl)) { + newPreconnectUrls.add(preconnectUrl); + } + } + + if (hrefsContent.size === 0) { + return content; + } + + // Replace link with style tag. + const { rewriter, transformedContent } = await htmlRewritingStream(content); + rewriter.on('startTag', (tag) => { + const { tagName, attrs } = tag; + + switch (tagName) { + case 'head': + rewriter.emitStartTag(tag); + for (const url of newPreconnectUrls) { + rewriter.emitRaw(``); + } + break; + + case 'link': { + const hrefAttr = + attrs.some(({ name, value }) => name === 'rel' && value === 'stylesheet') && + attrs.find(({ name, value }) => name === 'href' && hrefsContent.has(value)); + if (hrefAttr) { + const href = hrefAttr.value; + const cssContent = hrefsContent.get(href); + rewriter.emitRaw(``); + } else { + rewriter.emitStartTag(tag); + } + break; + } + default: + rewriter.emitStartTag(tag); + + break; + } + }); + + return transformedContent(); + } + + private async getResponse(url: URL): Promise { + let cacheFile; + if (this.cachePath) { + const key = createHash(CONTENT_HASH_ALGORITHM).update(`${url}`).digest('hex'); + cacheFile = join(this.cachePath, key); + } + + if (cacheFile) { + try { + const data = await readFile(cacheFile, 'utf8'); + // Check for valid content via stored hash + if (data.length > CONTENT_HASH_LENGTH) { + const storedHash = data.slice(0, CONTENT_HASH_LENGTH); + const content = data.slice(CONTENT_HASH_LENGTH); + const contentHash = createHash(CONTENT_HASH_ALGORITHM).update(content).digest('hex'); + if (storedHash === contentHash) { + // Return valid content + return content; + } else { + // Delete corrupted cache content + await rm(cacheFile); + } + } + } catch {} + } + + const httpsProxy = process.env.HTTPS_PROXY ?? process.env.https_proxy; + let agent: Agent | undefined; + if (httpsProxy) { + // TODO: Remove `https-proxy-agent` usage once the min supported version of Node.js is 24.5.0 + // https.globalAgent = new https.Agent({ + // proxyEnv: { HTTPS_PROXY: 'http://proxy.company.com:8080' }, + // }); + // See: https://nodejs.org/en/learn/http/enterprise-network-configuration + // See: https://nodejs.org/docs/latest/api/https.html + + const { HttpsProxyAgent } = (await import('https-proxy-agent' as string)) as typeof import( + 'https-proxy-agent', + { with: { 'resolution-mode': 'import' } } + ); + agent = new HttpsProxyAgent(httpsProxy) as unknown as Agent; + } + + const data = await new Promise((resolve, reject) => { + let rawResponse = ''; + httpsGet( + url, + { + agent, + headers: { + /** + * Always use a Windows UA. This is because Google fonts will including hinting in fonts for Windows. + * Hinting is a technique used with Windows files to improve appearance however + * results in 20-50% larger file sizes. + * + * @see http://google3/java/com/google/fonts/css/OpenSansWebFontsCssBuilder.java?l=22 + * @see https://fonts.google.com/knowledge/glossary/hinting (short) + * @see https://glyphsapp.com/learn/hinting-manual-truetype-hinting (deep dive) + */ + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + }, + }, + (res) => { + if (res.statusCode !== 200) { + reject( + new Error( + `Inlining of fonts failed. ${url} returned status code: ${res.statusCode}.`, + ), + ); + + return; + } + + res.on('data', (chunk) => (rawResponse += chunk)).on('end', () => resolve(rawResponse)); + }, + ).on('error', (e) => + reject( + new Error( + `Inlining of fonts failed. An error has occurred while retrieving ${url} over the internet.\n` + + e.message, + ), + ), + ); + }); + + if (cacheFile && this.cachePath) { + try { + await mkdir(this.cachePath, { recursive: true }); + const dataHash = createHash(CONTENT_HASH_ALGORITHM).update(data).digest('hex'); + await writeFile(cacheFile, dataHash + data); + } catch {} + } + + return data; + } + + async processURL(url: string | URL): Promise { + const normalizedURL = url instanceof URL ? url : this.createNormalizedUrl(url); + if (!normalizedURL) { + return; + } + + const provider = this.getFontProviderDetails(normalizedURL); + if (!provider) { + return undefined; + } + + let cssContent = await this.getResponse(normalizedURL); + + if (this.options.minify) { + cssContent = cssContent + // Comments. + .replace(/\/\*([\s\S]*?)\*\//g, '') + // New lines. + .replace(/\n/g, '') + // Safe spaces. + .replace(/\s?[{:;]\s+/g, (s) => s.trim()); + } + + return cssContent; + } + + canInlineRequest(url: string): boolean { + const normalizedUrl = this.createNormalizedUrl(url); + + return normalizedUrl ? !!this.getFontProviderDetails(normalizedUrl) : false; + } + + private getFontProviderDetails(url: URL): FontProviderDetails | undefined { + return SUPPORTED_PROVIDERS[url.hostname]; + } + + private createNormalizedUrl(value: string): URL | undefined { + // Need to convert '//' to 'https://' because the URL parser will fail with '//'. + const url = new URL(value.startsWith('//') ? `https:${value}` : value, 'resolve://'); + + switch (url.protocol) { + case 'http:': + case 'https:': + url.protocol = 'https:'; + + return url; + default: + return undefined; + } + } +} diff --git a/packages/angular/build/src/utils/index-file/inline-fonts_spec.ts b/packages/angular/build/src/utils/index-file/inline-fonts_spec.ts new file mode 100644 index 000000000000..b2dea06b570a --- /dev/null +++ b/packages/angular/build/src/utils/index-file/inline-fonts_spec.ts @@ -0,0 +1,215 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { createHash } from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import type { ClientRequest, IncomingMessage } from 'node:http'; +import https from 'node:https'; +import { join } from 'node:path'; +import { Readable } from 'node:stream'; +import { InlineFontsProcessor } from './inline-fonts'; + +describe('InlineFontsProcessor', () => { + describe('disk cache', () => { + const url = 'https://fonts.googleapis.com/css2?family=Roboto'; + const content = '@font-face { font-family: Roboto; src: url(roboto.woff2); }'; + let tempRoot: string; + let cache: { enabled: boolean; path: string; basePath: string }; + let cacheDirectory: string; + let cacheFile: string; + let getSpy: jasmine.Spy; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-font-cache-test-')); + cache = { enabled: true, path: join(tempRoot, 'cache'), basePath: tempRoot }; + cacheDirectory = join(cache.path, 'angular-build-fonts'); + cacheFile = join(cacheDirectory, createHash('sha256').update(url).digest('hex')); + + getSpy = spyOn(https, 'get').and.callFake((...args: unknown[]) => { + const callback = args.at(-1); + assert(typeof callback === 'function'); + const response = Readable.from([content]) as IncomingMessage; + response.statusCode = 200; + callback(response); + + return new EventEmitter() as ClientRequest; + }); + }); + + afterEach(async () => { + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }); + } + }); + + it('should create the cache directory and save the stylesheet', async () => { + const processor = new InlineFontsProcessor({ cache }); + + expect(await processor.processURL(url)).toBe(content); + expect(await readdir(cacheDirectory)).toHaveSize(1); + expect(await readFile(cacheFile, 'utf8')).toBe( + createHash('sha256').update(content).digest('hex') + content, + ); + }); + + it('should reuse the stylesheet across processor instances without another request', async () => { + await mkdir(cacheDirectory, { recursive: true }); + expect(await new InlineFontsProcessor({ cache }).processURL(url)).toBe(content); + getSpy.calls.reset(); + getSpy.and.throwError('Unexpected font request'); + + expect(await new InlineFontsProcessor({ cache }).processURL(url)).toBe(content); + expect(getSpy).not.toHaveBeenCalled(); + expect(existsSync(cacheFile)).toBeTrue(); + }); + + it('should replace corrupted cache content with a downloaded stylesheet', async () => { + await mkdir(cacheDirectory, { recursive: true }); + await writeFile(cacheFile, '0'.repeat(64) + content); + + expect(await new InlineFontsProcessor({ cache }).processURL(url)).toBe(content); + expect(getSpy).toHaveBeenCalledTimes(1); + expect(await readFile(cacheFile, 'utf8')).toBe( + createHash('sha256').update(content).digest('hex') + content, + ); + }); + + it('should not cache stylesheets when the cache is disabled', async () => { + const processor = new InlineFontsProcessor({ cache: { ...cache, enabled: false } }); + + expect(await processor.processURL(url)).toBe(content); + expect(await processor.processURL(url)).toBe(content); + expect(getSpy).toHaveBeenCalledTimes(2); + expect(existsSync(cache.path)).toBeFalse(); + }); + + it('should still return the stylesheet when the cache cannot be written', async () => { + await writeFile(cache.path, 'not a directory'); + + expect(await new InlineFontsProcessor({ cache }).processURL(url)).toBe(content); + expect(getSpy).toHaveBeenCalledTimes(1); + }); + }); + + describe('Google fonts', () => { + const content = ` + + + + + + `; + + it('works with // protocol', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: false, + }); + + const html = await inlineFontsProcessor.process(content.replace('https://', '//')); + expect(html).toContain(`format('woff2');`); + }); + + it('should inline supported fonts and icons in HTML', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: false, + }); + + const html = await inlineFontsProcessor.process(` + + + + + + + + `); + + expect(html).not.toContain( + 'href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"', + ); + expect(html).not.toContain('href="https://fonts.googleapis.com/icon?family=Material+Icons"'); + expect(html).toContain('href="theme.css"'); + expect(html).toContain(`font-family: 'Roboto'`); + expect(html).toContain(`font-family: 'Material Icons'`); + }); + + it('should inline multiple fonts from a single request with minification enabled', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: true, + }); + + const html = await inlineFontsProcessor.process(` + + + + + + + `); + + expect(html).toContain(`'Google Sans'`); + expect(html).toContain(`'Roboto'`); + expect(html).toContain(`'Roboto Mono'`); + expect(html).toContain(`'Material Icons'`); + }); + + it('works with http protocol', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: false, + }); + + const html = await inlineFontsProcessor.process(content.replace('https://', 'http://')); + expect(html).toContain(`format('woff2');`); + }); + + it('should remove comments and line breaks when `minifyInlinedCSS` is true', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: true, + }); + + const html = await inlineFontsProcessor.process(content); + expect(html).not.toContain('/*'); + expect(html).toContain(';font-style:normal;'); + }); + + it('should add preconnect hint', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: false, + }); + + const html = await inlineFontsProcessor.process(content); + expect(html).toContain( + ``, + ); + }); + }); + + describe('Adobe Typekit fonts', () => { + const content = ` + + + + + + `; + + it('should add preconnect hint', async () => { + const inlineFontsProcessor = new InlineFontsProcessor({ + minify: false, + }); + + const html = await inlineFontsProcessor.process(content); + expect(html).toContain(``); + }); + }); +}); diff --git a/packages/angular/build/src/utils/index-file/ngcm-attribute.ts b/packages/angular/build/src/utils/index-file/ngcm-attribute.ts new file mode 100644 index 000000000000..af74778915e6 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/ngcm-attribute.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { htmlRewritingStream } from './html-rewriting-stream'; + +/** + * Defines a name of an attribute that is added to the `` tag + * in the `index.html` file in case a given route was configured + * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode". + * + * @see https://github.com/angular/angular/pull/58004 + */ +const CLIENT_RENDER_MODE_FLAG = 'ngcm'; + +/** + * Transforms the provided HTML by adding the `ngcm` attribute to the `` tag. + * This is used in the client-side rendered (CSR) version of `index.html` to prevent hydration warnings. + * + * @param html The HTML markup to be transformed. + * @returns A promise that resolves to the transformed HTML string with the necessary modifications. + */ +export async function addNgcmAttribute(html: string): Promise { + const { rewriter, transformedContent } = await htmlRewritingStream(html); + + rewriter.on('startTag', (tag) => { + if ( + tag.tagName === 'body' && + !tag.attrs.some((attr) => attr.name === CLIENT_RENDER_MODE_FLAG) + ) { + tag.attrs.push({ name: CLIENT_RENDER_MODE_FLAG, value: '' }); + } + + rewriter.emitStartTag(tag); + }); + + return transformedContent(); +} diff --git a/packages/angular/build/src/utils/index-file/ngcm-attribute_spec.ts b/packages/angular/build/src/utils/index-file/ngcm-attribute_spec.ts new file mode 100644 index 000000000000..2eec900c862d --- /dev/null +++ b/packages/angular/build/src/utils/index-file/ngcm-attribute_spec.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { addNgcmAttribute } from './ngcm-attribute'; + +describe('addNgcmAttribute', () => { + it('should add the ngcm attribute to the tag', async () => { + const result = await addNgcmAttribute(` + + +

hello world!

+ + `); + + expect(result).toContain('

hello world!

'); + }); + + it('should not override an existing ngcm attribute', async () => { + const result = await addNgcmAttribute(` + + +

hello world!

+ + `); + + expect(result).toContain('

hello world!

'); + }); +}); diff --git a/packages/angular/build/src/utils/index-file/nonce.ts b/packages/angular/build/src/utils/index-file/nonce.ts new file mode 100644 index 000000000000..fabb118cd9da --- /dev/null +++ b/packages/angular/build/src/utils/index-file/nonce.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { htmlRewritingStream } from './html-rewriting-stream'; + +/** + * Pattern matching the name of the Angular nonce attribute. Note that this is + * case-insensitive, because HTML attribute names are case-insensitive as well. + */ +const NONCE_ATTR_PATTERN = /ngCspNonce/i; + +const TARGET_LINK_RELS: ReadonlySet = new Set(['stylesheet', 'modulepreload']); + +/** + * Finds the `ngCspNonce` value and copies it to all ` + + + + + + + `); + + expect(result).toContain(''); + expect(result).toContain(''); + }); + + it('should add a lowercase nonce expression to style tags', async () => { + const result = await addNonce(` + + + + + + + + + `); + + expect(result).toContain(''); + }); + + it('should preserve any pre-existing nonces', async () => { + const result = await addNonce(` + + + + + + + + + + `); + + expect(result).toContain(''); + expect(result).toContain(''); + }); + + it('should use the first nonce that is defined on the page', async () => { + const result = await addNonce(` + + + + + + + + + + `); + + expect(result).toContain(''); + }); + + it('should to all script tags', async () => { + const result = await addNonce(` + + + + + + + + + + + `); + + expect(result).toContain(``); + expect(result).toContain(''); + expect(result).toContain(``); + }); + + it('should add the nonce expression to stylesheet and modulepreload link tags', async () => { + const result = await addNonce(` + + + + + + + + + + + `); + + expect(result).toContain(''); + expect(result).toContain(''); + expect(result).toContain(''); + }); + + it('should add the nonce expression when link rel has mixed case or multiple tokens', async () => { + const result = await addNonce(` + + + + + + + + + + `); + + expect(result).toContain(''); + expect(result).toContain(''); + }); +}); diff --git a/packages/angular/build/src/utils/index-file/valid-self-closing-tags.ts b/packages/angular/build/src/utils/index-file/valid-self-closing-tags.ts new file mode 100644 index 000000000000..f86d556b36f0 --- /dev/null +++ b/packages/angular/build/src/utils/index-file/valid-self-closing-tags.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** A list of valid self closing HTML elements */ +export const VALID_SELF_CLOSING_TAGS = new Set([ + 'area', + 'base', + 'br', + 'col', + 'embed', + 'hr', + 'img', + 'input', + 'link', + 'meta', + 'param', + 'source', + 'track', + 'wbr', + + /** SVG tags */ + 'animate', + 'animateMotion', + 'animateTransform', + 'circle', + 'ellipse', + 'feBlend', + 'feColorMatrix', + 'feComponentTransfer', + 'feComposite', + 'feConvolveMatrix', + 'feDiffuseLighting', + 'feDisplacementMap', + 'feDistantLight', + 'feDropShadow', + 'feFlood', + 'feFuncA', + 'feFuncB', + 'feFuncG', + 'feFuncR', + 'feGaussianBlur', + 'feImage', + 'feMerge', + 'feMergeNode', + 'feMorphology', + 'feOffset', + 'fePointLight', + 'feSpecularLighting', + 'feSpotLight', + 'feTile', + 'feTurbulence', + 'line', + 'path', + 'polygon', + 'polyline', + 'rect', + 'text', + 'tspan', + 'linearGradient', + 'radialGradient', + 'stop', + 'image', + 'pattern', + 'defs', + 'g', + 'marker', + 'mask', + 'style', + 'symbol', + 'use', + 'view', + + /** MathML tags */ + 'mspace', + 'mphantom', + 'mrow', + 'mfrac', + 'msqrt', + 'mroot', + 'mstyle', + 'merror', + 'mpadded', + 'mtable', +]); diff --git a/packages/angular/build/src/utils/index.ts b/packages/angular/build/src/utils/index.ts new file mode 100644 index 000000000000..9df32fc10568 --- /dev/null +++ b/packages/angular/build/src/utils/index.ts @@ -0,0 +1,13 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './normalize-asset-patterns'; +export * from './normalize-optimization'; +export * from './normalize-source-maps'; +export * from './load-proxy-config'; +export * from './source-map'; diff --git a/packages/angular/build/src/utils/load-esm.ts b/packages/angular/build/src/utils/load-esm.ts new file mode 100644 index 000000000000..6a6220f66288 --- /dev/null +++ b/packages/angular/build/src/utils/load-esm.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * Lazily compiled dynamic import loader function. + */ +let load: ((modulePath: string | URL) => Promise) | undefined; + +/** + * This uses a dynamic import to load a module which may be ESM. + * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript + * will currently, unconditionally downlevel dynamic import into a require call. + * require calls cannot load ESM code and will result in a runtime error. To workaround + * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. + * Once TypeScript provides support for keeping the dynamic import this workaround can + * be dropped. + * + * @param modulePath The path of the module to load. + * @returns A Promise that resolves to the dynamically imported module. + */ +export function loadEsmModule(modulePath: string | URL): Promise { + load ??= new Function('modulePath', `return import(modulePath);`) as Exclude< + typeof load, + undefined + >; + + return load(modulePath); +} diff --git a/packages/angular/build/src/utils/load-proxy-config.ts b/packages/angular/build/src/utils/load-proxy-config.ts new file mode 100644 index 000000000000..f32db992ac92 --- /dev/null +++ b/packages/angular/build/src/utils/load-proxy-config.ts @@ -0,0 +1,221 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { existsSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import { extname, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { makeRe as makeRegExpFromGlob } from 'picomatch'; +import { isDynamicPattern } from 'tinyglobby'; +import { assertIsError } from './error'; +import { loadEsmModule } from './load-esm'; + +export async function loadProxyConfiguration( + root: string, + proxyConfig: string | undefined, +): Promise | undefined> { + if (!proxyConfig) { + return undefined; + } + + const proxyPath = resolve(root, proxyConfig); + + if (!existsSync(proxyPath)) { + throw new Error(`Proxy configuration file ${proxyPath} does not exist.`); + } + + let proxyConfiguration; + switch (extname(proxyPath)) { + case '.json': { + const content = await readFile(proxyPath, 'utf-8'); + + const { parse, printParseErrorCode } = await import('jsonc-parser'); + const parseErrors: import('jsonc-parser').ParseError[] = []; + proxyConfiguration = parse(content, parseErrors, { allowTrailingComma: true }); + + if (parseErrors.length > 0) { + let errorMessage = `Proxy configuration file ${proxyPath} contains parse errors:`; + for (const parseError of parseErrors) { + const { line, column } = getJsonErrorLineColumn(parseError.offset, content); + errorMessage += `\n[${line}, ${column}] ${printParseErrorCode(parseError.error)}`; + } + throw new Error(errorMessage); + } + + break; + } + default: { + try { + proxyConfiguration = await import(proxyPath); + } catch (e) { + assertIsError(e); + if (e.code !== 'ERR_REQUIRE_ASYNC_MODULE') { + throw e; + } + + proxyConfiguration = await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)); + } + + break; + } + } + + if ('default' in proxyConfiguration) { + proxyConfiguration = proxyConfiguration.default; + } + + return normalizeProxyConfiguration(proxyConfiguration); +} + +/** + * Converts glob patterns to regular expressions to support Vite's proxy option. + * Also converts the Webpack supported array form to an object form supported by both. + * + * @param proxy A proxy configuration object. + */ +function normalizeProxyConfiguration( + proxy: Record | object[], +): Record { + let normalizedProxy: Record | undefined; + + if (Array.isArray(proxy)) { + // Construct an object-form proxy configuration from the array + normalizedProxy = {}; + for (const proxyEntry of proxy) { + if (!('context' in proxyEntry)) { + continue; + } + + // Array-form entries contain a context string array with the path(s) + // to use for the configuration entry. A single path string is also + // accepted, as with the Webpack-based development server. + const context = + typeof proxyEntry.context === 'string' ? [proxyEntry.context] : proxyEntry.context; + if (!Array.isArray(context)) { + continue; + } + + delete proxyEntry.context; + for (const contextEntry of context) { + if (typeof contextEntry !== 'string') { + continue; + } + + normalizedProxy[contextEntry] = proxyEntry; + } + } + } else { + normalizedProxy = proxy; + } + + // TODO: Consider upstreaming glob support + // The object is rebuilt so that converted glob entries keep their original position, + // since Vite proxies a request with the first entry that matches it. + const orderedProxy: Record = {}; + for (const [key, value] of Object.entries(normalizedProxy)) { + const context = key[0] !== '^' && isDynamicPattern(key) ? makeUrlRegExpFromGlob(key) : key; + orderedProxy[context] = value; + } + normalizedProxy = orderedProxy; + + // Replace `pathRewrite` field with a `rewrite` function + for (const proxyEntry of Object.values(normalizedProxy)) { + if ( + typeof proxyEntry === 'object' && + 'pathRewrite' in proxyEntry && + proxyEntry.pathRewrite && + typeof proxyEntry.pathRewrite === 'object' + ) { + // Preprocess path rewrite entries + const pathRewriteEntries: [RegExp, string][] = []; + for (const [pattern, value] of Object.entries( + proxyEntry.pathRewrite as Record, + )) { + pathRewriteEntries.push([new RegExp(pattern), value]); + } + + (proxyEntry as Record).rewrite = pathRewriter.bind( + undefined, + pathRewriteEntries, + ); + + delete proxyEntry.pathRewrite; + } + } + + return normalizedProxy; +} + +/** + * Converts a glob pattern to a regular expression source string that matches + * the pathname portion of a request URL while allowing an optional query string. + * + * Vite tests regex proxy keys against `req.url`, which includes the query string, + * whereas `picomatch` generates regexes assuming the input is only a pathname. + */ +function makeUrlRegExpFromGlob(glob: string): string { + const { source } = makeRegExpFromGlob(glob); + + return ( + source + // Ensure picomatch's "at least one character" lookahead does not + // treat the `?` query delimiter as a pathname character (e.g., `/api/*` on `/api/?a=1`). + .replaceAll('(?=.)', '(?=[^?])') + // Prevent single-segment wildcards (`*` and `?`) from matching + // across `?` into the query string (e.g., `/api/*.json` on `/api/users?file=data.json`). + .replaceAll('[^/]', '[^/?]') + // Prevent leading-dot-aware `?` wildcards from matching the `?` delimiter. + .replaceAll('[^.\\/]', '[^.\\/?]') + // Prevent multi-segment globstars (`**`) from matching across `?` into the query string + // (e.g., `/api/**/users` on `/api/other?redirect=/users`). + .replaceAll('\\.).)*?', '\\.)[^?])*?') + // Replace unescaped end-of-input anchors (`$`, both at the end of the pattern and inside + // internal alternation groups for trailing `/**` or negated globs) so an optional query + // string is permitted after the matched pathname. + .replace(/(? offset) { + break; + } + + position = nextNewline + 1; + } + + return { line, column: offset - position + 1 }; +} diff --git a/packages/angular/build/src/utils/load-proxy-config_spec.ts b/packages/angular/build/src/utils/load-proxy-config_spec.ts new file mode 100644 index 000000000000..c44d74e9556b --- /dev/null +++ b/packages/angular/build/src/utils/load-proxy-config_spec.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { loadProxyConfiguration } from './load-proxy-config'; + +describe('loadProxyConfiguration', () => { + let tempDir: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempDir = await mkdtemp(join(baseTmpDir, 'angular-proxy-config-spec-')); + }); + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + async function createGlobMatcher(glob: string): Promise<(url: string) => boolean> { + const configPath = join(tempDir, 'proxy.conf.json'); + await writeFile(configPath, JSON.stringify({ [glob]: { target: 'http://localhost:3000' } })); + const proxy = await loadProxyConfiguration(tempDir, 'proxy.conf.json'); + assert(proxy, 'Expected proxy configuration to be loaded'); + const keys = Object.keys(proxy); + expect(keys.length).toBe(1); + const regex = new RegExp(keys[0]); + + return (url: string) => regex.test(url); + } + + describe('glob to RegExp conversion with query strings', () => { + it('handles trailing globstar (/**) with and without query strings', async () => { + const matches = await createGlobMatcher('/search/**'); + + expect(matches('/search')).toBeTrue(); + expect(matches('/search?q=angular')).toBeTrue(); + expect(matches('/search/')).toBeTrue(); + expect(matches('/search/?q=angular')).toBeTrue(); + expect(matches('/search/items')).toBeTrue(); + expect(matches('/search/items?q=angular')).toBeTrue(); + expect(matches('/search/items?callback=/.hidden')).toBeTrue(); + + expect(matches('/searching')).toBeFalse(); + expect(matches('/searching?q=angular')).toBeFalse(); + expect(matches('/other?redirect=/search')).toBeFalse(); + }); + + it('handles single-segment wildcard (*) without matching across slashes or query strings', async () => { + const matches = await createGlobMatcher('/api/*'); + + expect(matches('/api/users')).toBeTrue(); + expect(matches('/api/users?id=1')).toBeTrue(); + expect(matches('/api/users?redirect=/home/page')).toBeTrue(); + + expect(matches('/api')).toBeFalse(); + expect(matches('/api/')).toBeFalse(); + expect(matches('/api/?a=1')).toBeFalse(); + expect(matches('/api/users/profile')).toBeFalse(); + expect(matches('/api/users/profile?a=1')).toBeFalse(); + }); + + it('handles suffix globs (*.json) without matching query parameters', async () => { + const matches = await createGlobMatcher('/api/*.json'); + + expect(matches('/api/data.json')).toBeTrue(); + expect(matches('/api/data.json?v=1')).toBeTrue(); + + expect(matches('/api/users')).toBeFalse(); + expect(matches('/api/users?file=data.json')).toBeFalse(); + expect(matches('/api/.json?v=1')).toBeFalse(); + }); + + it('handles middle globstar (/**/) without matching paths in query parameters', async () => { + const matches = await createGlobMatcher('/api/**/users'); + + expect(matches('/api/users')).toBeTrue(); + expect(matches('/api/users?page=1')).toBeTrue(); + expect(matches('/api/v1/users?page=1')).toBeTrue(); + expect(matches('/api/v1/v2/users?page=1')).toBeTrue(); + + expect(matches('/api/other?redirect=/users')).toBeFalse(); + expect(matches('/api/users/profile?page=1')).toBeFalse(); + }); + + it('handles single-character wildcard (?) without matching the query delimiter', async () => { + const matches = await createGlobMatcher('/api/v?'); + + expect(matches('/api/v1')).toBeTrue(); + expect(matches('/api/v1?a=1')).toBeTrue(); + + expect(matches('/api/v')).toBeFalse(); + expect(matches('/api/v?')).toBeFalse(); + expect(matches('/api/v?a=1')).toBeFalse(); + expect(matches('/api/v12?a=1')).toBeFalse(); + }); + + it('handles negated globs (!) with and without query strings', async () => { + const matches = await createGlobMatcher('!/api/public/**'); + + expect(matches('/api/public')).toBeFalse(); + expect(matches('/api/public?foo=1')).toBeFalse(); + expect(matches('/api/public/assets?foo=1')).toBeFalse(); + + expect(matches('/api/private')).toBeTrue(); + expect(matches('/api/private?foo=1')).toBeTrue(); + }); + + it('handles brace expansion and extglobs with query strings', async () => { + const matchesBraces = await createGlobMatcher('/api/{auth,users}/**'); + expect(matchesBraces('/api/auth?q=1')).toBeTrue(); + expect(matchesBraces('/api/users/list?q=1')).toBeTrue(); + expect(matchesBraces('/api/other?q=1')).toBeFalse(); + + const matchesExtglob = await createGlobMatcher('/**/!(*.d).ts'); + expect(matchesExtglob('/app/main.ts')).toBeTrue(); + expect(matchesExtglob('/app/main.ts?extra=.d.ts')).toBeTrue(); + expect(matchesExtglob('/app/main.d.ts')).toBeFalse(); + expect(matchesExtglob('/app/main.d.ts?extra=.ts')).toBeFalse(); + }); + }); +}); diff --git a/packages/angular/build/src/utils/load-rolldown.ts b/packages/angular/build/src/utils/load-rolldown.ts new file mode 100644 index 000000000000..78af6aeb3c9d --- /dev/null +++ b/packages/angular/build/src/utils/load-rolldown.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 MIMALLOC_PURGE_DELAY = 'MIMALLOC_PURGE_DELAY'; + +let rolldownPromise: Promise | undefined; + +/** + * Dynamically loads the `rolldown` module while configuring its embedded + * mimalloc v3 allocator to immediately purge freed arena memory. + * + * Rolldown's native binding statically links mimalloc v3, which defaults to a + * 4-second arena purge delay (`MIMALLOC_PURGE_DELAY=1000` * `MIMALLOC_ARENA_PURGE_MULT=4`) + * and only triggers purges cooperatively during subsequent allocations. In single-run + * CLI builds where Rolldown is not invoked again after bundling completes, non-zero + * purge delays prevent freed arena pages from being decommitted back to the OS, + * leading to high peak RSS during post-bundle stages. + * + * Because mimalloc reads and caches environment options synchronously when the native + * `.node` addon is first loaded (`mi_process_init` -> `_mi_options_init`), temporarily + * setting `MIMALLOC_PURGE_DELAY=0` during the initial `import('rolldown')` call + * configures Rolldown's allocator without leaving the environment variable set for + * subsequent code or child processes. + * + * @returns A promise that resolves to the `rolldown` module namespace. + */ +export function loadRolldown(): Promise { + if (!rolldownPromise) { + const hasCustomPurgeDelay = Object.hasOwn(process.env, MIMALLOC_PURGE_DELAY); + if (!hasCustomPurgeDelay) { + process.env[MIMALLOC_PURGE_DELAY] = '0'; + } + + rolldownPromise = import('rolldown').finally(() => { + if (!hasCustomPurgeDelay) { + delete process.env[MIMALLOC_PURGE_DELAY]; + } + }); + } + + return rolldownPromise; +} diff --git a/packages/angular/build/src/utils/load-rolldown_spec.ts b/packages/angular/build/src/utils/load-rolldown_spec.ts new file mode 100644 index 000000000000..0f7ea7cb4a80 --- /dev/null +++ b/packages/angular/build/src/utils/load-rolldown_spec.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 MIMALLOC_PURGE_DELAY = 'MIMALLOC_PURGE_DELAY'; + +describe('loadRolldown', () => { + const originalEnvValue = process.env[MIMALLOC_PURGE_DELAY]; + + function getFreshLoadRolldown(): typeof import('./load-rolldown') { + delete require.cache[require.resolve('./load-rolldown')]; + + return require('./load-rolldown'); + } + + afterEach(() => { + if (originalEnvValue !== undefined) { + process.env[MIMALLOC_PURGE_DELAY] = originalEnvValue; + } else { + delete process.env[MIMALLOC_PURGE_DELAY]; + } + delete require.cache[require.resolve('./load-rolldown')]; + }); + + it('loads rolldown and cleans up temporary MIMALLOC_PURGE_DELAY when unset', async () => { + delete process.env[MIMALLOC_PURGE_DELAY]; + const { loadRolldown } = getFreshLoadRolldown(); + + const promise1 = loadRolldown(); + expect(process.env[MIMALLOC_PURGE_DELAY]).toBe('0'); + + const promise2 = loadRolldown(); + expect(promise1).toBe(promise2); + + const rolldownModule = await promise1; + expect(typeof rolldownModule.rolldown).toBe('function'); + expect(Object.hasOwn(process.env, MIMALLOC_PURGE_DELAY)).toBeFalse(); + }); + + it('preserves user-configured MIMALLOC_PURGE_DELAY when already set', async () => { + process.env[MIMALLOC_PURGE_DELAY] = '1000'; + const { loadRolldown } = getFreshLoadRolldown(); + + const promise = loadRolldown(); + expect(process.env[MIMALLOC_PURGE_DELAY]).toBe('1000'); + + const rolldownModule = await promise; + expect(typeof rolldownModule.rolldown).toBe('function'); + expect(process.env[MIMALLOC_PURGE_DELAY]).toBe('1000'); + }); +}); diff --git a/packages/angular/build/src/utils/load-translations.ts b/packages/angular/build/src/utils/load-translations.ts new file mode 100644 index 000000000000..e202273dc73d --- /dev/null +++ b/packages/angular/build/src/utils/load-translations.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Diagnostics } from '@angular/localize/tools'; +import { createHash } from 'node:crypto'; +import * as fs from 'node:fs'; + +export type TranslationLoader = (path: string) => { + translations: Record; + format: string; + locale?: string; + diagnostics: Diagnostics; + integrity: string; +}; + +export async function createTranslationLoader(): Promise { + const { parsers, diagnostics } = await importParsers(); + + return (path: string) => { + const content = fs.readFileSync(path, 'utf8'); + const unusedParsers = new Map(); + for (const [format, parser] of Object.entries(parsers)) { + const analysis = parser.analyze(path, content); + if (analysis.canParse) { + // Types don't overlap here so we need to use any. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { locale, translations } = parser.parse(path, content, analysis.hint as any); + const integrity = 'sha256-' + createHash('sha256').update(content).digest('base64'); + + return { format, locale, translations, diagnostics, integrity }; + } else { + unusedParsers.set(parser, analysis); + } + } + + const messages: string[] = []; + for (const [parser, analysis] of unusedParsers.entries()) { + messages.push(analysis.diagnostics.formatDiagnostics(`*** ${parser.constructor.name} ***`)); + } + throw new Error( + `Unsupported translation file format in ${path}. The following parsers were tried:\n` + + messages.join('\n'), + ); + }; +} + +async function importParsers() { + try { + // Load ESM `@angular/localize/tools` using the TypeScript dynamic import workaround. + // Once TypeScript provides support for keeping the dynamic import this workaround can be + // changed to a direct dynamic import. + const { + Diagnostics, + ArbTranslationParser, + SimpleJsonTranslationParser, + Xliff1TranslationParser, + Xliff2TranslationParser, + XtbTranslationParser, + } = await import('@angular/localize/tools'); + + const diagnostics = new Diagnostics(); + const parsers = { + arb: new ArbTranslationParser(), + json: new SimpleJsonTranslationParser(), + xlf: new Xliff1TranslationParser(), + xlf2: new Xliff2TranslationParser(), + // The name ('xmb') needs to match the AOT compiler option + xmb: new XtbTranslationParser(), + }; + + return { parsers, diagnostics }; + } catch { + throw new Error( + `Unable to load translation file parsers. Please ensure '@angular/localize' is installed.`, + ); + } +} diff --git a/packages/angular/build/src/utils/normalize-asset-patterns.ts b/packages/angular/build/src/utils/normalize-asset-patterns.ts new file mode 100644 index 000000000000..a95d91829766 --- /dev/null +++ b/packages/angular/build/src/utils/normalize-asset-patterns.ts @@ -0,0 +1,96 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { statSync } from 'node:fs'; +import path from 'node:path'; +import type { AssetPattern, AssetPatternClass } from '../builders/application/schema'; +import { isSubDirectory } from './path'; + +/** + * Asset pattern configuration normalized into its object form with a resolved `output` directory. + */ +export interface NormalizedAssetsPattern extends AssetPatternClass { + /** Relative output directory within the build output path. */ + output: string; +} + +/** + * Normalizes raw string and object asset patterns into {@link NormalizedAssetsPattern} objects + * and validates that all asset inputs and outputs stay within the workspace and output directories. + * + * @param assetPatterns Raw string or object asset patterns from builder options. + * @param workspaceRoot Workspace root directory path. + * @param projectRoot Project root directory path. + * @param projectSourceRoot Optional project source root directory path. + * @returns An array of normalized asset pattern configurations. + */ +export function normalizeAssetPatterns( + assetPatterns: AssetPattern[], + workspaceRoot: string, + projectRoot: string, + projectSourceRoot: string | undefined, +): NormalizedAssetsPattern[] { + if (assetPatterns.length === 0) { + return []; + } + + // When sourceRoot is not available, we default to ${projectRoot}/src. + const sourceRoot = projectSourceRoot || path.join(projectRoot, 'src'); + const resolvedWorkspaceRoot = path.resolve(workspaceRoot); + const resolvedSourceRoot = path.resolve(resolvedWorkspaceRoot, sourceRoot); + const resolvedProjectRoot = path.resolve(resolvedWorkspaceRoot, projectRoot); + + return assetPatterns.map((assetPattern) => { + let normalized: NormalizedAssetsPattern; + + // Normalize string asset patterns to objects. + if (typeof assetPattern === 'string') { + const assetPath = path.normalize(assetPattern); + const resolvedAssetPath = path.resolve(resolvedWorkspaceRoot, assetPath); + let root: string; + + // Check if the string asset is within sourceRoot. + if (isSubDirectory(resolvedSourceRoot, resolvedAssetPath)) { + root = resolvedSourceRoot; + } else if (isSubDirectory(resolvedProjectRoot, resolvedAssetPath)) { + root = resolvedProjectRoot; + } else if (isSubDirectory(resolvedWorkspaceRoot, resolvedAssetPath)) { + root = resolvedWorkspaceRoot; + } else { + throw new Error(`The ${assetPattern} asset path must be within the workspace root.`); + } + + let isDirectory = true; + try { + isDirectory = statSync(resolvedAssetPath, { throwIfNoEntry: false })?.isDirectory() ?? true; + } catch {} + const glob = isDirectory ? '**/*' : path.basename(assetPath); + const input = isDirectory ? assetPath : path.dirname(assetPath); + + // Output directory for both is the relative path from the root to input. + const output = path.relative(root, path.resolve(resolvedWorkspaceRoot, input)); + + normalized = { glob, input, output }; + } else { + if (!isSubDirectory(resolvedWorkspaceRoot, assetPattern.input)) { + throw new Error(`The ${assetPattern.input} asset path must be within the workspace root.`); + } + + normalized = { + ...assetPattern, + output: path.join('.', assetPattern.output ?? ''), + }; + } + + if (normalized.output.startsWith('..')) { + throw new Error('An asset cannot be written to a location outside of the output path.'); + } + + return normalized; + }); +} diff --git a/packages/angular/build/src/utils/normalize-asset-patterns_spec.ts b/packages/angular/build/src/utils/normalize-asset-patterns_spec.ts new file mode 100644 index 000000000000..d83a74fe0ee8 --- /dev/null +++ b/packages/angular/build/src/utils/normalize-asset-patterns_spec.ts @@ -0,0 +1,228 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import path, { join } from 'node:path'; +import { normalizeAssetPatterns } from './normalize-asset-patterns'; +import { resolveAssets } from './resolve-assets'; + +describe('normalizeAssetPatterns', () => { + let tempRoot: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-assets-test-')); + }); + + afterEach(async () => { + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }); + } + }); + + it('should return an empty array when given no asset patterns', () => { + expect(normalizeAssetPatterns([], tempRoot, '', 'src')).toEqual([]); + }); + + it('should normalize a string asset within sourceRoot relative to sourceRoot', async () => { + await mkdir(join(tempRoot, 'src/assets'), { recursive: true }); + await writeFile(join(tempRoot, 'src/assets/logo.png'), 'PNG'); + + const result = normalizeAssetPatterns( + ['src/assets', 'src/assets/logo.png'], + tempRoot, + '', + 'src', + ); + + expect(result).toEqual([ + { glob: '**/*', input: 'src/assets', output: 'assets' }, + { glob: 'logo.png', input: 'src/assets', output: 'assets' }, + ]); + }); + + it('should normalize a string asset in a sibling directory sharing a prefix with sourceRoot (e.g. src-assets)', async () => { + await mkdir(join(tempRoot, 'src-assets'), { recursive: true }); + await writeFile(join(tempRoot, 'src-assets/logo.png'), 'PNG'); + + const result = normalizeAssetPatterns( + ['src-assets', 'src-assets/logo.png'], + tempRoot, + '', + 'src', + ); + + expect(result).toEqual([ + { glob: '**/*', input: 'src-assets', output: 'src-assets' }, + { glob: 'logo.png', input: 'src-assets', output: 'src-assets' }, + ]); + }); + + it('should normalize a library string asset in a sibling directory sharing a prefix with projectSourceRoot', async () => { + await mkdir(join(tempRoot, 'projects/lib/src-assets'), { recursive: true }); + await writeFile(join(tempRoot, 'projects/lib/src-assets/logo.png'), 'PNG'); + + const result = normalizeAssetPatterns( + ['projects/lib/src-assets', 'projects/lib/src-assets/logo.png'], + tempRoot, + 'projects/lib', + 'projects/lib/src', + ); + + expect(result).toEqual([ + { + glob: '**/*', + input: path.normalize('projects/lib/src-assets'), + output: 'src-assets', + }, + { + glob: 'logo.png', + input: path.normalize('projects/lib/src-assets'), + output: 'src-assets', + }, + ]); + }); + + it('should normalize a string asset in a sibling directory sharing a prefix with projectRoot relative to workspaceRoot', async () => { + await mkdir(join(tempRoot, 'projects/lib-shared'), { recursive: true }); + await writeFile(join(tempRoot, 'projects/lib-shared/logo.png'), 'PNG'); + + const result = normalizeAssetPatterns( + ['projects/lib-shared/logo.png'], + tempRoot, + 'projects/lib', + 'projects/lib/src', + ); + + expect(result).toEqual([ + { + glob: 'logo.png', + input: path.normalize('projects/lib-shared'), + output: path.normalize('projects/lib-shared'), + }, + ]); + }); + + it('should throw when a string asset is in a sibling directory sharing a prefix with workspaceRoot', () => { + const siblingDir = `../${path.basename(tempRoot)}-outside/logo.png`; + + expect(() => normalizeAssetPatterns([siblingDir], tempRoot, '', 'src')).toThrowError( + /asset path must be within the workspace root/, + ); + }); +}); + +describe('resolveAssets', () => { + let tempRoot: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = await mkdtemp(join(baseTmpDir, 'angular-cli-resolve-assets-test-')); + }); + + afterEach(async () => { + if (tempRoot) { + await rm(tempRoot, { recursive: true, force: true }); + } + }); + + it('should ignore both root and nested .gitkeep files by default', async () => { + await mkdir(join(tempRoot, 'src/assets/nested/deep'), { recursive: true }); + await writeFile(join(tempRoot, 'src/assets/.gitkeep'), ''); + await writeFile(join(tempRoot, 'src/assets/nested/.gitkeep'), ''); + await writeFile(join(tempRoot, 'src/assets/nested/deep/.gitkeep'), ''); + await writeFile(join(tempRoot, 'src/assets/nested/deep/logo.png'), 'PNG'); + + const resolved = await resolveAssets( + [{ glob: '**/*', input: 'src/assets', output: 'assets' }], + tempRoot, + ); + + expect(resolved).toEqual([ + { + source: join(tempRoot, 'src/assets/nested/deep/logo.png'), + destination: join('assets', 'nested/deep/logo.png'), + }, + ]); + }); + + it('should throw when a resolved destination escapes the output root via ".." in glob', async () => { + await mkdir(join(tempRoot, 'src'), { recursive: true }); + await writeFile(join(tempRoot, 'outside.txt'), 'secret'); + + await expectAsync( + resolveAssets([{ glob: '../outside.txt', input: 'src', output: '.' }], tempRoot), + ).toBeRejectedWithError('An asset cannot be written to a location outside of the output path.'); + + await expectAsync( + resolveAssets([{ glob: '../*.txt', input: 'src', output: '.' }], tempRoot), + ).toBeRejectedWithError('An asset cannot be written to a location outside of the output path.'); + }); + + it('should not expand directory patterns in glob whether or not ignore is present', async () => { + await mkdir(join(tempRoot, 'src/assets/sub'), { recursive: true }); + await writeFile(join(tempRoot, 'src/assets/sub/file.txt'), 'content'); + await writeFile(join(tempRoot, 'src/assets/sub/ignored.txt'), 'ignored'); + await writeFile(join(tempRoot, 'src/assets/root.txt'), 'root'); + + const resolved = await resolveAssets( + [ + { glob: 'sub/', input: 'src/assets', output: 'assets' }, + { glob: 'sub/', input: 'src/assets', output: 'assets', ignore: ['ignored.txt'] }, + { glob: 'sub', input: 'src/assets', output: 'assets' }, + { glob: 'sub', input: 'src/assets', output: 'assets', ignore: ['ignored.txt'] }, + { glob: 'root.txt/', input: 'src/assets', output: 'assets' }, + { glob: 'root.txt/', input: 'src/assets', output: 'assets', ignore: ['ignored.txt'] }, + ], + tempRoot, + ); + + expect(resolved).toHaveSize(0); + }); + + it('should expand directory patterns in ignore while keeping non-ignored files', async () => { + await mkdir(join(tempRoot, 'src/assets/sub-a/nested'), { recursive: true }); + await mkdir(join(tempRoot, 'src/assets/sub-b/nested'), { recursive: true }); + await writeFile(join(tempRoot, 'src/assets/sub-a/nested/a.txt'), 'a'); + await writeFile(join(tempRoot, 'src/assets/sub-b/nested/b.txt'), 'b'); + await writeFile(join(tempRoot, 'src/assets/keep.txt'), 'keep'); + + const resolved = await resolveAssets( + [{ glob: '**/*', input: 'src/assets', output: 'assets', ignore: ['sub-a/', 'sub-b'] }], + tempRoot, + ); + + expect(resolved).toEqual([ + { + source: join(tempRoot, 'src/assets/keep.txt'), + destination: join('assets', 'keep.txt'), + }, + ]); + }); + + it('should ignore default ignored files even when specified as a static file glob without ignore', async () => { + await mkdir(join(tempRoot, 'src/assets'), { recursive: true }); + await writeFile(join(tempRoot, 'src/assets/.gitkeep'), ''); + await writeFile(join(tempRoot, 'src/assets/.DS_Store'), ''); + await writeFile(join(tempRoot, 'src/assets/Thumbs.db'), ''); + + const resolved = await resolveAssets( + [ + { glob: '.gitkeep', input: 'src/assets', output: 'assets' }, + { glob: '.DS_Store', input: 'src/assets', output: 'assets' }, + { glob: 'Thumbs.db', input: 'src/assets', output: 'assets' }, + ], + tempRoot, + ); + + expect(resolved).toHaveSize(0); + }); +}); diff --git a/packages/angular/build/src/utils/normalize-cache.ts b/packages/angular/build/src/utils/normalize-cache.ts new file mode 100644 index 000000000000..bb24f774f79b --- /dev/null +++ b/packages/angular/build/src/utils/normalize-cache.ts @@ -0,0 +1,152 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { existsSync, readFileSync, statSync } from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; + +/** Version placeholder is replaced during the build process with actual package version */ +const VERSION = '0.0.0-PLACEHOLDER'; + +export interface NormalizedCachedOptions { + /** Whether disk cache is enabled. */ + enabled: boolean; + + /** Disk cache path. Example: `/.angular/cache/v12.0.0`. */ + path: string; + + /** Disk cache base path. Example: `/.angular/cache`. */ + basePath: string; + + /** + * Workspace-local disk cache path. Example: `/.angular/cache/v12.0.0`. + * Always resolves relative to the current workspace root, even within a Git worktree. + */ + localPath?: string; + + /** + * Workspace-local disk cache base path. Example: `/.angular/cache`. + * Always resolves relative to the current workspace root, even within a Git worktree. + */ + localBasePath?: string; +} + +interface CacheMetadata { + enabled?: boolean; + environment?: 'local' | 'ci' | 'all'; + path?: string; +} + +function hasCacheMetadata(value: unknown): value is { cli: { cache: CacheMetadata } } { + return ( + !!value && + typeof value === 'object' && + 'cli' in value && + !!value['cli'] && + typeof value['cli'] === 'object' && + 'cache' in value['cli'] + ); +} + +function getCacheBasePath(workspaceRoot: string, cachePathSetting: string): string { + if (isAbsolute(cachePathSetting)) { + return cachePathSetting; + } + + try { + // Find the git directory, walking up from workspaceRoot if necessary + let currentDir = workspaceRoot; + while (true) { + const gitPath = join(currentDir, '.git'); + if (existsSync(gitPath)) { + const stat = statSync(gitPath); + if (stat.isFile()) { + // Could be a git worktree (or submodule) + const content = readFileSync(gitPath, 'utf8'); + const match = /^gitdir:\s*(.+)$/m.exec(content); + if (match) { + const gitdir = resolve(currentDir, match[1].trim()); + const commondirPath = join(gitdir, 'commondir'); + if (existsSync(commondirPath)) { + // It's a git worktree + const commondir = readFileSync(commondirPath, 'utf8').trim(); + const commonGitDir = resolve(gitdir, commondir); + const relativeWorkspacePath = relative(currentDir, workspaceRoot); + const mainWorkspaceRoot = resolve(dirname(commonGitDir), relativeWorkspacePath); + if (existsSync(mainWorkspaceRoot)) { + return resolve(mainWorkspaceRoot, cachePathSetting); + } + } + } + } + + break; + } + const parentDir = dirname(currentDir); + if (parentDir === currentDir) { + break; + } + currentDir = parentDir; + } + } catch {} + + return resolve(workspaceRoot, cachePathSetting); +} + +/** + * Normalizes the persistent disk cache configuration for a project or workspace. + * + * Resolves whether disk caching is enabled based on the CLI cache metadata, current runtime + * environment (local vs. CI, or WebContainers), and computes the versioned cache directory paths + * (resolving shared Git worktree paths when applicable). + * + * @param projectMetadata The project or workspace metadata object containing optional `cli.cache` settings. + * @param workspaceRoot The absolute path to the workspace root directory. + * @param projectName Optional name of the project used to scope the resolved cache path. + * @param builderName Optional name of the builder or tool used to further scope the resolved cache path. + * @returns The normalized disk cache options including enabled state and resolved directory paths. + */ +export function normalizeCacheOptions( + projectMetadata: unknown, + workspaceRoot: string, + projectName = '', + builderName = '', +): NormalizedCachedOptions { + const cacheMetadata = hasCacheMetadata(projectMetadata) ? projectMetadata.cli.cache : {}; + + const { + // Webcontainers do not currently benefit from persistent disk caching and can lead to increased browser memory usage + enabled = !process.versions.webcontainer, + environment = 'local', + path = '.angular/cache', + } = cacheMetadata; + const isCI = process.env['CI'] === '1' || process.env['CI']?.toLowerCase() === 'true'; + + let cacheEnabled = enabled; + if (cacheEnabled) { + switch (environment) { + case 'ci': + cacheEnabled = isCI; + break; + case 'local': + cacheEnabled = !isCI; + break; + } + } + + const cacheBasePath = getCacheBasePath(workspaceRoot, path); + const localCacheBasePath = isAbsolute(path) ? path : resolve(workspaceRoot, path); + const normalizedBuilderName = builderName.replace('@', '').replaceAll(/[:/]/g, '-'); + + return { + enabled: cacheEnabled, + basePath: cacheBasePath, + path: join(cacheBasePath, VERSION, projectName, normalizedBuilderName), + localBasePath: localCacheBasePath, + localPath: join(localCacheBasePath, VERSION, projectName, normalizedBuilderName), + }; +} diff --git a/packages/angular/build/src/utils/normalize-cache_spec.ts b/packages/angular/build/src/utils/normalize-cache_spec.ts new file mode 100644 index 000000000000..1a0520c96a96 --- /dev/null +++ b/packages/angular/build/src/utils/normalize-cache_spec.ts @@ -0,0 +1,292 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { normalizeCacheOptions } from './normalize-cache'; + +describe('normalizeCacheOptions', () => { + let tempDir: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempDir = await mkdtemp(join(baseTmpDir, 'angular-cache-spec-')); + }); + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + it('should resolve cache path relative to workspace root in a standard repository', async () => { + const workspaceRoot = join(tempDir, 'project'); + await mkdir(join(workspaceRoot, '.git'), { recursive: true }); + + const options = normalizeCacheOptions({}, workspaceRoot); + + expect(options.basePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localBasePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localPath).toBe(resolve(workspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + }); + + it('should resolve cache path relative to main repository root in a git worktree', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + + // Create main repo structure + await mkdir(mainGitDir, { recursive: true }); + + // Create worktree folder and .git file pointing to the main repo's worktree metadata folder + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + + // Create the commondir file in the worktree metadata folder pointing back to the main .git dir + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions({}, worktreeRoot); + + expect(options.basePath).toBe(resolve(mainRepoRoot, '.angular/cache')); + expect(options.path).toBe(resolve(mainRepoRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + expect(options.localBasePath).toBe(resolve(worktreeRoot, '.angular/cache')); + expect(options.localPath).toBe(resolve(worktreeRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + }); + + it('should resolve cache path relative to corresponding nested workspace in main repository for a git worktree', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const mainWorkspaceRoot = join(mainRepoRoot, 'Site1/ClientApp'); + const worktreeRoot = join(tempDir, 'worktree'); + const worktreeWorkspaceRoot = join(worktreeRoot, 'Site1/ClientApp'); + + // Create main repo with a nested Angular workspace directory + await mkdir(mainGitDir, { recursive: true }); + await mkdir(mainWorkspaceRoot, { recursive: true }); + + // Create worktree with the same nested Angular workspace structure and a .git file at the worktree root + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeWorkspaceRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + + // Point the worktree metadata back to the main .git directory + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions({}, worktreeWorkspaceRoot); + + expect(options.basePath).toBe(resolve(mainWorkspaceRoot, '.angular/cache')); + expect(options.path).toBe(resolve(mainWorkspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + expect(options.localBasePath).toBe(resolve(worktreeWorkspaceRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(worktreeWorkspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER'), + ); + }); + + it('should fall back to worktree workspace root when nested workspace does not exist in main repository', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + const worktreeWorkspaceRoot = join(worktreeRoot, 'NewSite/ClientApp'); + + // Create main repo without the 'NewSite/ClientApp' subdirectory (e.g., added only on the worktree branch) + await mkdir(mainGitDir, { recursive: true }); + + // Create worktree with the new nested Angular workspace and link it to the main repo's .git directory + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeWorkspaceRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions({}, worktreeWorkspaceRoot); + + expect(options.basePath).toBe(resolve(worktreeWorkspaceRoot, '.angular/cache')); + expect(options.path).toBe( + resolve(worktreeWorkspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER'), + ); + expect(options.localBasePath).toBe(resolve(worktreeWorkspaceRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(worktreeWorkspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER'), + ); + }); + + it('should resolve local cache path relative to worktree root with custom relative path', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + + await mkdir(mainGitDir, { recursive: true }); + + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions( + { cli: { cache: { path: 'custom-cache' } } }, + worktreeRoot, + ); + + expect(options.basePath).toBe(resolve(mainRepoRoot, 'custom-cache')); + expect(options.path).toBe(resolve(mainRepoRoot, 'custom-cache', '0.0.0-PLACEHOLDER')); + expect(options.localBasePath).toBe(resolve(worktreeRoot, 'custom-cache')); + expect(options.localPath).toBe(resolve(worktreeRoot, 'custom-cache', '0.0.0-PLACEHOLDER')); + }); + + it('should preserve absolute cache path for both shared and local paths', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + const absoluteCachePath = join(tempDir, 'absolute-cache'); + + await mkdir(mainGitDir, { recursive: true }); + + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions( + { cli: { cache: { path: absoluteCachePath } } }, + worktreeRoot, + ); + + expect(options.basePath).toBe(absoluteCachePath); + expect(options.path).toBe(resolve(absoluteCachePath, '0.0.0-PLACEHOLDER')); + expect(options.localBasePath).toBe(absoluteCachePath); + expect(options.localPath).toBe(resolve(absoluteCachePath, '0.0.0-PLACEHOLDER')); + }); + + it('should resolve cache path relative to workspace root in a git submodule', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const submoduleRoot = join(mainRepoRoot, 'submodule'); + + // Create main repo structure and submodule metadata folder + const submoduleGitDir = join(mainRepoRoot, '.git/modules/sub'); + await mkdir(submoduleGitDir, { recursive: true }); + await mkdir(submoduleRoot, { recursive: true }); + + // Create .git file in submodule pointing to the metadata folder + await writeFile(join(submoduleRoot, '.git'), `gitdir: ../.git/modules/sub`); + + // Submodules do NOT have a 'commondir' file. + const options = normalizeCacheOptions({}, submoduleRoot); + + expect(options.basePath).toBe(resolve(submoduleRoot, '.angular/cache')); + expect(options.localBasePath).toBe(resolve(submoduleRoot, '.angular/cache')); + expect(options.localPath).toBe(resolve(submoduleRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + }); + + it('should resolve cache path relative to workspace root when there is no git repository', async () => { + const workspaceRoot = join(tempDir, 'project'); + await mkdir(workspaceRoot, { recursive: true }); + + const options = normalizeCacheOptions({}, workspaceRoot); + + expect(options.basePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localBasePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localPath).toBe(resolve(workspaceRoot, '.angular/cache', '0.0.0-PLACEHOLDER')); + }); + + it('should scope path and localPath to projectName when provided', async () => { + const workspaceRoot = join(tempDir, 'project'); + await mkdir(join(workspaceRoot, '.git'), { recursive: true }); + + const options = normalizeCacheOptions({}, workspaceRoot, 'my-app'); + + expect(options.basePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.path).toBe(resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app')); + expect(options.localBasePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app'), + ); + }); + + it('should scope path and localPath to projectName in a git worktree', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + + await mkdir(mainGitDir, { recursive: true }); + + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions({}, worktreeRoot, 'my-lib'); + + expect(options.basePath).toBe(resolve(mainRepoRoot, '.angular/cache')); + expect(options.path).toBe(resolve(mainRepoRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-lib')); + expect(options.localBasePath).toBe(resolve(worktreeRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(worktreeRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-lib'), + ); + }); + + it('should scope path and localPath to projectName and builderName when provided', async () => { + const workspaceRoot = join(tempDir, 'project'); + await mkdir(join(workspaceRoot, '.git'), { recursive: true }); + + const options = normalizeCacheOptions({}, workspaceRoot, 'my-app', 'vite'); + + expect(options.basePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.path).toBe( + resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/vite'), + ); + expect(options.localBasePath).toBe(resolve(workspaceRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/vite'), + ); + }); + + it('should scope path and localPath to projectName and builderName in a git worktree', async () => { + const mainRepoRoot = join(tempDir, 'main-repo'); + const mainGitDir = join(mainRepoRoot, '.git'); + const worktreeRoot = join(tempDir, 'worktree'); + + await mkdir(mainGitDir, { recursive: true }); + + const worktreeMetadataDir = join(mainGitDir, 'worktrees/wt-1'); + await mkdir(worktreeMetadataDir, { recursive: true }); + await mkdir(worktreeRoot, { recursive: true }); + await writeFile(join(worktreeRoot, '.git'), `gitdir: ${worktreeMetadataDir}`); + await writeFile(join(worktreeMetadataDir, 'commondir'), '../..'); + + const options = normalizeCacheOptions({}, worktreeRoot, 'my-app', 'vite'); + + expect(options.basePath).toBe(resolve(mainRepoRoot, '.angular/cache')); + expect(options.path).toBe( + resolve(mainRepoRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/vite'), + ); + expect(options.localBasePath).toBe(resolve(worktreeRoot, '.angular/cache')); + expect(options.localPath).toBe( + resolve(worktreeRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/vite'), + ); + }); + + it('should normalize builderName to avoid invalid path characters', async () => { + const workspaceRoot = join(tempDir, 'project'); + await mkdir(join(workspaceRoot, '.git'), { recursive: true }); + + const options = normalizeCacheOptions({}, workspaceRoot, 'my-app', '@angular/build:unit-test'); + + expect(options.path).toBe( + resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/angular-build-unit-test'), + ); + expect(options.localPath).toBe( + resolve(workspaceRoot, '.angular/cache/0.0.0-PLACEHOLDER/my-app/angular-build-unit-test'), + ); + }); +}); diff --git a/packages/angular/build/src/utils/normalize-optimization.ts b/packages/angular/build/src/utils/normalize-optimization.ts new file mode 100644 index 000000000000..fcd5b556f27f --- /dev/null +++ b/packages/angular/build/src/utils/normalize-optimization.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { + FontsClass, + OptimizationClass, + OptimizationUnion, + StylesClass, +} from '../builders/application/schema'; + +export type NormalizedOptimizationOptions = Required< + Omit +> & { + fonts: FontsClass; + styles: StylesClass; +}; + +export function normalizeOptimization( + optimization: OptimizationUnion = true, +): NormalizedOptimizationOptions { + if (typeof optimization === 'object') { + const styleOptimization = !!optimization.styles; + + return { + scripts: !!optimization.scripts, + styles: + typeof optimization.styles === 'object' + ? optimization.styles + : { + minify: styleOptimization, + removeSpecialComments: styleOptimization, + inlineCritical: styleOptimization, + }, + fonts: + typeof optimization.fonts === 'object' + ? optimization.fonts + : { + inline: !!optimization.fonts, + }, + }; + } + + return { + scripts: optimization, + styles: { + minify: optimization, + inlineCritical: optimization, + removeSpecialComments: optimization, + }, + fonts: { + inline: optimization, + }, + }; +} diff --git a/packages/angular/build/src/utils/normalize-source-maps.ts b/packages/angular/build/src/utils/normalize-source-maps.ts new file mode 100644 index 000000000000..cf26ca236bae --- /dev/null +++ b/packages/angular/build/src/utils/normalize-source-maps.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { SourceMapClass, SourceMapUnion } from '../builders/application/schema'; + +export function normalizeSourceMaps(sourceMap: SourceMapUnion): SourceMapClass { + const scripts = typeof sourceMap === 'object' ? sourceMap.scripts : sourceMap; + const styles = typeof sourceMap === 'object' ? sourceMap.styles : sourceMap; + const hidden = (typeof sourceMap === 'object' && sourceMap.hidden) || false; + const vendor = (typeof sourceMap === 'object' && sourceMap.vendor) || false; + const sourcesContent = typeof sourceMap === 'object' ? sourceMap.sourcesContent : sourceMap; + + return { + vendor, + hidden, + scripts, + styles, + sourcesContent, + }; +} diff --git a/packages/angular/build/src/utils/path.ts b/packages/angular/build/src/utils/path.ts new file mode 100644 index 000000000000..a236878d134e --- /dev/null +++ b/packages/angular/build/src/utils/path.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { isAbsolute, posix, relative, resolve } from 'node:path'; +import { platform } from 'node:process'; + +const WINDOWS_PATH_SEPERATOR_REGEXP = /\\/g; + +/** + * Converts a Windows-style file path to a POSIX-compliant path. + * + * This function replaces all backslashes (`\`) with forward slashes (`/`). + * It is a no-op on POSIX systems (e.g., Linux, macOS), as the conversion + * only runs on Windows (`win32`). + * + * @param path - The file path to convert. + * @returns The POSIX-compliant file path. + * + * @example + * ```ts + * // On a Windows system: + * toPosixPath('C:\\Users\\Test\\file.txt'); + * // => 'C:/Users/Test/file.txt' + * + * // On a POSIX system (Linux/macOS): + * toPosixPath('/home/user/file.txt'); + * // => '/home/user/file.txt' + * ``` + */ +export function toPosixPath(path: string): string { + return platform === 'win32' ? path.replace(WINDOWS_PATH_SEPERATOR_REGEXP, posix.sep) : path; +} + +/** + * Determines if a path is a subdirectory or file within a parent directory. + * + * @param parent - The parent directory path. + * @param child - The child path to check. + * @returns `true` if the child path is within the parent directory, `false` otherwise. + */ +export function isSubDirectory(parent: string, child: string): boolean { + const resolvedParent = resolve(parent); + const resolvedChild = resolve(parent, child); + const relativePath = toPosixPath(relative(resolvedParent, resolvedChild)); + + return relativePath !== '..' && !relativePath.startsWith('../') && !isAbsolute(relativePath); +} + +/** + * Canonicalizes a file path by normalising Windows drive-letter casing to uppercase. + * + * @param pathString - The file path to canonicalize. + * @returns The canonicalized file path. + */ +export function canonicalizePath(pathString: string): string { + if (platform === 'win32' && /^[a-z]:/.test(pathString)) { + return pathString[0].toUpperCase() + pathString.slice(1); + } + + return pathString; +} diff --git a/packages/angular/build/src/utils/path_spec.ts b/packages/angular/build/src/utils/path_spec.ts new file mode 100644 index 000000000000..cd8ca3372433 --- /dev/null +++ b/packages/angular/build/src/utils/path_spec.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { canonicalizePath, isSubDirectory } from './path'; + +describe('isSubDirectory', () => { + it('should return true for a direct child', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar/baz')).toBeTrue(); + }); + + it('should return true for a nested child', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar/baz/qux/file.txt')).toBeTrue(); + }); + + it('should return true if paths are identical', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar')).toBeTrue(); + }); + + it('should return false for a sibling directory starting with same prefix', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar-outside')).toBeFalse(); + expect(isSubDirectory('/foo/bar', '/foo/bar-outside/file.txt')).toBeFalse(); + }); + + it('should return false for directory outside parent via traversal', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar/../outside')).toBeFalse(); + }); + + it('should return false for parent directory', () => { + expect(isSubDirectory('/foo/bar', '/foo')).toBeFalse(); + }); + + it('should return true for children containing directory names starting with double dots', () => { + expect(isSubDirectory('/foo/bar', '/foo/bar/..baz')).toBeTrue(); + expect(isSubDirectory('/foo/bar', '/foo/bar/..baz/qux')).toBeTrue(); + }); +}); + +describe('canonicalizePath', () => { + it('should return the path unmodified on POSIX systems', () => { + expect(canonicalizePath('/foo/bar/baz')).toBe('/foo/bar/baz'); + }); + + if (process.platform === 'win32') { + it('should uppercase Windows drive-letter casing', () => { + expect(canonicalizePath('c:/foo/bar')).toBe('C:/foo/bar'); + expect(canonicalizePath('d:\\foo\\bar')).toBe('D:\\foo\\bar'); + expect(canonicalizePath('C:/foo/bar')).toBe('C:/foo/bar'); + }); + } +}); diff --git a/packages/angular/build/src/utils/postcss-configuration.ts b/packages/angular/build/src/utils/postcss-configuration.ts new file mode 100644 index 000000000000..e5a4076232a0 --- /dev/null +++ b/packages/angular/build/src/utils/postcss-configuration.ts @@ -0,0 +1,157 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile, readdir } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { join, relative } from 'node:path'; + +export interface PostcssConfiguration { + plugins: [name: string, options?: object | string][]; +} + +interface RawPostcssConfiguration { + plugins?: Record | (string | [string, object])[]; +} + +const postcssConfigurationFiles: string[] = ['postcss.config.json', '.postcssrc.json']; +const tailwindConfigFiles: string[] = [ + 'tailwind.config.js', + 'tailwind.config.cjs', + 'tailwind.config.mjs', + 'tailwind.config.ts', +]; + +export interface SearchDirectory { + root: string; + files: Set; +} + +export function generateSearchDirectories(roots: string[]): Promise { + return Promise.all( + roots.map((root) => + readdir(root, { withFileTypes: true }).then((entries) => ({ + root, + files: new Set(entries.filter((entry) => entry.isFile()).map((entry) => entry.name)), + })), + ), + ); +} + +function findFile( + searchDirectories: SearchDirectory[], + potentialFiles: string[], +): string | undefined { + for (const { root, files } of searchDirectories) { + for (const potential of potentialFiles) { + if (files.has(potential)) { + return join(root, potential); + } + } + } + + return undefined; +} + +export function findTailwindConfiguration( + searchDirectories: SearchDirectory[], +): string | undefined { + return findFile(searchDirectories, tailwindConfigFiles); +} + +export function getTailwindConfig( + searchDirectories: SearchDirectory[], + workspaceRoot: string, + logger?: { warn(message: string): void }, +): { file: string; package: string } | undefined { + const tailwindConfigurationPath = findTailwindConfiguration(searchDirectories); + if (!tailwindConfigurationPath) { + return undefined; + } + + // Create a node resolver from the configuration file + const resolver = createRequire(tailwindConfigurationPath); + try { + return { + file: tailwindConfigurationPath, + package: resolver.resolve('tailwindcss'), + }; + } catch { + const relativeTailwindConfigPath = relative(workspaceRoot, tailwindConfigurationPath); + logger?.warn( + `Tailwind CSS configuration file found (${relativeTailwindConfigPath})` + + ` but the 'tailwindcss' package is not installed.` + + ` To enable Tailwind CSS, please install the 'tailwindcss' package.`, + ); + } + + return undefined; +} + +async function readPostcssConfiguration( + configurationFile: string, +): Promise { + const data = await readFile(configurationFile, 'utf-8'); + const config = JSON.parse(data) as RawPostcssConfiguration; + + return config; +} + +export async function loadPostcssConfiguration(searchDirectories: SearchDirectory[]): Promise< + | { + configPath: string; + config: PostcssConfiguration; + } + | undefined +> { + const configPath = findFile(searchDirectories, postcssConfigurationFiles); + if (!configPath) { + return undefined; + } + + const raw = await readPostcssConfiguration(configPath); + + // If no plugins are defined, consider it equivalent to no configuration + if (!raw.plugins || typeof raw.plugins !== 'object') { + return undefined; + } + + // Normalize plugin array form + if (Array.isArray(raw.plugins)) { + if (raw.plugins.length < 1) { + return undefined; + } + + const config: PostcssConfiguration = { plugins: [] }; + for (const element of raw.plugins) { + if (typeof element === 'string') { + config.plugins.push([element]); + } else { + config.plugins.push(element); + } + } + + return { config, configPath }; + } + + // Normalize plugin object map form + const entries = Object.entries(raw.plugins); + if (entries.length < 1) { + return undefined; + } + + const config: PostcssConfiguration = { plugins: [] }; + for (const [name, options] of entries) { + if (!options || (typeof options !== 'object' && typeof options !== 'string')) { + continue; + } + + config.plugins.push([name, options]); + } + + return { config, configPath }; +} diff --git a/packages/angular/build/src/utils/profiling.ts b/packages/angular/build/src/utils/profiling.ts new file mode 100644 index 000000000000..762a739bd318 --- /dev/null +++ b/packages/angular/build/src/utils/profiling.ts @@ -0,0 +1,112 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { debugPerformance } from './environment-options'; + +let cumulativeDurations: Map | undefined; + +export function resetCumulativeDurations(): void { + cumulativeDurations?.clear(); +} + +export function getAndClearCumulativeDurations(): Record | undefined { + if (!cumulativeDurations || cumulativeDurations.size === 0) { + return undefined; + } + + const data = Object.fromEntries(cumulativeDurations); + + cumulativeDurations.clear(); + + return data; +} + +export function mergeCumulativeDurations(data: Record): void { + cumulativeDurations ??= new Map(); + + for (const [name, durations] of Object.entries(data)) { + let existing = cumulativeDurations.get(name); + if (!existing) { + existing = []; + cumulativeDurations.set(name, existing); + } + + existing.push(...durations); + } +} + +export function logCumulativeDurations(): void { + if (!debugPerformance || !cumulativeDurations) { + return; + } + + for (const [name, durations] of cumulativeDurations) { + let total = 0; + let min; + let max; + for (const duration of durations) { + total += duration; + if (min === undefined || duration < min) { + min = duration; + } + if (max === undefined || duration > max) { + max = duration; + } + } + const average = total / durations.length; + // eslint-disable-next-line no-console + console.log( + `DURATION[${name}]: ${total.toFixed(9)}s [count: ${durations.length}; avg: ${average.toFixed( + 9, + )}s; min: ${min?.toFixed(9)}s; max: ${max?.toFixed(9)}s]`, + ); + } +} + +function recordDuration(name: string, startTime: bigint, cumulative?: boolean): void { + const duration = Number(process.hrtime.bigint() - startTime) / 10 ** 9; + if (cumulative) { + cumulativeDurations ??= new Map(); + const durations = cumulativeDurations.get(name) ?? []; + durations.push(duration); + cumulativeDurations.set(name, durations); + } else { + // eslint-disable-next-line no-console + console.log(`DURATION[${name}]: ${duration.toFixed(9)}s`); + } +} + +export async function profileAsync( + name: string, + action: () => Promise, + cumulative?: boolean, +): Promise { + if (!debugPerformance) { + return action(); + } + + const startTime = process.hrtime.bigint(); + try { + return await action(); + } finally { + recordDuration(name, startTime, cumulative); + } +} + +export function profileSync(name: string, action: () => T, cumulative?: boolean): T { + if (!debugPerformance) { + return action(); + } + + const startTime = process.hrtime.bigint(); + try { + return action(); + } finally { + recordDuration(name, startTime, cumulative); + } +} diff --git a/packages/angular/build/src/utils/project-metadata.ts b/packages/angular/build/src/utils/project-metadata.ts new file mode 100644 index 000000000000..31912d5e9905 --- /dev/null +++ b/packages/angular/build/src/utils/project-metadata.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { join } from 'node:path'; + +/** + * Normalize a directory path string. + * Currently only removes a trailing slash if present. + * @param path A path string. + * @returns A normalized path string. + */ +export function normalizeDirectoryPath(path: string): string { + const last = path.at(-1); + if (last === '/' || last === '\\') { + return path.slice(0, -1); + } + + return path; +} + +export function getProjectRootPaths( + workspaceRoot: string, + projectMetadata: { root?: string; sourceRoot?: string }, +) { + const projectRoot = normalizeDirectoryPath(join(workspaceRoot, projectMetadata.root ?? '')); + const rawSourceRoot = projectMetadata.sourceRoot; + const projectSourceRoot = normalizeDirectoryPath( + rawSourceRoot === undefined ? join(projectRoot, 'src') : join(workspaceRoot, rawSourceRoot), + ); + + return { projectRoot, projectSourceRoot }; +} diff --git a/packages/angular/build/src/utils/purge-cache.ts b/packages/angular/build/src/utils/purge-cache.ts new file mode 100644 index 000000000000..545d2dd97bba --- /dev/null +++ b/packages/angular/build/src/utils/purge-cache.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext } from '@angular-devkit/architect'; +import { readdir, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { normalizeCacheOptions } from './normalize-cache'; + +/** Delete stale cache directories used by previous versions of build-angular. */ +export async function purgeStaleBuildCache(context: BuilderContext): Promise { + const projectName = context.target?.project; + if (!projectName) { + return; + } + + const metadata = await context.getProjectMetadata(projectName); + const { basePath, path, localBasePath, localPath, enabled } = normalizeCacheOptions( + metadata, + context.workspaceRoot, + ); + + if (!enabled) { + return; + } + + const basePaths = new Set([basePath]); + if (localBasePath) { + basePaths.add(localBasePath); + } + + for (const base of basePaths) { + let baseEntries; + try { + baseEntries = await readdir(base, { withFileTypes: true }); + } catch { + // No purging possible if base path does not exist or cannot otherwise be accessed + continue; + } + + const currentPath = base === localBasePath ? localPath : path; + if (!currentPath) { + // Avoid purging if current path is unavailable to prevent deleting the active cache + continue; + } + + const entriesToDelete = baseEntries + .filter((d) => d.isDirectory()) + .map((d) => join(base, d.name)) + .filter((cachePath) => cachePath !== currentPath) + .map((stalePath) => rm(stalePath, { force: true, recursive: true, maxRetries: 3 })); + + await Promise.allSettled(entriesToDelete); + } +} diff --git a/packages/angular/build/src/utils/resolve-assets.ts b/packages/angular/build/src/utils/resolve-assets.ts new file mode 100644 index 000000000000..d7990288b603 --- /dev/null +++ b/packages/angular/build/src/utils/resolve-assets.ts @@ -0,0 +1,141 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { lstat, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { glob, isDynamicPattern } from 'tinyglobby'; +import { MAX_CONCURRENT_READS, mapConcurrent } from './concurrency'; +import { isSubDirectory } from './path'; + +const DEFAULT_ASSET_IGNORE_FILES: ReadonlySet = new Set([ + '.gitkeep', + '.DS_Store', + 'Thumbs.db', +]); +const DEFAULT_ASSET_IGNORE_PATTERNS: readonly string[] = Array.from( + DEFAULT_ASSET_IGNORE_FILES, + (file) => `**/${file}`, +); + +/** + * Normalizes an ignore glob pattern to match directory-exclusion semantics by stripping + * trailing slashes, normalizing POSIX segments, and expanding patterns with `/**` + * (returning both `normalized` and `${normalized}/**` for single-wildcard suffixes + * because `picomatch` does not make trailing `/**` optional after `*`). + * + * @param pattern The raw ignore glob pattern string. + * @returns The normalized POSIX glob patterns. + */ +function normalizeIgnorePattern(pattern: string): string[] { + if (!pattern) { + return []; + } + + const posixNormalized = path.posix.normalize(pattern); + const normalized = + posixNormalized.length > 1 && posixNormalized.endsWith('/') + ? posixNormalized.slice(0, -1) + : posixNormalized; + + if (!normalized.endsWith('*')) { + return [`${normalized}/**`]; + } + + if (normalized === '**' || normalized.endsWith('/**')) { + return [normalized]; + } + + return [normalized, `${normalized}/**`]; +} + +/** + * Combines default asset ignore patterns with user-provided ignore patterns and normalizes + * them so directory patterns (such as `'sub'` or `'sub/'`) exclude all nested files. + * + * @param ignore Optional user-provided ignore glob patterns. + * @returns The normalized ignore glob patterns. + */ +export function normalizeAssetIgnorePatterns(ignore?: readonly string[]): string[] { + if (!ignore?.length) { + return [...DEFAULT_ASSET_IGNORE_PATTERNS]; + } + + return [ + ...DEFAULT_ASSET_IGNORE_PATTERNS, + ...ignore.flatMap((pattern) => normalizeIgnorePattern(pattern)), + ]; +} + +export async function resolveAssets( + entries: { + glob: string; + ignore?: string[]; + input: string; + output: string; + flatten?: boolean; + followSymlinks?: boolean; + }[], + root: string, +): Promise<{ source: string; destination: string }[]> { + const resolvedEntries = await mapConcurrent(entries, MAX_CONCURRENT_READS, async (entry) => { + if (!isSubDirectory(root, entry.input)) { + throw new Error(`The ${entry.input} asset path must be within the workspace root.`); + } + + if (!entry.glob || entry.glob.endsWith('/')) { + return []; + } + + const cwd = path.resolve(root, entry.input); + + if (!entry.ignore?.length && !isDynamicPattern(entry.glob)) { + const src = path.join(cwd, entry.glob); + if (isSubDirectory(cwd, src)) { + if (DEFAULT_ASSET_IGNORE_FILES.has(path.basename(src))) { + return []; + } + + try { + const stats = await (entry.followSymlinks ? stat(src) : lstat(src)); + if (stats.isFile()) { + const filePath = entry.flatten ? path.basename(src) : path.relative(cwd, src); + + return [{ source: src, destination: path.join(entry.output, filePath) }]; + } + + return []; + } catch { + // File does not exist or cannot be accessed. + return []; + } + } + } + + const files = await glob(entry.glob, { + cwd, + dot: true, + expandDirectories: false, + ignore: normalizeAssetIgnorePatterns(entry.ignore), + followSymbolicLinks: entry.followSymlinks ?? false, + }); + + return files.map((file) => { + const destination = path.join(entry.output, entry.flatten ? path.basename(file) : file); + if (destination === '..' || destination.startsWith(`..${path.sep}`)) { + throw new Error('An asset cannot be written to a location outside of the output path.'); + } + + return { + source: path.join(cwd, file), + destination, + }; + }); + }); + + return resolvedEntries.flat(); +} diff --git a/packages/angular/build/src/utils/resolve-project.ts b/packages/angular/build/src/utils/resolve-project.ts new file mode 100644 index 000000000000..ad31825683c4 --- /dev/null +++ b/packages/angular/build/src/utils/resolve-project.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createRequire } from 'node:module'; +import { join } from 'node:path'; + +/** + * Creates a module resolver function that is strictly scoped to the project root. + * This prevents module resolution from leaking the parent module context when executing inside virtual stores (like pnpm). + * + * @param projectRoot The root directory of the project. + * @returns A resolver function that takes a package name/path and returns its resolved path. + */ +export function createProjectResolver(projectRoot: string): (packageName: string) => string { + const projectRequire = createRequire(join(projectRoot, 'package.json')); + + return (packageName: string) => projectRequire.resolve(packageName, { paths: [projectRoot] }); +} diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts new file mode 100644 index 000000000000..6ff4c8f8191c --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +/** + * @note For some unknown reason, setting `globalThis.ngServerMode = true` does not work when using ESM loader hooks. + */ +const NG_SERVER_MODE_INIT_BYTES = new TextEncoder().encode('var ngServerMode=true;'); +const UTF8_DECODER = new TextDecoder(); + +/** + * Node.js ESM loader to redirect imports to in memory files. + * @see: https://nodejs.org/api/esm.html#loaders for more information about loaders. + */ + +const MEMORY_URL_SCHEME = 'memory://'; + +export interface ESMInMemoryFileLoaderWorkerData { + outputFiles: Record; + workspaceRoot: string; +} + +let memoryVirtualRootUrl: string; +let outputFiles: Record; + +export function initialize(data: ESMInMemoryFileLoaderWorkerData) { + // This path does not actually exist but is used to overlay the in memory files with the + // actual filesystem for resolution purposes. + // A custom URL schema (such as `memory://`) cannot be used for the resolve output because + // the in-memory files may use `import.meta.url` in ways that assume a file URL. + // `createRequire` is one example of this usage. + memoryVirtualRootUrl = pathToFileURL( + join(data.workspaceRoot, `.angular/prerender-root/${randomUUID()}/`), + ).href; + outputFiles = data.outputFiles; +} + +export function resolve( + specifier: string, + context: { parentURL: undefined | string }, + nextResolve: Function, +) { + // In-memory files loaded from external code will contain a memory scheme + if (specifier.startsWith(MEMORY_URL_SCHEME)) { + let memoryUrl; + try { + memoryUrl = new URL(specifier); + } catch { + assert.fail('External code attempted to use malformed memory scheme: ' + specifier); + } + + // Resolve with a URL based from the virtual filesystem root + return { + format: 'module', + shortCircuit: true, + url: new URL(memoryUrl.pathname.slice(1), memoryVirtualRootUrl).href, + }; + } + + // Use next/default resolve if the parent is not from the virtual root + if (!context.parentURL?.startsWith(memoryVirtualRootUrl)) { + return nextResolve(specifier, context); + } + + // Check for `./` and `../` relative specifiers + const isRelative = + specifier[0] === '.' && + (specifier[1] === '/' || (specifier[1] === '.' && specifier[2] === '/')); + + // Relative specifiers from memory file should be based from the parent memory location + if (isRelative) { + let specifierUrl; + try { + specifierUrl = new URL(specifier, context.parentURL); + } catch {} + + if ( + specifierUrl?.href.startsWith(memoryVirtualRootUrl) && + Object.hasOwn(outputFiles, specifierUrl.href.slice(memoryVirtualRootUrl.length)) + ) { + return { + format: 'module', + shortCircuit: true, + url: specifierUrl.href, + }; + } + + assert.fail( + `In-memory ESM relative file should always exist: '${context.parentURL}' --> '${specifier}'`, + ); + } + + // Update the parent URL to allow for module resolution for the workspace. + // This handles bare specifiers (npm packages) and absolute paths. + // Defer to the next hook in the chain, which would be the + // Node.js default resolve if this is the last user-specified loader. + return nextResolve(specifier, { + ...context, + parentURL: new URL('index.js', memoryVirtualRootUrl).href, + }); +} + +export function load(url: string, context: { format?: string | null }, nextLoad: Function) { + const { format } = context; + + // Load the file from memory if the URL is based in the virtual root + if (url.startsWith(memoryVirtualRootUrl)) { + const rawSource = outputFiles[url.slice(memoryVirtualRootUrl.length)]; + assert(rawSource !== undefined, 'Resolved in-memory ESM file should always exist: ' + url); + + const source = typeof rawSource === 'string' ? rawSource : UTF8_DECODER.decode(rawSource); + + // In-memory files have already been transformer during bundling and can be returned directly + return { + format: format ?? 'module', + shortCircuit: true, + source, + }; + } + + // Only module files potentially require transformation. Angular libraries that would + // need linking are ESM only. + if (format === 'module' && isFileProtocol(url)) { + // Check url instead of filePath so the check is robust across Windows and POSIX path separators. + if (!url.includes('/@angular/')) { + return nextLoad(url, context); + } + + const filePath = fileURLToPath(url); + const fileBytes = readFileSync(filePath); + const source = Buffer.concat([NG_SERVER_MODE_INIT_BYTES, fileBytes]); + + return { + format, + shortCircuit: true, + source, + }; + } + + // Let Node.js handle all other URLs. + return nextLoad(url); +} + +function isFileProtocol(url: string): boolean { + return url.startsWith('file://'); +} diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks_spec.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks_spec.ts new file mode 100644 index 000000000000..0b32c2248b10 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks_spec.ts @@ -0,0 +1,275 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { initialize, load, resolve } from './loader-hooks'; +import { createSharedServerFiles } from './utils'; + +describe('esm-in-memory-loader loader-hooks', () => { + const workspaceRoot = '/mock/workspace/root'; + const sharedFiles = createSharedServerFiles({ + 'main.server.mjs': 'export const main = true;', + 'chunk-abc.mjs': 'export const chunk = "abc";', + 'nested/chunk-sub.mjs': 'export const sub = "sub";', + 'utf8.mjs': 'export const text = "🔥 UTF-8 🚀";', + 'empty.mjs': '', + }); + + beforeEach(() => { + initialize({ + workspaceRoot, + outputFiles: sharedFiles, + }); + }); + + describe('resolve', () => { + it('should resolve memory:// URLs into virtual filesystem URLs', () => { + const nextResolve = jasmine.createSpy('nextResolve'); + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const result = resolve(memoryUrl, { parentURL: undefined }, nextResolve); + + expect(nextResolve).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.url).toContain('/.angular/prerender-root/'); + expect(result.url).toContain('/main.server.mjs'); + }); + + it('should fail when memory:// URL is malformed', () => { + const nextResolve = jasmine.createSpy('nextResolve'); + expect(() => { + resolve('memory://::invalid', { parentURL: undefined }, nextResolve); + }).toThrowMatching((err: Error) => + err.message.includes('External code attempted to use malformed memory scheme'), + ); + expect(nextResolve).not.toHaveBeenCalled(); + }); + + it('should resolve relative specifiers within in-memory files', () => { + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const parentURL = rootResolve.url; + + const nextResolve = jasmine.createSpy('nextResolve'); + const result = resolve('./chunk-abc.mjs', { parentURL }, nextResolve); + + expect(nextResolve).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.url).toContain('/chunk-abc.mjs'); + }); + + it('should resolve relative specifiers navigating parent directories within in-memory files', () => { + const memoryUrl = new URL('./nested/chunk-sub.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const parentURL = rootResolve.url; + + const nextResolve = jasmine.createSpy('nextResolve'); + const result = resolve('../chunk-abc.mjs', { parentURL }, nextResolve); + + expect(nextResolve).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.url).toContain('/chunk-abc.mjs'); + }); + + it('should fail when relative specifier from in-memory file does not exist', () => { + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const parentURL = rootResolve.url; + + const nextResolve = jasmine.createSpy('nextResolve'); + expect(() => { + resolve('./non-existent.mjs', { parentURL }, nextResolve); + }).toThrowMatching((err: Error) => + err.message.includes('In-memory ESM relative file should always exist'), + ); + expect(nextResolve).not.toHaveBeenCalled(); + }); + + it('should rewrite parentURL to index.js in virtual root for bare package specifiers', () => { + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const parentURL = rootResolve.url; + + const nextResolve = jasmine + .createSpy('nextResolve') + .and.returnValue({ url: 'file:///some/node_modules/@angular/core/index.js' }); + const result = resolve('@angular/core', { parentURL }, nextResolve); + + expect(nextResolve).toHaveBeenCalledWith( + '@angular/core', + jasmine.objectContaining({ + parentURL: jasmine.stringMatching(/\/\.angular\/prerender-root\/[^/]+\/index\.js$/), + }), + ); + expect(result.url).toBe('file:///some/node_modules/@angular/core/index.js'); + }); + + it('should delegate to nextResolve for external non-memory URLs', () => { + const nextResolve = jasmine + .createSpy('nextResolve') + .and.returnValue({ url: 'file:///some/ext/pkg' }); + const result = resolve('some-pkg', { parentURL: 'file:///some/ext/file.js' }, nextResolve); + + expect(nextResolve).toHaveBeenCalledWith('some-pkg', { + parentURL: 'file:///some/ext/file.js', + }); + expect(result.url).toBe('file:///some/ext/pkg'); + }); + }); + + describe('load', () => { + it('should load in-memory file source from SharedArrayBuffer backed Uint8Array', () => { + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nextLoad = jasmine.createSpy('nextLoad'); + + const result = load(rootResolve.url, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.source).toBe('export const main = true;'); + }); + + it('should load in-memory file with multi-byte UTF-8 characters', () => { + const memoryUrl = new URL('./utf8.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nextLoad = jasmine.createSpy('nextLoad'); + + const result = load(rootResolve.url, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.source).toBe('export const text = "🔥 UTF-8 🚀";'); + }); + + it('should load in-memory file with empty content', () => { + const memoryUrl = new URL('./empty.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nextLoad = jasmine.createSpy('nextLoad'); + + const result = load(rootResolve.url, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.source).toBe(''); + }); + + it('should load in-memory file source with non-zero byteOffset in Uint8Array', () => { + const target = 'export const sliced = 42;'; + const fullBuffer = Buffer.from(`__PADDING__${target}__MORE__`); + const offset = Buffer.byteLength('__PADDING__', 'utf-8'); + const length = Buffer.byteLength(target, 'utf-8'); + const subView = new Uint8Array(fullBuffer.buffer, fullBuffer.byteOffset + offset, length); + + initialize({ + workspaceRoot, + outputFiles: { + 'sliced.mjs': subView, + }, + }); + + const memoryUrl = new URL('./sliced.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nextLoad = jasmine.createSpy('nextLoad'); + + const result = load(rootResolve.url, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.source).toBe(target); + }); + + it('should load in-memory file source when outputFiles contain string values', () => { + initialize({ + workspaceRoot, + outputFiles: { + 'string-file.mjs': 'export const fromString = 1;', + }, + }); + + const memoryUrl = new URL('./string-file.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nextLoad = jasmine.createSpy('nextLoad'); + + const result = load(rootResolve.url, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(result.source).toBe('export const fromString = 1;'); + }); + + it('should throw when in-memory file does not exist in outputFiles', () => { + const memoryUrl = new URL('./main.server.mjs', 'memory://').href; + const rootResolve = resolve(memoryUrl, { parentURL: undefined }, () => {}); + const nonExistentVirtualUrl = rootResolve.url.replace('main.server.mjs', 'missing.mjs'); + const nextLoad = jasmine.createSpy('nextLoad'); + + expect(() => load(nonExistentVirtualUrl, { format: 'module' }, nextLoad)).toThrowError( + /Resolved in-memory ESM file should always exist/, + ); + expect(nextLoad).not.toHaveBeenCalled(); + }); + + it('should prepend ngServerMode initialization for @angular/ file URLs', async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + const tmpDir = await mkdtemp(join(baseTmpDir, 'loader-hooks-test-')); + + try { + const angularDir = join(tmpDir, '@angular/core'); + await mkdir(angularDir, { recursive: true }); + const filePath = join(angularDir, 'index.mjs'); + await writeFile(filePath, 'export const VERSION = "1.0.0";'); + + const nextLoad = jasmine.createSpy('nextLoad'); + const result = load(pathToFileURL(filePath).href, { format: 'module' }, nextLoad); + + expect(nextLoad).not.toHaveBeenCalled(); + expect(result.format).toBe('module'); + expect(result.shortCircuit).toBeTrue(); + expect(new TextDecoder().decode(result.source)).toBe( + 'var ngServerMode=true;export const VERSION = "1.0.0";', + ); + } finally { + await rm(tmpDir, { recursive: true, force: true }); + } + }); + + it('should delegate to nextLoad for non-angular file URLs', () => { + const nextLoad = jasmine.createSpy('nextLoad').and.returnValue({ format: 'module' }); + const result = load( + 'file:///workspace/node_modules/rxjs/index.js', + { format: 'module' }, + nextLoad, + ); + + expect(nextLoad).toHaveBeenCalledWith('file:///workspace/node_modules/rxjs/index.js', { + format: 'module', + }); + expect(result.format).toBe('module'); + }); + + it('should delegate to nextLoad for non-memory non-file URLs', () => { + const nextLoad = jasmine.createSpy('nextLoad').and.returnValue({ format: 'builtin' }); + const result = load('node:fs', { format: 'builtin' }, nextLoad); + + expect(nextLoad).toHaveBeenCalledWith('node:fs'); + expect(result.format).toBe('builtin'); + }); + }); +}); diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/register-hooks.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/register-hooks.ts new file mode 100644 index 000000000000..56747e17bd03 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/register-hooks.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { registerHooks } from 'node:module'; +import { workerData } from 'node:worker_threads'; +import { initialize, load, resolve } from './loader-hooks'; + +initialize(workerData); +registerHooks({ resolve, load }); diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils.ts new file mode 100644 index 000000000000..7eb2bd1f5c49 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export const IMPORT_EXEC_ARGV = + '--import=' + pathToFileURL(join(__dirname, 'register-hooks.js')).href; + +/** + * Creates a shared zero-copy `Uint8Array` backed by a `SharedArrayBuffer` for the given file content. + */ +export function createSharedFile(content: string | Uint8Array): Uint8Array { + if (typeof content === 'string') { + const byteLength = Buffer.byteLength(content, 'utf-8'); + const sab = new SharedArrayBuffer(byteLength); + Buffer.from(sab).write(content, 'utf-8'); + + return new Uint8Array(sab); + } + + if (content.buffer instanceof SharedArrayBuffer) { + return content; + } + + const sab = new SharedArrayBuffer(content.byteLength); + const view = new Uint8Array(sab); + view.set(content); + + return view; +} + +/** + * Creates shared zero-copy `Uint8Array` views backed by `SharedArrayBuffer` for all output files. + */ +export function createSharedServerFiles( + outputFiles: Record, +): Record { + const sharedFiles: Record = {}; + + for (const [key, value] of Object.entries(outputFiles)) { + sharedFiles[key] = createSharedFile(value); + } + + return sharedFiles; +} diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils_spec.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils_spec.ts new file mode 100644 index 000000000000..b7bb2844b66e --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/utils_spec.ts @@ -0,0 +1,147 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createSharedFile, createSharedServerFiles } from './utils'; + +describe('server-rendering shared file utilities', () => { + describe('createSharedFile', () => { + it('should create a Uint8Array backed by SharedArrayBuffer from string', () => { + const text = 'console.log("hello world");'; + const shared = createSharedFile(text); + + expect(shared instanceof Uint8Array).toBeTrue(); + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + expect(shared.byteLength).toBe(Buffer.byteLength(text, 'utf-8')); + + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe(text); + }); + + it('should correctly handle multi-byte UTF-8 characters', () => { + const text = 'export const greeting = "🚀 Привет, мир! 🌍";'; + const shared = createSharedFile(text); + + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe(text); + }); + + it('should handle empty string', () => { + const shared = createSharedFile(''); + + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + expect(shared.byteLength).toBe(0); + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe(''); + }); + + it('should handle empty Uint8Array', () => { + const shared = createSharedFile(new Uint8Array(0)); + + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + expect(shared.byteLength).toBe(0); + }); + + it('should return the same Uint8Array if already backed by SharedArrayBuffer', () => { + const text = 'export default 42;'; + const shared1 = createSharedFile(text); + const shared2 = createSharedFile(shared1); + + expect(shared2).toBe(shared1); + expect(shared2.buffer).toBe(shared1.buffer); + }); + + it('should return existing Uint8Array view if already backed by SharedArrayBuffer with non-zero byteOffset', () => { + const text = '0123456789abcdef'; + const shared1 = createSharedFile(text); + const subView = new Uint8Array(shared1.buffer, 4, 8); + const shared2 = createSharedFile(subView); + + expect(shared2).toBe(subView); + expect(shared2.byteOffset).toBe(4); + expect(shared2.byteLength).toBe(8); + + const decoded = Buffer.from(shared2.buffer, shared2.byteOffset, shared2.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe('456789ab'); + }); + + it('should convert standard Uint8Array to SharedArrayBuffer backed Uint8Array', () => { + const regularBuffer = Buffer.from('export const test = true;'); + expect(regularBuffer.buffer instanceof SharedArrayBuffer).toBeFalse(); + + const shared = createSharedFile(regularBuffer); + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe('export const test = true;'); + }); + + it('should handle Uint8Array slice with non-zero byteOffset from standard ArrayBuffer', () => { + const target = 'export const data = 123;'; + const fullBuffer = Buffer.from(`__PREFIX__${target}__SUFFIX__`); + const offset = Buffer.byteLength('__PREFIX__', 'utf-8'); + const length = Buffer.byteLength(target, 'utf-8'); + const subView = new Uint8Array(fullBuffer.buffer, fullBuffer.byteOffset + offset, length); + + const shared = createSharedFile(subView); + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + expect(shared.byteLength).toBe(length); + + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe(target); + }); + }); + + describe('createSharedServerFiles', () => { + it('should convert all entries in a record to SharedArrayBuffer backed Uint8Arrays', () => { + const files: Record = { + 'main.server.mjs': 'export default function() {}', + 'chunk-1.mjs': 'export const x = 1;', + 'render-utils.mjs': Buffer.from('export const helper = () => true;'), + }; + + const sharedFiles = createSharedServerFiles(files); + + expect(Object.keys(sharedFiles)).toEqual([ + 'main.server.mjs', + 'chunk-1.mjs', + 'render-utils.mjs', + ]); + + for (const [key, shared] of Object.entries(sharedFiles)) { + expect(shared instanceof Uint8Array).toBeTrue(); + expect(shared.buffer instanceof SharedArrayBuffer).toBeTrue(); + + const expectedText = + typeof files[key] === 'string' ? files[key] : (files[key] as Buffer).toString('utf-8'); + + const decoded = Buffer.from(shared.buffer, shared.byteOffset, shared.byteLength).toString( + 'utf-8', + ); + expect(decoded).toBe(expectedText); + } + }); + + it('should handle empty file map', () => { + const sharedFiles = createSharedServerFiles({}); + expect(Object.keys(sharedFiles).length).toBe(0); + }); + }); +}); diff --git a/packages/angular/build/src/utils/server-rendering/fetch-patch.ts b/packages/angular/build/src/utils/server-rendering/fetch-patch.ts new file mode 100644 index 000000000000..c099d7dd902c --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/fetch-patch.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { lookup as lookupMimeType } from 'mrmime'; +import { readFile } from 'node:fs/promises'; +import { extname } from 'node:path'; +import { workerData } from 'node:worker_threads'; + +/** + * This is passed as workerData when setting up the worker via the `piscina` package. + */ +const { assetFiles } = workerData as { + assetFiles: Record; +}; + +const assetsCache: Map; content: Buffer }> = + new Map(); + +export function patchFetchToLoadInMemoryAssets(baseURL: URL): void { + const originalFetch = globalThis.fetch; + const patchedFetch: typeof fetch = async (input, init) => { + let url: URL; + if (input instanceof URL) { + url = input; + } else if (typeof input === 'string') { + url = new URL(input, baseURL); + } else if (typeof input === 'object' && 'url' in input) { + url = new URL(input.url, baseURL); + } else { + return originalFetch(input, init); + } + + const { hostname } = url; + const pathname = decodeURIComponent(url.pathname); + + if (hostname !== baseURL.hostname || !assetFiles[pathname]) { + // Only handle relative requests or files that are in assets. + return originalFetch(input, init); + } + + const cachedAsset = assetsCache.get(pathname); + if (cachedAsset) { + const { content, headers } = cachedAsset; + + return new Response(content, { + headers, + }); + } + + const extension = extname(pathname); + const mimeType = lookupMimeType(extension); + const content = await readFile(assetFiles[pathname]); + const headers = mimeType + ? { + 'Content-Type': mimeType, + } + : undefined; + + assetsCache.set(pathname, { headers, content }); + + return new Response(content, { + headers, + }); + }; + + globalThis.fetch = patchedFetch; +} diff --git a/packages/angular/build/src/utils/server-rendering/launch-server.ts b/packages/angular/build/src/utils/server-rendering/launch-server.ts new file mode 100644 index 000000000000..95b2784c6f63 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/launch-server.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { createServer } from 'node:http'; +import { loadEsmModuleFromMemory } from './load-esm-from-memory'; +import { isSsrNodeRequestHandler, isSsrRequestHandler } from './utils'; + +export const DEFAULT_URL = new URL('http://ng-localhost/'); + +/** + * Launches a server that handles local requests. + * + * @returns A promise that resolves to the URL of the running server. + */ +export async function launchServer(): Promise { + const { reqHandler } = await loadEsmModuleFromMemory('./server.mjs'); + const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); + + if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) { + return DEFAULT_URL; + } + + const server = createServer((req, res) => { + (async () => { + // handle request + if (isSsrNodeRequestHandler(reqHandler)) { + await reqHandler(req, res, (e) => { + throw e ?? new Error(`Unable to handle request: '${req.url}'.`); + }); + } else { + const webRes = await reqHandler(createWebRequestFromNodeRequest(req)); + if (webRes) { + await writeResponseToNodeResponse(webRes, res); + } else { + res.statusCode = 501; + res.end('Not Implemented.'); + } + } + })().catch((e) => { + res.statusCode = 500; + res.end('Internal Server Error.'); + // eslint-disable-next-line no-console + console.error(e); + }); + }); + + server.unref(); + + await new Promise((resolve) => server.listen(0, 'localhost', resolve)); + + const serverAddress = server.address(); + assert(serverAddress, 'Server address should be defined.'); + assert(typeof serverAddress !== 'string', 'Server address should not be a string.'); + + return new URL(`http://localhost:${serverAddress.port}/`); +} diff --git a/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts b/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts new file mode 100644 index 000000000000..87ca9928a86f --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ApplicationRef, Type } from '@angular/core'; +import type { BootstrapContext } from '@angular/platform-browser'; +import type { ɵextractRoutesAndCreateRouteTree, ɵgetOrCreateAngularServerApp } from '@angular/ssr'; +import { assertIsError } from '../error'; +import { loadEsmModule } from '../load-esm'; + +/** + * Represents the exports available from the main server bundle. + */ +interface MainServerBundleExports { + default: ((context: BootstrapContext) => Promise) | Type; + ɵextractRoutesAndCreateRouteTree: typeof ɵextractRoutesAndCreateRouteTree; + ɵgetOrCreateAngularServerApp: typeof ɵgetOrCreateAngularServerApp; +} + +/** + * Represents the exports available from the server bundle. + */ +interface ServerBundleExports { + reqHandler?: unknown; +} + +export function loadEsmModuleFromMemory( + path: './main.server.mjs', +): Promise; +export function loadEsmModuleFromMemory(path: './server.mjs'): Promise; +export function loadEsmModuleFromMemory( + path: './main.server.mjs' | './server.mjs', +): Promise { + return loadEsmModule(new URL(path, 'memory://')).catch((e) => { + assertIsError(e); + + // While the error is an 'instanceof Error', it is extended with non transferable properties + // and cannot be transferred from a worker when using `--import`. This results in the error object + // displaying as '[Object object]' when read outside of the worker. Therefore, we reconstruct the error message here. + const error: Error & { code?: string } = new Error(e.message); + error.stack = e.stack; + error.name = e.name; + error.code = e.code; + + throw error; + }) as Promise; +} diff --git a/packages/angular/build/src/utils/server-rendering/manifest.ts b/packages/angular/build/src/utils/server-rendering/manifest.ts new file mode 100644 index 000000000000..b9d60f4edd1d --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/manifest.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import { Buffer } from 'node:buffer'; +import { extname } from 'node:path'; +import { + INDEX_HTML_SERVER, + NormalizedApplicationBuildOptions, +} from '../../builders/application/options'; +import { + type BuildOutputFile, + BuildOutputFileType, + createOutputFile, +} from '../../tools/esbuild/bundler-files'; +import { findNonce } from '../index-file/nonce'; +import { joinUrlParts } from '../url'; + +export const SERVER_APP_MANIFEST_FILENAME = 'angular-app-manifest.mjs'; +export const SERVER_APP_ENGINE_MANIFEST_FILENAME = 'angular-app-engine-manifest.mjs'; + +/** + * A set of server-generated dependencies that are treated as external. + * + * These dependencies are marked as external because they are produced by a + * separate bundling process and are not included in the primary bundle. This + * ensures that these generated files are resolved from an external source rather + * than being part of the main bundle. + */ +export const SERVER_GENERATED_EXTERNALS = new Set([ + './polyfills.server.mjs', + './' + SERVER_APP_MANIFEST_FILENAME, + './' + SERVER_APP_ENGINE_MANIFEST_FILENAME, +]); + +const MAIN_SERVER_OUTPUT_FILENAME = 'main.server.mjs'; + +/** + * A mapping of unsafe characters to their escaped Unicode equivalents. + */ +const UNSAFE_CHAR_MAP: Record = { + '`': '\\`', + '$': '\\$', + '\\': '\\\\', +}; + +/** + * Escapes unsafe characters in a given string by replacing them with + * their Unicode escape sequences. + * + * @param str - The string to be escaped. + * @returns The escaped string where unsafe characters are replaced. + */ +function escapeUnsafeChars(str: string): string { + return str.replace(/[$`\\]/g, (c) => UNSAFE_CHAR_MAP[c]); +} + +/** + * Generates the server manifest for the App Engine environment. + * + * This manifest is used to configure the server-side rendering (SSR) setup for the + * Angular application when deployed to Google App Engine. It includes the entry points + * for different locales and the base HREF for the application. + * + * @param i18nOptions - The internationalization options for the application build. This + * includes settings for inlining locales and determining the output structure. + * @param allowedHosts - A list of hosts that are allowed to access the server-side application. + * @param baseHref - The base HREF for the application. This is used to set the base URL + * for all relative URLs in the application. + */ +export function generateAngularServerAppEngineManifest( + i18nOptions: NormalizedApplicationBuildOptions['i18nOptions'], + allowedHosts: string[], + baseHref: string | undefined, +): string { + const entryPoints: Record = {}; + const supportedLocales: Record = {}; + + if (i18nOptions.shouldInline && !i18nOptions.flatOutput) { + for (const locale of i18nOptions.inlineLocales) { + const { subPath } = i18nOptions.locales[locale]; + const importPath = `${subPath ? `${subPath}/` : ''}${MAIN_SERVER_OUTPUT_FILENAME}`; + entryPoints[subPath] = `() => import(${JSON.stringify(`./${importPath}`)})`; + supportedLocales[locale] = subPath; + } + } else { + entryPoints[''] = `() => import('./${MAIN_SERVER_OUTPUT_FILENAME}')`; + supportedLocales[i18nOptions.sourceLocale] = ''; + } + + // Remove trailing slash but retain leading slash. + let basePath = baseHref || '/'; + if (basePath.length > 1 && basePath.at(-1) === '/') { + basePath = basePath.slice(0, -1); + } + + const manifestContent = ` +export default { + basePath: ${JSON.stringify(basePath)}, + allowedHosts: ${JSON.stringify(allowedHosts, undefined, 2)}, + supportedLocales: ${JSON.stringify(supportedLocales, undefined, 2)}, + entryPoints: { + ${Object.entries(entryPoints) + .map(([key, value]) => `${JSON.stringify(key)}: ${value}`) + .join(',\n ')} + }, +}; +`; + + return manifestContent; +} + +/** + * Generates the server manifest for the standard Node.js environment. + * + * This manifest is used to configure the server-side rendering (SSR) setup for the + * Angular application when running in a standard Node.js environment. It includes + * information about the bootstrap module, whether to inline critical CSS, and any + * additional HTML and CSS output files. + * + * @param additionalHtmlOutputFiles - A map of additional HTML output files generated + * during the build process, keyed by their file paths. + * @param outputFiles - An array of all output files from the build process, including + * JavaScript and CSS files. + * @param inlineCriticalCss - A boolean indicating whether critical CSS should be inlined + * in the server-side rendered pages. + * @param routes - An optional array of route definitions for the application, used for + * server-side rendering and routing. + * @param locale - An optional string representing the locale or language code to be used for + * the application, helping with localization and rendering content specific to the locale. + * @param baseHref - The base HREF for the application. This is used to set the base URL + * for all relative URLs in the application. + * @param initialFiles - A list of initial files that preload tags have already been added for. + * @param metafile - An esbuild metafile object. + * @param publicPath - The configured public path. + * + * @returns An object containing: + * - `manifestContent`: A string of the SSR manifest content. + * - `serverAssetsChunks`: An array of build output files containing the generated assets for the server. + */ +export async function generateAngularServerAppManifest( + additionalHtmlOutputFiles: Map, + outputFiles: BuildOutputFile[], + inlineCriticalCss: boolean, + routes: readonly unknown[] | undefined, + locale: string | undefined, + baseHref: string, + initialFiles: Set, + metafile: Metafile, + publicPath: string | undefined, +): Promise<{ + manifestContent: string; + serverAssetsChunks: BuildOutputFile[]; +}> { + const serverAssetsChunks: BuildOutputFile[] = []; + const serverAssets: Record = {}; + const criticalCssPlans: unknown[] = []; + let nonce: string | undefined; + + // TODO(alanagius): This is done here as we do not use module resolution bundler/node16 + const { compileSheet, encodePlan } = (await import( + 'beasties/compiler' as string + )) as typeof import('beasties/compiler', { with: { 'resolution-mode': 'import' } }); + + for (const file of [...additionalHtmlOutputFiles.values(), ...outputFiles]) { + const extension = extname(file.path); + if (extension === '.html') { + // Mirror the asset path, which is unique, so that two assets never share a chunk. + const jsChunkFilePath = `assets-chunks/${file.path}.mjs`; + const escapedContent = escapeUnsafeChars(file.text); + + serverAssetsChunks.push( + createOutputFile( + jsChunkFilePath, + `export default \`${escapedContent}\`;`, + BuildOutputFileType.ServerApplication, + ), + ); + + // JavaScript engine script parsers normalize `\r\n` (2 bytes in UTF-8) to `\n` (1 byte in UTF-8) in template literals. + // Subtracting the count of `\r\n` occurrences avoids allocating any temporary strings or match arrays for large assets. + let size = Buffer.byteLength(file.text); + let pos = file.text.indexOf('\r\n'); + while (pos !== -1) { + size--; + pos = file.text.indexOf('\r\n', pos + 2); + } + + // Asset paths are derived from route paths and can contain arbitrary characters, so they are + // serialized rather than interpolated into the generated executable manifest. + serverAssets[file.path] = + `{size: ${size}, hash: ${JSON.stringify(file.hash)}, ` + + `text: () => import(${JSON.stringify(`./${jsChunkFilePath}`)}).then(m => m.default)}`; + } else if (inlineCriticalCss && extension === '.css') { + const sheet = compileSheet(file.text, { + href: joinUrlParts(publicPath ?? '', file.path), + }); + criticalCssPlans.push(encodePlan(sheet)); + } + } + + const indexHtml = additionalHtmlOutputFiles.get(INDEX_HTML_SERVER)?.text; + if (indexHtml) { + nonce = (await findNonce(indexHtml)) ?? undefined; + } + + // When routes have been extracted, mappings are no longer needed, as preloads will be included in the metadata. + const entryPointToBrowserMapping = routes?.length + ? undefined + : generateLazyLoadedFilesMappings(metafile, initialFiles, publicPath); + + const manifestContent = ` +export default { + bootstrap: () => import('./main.server.mjs').then(m => m.default), + baseHref: ${JSON.stringify(baseHref)}, +${criticalCssPlans.length ? ` criticalCssPlans: ${JSON.stringify(criticalCssPlans)},\n` : ''}${ + nonce ? ` nonce: ${JSON.stringify(nonce)},\n` : '' + } locale: ${JSON.stringify(locale)}, + routes: ${JSON.stringify(routes, undefined, 2)}, + entryPointToBrowserMapping: ${JSON.stringify(entryPointToBrowserMapping, undefined, 2)}, + assets: { + ${Object.entries(serverAssets) + .map(([key, value]) => `${JSON.stringify(key)}: ${value}`) + .join(',\n ')} + }, +}; +`; + + return { manifestContent, serverAssetsChunks }; +} + +/** + * Maps entry points to their corresponding browser bundles for lazy loading. + * + * This function processes a metafile's outputs to generate a mapping between browser-side entry points + * and the associated JavaScript files that should be loaded in the browser. It includes the entry-point's + * own path and any valid imports while excluding initial files or external resources. + */ +function generateLazyLoadedFilesMappings( + metafile: Metafile, + initialFiles: Set, + publicPath = '', +): Record { + const entryPointToBundles: Record = {}; + for (const [fileName, { entryPoint, exports, imports }] of Object.entries(metafile.outputs)) { + // Skip files that don't have an entryPoint, no exports, or are not .js + if (!entryPoint || exports?.length < 1 || !fileName.endsWith('.js')) { + continue; + } + + const importedPaths: string[] = [`${publicPath}${fileName}`]; + + for (const { kind, external, path } of imports) { + if (external || initialFiles.has(path) || kind !== 'import-statement') { + continue; + } + + importedPaths.push(`${publicPath}${path}`); + } + + entryPointToBundles[entryPoint] = importedPaths; + } + + return entryPointToBundles; +} diff --git a/packages/angular/build/src/utils/server-rendering/manifest_spec.ts b/packages/angular/build/src/utils/server-rendering/manifest_spec.ts new file mode 100644 index 000000000000..84701309eccb --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/manifest_spec.ts @@ -0,0 +1,233 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import { BuildOutputFileType, createOutputFile } from '../../tools/esbuild/bundler-files'; +import { initializeHash } from '../hash'; +import { generateAngularServerAppManifest } from './manifest'; + +describe('generateAngularServerAppManifest', () => { + beforeAll(async () => { + await initializeHash(); + }); + + const dummyMetafile = { inputs: {}, outputs: {} } as unknown as Metafile; + + /** + * Evaluates a generated manifest, which both asserts that it is syntactically valid JavaScript and + * gives access to the values it declares. The dynamic imports it contains are never invoked. + */ + function evaluateManifest(manifestContent: string): unknown { + return new Function(manifestContent.replace('export default', 'return'))(); + } + + function generateManifest( + htmlOutputFiles: Record, + baseHref = '/', + ): ReturnType { + const additionalHtmlOutputFiles = new Map( + Object.entries(htmlOutputFiles).map(([path, content]) => [ + path, + createOutputFile(path, content, BuildOutputFileType.Browser), + ]), + ); + + return generateAngularServerAppManifest( + additionalHtmlOutputFiles, + [], + false, + undefined, + undefined, + baseHref, + new Set(), + dummyMetafile, + undefined, + ); + } + + it('should include criticalCssPlans when inlineCriticalCss is true', async () => { + const additionalHtml = new Map([ + [ + 'index.server.html', + createOutputFile( + 'index.server.html', + '', + BuildOutputFileType.ServerApplication, + ), + ], + ]); + const outputFiles = [ + createOutputFile('styles.css', 'h1 { color: blue; }', BuildOutputFileType.Browser), + ]; + + const { manifestContent } = await generateAngularServerAppManifest( + additionalHtml, + outputFiles, + true, + undefined, + undefined, + '/', + new Set(), + dummyMetafile, + undefined, + ); + + expect(manifestContent).toContain('criticalCssPlans: ['); + expect(manifestContent).toContain('styles.css'); + expect(manifestContent).not.toContain('nonce:'); + }); + + it('should not include criticalCssPlans when inlineCriticalCss is false', async () => { + const additionalHtml = new Map([ + [ + 'index.server.html', + createOutputFile( + 'index.server.html', + '', + BuildOutputFileType.ServerApplication, + ), + ], + ]); + const outputFiles = [ + createOutputFile('styles.css', 'h1 { color: blue; }', BuildOutputFileType.Browser), + ]; + + const { manifestContent } = await generateAngularServerAppManifest( + additionalHtml, + outputFiles, + false, + undefined, + undefined, + '/', + new Set(), + dummyMetafile, + undefined, + ); + + expect(manifestContent).not.toContain('criticalCssPlans:'); + }); + + it('should extract template nonce from index HTML when present', async () => { + const additionalHtml = new Map([ + [ + 'index.server.html', + createOutputFile( + 'index.server.html', + '', + BuildOutputFileType.ServerApplication, + ), + ], + ]); + const outputFiles = [ + createOutputFile('styles.css', 'h1 { color: blue; }', BuildOutputFileType.Browser), + ]; + + const { manifestContent } = await generateAngularServerAppManifest( + additionalHtml, + outputFiles, + true, + undefined, + undefined, + '/', + new Set(), + dummyMetafile, + undefined, + ); + + expect(manifestContent).toContain('nonce: "{% nonce %}"'); + }); + + it('should not include css files in serverAssetsChunks or assets', async () => { + const additionalHtml = new Map([ + [ + 'index.server.html', + createOutputFile( + 'index.server.html', + '', + BuildOutputFileType.ServerApplication, + ), + ], + ]); + const outputFiles = [ + createOutputFile('styles.css', 'h1 { color: blue; }', BuildOutputFileType.Browser), + ]; + + const { manifestContent, serverAssetsChunks } = await generateAngularServerAppManifest( + additionalHtml, + outputFiles, + true, + undefined, + undefined, + '/', + new Set(), + dummyMetafile, + undefined, + ); + + expect(serverAssetsChunks.some((chunk) => chunk.path.includes('styles'))).toBeFalse(); + expect(manifestContent).not.toContain('"styles.css":'); + }); + + it('should serialize asset paths which contain JavaScript string delimiters', async () => { + const assetPath = "catalog/customer's-choice/index.html"; + const { manifestContent } = await generateManifest({ + [assetPath]: '
Featured
', + }); + + expect(evaluateManifest(manifestContent)).toEqual( + jasmine.objectContaining({ + assets: { + [assetPath]: jasmine.objectContaining({ + size: 21, + hash: jasmine.any(String), + text: jasmine.any(Function), + }), + }, + }), + ); + }); + + it('should generate a separate chunk for each asset', async () => { + const { manifestContent, serverAssetsChunks } = await generateManifest({ + 'blog/archive/index.html': '
Archive
', + 'blog_archive/index.html': '
Landing
', + 'blog.archive/index.html': '
Release
', + }); + + expect(serverAssetsChunks).toEqual([ + jasmine.objectContaining({ + path: 'assets-chunks/blog/archive/index.html.mjs', + text: 'export default `
Archive
`;', + }), + jasmine.objectContaining({ + path: 'assets-chunks/blog_archive/index.html.mjs', + text: 'export default `
Landing
`;', + }), + jasmine.objectContaining({ + path: 'assets-chunks/blog.archive/index.html.mjs', + text: 'export default `
Release
`;', + }), + ]); + expect(manifestContent).toContain('import("./assets-chunks/blog/archive/index.html.mjs")'); + expect(manifestContent).toContain('import("./assets-chunks/blog_archive/index.html.mjs")'); + expect(manifestContent).toContain('import("./assets-chunks/blog.archive/index.html.mjs")'); + }); + + it('should serialize a base href which contains JavaScript string delimiters', async () => { + const { manifestContent } = await generateManifest( + { 'index.html': '
' }, + "/o'brien/", + ); + + expect(evaluateManifest(manifestContent)).toEqual( + jasmine.objectContaining({ + baseHref: "/o'brien/", + }), + ); + }); +}); diff --git a/packages/angular/build/src/utils/server-rendering/models.ts b/packages/angular/build/src/utils/server-rendering/models.ts new file mode 100644 index 000000000000..9a9020d2db7f --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/models.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { RenderMode, ɵextractRoutesAndCreateRouteTree } from '@angular/ssr'; +import { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; + +type Writeable = T extends readonly (infer U)[] ? U[] : never; + +export interface RoutesExtractorWorkerData extends ESMInMemoryFileLoaderWorkerData { + assetFiles: Record; +} + +export type SerializableRouteTreeNode = ReturnType< + Awaited>['routeTree']['toObject'] +>; + +export type WritableSerializableRouteTreeNode = Writeable; + +export interface RoutersExtractorWorkerResult { + serializedRouteTree: SerializableRouteTreeNode; + appShellRoute?: string; + errors: string[]; +} + +/** + * Local copy of `RenderMode` exported from `@angular/ssr`. + * This constant is needed to handle interop between CommonJS (CJS) and ES Modules (ESM) formats. + * + * It maps `RenderMode` enum values to their corresponding numeric identifiers. + */ +export const RouteRenderMode: Record = { + Server: 0, + Client: 1, + Prerender: 2, +}; diff --git a/packages/angular/build/src/utils/server-rendering/prerender.ts b/packages/angular/build/src/utils/server-rendering/prerender.ts new file mode 100644 index 000000000000..ec687be0e011 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/prerender.ts @@ -0,0 +1,477 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { extname, posix } from 'node:path'; +import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; +import { OutputMode, Format as PrerenderFormat } from '../../builders/application/schema'; +import { + BuildOutputAsset, + PrerenderedRoutesRecord, +} from '../../tools/esbuild/bundler-execution-result'; +import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundler-files'; +import { assertIsError } from '../error'; +import { toPosixPath } from '../path'; +import { addLeadingSlash, addTrailingSlash, joinUrlParts, stripLeadingSlash } from '../url'; +import { WorkerPool } from '../worker-pool'; +import { + IMPORT_EXEC_ARGV, + createSharedFile, + createSharedServerFiles, +} from './esm-in-memory-loader/utils'; +import { SERVER_APP_MANIFEST_FILENAME } from './manifest'; +import { + RouteRenderMode, + RoutersExtractorWorkerResult, + RoutesExtractorWorkerData, + SerializableRouteTreeNode, + WritableSerializableRouteTreeNode, +} from './models'; +import type { RenderResult, RenderWorkerData } from './render-worker'; +import { generateRedirectStaticPage } from './utils'; + +type PrerenderOptions = NormalizedApplicationBuildOptions['prerenderOptions']; +type AppShellOptions = NormalizedApplicationBuildOptions['appShellOptions']; + +/** + * Represents the output of a prerendering process. + * + * The key is the file path, and the value is an object containing the following properties: + * + * - `content`: The HTML content or output generated for the corresponding file path. + * - `appShellRoute`: A boolean flag indicating whether the content is an app shell. + * + * @example + * { + * '/index.html': { content: '...', appShell: false }, + * '/shell/index.html': { content: '...', appShellRoute: true } + * } + */ +type PrerenderOutput = Record; + +export async function prerenderPages( + workspaceRoot: string, + baseHref: string, + appShellOptions: AppShellOptions | undefined, + prerenderOptions: PrerenderOptions | undefined, + outputFiles: Readonly, + assets: Readonly, + outputMode: OutputMode | undefined, + sourcemap = false, + maxThreads = 1, +): Promise<{ + output: PrerenderOutput; + warnings: string[]; + errors: string[]; + prerenderedRoutes: PrerenderedRoutesRecord; + serializableRouteTreeNode: SerializableRouteTreeNode; +}> { + const rawOutputFiles: Record = {}; + const serverBundlesSourceMaps = new Map(); + const warnings: string[] = []; + const errors: string[] = []; + + for (const { text, path, type } of outputFiles) { + if (type !== BuildOutputFileType.ServerApplication && type !== BuildOutputFileType.ServerRoot) { + continue; + } + + // Contains the server runnable application code + if (extname(path) === '.map') { + serverBundlesSourceMaps.set(path.slice(0, -4), text); + } else { + rawOutputFiles[path] = text; + } + } + + // Inline sourcemap into JS file. This is needed to make Node.js resolve sourcemaps + // when using `--enable-source-maps` when using in memory files. + for (const [filePath, map] of serverBundlesSourceMaps) { + const jsContent = rawOutputFiles[filePath]; + if (jsContent) { + rawOutputFiles[filePath] = + jsContent + + '\n//# sourceMappingURL=' + + `data:application/json;base64,${Buffer.from(map).toString('base64')}`; + } + } + serverBundlesSourceMaps.clear(); + + const outputFilesForWorker = createSharedServerFiles(rawOutputFiles); + + const assetsReversed: Record = {}; + for (const { source, destination } of assets) { + // Assets are not stored with baseHref when using i18n, + // we append the base href so that requests are resolved correctly. + assetsReversed[joinUrlParts(baseHref, toPosixPath(destination))] = source; + } + + // Get routes to prerender + const { + errors: extractionErrors, + serializedRouteTree: serializableRouteTreeNode, + appShellRoute, + } = await getAllRoutes( + workspaceRoot, + baseHref, + outputFilesForWorker, + assetsReversed, + appShellOptions, + prerenderOptions, + sourcemap, + outputMode, + ).catch((err) => { + assertIsError(err); + + return { + errors: [ + `An error occurred while extracting routes.\n\n${err.stack ?? err.message ?? err.code ?? err}`, + ], + serializedRouteTree: [], + appShellRoute: undefined, + }; + }); + + errors.push(...extractionErrors); + + const serializableRouteTreeNodeForPrerender: WritableSerializableRouteTreeNode = []; + for (const metadata of serializableRouteTreeNode) { + if (outputMode !== OutputMode.Static && metadata.redirectTo) { + // Skip redirects if output mode is not static. + continue; + } + + if (metadata.route.includes('*')) { + // Skip catch all routes from prerender. + continue; + } + + switch (metadata.renderMode) { + case undefined: /* Legacy building mode */ + case RouteRenderMode.Prerender: + serializableRouteTreeNodeForPrerender.push(metadata); + break; + case RouteRenderMode.Server: + if (outputMode === OutputMode.Static) { + errors.push( + `Route '${metadata.route}' is configured with server render mode, but the build 'outputMode' is set to 'static'.`, + ); + } + break; + } + } + + if (!serializableRouteTreeNodeForPrerender.length || errors.length > 0) { + return { + errors, + warnings, + output: {}, + prerenderedRoutes: {}, + serializableRouteTreeNode, + }; + } + + // Add the extracted routes to the manifest file. + // We could re-generate it from the start, but that would require a number of options to be passed down. + const manifest = outputFilesForWorker[SERVER_APP_MANIFEST_FILENAME]; + if (manifest) { + const manifestText = new TextDecoder().decode(manifest); + + outputFilesForWorker[SERVER_APP_MANIFEST_FILENAME] = createSharedFile( + manifestText.replace( + 'routes: undefined,', + `routes: ${JSON.stringify(serializableRouteTreeNodeForPrerender, undefined, 2)},`, + ), + ); + } + + // Render routes + const { errors: renderingErrors, output } = await renderPages( + baseHref, + sourcemap, + serializableRouteTreeNodeForPrerender, + maxThreads, + workspaceRoot, + outputFilesForWorker, + assetsReversed, + outputMode, + prerenderOptions?.format, + appShellRoute ?? appShellOptions?.route, + ); + + errors.push(...renderingErrors); + + const prerenderedRoutes: PrerenderedRoutesRecord = {}; + const baseHrefPathnameWithLeadingSlash = new URL(baseHref, 'http://localhost').pathname; + + for (const metadata of serializableRouteTreeNodeForPrerender) { + const outPath = getRouteOutPath( + metadata.route, + baseHrefPathnameWithLeadingSlash, + prerenderOptions?.format, + ); + + if (output[outPath]) { + prerenderedRoutes[metadata.route] = { headers: metadata.headers }; + } + } + + return { + errors, + warnings, + output, + prerenderedRoutes, + serializableRouteTreeNode, + }; +} + +async function renderPages( + baseHref: string, + sourcemap: boolean, + serializableRouteTreeNode: SerializableRouteTreeNode, + maxThreads: number, + workspaceRoot: string, + outputFilesForWorker: Record, + assetFilesForWorker: Record, + outputMode: OutputMode | undefined, + format: PrerenderFormat | undefined, + appShellRoute: string | undefined, +): Promise<{ + output: PrerenderOutput; + errors: string[]; +}> { + const output: PrerenderOutput = {}; + const errors: string[] = []; + + const baseHrefPathnameWithLeadingSlash = new URL(baseHref, 'http://localhost').pathname; + const appShellRouteWithoutBaseHref = appShellRoute + ? addLeadingSlash(getRouteWithoutBaseHref(appShellRoute, baseHrefPathnameWithLeadingSlash)) + : undefined; + + const routesToRender: { route: string; outPath: string; isAppShell: boolean }[] = []; + + for (const { route, redirectTo } of serializableRouteTreeNode) { + // Remove the base href from the file output path. + const routeWithoutBaseHref = getRouteWithoutBaseHref(route, baseHrefPathnameWithLeadingSlash); + const outPath = getRouteOutPath(route, baseHrefPathnameWithLeadingSlash, format); + + if (typeof redirectTo === 'string') { + output[outPath] = { content: generateRedirectStaticPage(redirectTo), appShellRoute: false }; + + continue; + } + + routesToRender.push({ + route, + outPath, + isAppShell: appShellRouteWithoutBaseHref === routeWithoutBaseHref, + }); + } + + if (routesToRender.length === 0) { + return { + errors, + output, + }; + } + + // Batch routes to reduce IPC overhead while ensuring enough batches exist for load balancing across worker threads. + const batchSize = Math.max(1, Math.min(50, Math.ceil(routesToRender.length / (maxThreads * 4)))); + const numBatches = Math.ceil(routesToRender.length / batchSize); + const effectiveMaxThreads = Math.min(numBatches, maxThreads); + + const workerExecArgv = [IMPORT_EXEC_ARGV]; + if (sourcemap) { + workerExecArgv.push('--enable-source-maps'); + } + + const renderWorker = new WorkerPool({ + filename: require.resolve('./render-worker'), + maxThreads: effectiveMaxThreads, + workerData: { + workspaceRoot, + outputFiles: outputFilesForWorker, + assetFiles: assetFilesForWorker, + outputMode, + hasSsrEntry: !!outputFilesForWorker['server.mjs'], + } as RenderWorkerData, + execArgv: workerExecArgv, + env: { + ...process.env, + 'NG_ALLOWED_HOSTS': 'localhost', + }, + }); + + try { + const routeOutPathMap = new Map(); + for (const item of routesToRender) { + routeOutPathMap.set(item.route, item); + } + + const renderingPromises: Promise[] = []; + + for (let i = 0; i < routesToRender.length; i += batchSize) { + const batch = routesToRender.slice(i, i + batchSize); + const urls = batch.map((item) => item.route); + const renderBatchPromise: Promise = renderWorker.run(urls); + const batchResultPromise = renderBatchPromise + .then((results) => { + for (const result of results) { + if ('error' in result) { + errors.push( + `An error occurred while prerendering route '${result.url}'.\n\n${result.error}`, + ); + continue; + } + + const routeInfo = routeOutPathMap.get(result.url); + if (routeInfo) { + output[routeInfo.outPath] = { + content: result.content, + appShellRoute: routeInfo.isAppShell, + }; + } + } + }) + .catch((err) => { + assertIsError(err); + for (const url of urls) { + errors.push( + `An error occurred while prerendering route '${url}'.\n\n${err.stack ?? err.message ?? err.code ?? err}`, + ); + } + }); + + renderingPromises.push(batchResultPromise); + } + + await Promise.all(renderingPromises); + } finally { + void renderWorker.destroy(); + } + + return { + errors, + output, + }; +} + +async function getAllRoutes( + workspaceRoot: string, + baseHref: string, + outputFilesForWorker: Record, + assetFilesForWorker: Record, + appShellOptions: AppShellOptions | undefined, + prerenderOptions: PrerenderOptions | undefined, + sourcemap: boolean, + outputMode: OutputMode | undefined, +): Promise<{ + serializedRouteTree: SerializableRouteTreeNode; + appShellRoute?: string; + errors: string[]; +}> { + const { routesFile, discoverRoutes } = prerenderOptions ?? {}; + const routes: WritableSerializableRouteTreeNode = []; + let appShellRoute: string | undefined; + + if (appShellOptions) { + appShellRoute = joinUrlParts(baseHref, appShellOptions.route); + + routes.push({ + renderMode: RouteRenderMode.Prerender, + route: appShellRoute, + }); + } + + if (routesFile) { + const routesFromFile = (await readFile(routesFile, 'utf8')).split(/\r?\n/); + for (const route of routesFromFile) { + routes.push({ + renderMode: RouteRenderMode.Prerender, + route: joinUrlParts(baseHref, route.trim()), + }); + } + } + + if (!discoverRoutes) { + return { errors: [], appShellRoute, serializedRouteTree: routes }; + } + + const workerExecArgv = [IMPORT_EXEC_ARGV]; + + if (sourcemap) { + workerExecArgv.push('--enable-source-maps'); + } + + const renderWorker = new WorkerPool({ + filename: require.resolve('./routes-extractor-worker'), + maxThreads: 1, + workerData: { + workspaceRoot, + outputFiles: outputFilesForWorker, + assetFiles: assetFilesForWorker, + outputMode, + hasSsrEntry: !!outputFilesForWorker['server.mjs'], + } as RoutesExtractorWorkerData, + execArgv: workerExecArgv, + env: { + ...process.env, + 'NG_ALLOWED_HOSTS': 'localhost', + }, + }); + + try { + const { serializedRouteTree, appShellRoute, errors }: RoutersExtractorWorkerResult = + await renderWorker.run({}); + + if (!routes.length) { + return { errors, appShellRoute, serializedRouteTree }; + } + + // Merge the routing trees + const uniqueRoutes = new Map(); + for (const item of [...routes, ...serializedRouteTree]) { + if (!uniqueRoutes.has(item.route)) { + uniqueRoutes.set(item.route, item); + } + } + + return { errors, serializedRouteTree: Array.from(uniqueRoutes.values()) }; + } catch (err) { + assertIsError(err); + + return { + errors: [ + `An error occurred while extracting routes.\n\n${err.stack ?? err.message ?? err.code ?? err}`, + ], + serializedRouteTree: [], + }; + } finally { + void renderWorker.destroy(); + } +} + +function getRouteWithoutBaseHref(route: string, baseHrefPathname: string): string { + return addTrailingSlash(route).startsWith(baseHrefPathname) + ? addLeadingSlash(route.slice(baseHrefPathname.length)) + : route; +} + +function getRouteOutPath( + route: string, + baseHrefPathname: string, + format: PrerenderFormat | undefined, +): string { + const routeWithoutBaseHref = getRouteWithoutBaseHref(route, baseHrefPathname); + + if (format === PrerenderFormat.File && routeWithoutBaseHref !== '/') { + return stripLeadingSlash(`${routeWithoutBaseHref}.html`); + } + + return stripLeadingSlash(posix.join(routeWithoutBaseHref, 'index.html')); +} diff --git a/packages/angular/build/src/utils/server-rendering/render-worker.ts b/packages/angular/build/src/utils/server-rendering/render-worker.ts new file mode 100644 index 000000000000..df1fdb4ea103 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/render-worker.ts @@ -0,0 +1,113 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { workerData } from 'node:worker_threads'; +import type { OutputMode } from '../../builders/application/schema'; +import { assertIsError } from '../error'; +import type { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; +import { patchFetchToLoadInMemoryAssets } from './fetch-patch'; +import { DEFAULT_URL, launchServer } from './launch-server'; +import { loadEsmModuleFromMemory } from './load-esm-from-memory'; +import { generateRedirectStaticPage } from './utils'; + +export interface RenderWorkerData extends ESMInMemoryFileLoaderWorkerData { + assetFiles: Record; + outputMode: OutputMode | undefined; + hasSsrEntry: boolean; +} + +export type RenderResultItem = + | { + url: string; + content: string; + } + | { + url: string; + error: string; + }; + +export type RenderResult = RenderResultItem[]; + +/** + * This is passed as workerData when setting up the worker via the `piscina` package. + */ +const { outputMode, hasSsrEntry } = workerData as { + outputMode: OutputMode | undefined; + hasSsrEntry: boolean; +}; + +let serverURL = DEFAULT_URL; + +/** + * Renders a single route URL. + */ +async function renderPage( + url: string, + angularServerApp: { handle: (request: Request) => Promise }, +): Promise { + const response = await angularServerApp.handle( + new Request(new URL(url, serverURL), { signal: AbortSignal.timeout(30_000) }), + ); + + if (!response) { + return null; + } + + const location = response.headers.get('Location'); + + return location ? generateRedirectStaticPage(location) : response.text(); +} + +/** + * Renders routes in batch or individual URL. + */ +async function renderPages(urls: string[]): Promise { + const { ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp } = + await loadEsmModuleFromMemory('./main.server.mjs'); + + const angularServerApp = getOrCreateAngularServerApp({ + allowStaticRouteRender: true, + }); + + const results: RenderResult = []; + for (const currentUrl of urls) { + try { + const content = await renderPage(currentUrl, angularServerApp); + + if (content === null) { + throw new Error('The content returned was empty.'); + } + + results.push({ url: currentUrl, content }); + } catch (err) { + assertIsError(err); + results.push({ + url: currentUrl, + error: err.stack ?? err.message ?? err.code ?? `${err}`, + }); + } + } + + return results; +} + +async function initialize() { + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + + if (outputMode !== undefined && hasSsrEntry) { + serverURL = await launchServer(); + } + + patchFetchToLoadInMemoryAssets(serverURL); + + return renderPages; +} + +export default initialize(); diff --git a/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts b/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts new file mode 100644 index 000000000000..423a71e83ba5 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { workerData } from 'node:worker_threads'; +import { OutputMode } from '../../builders/application/schema'; +import { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; +import { patchFetchToLoadInMemoryAssets } from './fetch-patch'; +import { DEFAULT_URL, launchServer } from './launch-server'; +import { loadEsmModuleFromMemory } from './load-esm-from-memory'; +import { RoutersExtractorWorkerResult } from './models'; + +export interface ExtractRoutesWorkerData extends ESMInMemoryFileLoaderWorkerData { + outputMode: OutputMode | undefined; +} + +/** + * This is passed as workerData when setting up the worker via the `piscina` package. + */ +const { outputMode, hasSsrEntry } = workerData as { + outputMode: OutputMode | undefined; + hasSsrEntry: boolean; +}; + +/** Renders an application based on a provided options. */ +async function extractRoutes(): Promise { + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + + const serverURL = outputMode !== undefined && hasSsrEntry ? await launchServer() : DEFAULT_URL; + + patchFetchToLoadInMemoryAssets(serverURL); + + const { ɵextractRoutesAndCreateRouteTree: extractRoutesAndCreateRouteTree } = + await loadEsmModuleFromMemory('./main.server.mjs'); + + const { routeTree, appShellRoute, errors } = await extractRoutesAndCreateRouteTree({ + url: serverURL, + invokeGetPrerenderParams: outputMode !== undefined, + includePrerenderFallbackRoutes: outputMode === OutputMode.Server, + signal: AbortSignal.timeout(30_000), + }); + + return { + errors, + appShellRoute, + serializedRouteTree: routeTree.toObject(), + }; +} + +export default extractRoutes; diff --git a/packages/angular/build/src/utils/server-rendering/utils.ts b/packages/angular/build/src/utils/server-rendering/utils.ts new file mode 100644 index 000000000000..18ab7def9ec1 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/utils.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { createRequestHandler } from '@angular/ssr'; +import type { createNodeRequestHandler } from '@angular/ssr/node' with { + 'resolution-mode': 'import', +}; + +export function isSsrNodeRequestHandler( + value: unknown, +): value is ReturnType { + return typeof value === 'function' && '__ng_node_request_handler__' in value; +} +export function isSsrRequestHandler( + value: unknown, +): value is ReturnType { + return typeof value === 'function' && '__ng_request_handler__' in value; +} + +/** + * A mapping of the characters which have to be escaped to be interpolated into HTML, + * to their entity equivalents. + */ +const HTML_ESCAPE_CHARACTER_MAP: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', +}; + +/** + * Escapes the characters of a value which is interpolated into HTML text or into a quoted + * attribute value. + * + * @param text - The value to escape. + * @returns The escaped value. + */ +function escapeHtml(text: string): string { + return text.replace(/[&<>"']/g, (character) => HTML_ESCAPE_CHARACTER_MAP[character]); +} + +/** + * Generates a static HTML page with a meta refresh tag to redirect the user to a specified URL. + * + * This function creates a simple HTML page that performs a redirect using a meta tag. + * It includes a fallback link in case the meta-refresh doesn't work. + * + * The provided URL is HTML-escaped before being interpolated. + * + * @param url - The URL to which the page should redirect. + * @returns The HTML content of the static redirect page. + */ +export function generateRedirectStaticPage(url: string): string { + const escapedUrl = escapeHtml(url); + + return ` + + + + + Redirecting + + + +
Redirecting to ${escapedUrl}
+ + +`.trim(); +} diff --git a/packages/angular/build/src/utils/server-rendering/utils_spec.ts b/packages/angular/build/src/utils/server-rendering/utils_spec.ts new file mode 100644 index 000000000000..c8d738f8eec1 --- /dev/null +++ b/packages/angular/build/src/utils/server-rendering/utils_spec.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { generateRedirectStaticPage } from './utils'; + +describe('generateRedirectStaticPage', () => { + it('escapes the ampersands of a redirect target', () => { + const page = generateRedirectStaticPage('https://example.com/docs?from=ssg&next=/ssg'); + + expect(page).toContain( + '', + ); + expect(page).toContain( + '' + + 'https://example.com/docs?from=ssg&next=/ssg', + ); + }); + + it('escapes characters which would break out of the attribute or the tag', () => { + const page = generateRedirectStaticPage(`/">`); + + expect(page).not.toContain(' - - - - - - %SCRIPTS% - - - - - - - - diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-debug.html b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-debug.html deleted file mode 100644 index 8c3fe313059d..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-debug.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - -%X_UA_COMPATIBLE% - Karma DEBUG RUNNER - - - - - - - - - - - - - - - %SCRIPTS% - - - - - - - - diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-webpack-failure-cb.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-webpack-failure-cb.ts deleted file mode 100644 index b4c02479bd6e..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma-webpack-failure-cb.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -// Force Webpack to throw compilation errors. Useful with karma-webpack when in single-run mode. -// Workaround for https://github.com/webpack-contrib/karma-webpack/issues/66 - -export class KarmaWebpackFailureCb { - constructor(private callback: (error: string | undefined, errors: string[]) => void) { } - - apply(compiler: any): void { - compiler.hooks.done.tap('KarmaWebpackFailureCb', (stats: any) => { - if (stats.compilation.errors.length > 0) { - this.callback(undefined, stats.compilation.errors.map((error: any) => error.message? error.message : error.toString())); - } - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma.ts deleted file mode 100644 index 86c7ffac7e0f..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/karma.ts +++ /dev/null @@ -1,328 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -import * as path from 'path'; -import * as glob from 'glob'; -import * as webpack from 'webpack'; -const webpackDevMiddleware = require('webpack-dev-middleware'); - -import { KarmaWebpackFailureCb } from './karma-webpack-failure-cb'; -import { statsErrorsToString } from '../utilities/stats'; -import { getWebpackStatsConfig } from '../models/webpack-configs/stats'; -import { createConsoleLogger } from '@angular-devkit/core/node'; -import { logging } from '@angular-devkit/core'; -import { WebpackTestOptions } from '../models/build-options'; -import { normalizeSourceMaps } from '../../utils/index'; - -/** - * Enumerate needed (but not require/imported) dependencies from this file - * to let the dependency validator know they are used. - * - * require('source-map-support') - * require('karma-source-map-support') - */ - - -let blocked: any[] = []; -let isBlocked = false; -let webpackMiddleware: any; -let successCb: () => void; -let failureCb: () => void; - -// Add files to the Karma files array. -function addKarmaFiles(files: any[], newFiles: any[], prepend = false) { - const defaults = { - included: true, - served: true, - watched: true - }; - - const processedFiles = newFiles - // Remove globs that do not match any files, otherwise Karma will show a warning for these. - .filter(file => glob.sync(file.pattern, { nodir: true }).length != 0) - // Fill in pattern properties with defaults. - .map(file => ({ ...defaults, ...file })); - - // It's important to not replace the array, because - // karma already has a reference to the existing array. - if (prepend) { - files.unshift(...processedFiles); - } else { - files.push(...processedFiles); - } -} - -const init: any = (config: any, emitter: any, customFileHandlers: any) => { - if (!config.buildWebpack) { - throw new Error(`The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to` + - ` be used from within Angular CLI and will not work correctly outside of it.` - ) - } - const options = config.buildWebpack.options as WebpackTestOptions; - const logger: logging.Logger = config.buildWebpack.logger || createConsoleLogger(); - successCb = config.buildWebpack.successCb; - failureCb = config.buildWebpack.failureCb; - - // When using code-coverage, auto-add coverage-istanbul. - config.reporters = config.reporters || []; - if (options.codeCoverage && config.reporters.indexOf('coverage-istanbul') === -1) { - config.reporters.push('coverage-istanbul'); - } - - // Add a reporter that fixes sourcemap urls. - if (normalizeSourceMaps(options.sourceMap).scripts) { - config.reporters.push('@angular-devkit/build-angular--sourcemap-reporter'); - - // Code taken from https://github.com/tschaub/karma-source-map-support. - // We can't use it directly because we need to add it conditionally in this file, and karma - // frameworks cannot be added dynamically. - const smsPath = path.dirname(require.resolve('source-map-support')); - const ksmsPath = path.dirname(require.resolve('karma-source-map-support')); - - addKarmaFiles(config.files, [ - { pattern: path.join(smsPath, 'browser-source-map-support.js'), watched: false }, - { pattern: path.join(ksmsPath, 'client.js'), watched: false } - ], true); - } - - config.reporters.push('@angular-devkit/build-angular--event-reporter'); - - // Add webpack config. - const webpackConfig = config.buildWebpack.webpackConfig; - const webpackMiddlewareConfig = { - // Hide webpack output because its noisy. - logLevel: 'error', - stats: false, - watchOptions: { poll: options.poll }, - publicPath: '/_karma_webpack_/', - }; - - const compilationErrorCb = (error: string | undefined, errors: string[]) => { - // Notify potential listeners of the compile error - emitter.emit('compile_error', errors); - - // Finish Karma run early in case of compilation error. - emitter.emit('run_complete', [], { exitCode: 1 }); - - // Unblock any karma requests (potentially started using `karma run`) - unblock(); - } - webpackConfig.plugins.push(new KarmaWebpackFailureCb(compilationErrorCb)); - - // Use existing config if any. - config.webpack = Object.assign(webpackConfig, config.webpack); - config.webpackMiddleware = Object.assign(webpackMiddlewareConfig, config.webpackMiddleware); - - // Our custom context and debug files list the webpack bundles directly instead of using - // the karma files array. - config.customContextFile = `${__dirname}/karma-context.html`; - config.customDebugFile = `${__dirname}/karma-debug.html`; - - // Add the request blocker and the webpack server fallback. - config.beforeMiddleware = config.beforeMiddleware || []; - config.beforeMiddleware.push('@angular-devkit/build-angular--blocker'); - config.middleware = config.middleware || []; - config.middleware.push('@angular-devkit/build-angular--fallback'); - - // The webpack tier owns the watch behavior so we want to force it in the config. - webpackConfig.watch = !config.singleRun; - if (config.singleRun) { - // There's no option to turn off file watching in webpack-dev-server, but - // we can override the file watcher instead. - webpackConfig.plugins.unshift({ - apply: (compiler: any) => { // tslint:disable-line:no-any - compiler.hooks.afterEnvironment.tap('karma', () => { - compiler.watchFileSystem = { watch: () => { } }; - }); - }, - }); - } - // Files need to be served from a custom path for Karma. - webpackConfig.output.path = '/_karma_webpack_/'; - webpackConfig.output.publicPath = '/_karma_webpack_/'; - - let compiler: any; - try { - compiler = webpack(webpackConfig); - } catch (e) { - logger.error(e.stack || e) - if (e.details) { - logger.error(e.details) - } - throw e; - } - - function handler(callback?: () => void) { - isBlocked = true; - - if (typeof callback === 'function') { - callback(); - } - } - - compiler.hooks.invalid.tap('karma', () => handler()); - - compiler.hooks.watchRun.tapAsync('karma', (_: any, callback: () => void) => handler(callback)); - - compiler.hooks.run.tapAsync('karma', (_: any, callback: () => void) => handler(callback)); - - function unblock(){ - isBlocked = false; - blocked.forEach((cb) => cb()); - blocked = []; - } - - let lastCompilationHash: string | undefined; - const statsConfig = getWebpackStatsConfig(); - compiler.hooks.done.tap('karma', (stats: any) => { - if (stats.compilation.errors.length > 0) { - const json = stats.toJson(config.stats); - // Print compilation errors. - logger.error(statsErrorsToString(json, statsConfig)); - lastCompilationHash = undefined; - // Emit a failure build event if there are compilation errors. - failureCb && failureCb(); - } else if (stats.hash != lastCompilationHash) { - // Refresh karma only when there are no webpack errors, and if the compilation changed. - lastCompilationHash = stats.hash; - emitter.refreshFiles(); - } - unblock(); - }); - - webpackMiddleware = new webpackDevMiddleware(compiler, webpackMiddlewareConfig); - - // Forward requests to webpack server. - customFileHandlers.push({ - urlRegex: /^\/_karma_webpack_\/.*/, - handler: function handler(req: any, res: any) { - webpackMiddleware(req, res, function () { - // Ensure script and style bundles are served. - // They are mentioned in the custom karma context page and we don't want them to 404. - const alwaysServe = [ - '/_karma_webpack_/runtime.js', - '/_karma_webpack_/polyfills.js', - '/_karma_webpack_/polyfills-es5.js', - '/_karma_webpack_/scripts.js', - '/_karma_webpack_/styles.js', - '/_karma_webpack_/vendor.js', - ]; - if (alwaysServe.indexOf(req.url) != -1) { - res.statusCode = 200; - res.end(); - } else { - res.statusCode = 404; - res.end('Not found'); - } - }); - } - }); - - emitter.on('exit', (done: any) => { - webpackMiddleware.close(); - done(); - }); -}; - -init.$inject = ['config', 'emitter', 'customFileHandlers']; - -// Block requests until the Webpack compilation is done. -function requestBlocker() { - return function (_request: any, _response: any, next: () => void) { - if (isBlocked) { - blocked.push(next); - } else { - next(); - } - }; -} - -// Copied from "karma-jasmine-diff-reporter" source code: -// In case, when multiple reporters are used in conjunction -// with initSourcemapReporter, they both will show repetitive log -// messages when displaying everything that supposed to write to terminal. -// So just suppress any logs from initSourcemapReporter by doing nothing on -// browser log, because it is an utility reporter, -// unless it's alone in the "reporters" option and base reporter is used. -function muteDuplicateReporterLogging(context: any, config: any) { - context.writeCommonMsg = function () { }; - const reporterName = '@angular/cli'; - const hasTrailingReporters = config.reporters.slice(-1).pop() !== reporterName; - - if (hasTrailingReporters) { - context.writeCommonMsg = function () { }; - } -} - -// Emits builder events. -const eventReporter: any = function (this: any, baseReporterDecorator: any, config: any) { - baseReporterDecorator(this); - - muteDuplicateReporterLogging(this, config); - - this.onRunComplete = function (_browsers: any, results: any) { - if (results.exitCode === 0) { - successCb && successCb(); - } else { - failureCb && failureCb(); - } - } - - // avoid duplicate failure message - this.specFailure = () => {}; -}; - -eventReporter.$inject = ['baseReporterDecorator', 'config']; - -// Strip the server address and webpack scheme (webpack://) from error log. -const sourceMapReporter: any = function (this: any, baseReporterDecorator: any, config: any) { - baseReporterDecorator(this); - - muteDuplicateReporterLogging(this, config); - - const urlRegexp = /http:\/\/localhost:\d+\/_karma_webpack_\/webpack:\//gi; - - this.onSpecComplete = function (_browser: any, result: any) { - if (!result.success && result.log.length > 0) { - result.log.forEach((log: string, idx: number) => { - result.log[idx] = log.replace(urlRegexp, ''); - }); - } - }; - - // avoid duplicate complete message - this.onRunComplete = () => {}; - - // avoid duplicate failure message - this.specFailure = () => {}; -}; - -sourceMapReporter.$inject = ['baseReporterDecorator', 'config']; - -// When a request is not found in the karma server, try looking for it from the webpack server root. -function fallbackMiddleware() { - return function (req: any, res: any, next: () => void) { - if (webpackMiddleware) { - const webpackUrl = '/_karma_webpack_' + req.url; - const webpackReq = { ...req, url: webpackUrl } - webpackMiddleware(webpackReq, res, next); - } else { - next(); - } - }; -} - -module.exports = { - 'framework:@angular-devkit/build-angular': ['factory', init], - 'reporter:@angular-devkit/build-angular--sourcemap-reporter': ['type', sourceMapReporter], - 'reporter:@angular-devkit/build-angular--event-reporter': ['type', eventReporter], - 'middleware:@angular-devkit/build-angular--blocker': ['factory', requestBlocker], - 'middleware:@angular-devkit/build-angular--fallback': ['factory', fallbackMiddleware] -}; diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/named-chunks-plugin.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/named-chunks-plugin.ts deleted file mode 100644 index 79769dcb0c37..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/named-chunks-plugin.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Compiler } from 'webpack'; -// Webpack doesn't export these so the deep imports can potentially break. -// There doesn't seem to exist any ergonomic way to alter chunk names for non-context lazy chunks -// (https://github.com/webpack/webpack/issues/9075) so this is the best alternative for now. -const ImportDependency = require('webpack/lib/dependencies/ImportDependency'); -const ImportDependenciesBlock = require('webpack/lib/dependencies/ImportDependenciesBlock'); -const Template = require('webpack/lib/Template'); - -export class NamedLazyChunksPlugin { - constructor() { } - apply(compiler: Compiler): void { - compiler.hooks.compilation.tap('named-lazy-chunks-plugin', compilation => { - // The dependencyReference hook isn't in the webpack typings so we have to type it as any. - // tslint:disable-next-line: no-any - (compilation.hooks as any).dependencyReference.tap('named-lazy-chunks-plugin', - // tslint:disable-next-line: no-any - (_: any, dependency: any) => { - if ( - // Check this dependency is from an `import()` statement. - dependency instanceof ImportDependency - && dependency.block instanceof ImportDependenciesBlock - // Don't rename chunks that already have a name. - && dependency.block.chunkName === null - ) { - // Convert the request to a valid chunk name using the same logic used - // in webpack/lib/ContextModule.js - dependency.block.chunkName = Template.toPath(dependency.request); - } - }); - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/postcss-cli-resources.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/postcss-cli-resources.ts deleted file mode 100644 index b809946daa57..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/postcss-cli-resources.ts +++ /dev/null @@ -1,219 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { interpolateName } from 'loader-utils'; -import * as path from 'path'; -import * as postcss from 'postcss'; -import * as url from 'url'; -import * as webpack from 'webpack'; - -function wrapUrl(url: string): string { - let wrappedUrl; - const hasSingleQuotes = url.indexOf('\'') >= 0; - - if (hasSingleQuotes) { - wrappedUrl = `"${url}"`; - } else { - wrappedUrl = `'${url}'`; - } - - return `url(${wrappedUrl})`; -} - -export interface PostcssCliResourcesOptions { - baseHref?: string; - deployUrl?: string; - resourcesOutputPath?: string; - rebaseRootRelative?: boolean; - filename: string; - loader: webpack.loader.LoaderContext; - emitFile: boolean; -} - -async function resolve( - file: string, - base: string, - resolver: (file: string, base: string) => Promise, -): Promise { - try { - return await resolver('./' + file, base); - } catch { - return resolver(file, base); - } -} - -export default postcss.plugin('postcss-cli-resources', (options: PostcssCliResourcesOptions) => { - const { - deployUrl = '', - baseHref = '', - resourcesOutputPath = '', - rebaseRootRelative = false, - filename, - loader, - emitFile, - } = options; - - const dedupeSlashes = (url: string) => url.replace(/\/\/+/g, '/'); - - const process = async (inputUrl: string, context: string, resourceCache: Map) => { - // If root-relative, absolute or protocol relative url, leave as is - if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) { - return inputUrl; - } - - if (!rebaseRootRelative && /^\//.test(inputUrl)) { - return inputUrl; - } - - // If starts with a caret, remove and return remainder - // this supports bypassing asset processing - if (inputUrl.startsWith('^')) { - return inputUrl.substr(1); - } - - const cacheKey = path.resolve(context, inputUrl); - const cachedUrl = resourceCache.get(cacheKey); - if (cachedUrl) { - return cachedUrl; - } - - if (inputUrl.startsWith('~')) { - inputUrl = inputUrl.substr(1); - } - - if (inputUrl.startsWith('/')) { - let outputUrl = ''; - if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) { - // If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is. - outputUrl = `${deployUrl.replace(/\/$/, '')}${inputUrl}`; - } else if (baseHref.match(/:\/\//)) { - // If baseHref contains a scheme, include it as is. - outputUrl = baseHref.replace(/\/$/, '') + dedupeSlashes(`/${deployUrl}/${inputUrl}`); - } else { - // Join together base-href, deploy-url and the original URL. - outputUrl = dedupeSlashes(`/${baseHref}/${deployUrl}/${inputUrl}`); - } - - resourceCache.set(cacheKey, outputUrl); - - return outputUrl; - } - - const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/')); - const resolver = (file: string, base: string) => new Promise((resolve, reject) => { - loader.resolve(base, decodeURI(file), (err, result) => { - if (err) { - reject(err); - - return; - } - resolve(result); - }); - }); - - const result = await resolve(pathname as string, context, resolver); - - return new Promise((resolve, reject) => { - loader.fs.readFile(result, (err: Error, content: Buffer) => { - if (err) { - reject(err); - - return; - } - - let outputPath = interpolateName( - { resourcePath: result } as webpack.loader.LoaderContext, - filename, - { content }, - ); - - if (resourcesOutputPath) { - outputPath = path.posix.join(resourcesOutputPath, outputPath); - } - - loader.addDependency(result); - if (emitFile) { - loader.emitFile(outputPath, content, undefined); - } - - let outputUrl = outputPath.replace(/\\/g, '/'); - if (hash || search) { - outputUrl = url.format({ pathname: outputUrl, hash, search }); - } - - if (deployUrl && loader.loaders[loader.loaderIndex].options.ident !== 'extracted') { - outputUrl = url.resolve(deployUrl, outputUrl); - } - - resourceCache.set(cacheKey, outputUrl); - resolve(outputUrl); - }); - }); - }; - - return (root) => { - const urlDeclarations: Array = []; - root.walkDecls(decl => { - if (decl.value && decl.value.includes('url')) { - urlDeclarations.push(decl); - } - }); - - if (urlDeclarations.length === 0) { - return; - } - - const resourceCache = new Map(); - - return Promise.all(urlDeclarations.map(async decl => { - const value = decl.value; - const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|(.+?))\s*\)/g; - const segments: string[] = []; - - let match; - let lastIndex = 0; - let modified = false; - - // We want to load it relative to the file that imports - const inputFile = decl.source && decl.source.input.file; - const context = inputFile && path.dirname(inputFile) || loader.context; - - // tslint:disable-next-line:no-conditional-assignment - while (match = urlRegex.exec(value)) { - const originalUrl = match[1] || match[2] || match[3]; - let processedUrl; - try { - processedUrl = await process(originalUrl, context, resourceCache); - } catch (err) { - loader.emitError(decl.error(err.message, { word: originalUrl }).toString()); - continue; - } - - if (lastIndex < match.index) { - segments.push(value.slice(lastIndex, match.index)); - } - - if (!processedUrl || originalUrl === processedUrl) { - segments.push(match[0]); - } else { - segments.push(wrapUrl(processedUrl)); - modified = true; - } - - lastIndex = match.index + match[0].length; - } - - if (lastIndex < value.length) { - segments.push(value.slice(lastIndex)); - } - - if (modified) { - decl.value = segments.join(''); - } - })); - }; -}); diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/raw-css-loader.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/raw-css-loader.ts deleted file mode 100644 index 9f7ff68b3032..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/raw-css-loader.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export default function(content: string, map: object) { - const stringifiedContent = JSON.stringify(content); - const stringifiedMap = map ? JSON.stringify(map) : `''`; - - return `module.exports = [[module.id, ${stringifiedContent}, '', ${stringifiedMap}]]`; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/remove-hash-plugin.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/remove-hash-plugin.ts deleted file mode 100644 index 0a9717bea1ed..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/remove-hash-plugin.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Compiler, compilation } from 'webpack'; -import { HashFormat } from '../models/webpack-configs/utils'; - - -export interface RemoveHashPluginOptions { - chunkNames: string[]; - hashFormat: HashFormat; -} - -export class RemoveHashPlugin { - - constructor(private options: RemoveHashPluginOptions) { } - - apply(compiler: Compiler): void { - compiler.hooks.compilation.tap('remove-hash-plugin', compilation => { - const mainTemplate = compilation.mainTemplate as compilation.MainTemplate & { - hooks: compilation.CompilationHooks; - }; - - mainTemplate.hooks.assetPath.tap('remove-hash-plugin', - (path: string, data: { chunk?: { name: string } }) => { - const chunkName = data.chunk && data.chunk.name; - const { chunkNames, hashFormat } = this.options; - - if (chunkName && chunkNames.includes(chunkName)) { - // Replace hash formats with empty strings. - return path - .replace(hashFormat.chunk, '') - .replace(hashFormat.extract, ''); - } - - return path; - }, - ); - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/scripts-webpack-plugin.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/scripts-webpack-plugin.ts deleted file mode 100644 index acb79134e8bd..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/scripts-webpack-plugin.ts +++ /dev/null @@ -1,166 +0,0 @@ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Compiler, loader } from 'webpack'; -import { CachedSource, ConcatSource, OriginalSource, RawSource, Source } from 'webpack-sources'; -import { interpolateName } from 'loader-utils'; -import * as path from 'path'; - -const Chunk = require('webpack/lib/Chunk'); -const EntryPoint = require('webpack/lib/Entrypoint'); - -export interface ScriptsWebpackPluginOptions { - name: string; - sourceMap: boolean; - scripts: string[]; - filename: string; - basePath: string; -} - -interface ScriptOutput { - filename: string; - source: CachedSource; -} - -function addDependencies(compilation: any, scripts: string[]): void { - for (const script of scripts) { - compilation.fileDependencies.add(script); - } -} - -function hook(compiler: any, action: (compilation: any, callback: (err?: Error) => void) => void) { - compiler.hooks.thisCompilation.tap('scripts-webpack-plugin', (compilation: any) => { - compilation.hooks.additionalAssets.tapAsync( - 'scripts-webpack-plugin', - (callback: (err?: Error) => void) => action(compilation, callback), - ); - }); -} - -export class ScriptsWebpackPlugin { - private _lastBuildTime?: number; - private _cachedOutput?: ScriptOutput; - - constructor(private options: Partial = {}) { } - - shouldSkip(compilation: any, scripts: string[]): boolean { - if (this._lastBuildTime == undefined) { - this._lastBuildTime = Date.now(); - return false; - } - - for (let i = 0; i < scripts.length; i++) { - const scriptTime = compilation.fileTimestamps.get(scripts[i]); - if (!scriptTime || scriptTime > this._lastBuildTime) { - this._lastBuildTime = Date.now(); - return false; - } - } - - return true; - } - - private _insertOutput(compilation: any, { filename, source }: ScriptOutput, cached = false) { - const chunk = new Chunk(this.options.name); - chunk.rendered = !cached; - chunk.id = this.options.name; - chunk.ids = [chunk.id]; - chunk.files.push(filename); - - const entrypoint = new EntryPoint(this.options.name); - entrypoint.pushChunk(chunk); - chunk.addGroup(entrypoint); - compilation.entrypoints.set(this.options.name, entrypoint); - compilation.chunks.push(chunk); - compilation.assets[filename] = source; - } - - apply(compiler: Compiler): void { - if (!this.options.scripts || this.options.scripts.length === 0) { - return; - } - - const scripts = this.options.scripts - .filter(script => !!script) - .map(script => path.resolve(this.options.basePath || '', script)); - - hook(compiler, (compilation, callback) => { - if (this.shouldSkip(compilation, scripts)) { - if (this._cachedOutput) { - this._insertOutput(compilation, this._cachedOutput, true); - } - - addDependencies(compilation, scripts); - callback(); - - return; - } - - const sourceGetters = scripts.map(fullPath => { - return new Promise((resolve, reject) => { - compilation.inputFileSystem.readFile(fullPath, (err: Error, data: Buffer) => { - if (err) { - reject(err); - return; - } - - const content = data.toString(); - - let source; - if (this.options.sourceMap) { - // TODO: Look for source map file (for '.min' scripts, etc.) - - let adjustedPath = fullPath; - if (this.options.basePath) { - adjustedPath = path.relative(this.options.basePath, fullPath); - } - source = new OriginalSource(content, adjustedPath); - } else { - source = new RawSource(content); - } - - resolve(source); - }); - }); - }); - - Promise.all(sourceGetters) - .then(sources => { - const concatSource = new ConcatSource(); - sources.forEach(source => { - concatSource.add(source); - concatSource.add('\n;'); - }); - - const combinedSource = new CachedSource(concatSource); - const filename = interpolateName( - { resourcePath: 'scripts.js' } as loader.LoaderContext, - this.options.filename as string, - { content: combinedSource.source() }, - ); - - const output = { filename, source: combinedSource }; - this._insertOutput(compilation, output); - this._cachedOutput = output; - addDependencies(compilation, scripts); - - callback(); - }) - .catch((err: Error) => callback(err)); - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/single-test-transform.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/single-test-transform.ts deleted file mode 100644 index ea8b09fdc038..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/single-test-transform.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { logging } from '@angular-devkit/core'; -import { getOptions } from 'loader-utils'; -import { extname, join } from 'path'; -import { loader } from 'webpack'; - -export interface SingleTestTransformLoaderOptions { - files: string[]; // list of paths relative to main - logger: logging.Logger; -} - -export const SingleTestTransformLoader = require.resolve(join(__dirname, 'single-test-transform')); - -/** - * This loader transforms the default test file to only run tests - * for some specs instead of all specs. - * It works by replacing the known content of the auto-generated test file: - * const context = require.context('./', true, /\.spec\.ts$/); - * context.keys().map(context); - * with: - * const context = { keys: () => ({ map: (_a) => { } }) }; - * context.keys().map(context); - * So that it does nothing. - * Then it adds import statements for each file in the files options - * array to import them directly, and thus run the tests there. - */ -export default function loader(this: loader.LoaderContext, source: string) { - const options = getOptions(this) as SingleTestTransformLoaderOptions; - const lineSeparator = process.platform === 'win32' ? '\r\n' : '\n'; - - const targettedImports = options.files - .map(path => `require('./${path.replace('.' + extname(path), '')}');`) - .join(lineSeparator); - - // TODO: maybe a documented 'marker/comment' inside test.ts would be nicer? - const regex = /require\.context\(.*/; - - // signal the user that expected content is not present - if (!regex.test(source)) { - const message = [ - `The 'include' option requires that the 'main' file for tests include the line below:`, - `const context = require.context('./', true, /\.spec\.ts$/);`, - `Arguments passed to require.context are not strict and can be changed`, - ]; - options.logger.error(message.join(lineSeparator)); - } - - const mockedRequireContext = '{ keys: () => ({ map: (_a) => { } }) };' + lineSeparator; - source = source.replace(regex, mockedRequireContext + targettedImports); - - return source; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/suppress-entry-chunks-webpack-plugin.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/suppress-entry-chunks-webpack-plugin.ts deleted file mode 100644 index c02bf346b9e6..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/suppress-entry-chunks-webpack-plugin.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -// Remove .js files from entry points consisting entirely of .css|scss|sass|less|styl. -// To be used together with ExtractTextPlugin. - -export class SuppressExtractedTextChunksWebpackPlugin { - constructor() { } - - apply(compiler: any): void { - compiler.hooks.compilation.tap('SuppressExtractedTextChunks', (compilation: any) => { - // find which chunks have css only entry points - const cssOnlyChunks: string[] = []; - const entryPoints = compilation.options.entry; - // determine which entry points are composed entirely of css files - for (let entryPoint of Object.keys(entryPoints)) { - let entryFiles: string[] | string = entryPoints[entryPoint]; - // when type of entryFiles is not array, make it as an array - entryFiles = entryFiles instanceof Array ? entryFiles : [entryFiles]; - if (entryFiles.every((el: string) => - el.match(/\.(css|scss|sass|less|styl)$/) !== null)) { - cssOnlyChunks.push(entryPoint); - } - } - // Remove the js file for supressed chunks - compilation.hooks.afterSeal.tap('SuppressExtractedTextChunks', () => { - compilation.chunks - .filter((chunk: any) => cssOnlyChunks.indexOf(chunk.name) !== -1) - .forEach((chunk: any) => { - let newFiles: string[] = []; - chunk.files.forEach((file: string) => { - if (file.match(/\.js(\.map)?$/)) { - // remove js files - delete compilation.assets[file]; - } else { - newFiles.push(file); - } - }); - chunk.files = newFiles; - }); - }); - // Remove scripts tags with a css file as source, because HtmlWebpackPlugin will use - // a css file as a script for chunks without js files. - // TODO: Enable this once HtmlWebpackPlugin supports Webpack 4 - // compilation.plugin('html-webpack-plugin-alter-asset-tags', - // (htmlPluginData: any, callback: any) => { - // const filterFn = (tag: any) => - // !(tag.tagName === 'script' && tag.attributes.src.match(/\.css$/)); - // htmlPluginData.head = htmlPluginData.head.filter(filterFn); - // htmlPluginData.body = htmlPluginData.body.filter(filterFn); - // callback(null, htmlPluginData); - // }); - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack-rollup-loader.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack-rollup-loader.ts deleted file mode 100644 index 72db6a989aae..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack-rollup-loader.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -/** - * @license - * @author Erik Desjardins - * Forked as of SHA 10fb020f997a146725963b202d79290c8798a7a0 from https://github.com/erikdesjardins/webpack-rollup-loader. - * Licensed under a MIT license. - * See https://github.com/erikdesjardins/webpack-rollup-loader/blob/10fb020f997a146725963b202d79290c8798a7a0/LICENSE for full license. - */ - -import { VirtualFileSystemDecorator } from '@ngtools/webpack/src/virtual_file_system_decorator'; -import { dirname, join } from 'path'; -import { OutputAsset, OutputChunk, rollup } from 'rollup'; -import { RawSourceMap } from 'source-map'; -import webpack = require('webpack'); - -function splitRequest(request: string) { - const inx = request.lastIndexOf('!'); - if (inx === -1) { - return { - loaders: '', - resource: request, - }; - } else { - return { - loaders: request.slice(0, inx + 1), - resource: request.slice(inx + 1), - }; - } -} - -// Load resolve paths using Webpack. -function webpackResolutionPlugin( - loaderContext: webpack.loader.LoaderContext, - entryId: string, - entryIdCodeAndMap: { code: string, map: RawSourceMap }, -) { - return { - name: 'webpack-resolution-plugin', - resolveId: (id: string, importerId: string) => { - if (id === entryId) { - return entryId; - } else { - return new Promise((resolve, reject) => { - // split apart resource paths because Webpack's this.resolve() can't handle `loader!` - // prefixes - const parts = splitRequest(id); - const importerParts = splitRequest(importerId); - - // resolve the full path of the imported file with Webpack's module loader - // this will figure out node_modules imports, Webpack aliases, etc. - loaderContext.resolve( - dirname(importerParts.resource), - parts.resource, - (err, fullPath) => err ? reject(err) : resolve(parts.loaders + fullPath), - ); - }); - } - }, - load: (id: string) => { - if (id === entryId) { - return entryIdCodeAndMap; - } - - return new Promise((resolve, reject) => { - // load the module with Webpack - // this will apply all relevant loaders, etc. - loaderContext.loadModule( - id, - (err, source, map) => err ? reject(err) : resolve({ code: source, map: map }), - ); - }); - }, - }; -} - -export default function webpackRollupLoader( - this: webpack.loader.LoaderContext, - source: string, - sourceMap: RawSourceMap, -) { - // Note: this loader isn't cacheable because it will add the lazy chunks to the - // virtual file system on completion. - const callback = this.async(); - if (!callback) { - throw new Error('Async loader support is required.'); - } - const options = this.query || {}; - const entryId = this.resourcePath; - const sourcemap = this.sourceMap; - - // Get the VirtualFileSystemDecorator that AngularCompilerPlugin added so we can write to it. - // Since we use webpackRollupLoader as a post loader, this should be there. - // TODO: we should be able to do this in a more elegant way by again decorating webpacks - // input file system inside a custom WebpackRollupPlugin, modelled after AngularCompilerPlugin. - const vfs = this._compiler.inputFileSystem as VirtualFileSystemDecorator; - const virtualWrite = (path: string, data: string) => - vfs.getWebpackCompilerHost().writeFile(path, data, false); - - // Bundle with Rollup - const rollupOptions = { - ...options, - input: entryId, - plugins: [ - ...(options.plugins || []), - webpackResolutionPlugin(this, entryId, { code: source, map: sourceMap }), - ], - }; - - rollup(rollupOptions) - .then(build => build.generate({ format: 'es', sourcemap })) - .then( - (result) => { - const [mainChunk, ...otherChunksOrAssets] = result.output; - - // Write other chunks and assets to the virtual file system so that webpack can load them. - const resultDir = dirname(entryId); - otherChunksOrAssets.forEach(chunkOrAsset => { - const { fileName, type } = chunkOrAsset; - if (type == 'chunk') { - const { code, map } = chunkOrAsset as OutputChunk; - virtualWrite(join(resultDir, fileName), code); - if (map) { - // Also write the map if there's one. - // Probably need scriptsSourceMap set on CLI to load it. - virtualWrite(join(resultDir, `${fileName}.map`), map.toString()); - } - } else if (type == 'asset') { - const { source } = chunkOrAsset as OutputAsset; - // Source might be a Buffer. Just assuming it's a string for now. - virtualWrite(join(resultDir, fileName), source as string); - } - }); - - // Always return the main chunk from webpackRollupLoader. - // Cast to any here is needed because of a typings incompatibility between source-map versions. - // tslint:disable-next-line:no-any - callback(null, mainChunk.code, (mainChunk as any).map); - }, - (err) => callback(err), - ); -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack.ts deleted file mode 100644 index ff8505733c4c..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/plugins/webpack.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// Exports the webpack plugins we use internally. -export { CleanCssWebpackPlugin, CleanCssWebpackPluginOptions } from './cleancss-webpack-plugin'; -export { BundleBudgetPlugin, BundleBudgetPluginOptions } from './bundle-budget'; -export { ScriptsWebpackPlugin, ScriptsWebpackPluginOptions } from './scripts-webpack-plugin'; -export { SuppressExtractedTextChunksWebpackPlugin } from './suppress-entry-chunks-webpack-plugin'; -export { RemoveHashPlugin, RemoveHashPluginOptions } from './remove-hash-plugin'; -export { NamedLazyChunksPlugin as NamedChunksPlugin } from './named-chunks-plugin'; -export { - default as PostcssCliResources, - PostcssCliResourcesOptions, -} from './postcss-cli-resources'; - -import { join } from 'path'; -export const RawCssLoader = require.resolve(join(__dirname, 'raw-css-loader')); -export const WebpackRollupLoader = require.resolve(join(__dirname, 'webpack-rollup-loader')); diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator.ts deleted file mode 100644 index 8ef3cb93884f..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator.ts +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Budget } from '../../browser/schema'; - -export interface Compilation { - assets: { [name: string]: { size: () => number } }; - chunks: { name: string, files: string[], isOnlyInitial: () => boolean }[]; - warnings: string[]; - errors: string[]; -} - -export interface Size { - size: number; - label?: string; -} - -export function calculateSizes(budget: Budget, compilation: Compilation): Size[] { - const calculatorMap = { - all: AllCalculator, - allScript: AllScriptCalculator, - any: AnyCalculator, - anyScript: AnyScriptCalculator, - anyComponentStyle: AnyComponentStyleCalculator, - bundle: BundleCalculator, - initial: InitialCalculator, - }; - - const ctor = calculatorMap[budget.type]; - const calculator = new ctor(budget, compilation); - - return calculator.calculate(); -} - -export abstract class Calculator { - constructor (protected budget: Budget, protected compilation: Compilation) {} - - abstract calculate(): Size[]; -} - -/** - * A named bundle. - */ -class BundleCalculator extends Calculator { - calculate() { - const size: number = this.compilation.chunks - .filter(chunk => chunk.name === this.budget.name) - .reduce((files, chunk) => [...files, ...chunk.files], []) - .filter((file: string) => !file.endsWith('.map')) - .map((file: string) => this.compilation.assets[file].size()) - .reduce((total: number, size: number) => total + size, 0); - - return [{size, label: this.budget.name}]; - } -} - -/** - * The sum of all initial chunks (marked as initial by webpack). - */ -class InitialCalculator extends Calculator { - calculate() { - const initialChunks = this.compilation.chunks.filter(chunk => chunk.isOnlyInitial()); - const size: number = initialChunks - .reduce((files, chunk) => [...files, ...chunk.files], []) - .filter((file: string) => !file.endsWith('.map')) - .map((file: string) => this.compilation.assets[file].size()) - .reduce((total: number, size: number) => total + size, 0); - - return [{size, label: 'initial'}]; - } -} - -/** - * The sum of all the scripts portions. - */ -class AllScriptCalculator extends Calculator { - calculate() { - const size: number = Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.js')) - .map(key => this.compilation.assets[key]) - .map(asset => asset.size()) - .reduce((total: number, size: number) => total + size, 0); - - return [{size, label: 'total scripts'}]; - } -} - -/** - * All scripts and assets added together. - */ -class AllCalculator extends Calculator { - calculate() { - const size: number = Object.keys(this.compilation.assets) - .filter(key => !key.endsWith('.map')) - .map(key => this.compilation.assets[key].size()) - .reduce((total: number, size: number) => total + size, 0); - - return [{size, label: 'total'}]; - } -} - -/** - * Any components styles - */ -class AnyComponentStyleCalculator extends Calculator { - calculate() { - return Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.css')) - .map(key => ({ - size: this.compilation.assets[key].size(), - label: key, - })); - } -} - -/** - * Any script, individually. - */ -class AnyScriptCalculator extends Calculator { - calculate() { - return Object.keys(this.compilation.assets) - .filter(key => key.endsWith('.js')) - .map(key => { - const asset = this.compilation.assets[key]; - - return { - size: asset.size(), - label: key, - }; - }); - } -} - -/** - * Any script or asset (images, css, etc). - */ -class AnyCalculator extends Calculator { - calculate() { - return Object.keys(this.compilation.assets) - .filter(key => !key.endsWith('.map')) - .map(key => { - const asset = this.compilation.assets[key]; - - return { - size: asset.size(), - label: key, - }; - }); - } -} - -/** - * Calculate the bytes given a string value. - */ -export function calculateBytes( - input: string, - baseline?: string, - factor: 1 | -1 = 1, -): number { - const matches = input.match(/^\s*(\d+(?:\.\d+)?)\s*(%|(?:[mM]|[kK]|[gG])?[bB])?\s*$/); - if (!matches) { - return NaN; - } - - const baselineBytes = baseline && calculateBytes(baseline) || 0; - - let value = Number(matches[1]); - switch (matches[2] && matches[2].toLowerCase()) { - case '%': - value = baselineBytes * value / 100; - break; - case 'kb': - value *= 1024; - break; - case 'mb': - value *= 1024 * 1024; - break; - case 'gb': - value *= 1024 * 1024 * 1024; - break; - } - - if (baselineBytes === 0) { - return value; - } - - return baselineBytes + value * factor; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator_spec.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator_spec.ts deleted file mode 100644 index c2d3774b7ea3..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/bundle-calculator_spec.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { calculateBytes } from './bundle-calculator'; - -describe('bundle-calculator', () => { - it('converts an integer with no postfix', () => { - expect(calculateBytes('0')).toBe(0); - expect(calculateBytes('5')).toBe(5); - expect(calculateBytes('190')).toBe(190); - expect(calculateBytes('92')).toBe(92); - }); - - it('converts a decimal with no postfix', () => { - expect(calculateBytes('3.14')).toBe(3.14); - expect(calculateBytes('0.25')).toBe(0.25); - expect(calculateBytes('90.5')).toBe(90.5); - expect(calculateBytes('25.0')).toBe(25); - }); - - it('converts an integer with kb postfix', () => { - expect(calculateBytes('0kb')).toBe(0); - expect(calculateBytes('5kb')).toBe(5 * 1024); - expect(calculateBytes('190KB')).toBe(190 * 1024); - expect(calculateBytes('92Kb')).toBe(92 * 1024); - expect(calculateBytes('25kB')).toBe(25 * 1024); - }); - - it('converts a decimal with kb postfix', () => { - expect(calculateBytes('3.14kb')).toBe(3.14 * 1024); - expect(calculateBytes('0.25KB')).toBe(0.25 * 1024); - expect(calculateBytes('90.5Kb')).toBe(90.5 * 1024); - expect(calculateBytes('25.0kB')).toBe(25 * 1024); - }); - - it('converts an integer with mb postfix', () => { - expect(calculateBytes('0mb')).toBe(0); - expect(calculateBytes('5mb')).toBe(5 * 1024 * 1024); - expect(calculateBytes('190MB')).toBe(190 * 1024 * 1024); - expect(calculateBytes('92Mb')).toBe(92 * 1024 * 1024); - expect(calculateBytes('25mB')).toBe(25 * 1024 * 1024); - }); - - it('converts a decimal with mb postfix', () => { - expect(calculateBytes('3.14mb')).toBe(3.14 * 1024 * 1024); - expect(calculateBytes('0.25MB')).toBe(0.25 * 1024 * 1024); - expect(calculateBytes('90.5Mb')).toBe(90.5 * 1024 * 1024); - expect(calculateBytes('25.0mB')).toBe(25 * 1024 * 1024); - }); - - it('converts an integer with gb postfix', () => { - expect(calculateBytes('0gb')).toBe(0); - expect(calculateBytes('5gb')).toBe(5 * 1024 * 1024 * 1024); - expect(calculateBytes('190GB')).toBe(190 * 1024 * 1024 * 1024); - expect(calculateBytes('92Gb')).toBe(92 * 1024 * 1024 * 1024); - expect(calculateBytes('25gB')).toBe(25 * 1024 * 1024 * 1024); - }); - - it('converts a decimal with gb postfix', () => { - expect(calculateBytes('3.14gb')).toBe(3.14 * 1024 * 1024 * 1024); - expect(calculateBytes('0.25GB')).toBe(0.25 * 1024 * 1024 * 1024); - expect(calculateBytes('90.5Gb')).toBe(90.5 * 1024 * 1024 * 1024); - expect(calculateBytes('25.0gB')).toBe(25 * 1024 * 1024 * 1024); - }); - - it ('converts a decimal with mb and baseline', () => { - expect(calculateBytes('3mb', '5mb', -1)).toBe(2 * 1024 * 1024); - }); - - it ('converts a percentage with baseline', () => { - expect(calculateBytes('20%', '1mb')).toBe(1024 * 1024 * 1.2); - expect(calculateBytes('20%', '1mb', -1)).toBe(1024 * 1024 * 0.8); - }); - - it ('supports whitespace', () => { - expect(calculateBytes(' 5kb ')).toBe(5 * 1024); - expect(calculateBytes('0.25 MB')).toBe(0.25 * 1024 * 1024); - expect(calculateBytes(' 20 % ', ' 1 mb ')).toBe(1024 * 1024 * 1.2); - }); -}); diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/check-port.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/check-port.ts deleted file mode 100644 index 9c649cad133b..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/check-port.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as net from 'net'; - -export function checkPort(port: number, host: string, basePort = 49152): Promise { - return new Promise((resolve, reject) => { - function _getPort(portNumber: number) { - if (portNumber > 65535) { - reject(new Error(`There is no port available.`)); - } - - const server = net.createServer(); - - server.once('error', (err: Error & {code: string}) => { - if (err.code !== 'EADDRINUSE') { - reject(err); - } else if (port === 0) { - _getPort(portNumber + 1); - } else { - // If the port isn't available and we weren't looking for any port, throw error. - reject( - new Error(`Port ${port} is already in use. Use '--port' to specify a different port.`), - ); - } - }) - .once('listening', () => { - server.close(); - resolve(portNumber); - }) - .listen(portNumber, host); - } - - _getPort(port || basePort); - }); -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-tests.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-tests.ts deleted file mode 100644 index 72ec0019f103..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-tests.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { existsSync } from 'fs'; -import * as glob from 'glob'; -import { basename, dirname, extname, join } from 'path'; -import { isDirectory } from './is-directory'; - -// go through all patterns and find unique list of files -export function findTests(patterns: string[], cwd: string, workspaceRoot: string): string[] { - return patterns.reduce( - (files, pattern) => { - const relativePathToMain = cwd.replace(workspaceRoot, '').substr(1); // remove leading slash - const tests = findMatchingTests(pattern, cwd, relativePathToMain); - tests.forEach(file => { - if (!files.includes(file)) { - files.push(file); - } - }); - - return files; - }, - [] as string[], - ); -} - -function findMatchingTests(pattern: string, cwd: string, relativePathToMain: string): string[] { - // normalize pattern, glob lib only accepts forward slashes - pattern = pattern.replace(/\\/g, '/'); - relativePathToMain = relativePathToMain.replace(/\\/g, '/'); - - // remove relativePathToMain to support relative paths from root - // such paths are easy to get when running scripts via IDEs - if (pattern.startsWith(relativePathToMain + '/')) { - pattern = pattern.substr(relativePathToMain.length + 1); // +1 to include slash - } - - // special logic when pattern does not look like a glob - if (!glob.hasMagic(pattern)) { - if (isDirectory(join(cwd, pattern))) { - pattern = `${pattern}/**/*.spec.@(ts|tsx)`; - } else { - // see if matching spec file exists - const extension = extname(pattern); - const matchingSpec = `${basename(pattern, extension)}.spec${extension}`; - - if (existsSync(join(cwd, dirname(pattern), matchingSpec))) { - pattern = join(dirname(pattern), matchingSpec).replace(/\\/g, '/'); - } - } - } - - const files = glob.sync(pattern, { - cwd, - }); - - return files; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-up.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-up.ts deleted file mode 100644 index 037e99235956..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/find-up.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { existsSync } from 'fs'; -import * as path from 'path'; -import { isDirectory } from './is-directory'; - -export function findUp(names: string | string[], from: string, stopOnNodeModules = false) { - if (!Array.isArray(names)) { - names = [names]; - } - const root = path.parse(from).root; - - let currentDir = from; - while (currentDir && currentDir !== root) { - for (const name of names) { - const p = path.join(currentDir, name); - if (existsSync(p)) { - return p; - } - } - - if (stopOnNodeModules) { - const nodeModuleP = path.join(currentDir, 'node_modules'); - if (existsSync(nodeModuleP)) { - return null; - } - } - - currentDir = path.dirname(currentDir); - } - - return null; -} - -export function findAllNodeModules(from: string, root?: string) { - const nodeModules: string[] = []; - - let current = from; - while (current && current !== root) { - const potential = path.join(current, 'node_modules'); - if (existsSync(potential) && isDirectory(potential)) { - nodeModules.push(potential); - } - - const next = path.dirname(current); - if (next === current) { - break; - } - current = next; - } - - return nodeModules; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html.ts deleted file mode 100644 index 76864be1bd17..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html.ts +++ /dev/null @@ -1,286 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { createHash } from 'crypto'; -import { RawSource, ReplaceSource } from 'webpack-sources'; - -const parse5 = require('parse5'); - -export type LoadOutputFileFunctionType = (file: string) => Promise; - -export type CrossOriginValue = 'none' | 'anonymous' | 'use-credentials'; - -export interface AugmentIndexHtmlOptions { - /* Input file name (e. g. index.html) */ - input: string; - /* Input contents */ - inputContent: string; - baseHref?: string; - deployUrl?: string; - sri: boolean; - /** crossorigin attribute setting of elements that provide CORS support */ - crossOrigin?: CrossOriginValue; - /* - * Files emitted by the build. - * Js files will be added without 'nomodule' nor 'module'. - */ - files: FileInfo[]; - /** Files that should be added using 'nomodule'. */ - noModuleFiles?: FileInfo[]; - /** Files that should be added using 'module'. */ - moduleFiles?: FileInfo[]; - /* - * Function that loads a file used. - * This allows us to use different routines within the IndexHtmlWebpackPlugin and - * when used without this plugin. - */ - loadOutputFile: LoadOutputFileFunctionType; - /** Used to sort the inseration of files in the HTML file */ - entrypoints: string[]; - /** Used to set the document default locale */ - lang?: string; -} - -export interface FileInfo { - file: string; - name: string; - extension: string; -} - -/* - * Helper function used by the IndexHtmlWebpackPlugin. - * Can also be directly used by builder, e. g. in order to generate an index.html - * after processing several configurations in order to build different sets of - * bundles for differential serving. - */ -// tslint:disable-next-line: no-big-function -export async function augmentIndexHtml(params: AugmentIndexHtmlOptions): Promise { - const { loadOutputFile, files, noModuleFiles = [], moduleFiles = [], entrypoints } = params; - - let { crossOrigin = 'none' } = params; - if (params.sri && crossOrigin === 'none') { - crossOrigin = 'anonymous'; - } - - const stylesheets = new Set(); - const scripts = new Set(); - - // Sort files in the order we want to insert them by entrypoint and dedupes duplicates - const mergedFiles = [...moduleFiles, ...noModuleFiles, ...files]; - for (const entrypoint of entrypoints) { - for (const { extension, file, name } of mergedFiles) { - if (name !== entrypoint) { - continue; - } - - switch (extension) { - case '.js': - scripts.add(file); - break; - case '.css': - stylesheets.add(file); - break; - } - } - } - - // Find the head and body elements - const treeAdapter = parse5.treeAdapters.default; - const document = parse5.parse(params.inputContent, { treeAdapter, locationInfo: true }); - let headElement; - let bodyElement; - let htmlElement; - for (const docChild of document.childNodes) { - if (docChild.tagName === 'html') { - htmlElement = docChild; - for (const htmlChild of docChild.childNodes) { - if (htmlChild.tagName === 'head') { - headElement = htmlChild; - } else if (htmlChild.tagName === 'body') { - bodyElement = htmlChild; - } - } - } - } - - if (!headElement || !bodyElement) { - throw new Error('Missing head and/or body elements'); - } - - // Determine script insertion point - let scriptInsertionPoint; - if (bodyElement.__location && bodyElement.__location.endTag) { - scriptInsertionPoint = bodyElement.__location.endTag.startOffset; - } else { - // Less accurate fallback - // parse5 4.x does not provide locations if malformed html is present - scriptInsertionPoint = params.inputContent.indexOf(''); - } - - let styleInsertionPoint; - if (headElement.__location && headElement.__location.endTag) { - styleInsertionPoint = headElement.__location.endTag.startOffset; - } else { - // Less accurate fallback - // parse5 4.x does not provide locations if malformed html is present - styleInsertionPoint = params.inputContent.indexOf(''); - } - - // Inject into the html - const indexSource = new ReplaceSource(new RawSource(params.inputContent), params.input); - - let scriptElements = ''; - for (const script of scripts) { - const attrs: { name: string; value: string | null }[] = [ - { name: 'src', value: (params.deployUrl || '') + script }, - ]; - - if (crossOrigin !== 'none') { - attrs.push({ name: 'crossorigin', value: crossOrigin }); - } - - // We want to include nomodule or module when a file is not common amongs all - // such as runtime.js - const scriptPredictor = ({ file }: FileInfo): boolean => file === script; - if (!files.some(scriptPredictor)) { - // in some cases for differential loading file with the same name is avialable in both - // nomodule and module such as scripts.js - // we shall not add these attributes if that's the case - const isNoModuleType = noModuleFiles.some(scriptPredictor); - const isModuleType = moduleFiles.some(scriptPredictor); - - if (isNoModuleType && !isModuleType) { - attrs.push({ name: 'nomodule', value: null }); - if (!script.startsWith('polyfills-nomodule-es5')) { - attrs.push({ name: 'defer', value: null }); - } - } else if (isModuleType && !isNoModuleType) { - attrs.push({ name: 'type', value: 'module' }); - } else { - attrs.push({ name: 'defer', value: null }); - } - } else { - attrs.push({ name: 'defer', value: null }); - } - - if (params.sri) { - const content = await loadOutputFile(script); - attrs.push(..._generateSriAttributes(content)); - } - - const attributes = attrs - .map(attr => (attr.value === null ? attr.name : `${attr.name}="${attr.value}"`)) - .join(' '); - scriptElements += ``; - } - - indexSource.insert(scriptInsertionPoint, scriptElements); - - // Adjust base href if specified - if (typeof params.baseHref == 'string') { - let baseElement; - for (const headChild of headElement.childNodes) { - if (headChild.tagName === 'base') { - baseElement = headChild; - } - } - - const baseFragment = treeAdapter.createDocumentFragment(); - - if (!baseElement) { - baseElement = treeAdapter.createElement('base', undefined, [ - { name: 'href', value: params.baseHref }, - ]); - - treeAdapter.appendChild(baseFragment, baseElement); - indexSource.insert( - headElement.__location.startTag.endOffset, - parse5.serialize(baseFragment, { treeAdapter }), - ); - } else { - let hrefAttribute; - for (const attribute of baseElement.attrs) { - if (attribute.name === 'href') { - hrefAttribute = attribute; - } - } - if (hrefAttribute) { - hrefAttribute.value = params.baseHref; - } else { - baseElement.attrs.push({ name: 'href', value: params.baseHref }); - } - - treeAdapter.appendChild(baseFragment, baseElement); - indexSource.replace( - baseElement.__location.startOffset, - baseElement.__location.endOffset, - parse5.serialize(baseFragment, { treeAdapter }), - ); - } - } - - const styleElements = treeAdapter.createDocumentFragment(); - for (const stylesheet of stylesheets) { - const attrs = [ - { name: 'rel', value: 'stylesheet' }, - { name: 'href', value: (params.deployUrl || '') + stylesheet }, - ]; - - if (crossOrigin !== 'none') { - attrs.push({ name: 'crossorigin', value: crossOrigin }); - } - - if (params.sri) { - const content = await loadOutputFile(stylesheet); - attrs.push(..._generateSriAttributes(content)); - } - - const element = treeAdapter.createElement('link', undefined, attrs); - treeAdapter.appendChild(styleElements, element); - } - - indexSource.insert(styleInsertionPoint, parse5.serialize(styleElements, { treeAdapter })); - - // Adjust document locale if specified - if (typeof params.lang == 'string') { - - const htmlFragment = treeAdapter.createDocumentFragment(); - - let langAttribute; - for (const attribute of htmlElement.attrs) { - if (attribute.name === 'lang') { - langAttribute = attribute; - } - } - if (langAttribute) { - langAttribute.value = params.lang; - } else { - htmlElement.attrs.push({ name: 'lang', value: params.lang }); - } - // we want only openning tag - htmlElement.childNodes = []; - - treeAdapter.appendChild(htmlFragment, htmlElement); - indexSource.replace( - htmlElement.__location.startTag.startOffset, - htmlElement.__location.startTag.endOffset - 1, - parse5.serialize(htmlFragment, { treeAdapter }).replace('', ''), - ); - } - - return indexSource.source(); -} - -function _generateSriAttributes(content: string) { - const algo = 'sha384'; - const hash = createHash(algo) - .update(content, 'utf8') - .digest('base64'); - - return [{ name: 'integrity', value: `${algo}-${hash}` }]; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html_spec.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html_spec.ts deleted file mode 100644 index a986e007d0de..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/augment-index-html_spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { tags } from '@angular-devkit/core'; -import { AugmentIndexHtmlOptions, FileInfo, augmentIndexHtml } from './augment-index-html'; - -describe('augment-index-html', () => { - const indexGeneratorOptions: AugmentIndexHtmlOptions = { - input: 'index.html', - inputContent: '', - baseHref: '/', - sri: false, - files: [], - loadOutputFile: async (_fileName: string) => '', - entrypoints: ['scripts', 'polyfills', 'main', 'styles'], - }; - - const oneLineHtml = (html: TemplateStringsArray) => - tags.stripIndents`${html}`.replace(/(\>\s+)/g, '>'); - - it('can generate index.html', async () => { - const source = augmentIndexHtml({ - ...indexGeneratorOptions, - files: [ - { file: 'styles.css', extension: '.css', name: 'styles' }, - { file: 'runtime.js', extension: '.js', name: 'main' }, - { file: 'main.js', extension: '.js', name: 'main' }, - { file: 'runtime.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, - ], - }); - - const html = await source; - expect(html).toEqual(oneLineHtml` - - - - - - - - - - - `); - }); - - it(`should emit correct script tags when having 'module' and 'non-module' js`, async () => { - const es2015JsFiles: FileInfo[] = [ - { file: 'runtime-es2015.js', extension: '.js', name: 'main' }, - { file: 'main-es2015.js', extension: '.js', name: 'main' }, - { file: 'runtime-es2015.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills-es2015.js', extension: '.js', name: 'polyfills' }, - ]; - - const es5JsFiles: FileInfo[] = [ - { file: 'runtime-es5.js', extension: '.js', name: 'main' }, - { file: 'main-es5.js', extension: '.js', name: 'main' }, - { file: 'runtime-es5.js', extension: '.js', name: 'polyfills' }, - { file: 'polyfills-es5.js', extension: '.js', name: 'polyfills' }, - ]; - - const source = augmentIndexHtml({ - ...indexGeneratorOptions, - files: [ - { file: 'styles.css', extension: '.css', name: 'styles' }, - { file: 'styles.css', extension: '.css', name: 'styles' }, - ], - moduleFiles: es2015JsFiles, - noModuleFiles: es5JsFiles, - }); - - const html = await source; - expect(html).toEqual(oneLineHtml` - - - - - - - - - - - - - - - `); - }); - - it( - `should not add 'module' and 'non-module' attr to js files which are in both module formats`, - async () => { - const es2015JsFiles: FileInfo[] = [ - { file: 'scripts.js', extension: '.js', name: 'scripts' }, - { file: 'main-es2015.js', extension: '.js', name: 'main' }, - ]; - - const es5JsFiles: FileInfo[] = [ - { file: 'scripts.js', extension: '.js', name: 'scripts' }, - { file: 'main-es5.js', extension: '.js', name: 'main' }, - ]; - - const source = augmentIndexHtml({ - ...indexGeneratorOptions, - files: [ - { file: 'styles.css', extension: '.css', name: 'styles' }, - { file: 'styles.css', extension: '.css', name: 'styles' }, - ], - moduleFiles: es2015JsFiles, - noModuleFiles: es5JsFiles, - }); - - const html = await source; - expect(html).toEqual(oneLineHtml` - - - - - - - - - - - - `); - }); - - it('should add lang attribute', async () => { - const source = augmentIndexHtml({ - ...indexGeneratorOptions, - lang: 'fr', - }); - - const html = await source; - expect(html).toEqual(oneLineHtml` - - - - - - - - `); - }); -}); diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/write-index-html.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/write-index-html.ts deleted file mode 100644 index 1ec63a5dcc7f..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/index-file/write-index-html.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { EmittedFiles } from '@angular-devkit/build-webpack'; -import { Path, dirname, getSystemPath, join, virtualFs } from '@angular-devkit/core'; -import { Observable, of } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; -import { ExtraEntryPoint } from '../../../browser/schema'; -import { generateEntryPoints } from '../package-chunk-sort'; -import { stripBom } from '../strip-bom'; -import { CrossOriginValue, FileInfo, augmentIndexHtml } from './augment-index-html'; - -type ExtensionFilter = '.js' | '.css'; - -export interface WriteIndexHtmlOptions { - host: virtualFs.Host; - outputPath: Path; - indexPath: Path; - files?: EmittedFiles[]; - noModuleFiles?: EmittedFiles[]; - moduleFiles?: EmittedFiles[]; - baseHref?: string; - deployUrl?: string; - sri?: boolean; - scripts?: ExtraEntryPoint[]; - styles?: ExtraEntryPoint[]; - postTransform?: IndexHtmlTransform; - crossOrigin?: CrossOriginValue; - lang?: string; -} - -export type IndexHtmlTransform = (content: string) => Promise; - -export function writeIndexHtml({ - host, - outputPath, - indexPath, - files = [], - noModuleFiles = [], - moduleFiles = [], - baseHref, - deployUrl, - sri = false, - scripts = [], - styles = [], - postTransform, - crossOrigin, - lang, -}: WriteIndexHtmlOptions): Observable { - return host.read(indexPath).pipe( - map(content => stripBom(virtualFs.fileBufferToString(content))), - switchMap(content => - augmentIndexHtml({ - input: getSystemPath(outputPath), - inputContent: content, - baseHref, - deployUrl, - crossOrigin, - sri, - entrypoints: generateEntryPoints({ scripts, styles }), - files: filterAndMapBuildFiles(files, ['.js', '.css']), - noModuleFiles: filterAndMapBuildFiles(noModuleFiles, '.js'), - moduleFiles: filterAndMapBuildFiles(moduleFiles, '.js'), - loadOutputFile: async filePath => { - return host - .read(join(dirname(outputPath), filePath)) - .pipe(map(data => virtualFs.fileBufferToString(data))) - .toPromise(); - }, - lang: lang, - }), - ), - switchMap(content => (postTransform ? postTransform(content) : of(content))), - map(content => virtualFs.stringToFileBuffer(content)), - switchMap(content => host.write(outputPath, content)), - ); -} - -function filterAndMapBuildFiles( - files: EmittedFiles[], - extensionFilter: ExtensionFilter | ExtensionFilter[], -): FileInfo[] { - const filteredFiles: FileInfo[] = []; - const validExtensions: string[] = Array.isArray(extensionFilter) - ? extensionFilter - : [extensionFilter]; - - for (const { file, name, extension, initial } of files) { - if (name && initial && validExtensions.includes(extension)) { - filteredFiles.push({ file, extension, name }); - } - } - - return filteredFiles; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/is-directory.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/is-directory.ts deleted file mode 100644 index f4636a272531..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/is-directory.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -import * as fs from 'fs'; - -export function isDirectory(path: string) { - try { - return fs.statSync(path).isDirectory(); - } catch (_) { - return false; - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/package-chunk-sort.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/package-chunk-sort.ts deleted file mode 100644 index 442b80ebb34f..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/package-chunk-sort.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { ExtraEntryPoint } from '../../browser/schema'; -import { normalizeExtraEntryPoints } from '../models/webpack-configs/utils'; - -export function generateEntryPoints(appConfig: { - styles: ExtraEntryPoint[]; - scripts: ExtraEntryPoint[]; -}) { - // Add all styles/scripts, except lazy-loaded ones. - const extraEntryPoints = ( - extraEntryPoints: ExtraEntryPoint[], - defaultBundleName: string, - ): string[] => { - const entryPoints = normalizeExtraEntryPoints(extraEntryPoints, defaultBundleName) - .filter(entry => entry.inject) - .map(entry => entry.bundleName); - - // remove duplicates - return [...new Set(entryPoints)]; - }; - - const entryPoints = [ - 'polyfills-nomodule-es5', - 'runtime', - 'polyfills-es5', - 'polyfills', - 'sw-register', - ...extraEntryPoints(appConfig.styles, 'styles'), - ...extraEntryPoints(appConfig.scripts, 'scripts'), - 'vendor', - 'main', - ]; - - const duplicates = [ - ...new Set(entryPoints.filter(x => entryPoints.indexOf(x) !== entryPoints.lastIndexOf(x))), - ]; - - if (duplicates.length > 0) { - throw new Error(`Multiple bundles have been named the same: '${duplicates.join(`', '`)}'.`); - } - - return entryPoints; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/read-tsconfig.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/read-tsconfig.ts deleted file mode 100644 index 9d58349af889..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/read-tsconfig.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { ParsedConfiguration } from '@angular/compiler-cli'; -import * as path from 'path'; - -/** - * Reads and parses a given TsConfig file. - * - * @param tsconfigPath - An absolute or relative path from 'workspaceRoot' of the tsconfig file. - * @param workspaceRoot - workspaceRoot root location when provided - * it will resolve 'tsconfigPath' from this path. - */ -export function readTsconfig(tsconfigPath: string, workspaceRoot?: string): ParsedConfiguration { - const tsConfigFullPath = workspaceRoot - ? path.resolve(workspaceRoot, tsconfigPath) - : tsconfigPath; - - // We use 'ng' instead of 'ts' here because 'ts' is not aware of 'angularCompilerOptions' - // and will not merged them if they are at un upper level tsconfig file when using `extends`. - const ng: typeof import('@angular/compiler-cli') = require('@angular/compiler-cli'); - - const configResult = ng.readConfiguration(tsConfigFullPath); - if (configResult.errors && configResult.errors.length) { - throw new Error(ng.formatDiagnostics(configResult.errors)); - } - - return configResult; -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/service-worker/index.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/service-worker/index.ts deleted file mode 100644 index bb712e5b7894..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/service-worker/index.ts +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { - Path, - dirname, - getSystemPath, - join, - normalize, - relative, - tags, - virtualFs, -} from '@angular-devkit/core'; -import { - Filesystem, - Generator, -} from '@angular/service-worker/config'; // tslint:disable-line:no-implicit-dependencies -import * as crypto from 'crypto'; - -class CliFilesystem implements Filesystem { - constructor(private _host: virtualFs.Host, private base: string) { } - - list(path: string): Promise { - return this._recursiveList(this._resolve(path), []).catch(() => []); - } - - async read(path: string): Promise { - return virtualFs.fileBufferToString(await this._readIntoBuffer(path)); - } - - async hash(path: string): Promise { - const sha1 = crypto.createHash('sha1'); - sha1.update(Buffer.from(await this._readIntoBuffer(path))); - - return sha1.digest('hex'); - } - - write(path: string, content: string): Promise { - return this._host.write(this._resolve(path), virtualFs.stringToFileBuffer(content)) - .toPromise(); - } - - private _readIntoBuffer(path: string): Promise { - return this._host.read(this._resolve(path)).toPromise(); - } - - private _resolve(path: string): Path { - return join(normalize(this.base), normalize(path)); - } - - private async _recursiveList(path: Path, items: string[]): Promise { - const fragments = await this._host.list(path).toPromise(); - - for (const fragment of fragments) { - const item = join(path, fragment); - - if (await this._host.isDirectory(item).toPromise()) { - await this._recursiveList(item, items); - } else { - items.push('/' + relative(normalize(this.base), item)); - } - } - - return items; - } -} - -export async function augmentAppWithServiceWorker( - host: virtualFs.Host, - projectRoot: Path, - appRoot: Path, - outputPath: Path, - baseHref: string, - ngswConfigPath?: string, -): Promise { - const distPath = normalize(outputPath); - const systemProjectRoot = getSystemPath(projectRoot); - - // Find the service worker package - const workerPath = normalize( - require.resolve('@angular/service-worker/ngsw-worker.js', { paths: [systemProjectRoot] }), - ); - const swConfigPath = require.resolve( - '@angular/service-worker/config', - { paths: [systemProjectRoot] }, - ); - - // Determine the configuration file path - let configPath; - if (ngswConfigPath) { - configPath = normalize(ngswConfigPath); - } else { - configPath = join(appRoot, 'ngsw-config.json'); - } - - // Ensure the configuration file exists - const configExists = await host.exists(configPath).toPromise(); - if (!configExists) { - throw new Error(tags.oneLine` - Error: Expected to find an ngsw-config.json configuration - file in the ${getSystemPath(appRoot)} folder. Either provide one or disable Service Worker - in your angular.json configuration file. - `); - } - - // Read the configuration file - const config = JSON.parse(virtualFs.fileBufferToString(await host.read(configPath).toPromise())); - - // Generate the manifest - const GeneratorConstructor = require(swConfigPath).Generator as typeof Generator; - const generator = new GeneratorConstructor(new CliFilesystem(host, outputPath), baseHref); - const output = await generator.process(config); - - // Write the manifest - const manifest = JSON.stringify(output, null, 2); - await host.write(join(distPath, 'ngsw.json'), virtualFs.stringToFileBuffer(manifest)).toPromise(); - - // Write the worker code - // NOTE: This is inefficient (kernel -> userspace -> kernel). - // `fs.copyFile` would be a better option but breaks the host abstraction - const workerCode = await host.read(workerPath).toPromise(); - await host.write(join(distPath, 'ngsw-worker.js'), workerCode).toPromise(); - - // If present, write the safety worker code - const safetyPath = join(dirname(workerPath), 'safety-worker.js'); - if (await host.exists(safetyPath).toPromise()) { - const safetyCode = await host.read(safetyPath).toPromise(); - - await host.write(join(distPath, 'worker-basic.min.js'), safetyCode).toPromise(); - await host.write(join(distPath, 'safety-worker.js'), safetyCode).toPromise(); - } -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/stats.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/stats.ts deleted file mode 100644 index ac2bc7aa8fe3..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/stats.ts +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. -import { tags, terminal } from '@angular-devkit/core'; -import * as path from 'path'; - - -const { bold, green, red, reset, white, yellow } = terminal; - -export function formatSize(size: number): string { - if (size <= 0) { - return '0 bytes'; - } - - const abbreviations = ['bytes', 'kB', 'MB', 'GB']; - const index = Math.floor(Math.log(size) / Math.log(1024)); - - return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${abbreviations[index]}`; -} - -export function generateBundleStats( - info: { - id: string | number; - size?: number; - files: string[]; - names?: string[]; - entry: boolean; - initial: boolean; - rendered?: boolean; - }, - colors: boolean, -): string { - const g = (x: string) => (colors ? bold(green(x)) : x); - const y = (x: string) => (colors ? bold(yellow(x)) : x); - - const size = typeof info.size === 'number' ? ` ${formatSize(info.size)}` : ''; - const files = info.files.map(f => path.basename(f)).join(', '); - const names = info.names ? ` (${info.names.join(', ')})` : ''; - const initial = y(info.entry ? '[entry]' : info.initial ? '[initial]' : ''); - const flags = ['rendered', 'recorded'] - .map(f => (f && (info as any)[f] ? g(` [${f}]`) : '')) - .join(''); - - return `chunk {${y(info.id.toString())}} ${g(files)}${names}${size} ${initial}${flags}`; -} - -export function generateBuildStats(hash: string, time: number, colors: boolean): string { - const w = (x: string) => colors ? bold(white(x)) : x; - return `Date: ${w(new Date().toISOString())} - Hash: ${w(hash)} - Time: ${w('' + time)}ms` -} - -export function statsToString(json: any, statsConfig: any) { - const colors = statsConfig.colors; - const rs = (x: string) => colors ? reset(x) : x; - const w = (x: string) => colors ? bold(white(x)) : x; - - const changedChunksStats = json.chunks - .filter((chunk: any) => chunk.rendered) - .map((chunk: any) => { - const asset = json.assets.filter((x: any) => x.name == chunk.files[0])[0]; - return generateBundleStats({ ...chunk, size: asset && asset.size }, colors); - }); - - const unchangedChunkNumber = json.chunks.length - changedChunksStats.length; - - if (unchangedChunkNumber > 0) { - return '\n' + rs(tags.stripIndents` - Date: ${w(new Date().toISOString())} - Hash: ${w(json.hash)} - ${unchangedChunkNumber} unchanged chunks - ${changedChunksStats.join('\n')} - Time: ${w('' + json.time)}ms - `); - } else { - return '\n' + rs(tags.stripIndents` - ${changedChunksStats.join('\n')} - Date: ${w(new Date().toISOString())} - Hash: ${w(json.hash)} - Time: ${w('' + json.time)}ms - `); - } -} - -export function statsWarningsToString(json: any, statsConfig: any) { - const colors = statsConfig.colors; - const rs = (x: string) => colors ? reset(x) : x; - const y = (x: string) => colors ? bold(yellow(x)) : x; - - return rs('\n' + json.warnings.map((warning: any) => y(`WARNING in ${warning}`)).join('\n\n')); -} - -export function statsErrorsToString(json: any, statsConfig: any) { - const colors = statsConfig.colors; - const rs = (x: string) => colors ? reset(x) : x; - const r = (x: string) => colors ? bold(red(x)) : x; - - return rs('\n' + json.errors.map((error: any) => r(`ERROR in ${error}`)).join('\n')); -} diff --git a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/strip-bom.ts b/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/strip-bom.ts deleted file mode 100644 index f4aba38228b3..000000000000 --- a/packages/angular_devkit/build_angular/src/angular-cli-files/utilities/strip-bom.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -// TODO: cleanup this file, it's copied as is from Angular CLI. - -// Strip BOM from file data. -// https://stackoverflow.com/questions/24356713 -export function stripBom(data: string) { - return data.replace(/^\uFEFF/, ''); -} diff --git a/packages/angular_devkit/build_angular/src/app-shell/index.ts b/packages/angular_devkit/build_angular/src/app-shell/index.ts deleted file mode 100644 index 4d5680d51706..000000000000 --- a/packages/angular_devkit/build_angular/src/app-shell/index.ts +++ /dev/null @@ -1,177 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { - BuilderContext, - BuilderOutput, - createBuilder, - targetFromTargetString, -} from '@angular-devkit/architect'; -import { JsonObject, join, normalize, resolve } from '@angular-devkit/core'; -import { NodeJsSyncHost } from '@angular-devkit/core/node'; -import * as fs from 'fs'; -import * as path from 'path'; -import { augmentAppWithServiceWorker } from '../angular-cli-files/utilities/service-worker'; -import { BrowserBuilderOutput } from '../browser'; -import { Schema as BrowserBuilderSchema } from '../browser/schema'; -import { ServerBuilderOutput } from '../server'; -import { Schema as BuildWebpackAppShellSchema } from './schema'; - -async function _renderUniversal( - options: BuildWebpackAppShellSchema, - context: BuilderContext, - browserResult: BrowserBuilderOutput, - serverResult: ServerBuilderOutput, -): Promise { - // Get browser target options. - const browserTarget = targetFromTargetString(options.browserTarget); - const rawBrowserOptions = await context.getTargetOptions(browserTarget); - const browserBuilderName = await context.getBuilderNameForTarget(browserTarget); - const browserOptions = await context.validateOptions( - rawBrowserOptions, - browserBuilderName, - ); - - // Initialize zone.js - const root = context.workspaceRoot; - const zonePackage = require.resolve('zone.js', { paths: [root] }); - await import(zonePackage); - - const host = new NodeJsSyncHost(); - const projectName = context.target && context.target.project; - if (!projectName) { - throw new Error('The builder requires a target.'); - } - - const projectMetadata = await context.getProjectMetadata(projectName); - const projectRoot = resolve( - normalize(root), - normalize((projectMetadata.root as string) || ''), - ); - - for (const outputPath of browserResult.outputPaths) { - const localeDirectory = path.relative(browserResult.baseOutputPath, outputPath); - const browserIndexOutputPath = path.join(outputPath, 'index.html'); - const indexHtml = fs.readFileSync(browserIndexOutputPath, 'utf8'); - const serverBundlePath = await _getServerModuleBundlePath(options, context, serverResult, localeDirectory); - - const { - AppServerModule, - AppServerModuleNgFactory, - renderModule, - renderModuleFactory, - } = await import(serverBundlePath); - - let renderModuleFn: (module: unknown, options: {}) => Promise; - let AppServerModuleDef: unknown; - - if (renderModuleFactory && AppServerModuleNgFactory) { - renderModuleFn = renderModuleFactory; - AppServerModuleDef = AppServerModuleNgFactory; - } else if (renderModule && AppServerModule) { - renderModuleFn = renderModule; - AppServerModuleDef = AppServerModule; - } else { - throw new Error(`renderModule method and/or AppServerModule were not exported from: ${serverBundlePath}.`); - } - - // Load platform server module renderer - const renderOpts = { - document: indexHtml, - url: options.route, - }; - - const html = await renderModuleFn(AppServerModuleDef, renderOpts); - // Overwrite the client index file. - const outputIndexPath = options.outputIndexPath - ? path.join(root, options.outputIndexPath) - : browserIndexOutputPath; - - fs.writeFileSync(outputIndexPath, html); - - if (browserOptions.serviceWorker) { - await augmentAppWithServiceWorker( - host, - normalize(root), - projectRoot, - normalize(outputPath), - browserOptions.baseHref || '/', - browserOptions.ngswConfigPath, - ); - } - } - - return browserResult; -} - -async function _getServerModuleBundlePath( - options: BuildWebpackAppShellSchema, - context: BuilderContext, - serverResult: ServerBuilderOutput, - browserLocaleDirectory: string, -) { - if (options.appModuleBundle) { - return path.join(context.workspaceRoot, options.appModuleBundle); - } else { - const { baseOutputPath = '' } = serverResult; - const outputPath = path.join(baseOutputPath, browserLocaleDirectory); - - if (!fs.existsSync(outputPath)) { - throw new Error(`Could not find server output directory: ${outputPath}.`); - } - - const files = fs.readdirSync(outputPath, 'utf8'); - const re = /^main\.(?:[a-zA-Z0-9]{20}\.)?(?:bundle\.)?js$/; - const maybeMain = files.filter(x => re.test(x))[0]; - - if (!maybeMain) { - throw new Error('Could not find the main bundle.'); - } else { - return path.join(outputPath, maybeMain); - } - } -} - -async function _appShellBuilder( - options: JsonObject & BuildWebpackAppShellSchema, - context: BuilderContext, -): Promise { - const browserTarget = targetFromTargetString(options.browserTarget); - const serverTarget = targetFromTargetString(options.serverTarget); - - // Never run the browser target in watch mode. - // If service worker is needed, it will be added in _renderUniversal(); - const browserTargetRun = await context.scheduleTarget(browserTarget, { - watch: false, - serviceWorker: false, - }); - const serverTargetRun = await context.scheduleTarget(serverTarget, { - watch: false, - }); - - try { - const [browserResult, serverResult] = await Promise.all([ - browserTargetRun.result as unknown as BrowserBuilderOutput, - serverTargetRun.result as unknown as ServerBuilderOutput, - ]); - - if (browserResult.success === false || browserResult.baseOutputPath === undefined) { - return browserResult; - } else if (serverResult.success === false) { - return serverResult; - } - - return await _renderUniversal(options, context, browserResult, serverResult); - } catch (err) { - return { success: false, error: err.message }; - } finally { - // Just be good citizens and stop those jobs. - await Promise.all([browserTargetRun.stop(), serverTargetRun.stop()]); - } -} - -export default createBuilder(_appShellBuilder); diff --git a/packages/angular_devkit/build_angular/src/app-shell/schema.json b/packages/angular_devkit/build_angular/src/app-shell/schema.json deleted file mode 100644 index e7fb6156d47f..000000000000 --- a/packages/angular_devkit/build_angular/src/app-shell/schema.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "title": "App Shell Target", - "description": "App Shell target options for Build Facade.", - "type": "object", - "properties": { - "browserTarget": { - "type": "string", - "description": "Target to build." - }, - "serverTarget": { - "type": "string", - "description": "Server target to use for rendering the app shell." - }, - "appModuleBundle": { - "type": "string", - "description": "Script that exports the Server AppModule to render. This should be the main JavaScript outputted by the server target. By default we will resolve the outputPath of the serverTarget and find a bundle named 'main' in it (whether or not there's a hash tag)." - }, - "route": { - "type": "string", - "description": "The route to render.", - "default": "/" - }, - "inputIndexPath": { - "type": "string", - "description": "The input path for the index.html file. By default uses the output index.html of the browser target." - }, - "outputIndexPath": { - "type": "string", - "description": "The output path of the index.html file. By default will overwrite the input file." - } - }, - "additionalProperties": false, - "required": [ - "browserTarget", - "serverTarget" - ] -} diff --git a/packages/angular_devkit/build_angular/src/browser/index.ts b/packages/angular_devkit/build_angular/src/browser/index.ts deleted file mode 100644 index e80bf8500ca4..000000000000 --- a/packages/angular_devkit/build_angular/src/browser/index.ts +++ /dev/null @@ -1,755 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; -import { EmittedFiles, WebpackLoggingCallback, runWebpack } from '@angular-devkit/build-webpack'; -import { join, json, logging, normalize, tags, virtualFs } from '@angular-devkit/core'; -import { NodeJsSyncHost } from '@angular-devkit/core/node'; -import * as fs from 'fs'; -import * as path from 'path'; -import { Observable, from } from 'rxjs'; -import { concatMap, map, switchMap } from 'rxjs/operators'; -import { ScriptTarget } from 'typescript'; -import * as webpack from 'webpack'; -import { NgBuildAnalyticsPlugin } from '../../plugins/webpack/analytics'; -import { WebpackConfigOptions } from '../angular-cli-files/models/build-options'; -import { - getAotConfig, - getBrowserConfig, - getCommonConfig, - getNonAotConfig, - getStatsConfig, - getStylesConfig, - getWorkerConfig, - normalizeExtraEntryPoints, -} from '../angular-cli-files/models/webpack-configs'; -import { - IndexHtmlTransform, - writeIndexHtml, -} from '../angular-cli-files/utilities/index-file/write-index-html'; -import { readTsconfig } from '../angular-cli-files/utilities/read-tsconfig'; -import { augmentAppWithServiceWorker } from '../angular-cli-files/utilities/service-worker'; -import { - generateBuildStats, - generateBundleStats, - statsErrorsToString, - statsToString, - statsWarningsToString, -} from '../angular-cli-files/utilities/stats'; -import { ExecutionTransformer } from '../transforms'; -import { - BuildBrowserFeatures, - deleteOutputDir, - normalizeAssetPatterns, - normalizeOptimization, - normalizeSourceMaps, -} from '../utils'; -import { BundleActionExecutor } from '../utils/action-executor'; -import { findCachePath } from '../utils/cache-path'; -import { copyAssets } from '../utils/copy-assets'; -import { cachingDisabled } from '../utils/environment-options'; -import { i18nInlineEmittedFiles } from '../utils/i18n-inlining'; -import { I18nOptions } from '../utils/i18n-options'; -import { ensureOutputPaths } from '../utils/output-paths'; -import { - InlineOptions, - ProcessBundleFile, - ProcessBundleOptions, - ProcessBundleResult, -} from '../utils/process-bundle'; -import { assertCompatibleAngularVersion } from '../utils/version'; -import { - BrowserWebpackConfigOptions, - generateBrowserWebpackConfigFromContext, - generateI18nBrowserWebpackConfigFromContext, - getIndexInputFile, - getIndexOutputFile, -} from '../utils/webpack-browser-config'; -import { Schema as BrowserBuilderSchema } from './schema'; - -const cacheDownlevelPath = cachingDisabled ? undefined : findCachePath('angular-build-dl'); - -export type BrowserBuilderOutput = json.JsonObject & - BuilderOutput & { - baseOutputPath: string; - outputPaths: string[]; - /** - * @deprecated in version 9. Use 'outputPaths' instead. - */ - outputPath: string; - }; - -export function createBrowserLoggingCallback( - verbose: boolean, - logger: logging.LoggerApi, -): WebpackLoggingCallback { - return (stats, config) => { - // config.stats contains our own stats settings, added during buildWebpackConfig(). - const json = stats.toJson(config.stats); - if (verbose) { - logger.info(stats.toString(config.stats)); - } else { - logger.info(statsToString(json, config.stats)); - } - - if (stats.hasWarnings()) { - logger.warn(statsWarningsToString(json, config.stats)); - } - if (stats.hasErrors()) { - logger.error(statsErrorsToString(json, config.stats)); - } - }; -} - -// todo: the below should be cleaned once dev-server support the new i18n -interface ConfigFromContextReturn { - config: webpack.Configuration; - projectRoot: string; - projectSourceRoot?: string; -} - -export async function buildBrowserWebpackConfigFromContext( - options: BrowserBuilderSchema, - context: BuilderContext, - host: virtualFs.Host, - i18n: boolean, -): Promise; -export async function buildBrowserWebpackConfigFromContext( - options: BrowserBuilderSchema, - context: BuilderContext, - host?: virtualFs.Host, -): Promise; -export async function buildBrowserWebpackConfigFromContext( - options: BrowserBuilderSchema, - context: BuilderContext, - host: virtualFs.Host = new NodeJsSyncHost(), - i18n = false, -): Promise { - const webpackPartialGenerator = (wco: BrowserWebpackConfigOptions) => [ - getCommonConfig(wco), - getBrowserConfig(wco), - getStylesConfig(wco), - getStatsConfig(wco), - getAnalyticsConfig(wco, context), - getCompilerConfig(wco), - wco.buildOptions.webWorkerTsConfig ? getWorkerConfig(wco) : {}, - ]; - - if (i18n) { - return generateI18nBrowserWebpackConfigFromContext( - options, - context, - webpackPartialGenerator, - host, - ); - } - - return generateBrowserWebpackConfigFromContext(options, context, webpackPartialGenerator, host); -} - -function getAnalyticsConfig( - wco: WebpackConfigOptions, - context: BuilderContext, -): webpack.Configuration { - if (context.analytics) { - // If there's analytics, add our plugin. Otherwise no need to slow down the build. - let category = 'build'; - if (context.builder) { - // We already vetted that this is a "safe" package, otherwise the analytics would be noop. - category = - context.builder.builderName.split(':')[1] || context.builder.builderName || 'build'; - } - - // The category is the builder name if it's an angular builder. - return { - plugins: [new NgBuildAnalyticsPlugin( - wco.projectRoot, - context.analytics, - category, - !!wco.tsConfig.options.enableIvy, - )], - }; - } - - return {}; -} - -function getCompilerConfig(wco: WebpackConfigOptions): webpack.Configuration { - if (wco.buildOptions.main || wco.buildOptions.polyfills) { - return wco.buildOptions.aot ? getAotConfig(wco) : getNonAotConfig(wco); - } - - return {}; -} - -async function initialize( - options: BrowserBuilderSchema, - context: BuilderContext, - host: virtualFs.Host, - webpackConfigurationTransform?: ExecutionTransformer, -): Promise<{ - config: webpack.Configuration; - projectRoot: string; - projectSourceRoot?: string; - i18n: I18nOptions; -}> { - const originalOutputPath = options.outputPath; - const { - config, - projectRoot, - projectSourceRoot, - i18n, - } = await buildBrowserWebpackConfigFromContext(options, context, host, true); - - let transformedConfig; - if (webpackConfigurationTransform) { - transformedConfig = await webpackConfigurationTransform(config); - } - - if (options.deleteOutputPath) { - deleteOutputDir(context.workspaceRoot, originalOutputPath); - } - - return { config: transformedConfig || config, projectRoot, projectSourceRoot, i18n }; -} - -// tslint:disable-next-line: no-big-function -export function buildWebpackBrowser( - options: BrowserBuilderSchema, - context: BuilderContext, - transforms: { - webpackConfiguration?: ExecutionTransformer; - logging?: WebpackLoggingCallback; - indexHtml?: IndexHtmlTransform; - } = {}, -): Observable { - const host = new NodeJsSyncHost(); - const root = normalize(context.workspaceRoot); - const baseOutputPath = path.resolve(context.workspaceRoot, options.outputPath); - let outputPaths: undefined | string[]; - - // Check Angular version. - assertCompatibleAngularVersion(context.workspaceRoot, context.logger); - - return from(initialize(options, context, host, transforms.webpackConfiguration)).pipe( - // tslint:disable-next-line: no-big-function - switchMap(({ config, projectRoot, projectSourceRoot, i18n }) => { - const tsConfig = readTsconfig(options.tsConfig, context.workspaceRoot); - const target = tsConfig.options.target || ScriptTarget.ES5; - const buildBrowserFeatures = new BuildBrowserFeatures(projectRoot, target); - - const isDifferentialLoadingNeeded = buildBrowserFeatures.isDifferentialLoadingNeeded(); - - if (target > ScriptTarget.ES2015 && isDifferentialLoadingNeeded) { - context.logger.warn(tags.stripIndent` - WARNING: Using differential loading with targets ES5 and ES2016 or higher may - cause problems. Browsers with support for ES2015 will load the ES2016+ scripts - referenced with script[type="module"] but they may not support ES2016+ syntax. - `); - } - - const useBundleDownleveling = isDifferentialLoadingNeeded && !options.watch; - const startTime = Date.now(); - - return runWebpack(config, context, { - webpackFactory: require('webpack') as typeof webpack, - logging: - transforms.logging || - (useBundleDownleveling - ? () => {} - : createBrowserLoggingCallback(!!options.verbose, context.logger)), - }).pipe( - // tslint:disable-next-line: no-big-function - concatMap(async buildEvent => { - const { webpackStats, success, emittedFiles = [] } = buildEvent; - if (!webpackStats) { - throw new Error('Webpack stats build result is required.'); - } - - if (!success && useBundleDownleveling) { - // If using bundle downleveling then there is only one build - // If it fails show any diagnostic messages and bail - if (webpackStats && webpackStats.warnings.length > 0) { - context.logger.warn(statsWarningsToString(webpackStats, { colors: true })); - } - if (webpackStats && webpackStats.errors.length > 0) { - context.logger.error(statsErrorsToString(webpackStats, { colors: true })); - } - - return { success }; - } else if (success) { - outputPaths = ensureOutputPaths(baseOutputPath, i18n); - - let noModuleFiles: EmittedFiles[] | undefined; - let moduleFiles: EmittedFiles[] | undefined; - let files: EmittedFiles[] | undefined; - - const scriptsEntryPointName = normalizeExtraEntryPoints( - options.scripts || [], - 'scripts', - ).map(x => x.bundleName); - - if (isDifferentialLoadingNeeded && options.watch) { - moduleFiles = emittedFiles; - files = moduleFiles.filter( - x => x.extension === '.css' || (x.name && scriptsEntryPointName.includes(x.name)), - ); - if (i18n.shouldInline) { - const success = await i18nInlineEmittedFiles( - context, - emittedFiles, - i18n, - baseOutputPath, - outputPaths, - scriptsEntryPointName, - // tslint:disable-next-line: no-non-null-assertion - webpackStats.outputPath!, - target <= ScriptTarget.ES5, - options.i18nMissingTranslation, - ); - if (!success) { - return { success: false }; - } - } - } else if (isDifferentialLoadingNeeded) { - moduleFiles = []; - noModuleFiles = []; - - // Common options for all bundle process actions - const sourceMapOptions = normalizeSourceMaps(options.sourceMap || false); - const actionOptions: Partial = { - optimize: normalizeOptimization(options.optimization).scripts, - sourceMaps: sourceMapOptions.scripts, - hiddenSourceMaps: sourceMapOptions.hidden, - vendorSourceMaps: sourceMapOptions.vendor, - integrityAlgorithm: options.subresourceIntegrity ? 'sha384' : undefined, - }; - - let mainChunkId; - const actions: ProcessBundleOptions[] = []; - const seen = new Set(); - for (const file of emittedFiles) { - // Assets are not processed nor injected into the index - if (file.asset) { - continue; - } - - // Scripts and non-javascript files are not processed - if ( - file.extension !== '.js' || - (file.name && scriptsEntryPointName.includes(file.name)) - ) { - if (files === undefined) { - files = []; - } - files.push(file); - continue; - } - - // Ignore already processed files; emittedFiles can contain duplicates - if (seen.has(file.file)) { - continue; - } - seen.add(file.file); - - if (file.name === 'vendor' || (!mainChunkId && file.name === 'main')) { - // tslint:disable-next-line: no-non-null-assertion - mainChunkId = file.id!.toString(); - } - - // All files at this point except ES5 polyfills are module scripts - const es5Polyfills = - file.file.startsWith('polyfills-es5') || - file.file.startsWith('polyfills-nomodule-es5'); - if (!es5Polyfills) { - moduleFiles.push(file); - } - // If not optimizing then ES2015 polyfills do not need processing - // Unlike other module scripts, it is never downleveled - const es2015Polyfills = file.file.startsWith('polyfills-es2015'); - if (!actionOptions.optimize && es2015Polyfills) { - continue; - } - - // Retrieve the content/map for the file - // NOTE: Additional future optimizations will read directly from memory - // tslint:disable-next-line: no-non-null-assertion - let filename = path.join(webpackStats.outputPath!, file.file); - const code = fs.readFileSync(filename, 'utf8'); - let map; - if (actionOptions.sourceMaps) { - try { - map = fs.readFileSync(filename + '.map', 'utf8'); - if (es5Polyfills) { - fs.unlinkSync(filename + '.map'); - } - } catch {} - } - - if (es5Polyfills) { - fs.unlinkSync(filename); - filename = filename.replace('-es2015', ''); - } - - // Record the bundle processing action - // The runtime chunk gets special processing for lazy loaded files - actions.push({ - ...actionOptions, - filename, - code, - map, - // id is always present for non-assets - // tslint:disable-next-line: no-non-null-assertion - name: file.id!, - runtime: file.file.startsWith('runtime'), - ignoreOriginal: es5Polyfills, - optimizeOnly: es2015Polyfills, - }); - - // ES2015 polyfills are only optimized; optimization check was performed above - if (es2015Polyfills) { - continue; - } - - // Add the newly created ES5 bundles to the index as nomodule scripts - const newFilename = es5Polyfills - ? file.file.replace('-es2015', '') - : file.file.replace('es2015', 'es5'); - noModuleFiles.push({ ...file, file: newFilename }); - } - - const processActions: typeof actions = []; - let processRuntimeAction: ProcessBundleOptions | undefined; - const processResults: ProcessBundleResult[] = []; - for (const action of actions) { - // If SRI is enabled always process the runtime bundle - // Lazy route integrity values are stored in the runtime bundle - if (action.integrityAlgorithm && action.runtime) { - processRuntimeAction = action; - } else { - processActions.push(action); - } - } - - const executor = new BundleActionExecutor( - { cachePath: cacheDownlevelPath, i18n }, - options.subresourceIntegrity ? 'sha384' : undefined, - ); - - // Execute the bundle processing actions - try { - context.logger.info('Generating ES5 bundles for differential loading...'); - - for await (const result of executor.processAll(processActions)) { - processResults.push(result); - } - - // Runtime must be processed after all other files - if (processRuntimeAction) { - const runtimeOptions = { - ...processRuntimeAction, - runtimeData: processResults, - }; - processResults.push( - await import('../utils/process-bundle').then(m => m.process(runtimeOptions)), - ); - } - - context.logger.info('ES5 bundle generation complete.'); - - if (i18n.shouldInline) { - context.logger.info('Generating localized bundles...'); - - const inlineActions: InlineOptions[] = []; - const processedFiles = new Set(); - for (const result of processResults) { - if (result.original) { - inlineActions.push({ - filename: path.basename(result.original.filename), - code: fs.readFileSync(result.original.filename, 'utf8'), - map: - result.original.map && - fs.readFileSync(result.original.map.filename, 'utf8'), - outputPath: baseOutputPath, - es5: false, - missingTranslation: options.i18nMissingTranslation, - setLocale: result.name === mainChunkId, - }); - processedFiles.add(result.original.filename); - } - if (result.downlevel) { - inlineActions.push({ - filename: path.basename(result.downlevel.filename), - code: fs.readFileSync(result.downlevel.filename, 'utf8'), - map: - result.downlevel.map && - fs.readFileSync(result.downlevel.map.filename, 'utf8'), - outputPath: baseOutputPath, - es5: true, - missingTranslation: options.i18nMissingTranslation, - setLocale: result.name === mainChunkId, - }); - processedFiles.add(result.downlevel.filename); - } - } - - let hasErrors = false; - try { - for await (const result of executor.inlineAll(inlineActions)) { - if (options.verbose) { - context.logger.info( - `Localized "${result.file}" [${result.count} translation(s)].`, - ); - } - for (const diagnostic of result.diagnostics) { - if (diagnostic.type === 'error') { - hasErrors = true; - context.logger.error(diagnostic.message); - } else { - context.logger.warn(diagnostic.message); - } - } - } - - // Copy any non-processed files into the output locations - await copyAssets( - [ - { - glob: '**/*', - // tslint:disable-next-line: no-non-null-assertion - input: webpackStats.outputPath!, - output: '', - ignore: [...processedFiles].map(f => - // tslint:disable-next-line: no-non-null-assertion - path.relative(webpackStats.outputPath!, f), - ), - }, - ], - outputPaths, - '', - ); - } catch (err) { - context.logger.error('Localized bundle generation failed: ' + err.message); - - return { success: false }; - } - - context.logger.info( - `Localized bundle generation ${hasErrors ? 'failed' : 'complete'}.`, - ); - - if (hasErrors) { - return { success: false }; - } - } - } finally { - executor.stop(); - } - - // Copy assets - if (options.assets) { - try { - await copyAssets( - normalizeAssetPatterns( - options.assets, - new virtualFs.SyncDelegateHost(host), - root, - normalize(projectRoot), - projectSourceRoot === undefined ? undefined : normalize(projectSourceRoot), - ), - outputPaths, - context.workspaceRoot, - ); - } catch (err) { - context.logger.error('Unable to copy assets: ' + err.message); - - return { success: false }; - } - } - - type ArrayElement = A extends ReadonlyArray ? T : never; - function generateBundleInfoStats( - id: string | number, - bundle: ProcessBundleFile, - chunk: ArrayElement | undefined, - ): string { - return generateBundleStats( - { - id, - size: bundle.size, - files: bundle.map ? [bundle.filename, bundle.map.filename] : [bundle.filename], - names: chunk && chunk.names, - entry: !!chunk && chunk.names.includes('runtime'), - initial: !!chunk && chunk.initial, - rendered: true, - }, - true, - ); - } - - let bundleInfoText = ''; - const processedNames = new Set(); - for (const result of processResults) { - processedNames.add(result.name); - - const chunk = - webpackStats && - webpackStats.chunks && - webpackStats.chunks.find(c => result.name === c.id.toString()); - if (result.original) { - bundleInfoText += - '\n' + generateBundleInfoStats(result.name, result.original, chunk); - } - if (result.downlevel) { - bundleInfoText += - '\n' + generateBundleInfoStats(result.name, result.downlevel, chunk); - } - } - - if (webpackStats && webpackStats.chunks) { - for (const chunk of webpackStats.chunks) { - if (processedNames.has(chunk.id.toString())) { - continue; - } - - const asset = - webpackStats.assets && webpackStats.assets.find(a => a.name === chunk.files[0]); - bundleInfoText += - '\n' + generateBundleStats({ ...chunk, size: asset && asset.size }, true); - } - } - - bundleInfoText += - '\n' + - generateBuildStats( - (webpackStats && webpackStats.hash) || '', - Date.now() - startTime, - true, - ); - context.logger.info(bundleInfoText); - if (webpackStats && webpackStats.warnings.length > 0) { - context.logger.warn(statsWarningsToString(webpackStats, { colors: true })); - } - if (webpackStats && webpackStats.errors.length > 0) { - context.logger.error(statsErrorsToString(webpackStats, { colors: true })); - } - } else { - files = emittedFiles.filter(x => x.name !== 'polyfills-es5'); - noModuleFiles = emittedFiles.filter(x => x.name === 'polyfills-es5'); - if (i18n.shouldInline) { - const success = await i18nInlineEmittedFiles( - context, - emittedFiles, - i18n, - baseOutputPath, - outputPaths, - scriptsEntryPointName, - // tslint:disable-next-line: no-non-null-assertion - webpackStats.outputPath!, - target <= ScriptTarget.ES5, - options.i18nMissingTranslation, - ); - if (!success) { - return { success: false }; - } - } - } - - if (options.index) { - for (const outputPath of outputPaths) { - try { - await generateIndex( - outputPath, - options, - root, - files, - noModuleFiles, - moduleFiles, - transforms.indexHtml, - ); - } catch (err) { - return { success: false, error: mapErrorToMessage(err) }; - } - } - } - - if (!options.watch && options.serviceWorker) { - for (const outputPath of outputPaths) { - try { - await augmentAppWithServiceWorker( - host, - root, - normalize(projectRoot), - normalize(outputPath), - options.baseHref || '/', - options.ngswConfigPath, - ); - } catch (err) { - return { success: false, error: mapErrorToMessage(err) }; - } - } - } - } - - return { success }; - }), - map( - event => - ({ - ...event, - baseOutputPath, - outputPath: baseOutputPath, - outputPaths: outputPaths || [baseOutputPath], - } as BrowserBuilderOutput), - ), - ); - }), - ); -} - -function generateIndex( - baseOutputPath: string, - options: BrowserBuilderSchema, - root: string, - files: EmittedFiles[] | undefined, - noModuleFiles: EmittedFiles[] | undefined, - moduleFiles: EmittedFiles[] | undefined, - transformer?: IndexHtmlTransform, -): Promise { - const host = new NodeJsSyncHost(); - - return writeIndexHtml({ - host, - outputPath: join(normalize(baseOutputPath), getIndexOutputFile(options)), - indexPath: join(normalize(root), getIndexInputFile(options)), - files, - noModuleFiles, - moduleFiles, - baseHref: options.baseHref, - deployUrl: options.deployUrl, - sri: options.subresourceIntegrity, - scripts: options.scripts, - styles: options.styles, - postTransform: transformer, - crossOrigin: options.crossOrigin, - lang: options.i18nLocale, - }).toPromise(); -} - -function mapErrorToMessage(error: unknown): string | undefined { - if (error instanceof Error) { - return error.message; - } - - if (typeof error === 'string') { - return error; - } - - return undefined; -} - -export default createBuilder(buildWebpackBrowser); diff --git a/packages/angular_devkit/build_angular/src/browser/schema.json b/packages/angular_devkit/build_angular/src/browser/schema.json deleted file mode 100644 index 61c659e7d861..000000000000 --- a/packages/angular_devkit/build_angular/src/browser/schema.json +++ /dev/null @@ -1,557 +0,0 @@ -{ - "$schema": "http://json-schema.org/schema", - "title": "Webpack browser schema for Build Facade.", - "description": "Browser target options", - "type": "object", - "properties": { - "assets": { - "type": "array", - "description": "List of static application assets.", - "default": [], - "items": { - "$ref": "#/definitions/assetPattern" - } - }, - "main": { - "type": "string", - "description": "The full path for the main entry point to the app, relative to the current workspace.", - "$valueDescription": "fileName" - }, - "polyfills": { - "type": "string", - "description": "The full path for the polyfills file, relative to the current workspace." - }, - "tsConfig": { - "type": "string", - "description": "The full path for the TypeScript configuration file, relative to the current workspace." - }, - "scripts": { - "description": "Global scripts to be included in the build.", - "type": "array", - "default": [], - "items": { - "$ref": "#/definitions/extraEntryPoint" - } - }, - "styles": { - "description": "Global styles to be included in the build.", - "type": "array", - "default": [], - "items": { - "$ref": "#/definitions/extraEntryPoint" - } - }, - "stylePreprocessorOptions": { - "description": "Options to pass to style preprocessors.", - "type": "object", - "properties": { - "includePaths": { - "description": "Paths to include. Paths will be resolved to project root.", - "type": "array", - "items": { - "type": "string" - }, - "default": [] - } - }, - "additionalProperties": false - }, - "optimization": { - "description": "Enables optimization of the build output.", - "x-user-analytics": 16, - "oneOf": [ - { - "type": "object", - "properties": { - "scripts": { - "type": "boolean", - "description": "Enables optimization of the scripts output.", - "default": true - }, - "styles": { - "type": "boolean", - "description": "Enables optimization of the styles output.", - "default": true - } - }, - "additionalProperties": false - }, - { - "type": "boolean" - } - ] - }, - "fileReplacements": { - "description": "Replace files with other files in the build.", - "type": "array", - "items": { - "$ref": "#/definitions/fileReplacement" - }, - "default": [] - }, - "outputPath": { - "type": "string", - "description": "The full path for the new output directory, relative to the current workspace.\n\nBy default, writes output to a folder named dist/ in the current project." - }, - "resourcesOutputPath": { - "type": "string", - "description": "The path where style resources will be placed, relative to outputPath.", - "default": "" - }, - "aot": { - "type": "boolean", - "description": "Build using Ahead of Time compilation.", - "x-user-analytics": 13, - "default": false - }, - "sourceMap": { - "description": "Output sourcemaps.", - "default": true, - "oneOf": [ - { - "type": "object", - "properties": { - "scripts": { - "type": "boolean", - "description": "Output sourcemaps for all scripts.", - "default": true - }, - "styles": { - "type": "boolean", - "description": "Output sourcemaps for all styles.", - "default": true - }, - "hidden": { - "type": "boolean", - "description": "Output sourcemaps used for error reporting tools.", - "default": false - }, - "vendor": { - "type": "boolean", - "description": "Resolve vendor packages sourcemaps.", - "default": false - } - }, - "additionalProperties": false - }, - { - "type": "boolean" - } - ] - }, - "vendorSourceMap": { - "type": "boolean", - "description": "Resolve vendor packages sourcemaps.", - "x-deprecated": true, - "default": false - }, - "evalSourceMap": { - "type": "boolean", - "description": "Output in-file eval sourcemaps.", - "default": false, - "x-deprecated": true - }, - "vendorChunk": { - "type": "boolean", - "description": "Use a separate bundle containing only vendor libraries.", - "default": true - }, - "commonChunk": { - "type": "boolean", - "description": "Use a separate bundle containing code used across multiple bundles.", - "default": true - }, - "baseHref": { - "type": "string", - "description": "Base url for the application being built." - }, - "deployUrl": { - "type": "string", - "description": "URL where files will be deployed." - }, - "verbose": { - "type": "boolean", - "description": "Adds more details to output logging.", - "default": false - }, - "progress": { - "type": "boolean", - "description": "Log progress to the console while building." - }, - "i18nFile": { - "type": "string", - "description": "Localization file to use for i18n.", - "x-deprecated": "Use 'locales' object in the project metadata instead." - }, - "i18nFormat": { - "type": "string", - "description": "Format of the localization file specified with --i18n-file.", - "x-deprecated": "No longer needed as the format will be determined automatically." - }, - "i18nLocale": { - "type": "string", - "description": "Locale to use for i18n.", - "x-deprecated": "Use 'localize' instead." - }, - "i18nMissingTranslation": { - "type": "string", - "description": "How to handle missing translations for i18n.", - "enum": ["warning", "error", "ignore"], - "default": "warning" - }, - "localize": { - "oneOf": [ - { - "type": "boolean", - "description": "Translate all locales." - }, - { - "type": "array", - "description": "List of locales ID's to translate.", - "minItems": 1, - "items": { - "type": "string", - "pattern": "^[a-z]{2}(-[a-zA-Z]{2,})?$" - } - } - ] - }, - "extractCss": { - "type": "boolean", - "description": "Extract css from global styles into css files instead of js ones.", - "default": false - }, - "watch": { - "type": "boolean", - "description": "Run build when files change.", - "default": false - }, - "outputHashing": { - "type": "string", - "description": "Define the output filename cache-busting hashing mode.", - "default": "none", - "enum": [ - "none", - "all", - "media", - "bundles" - ] - }, - "poll": { - "type": "number", - "description": "Enable and define the file watching poll time period in milliseconds." - }, - "deleteOutputPath": { - "type": "boolean", - "description": "Delete the output path before building.", - "default": true - }, - "preserveSymlinks": { - "type": "boolean", - "description": "Do not use the real path when resolving modules.", - "default": false - }, - "extractLicenses": { - "type": "boolean", - "description": "Extract all licenses in a separate file.", - "default": false - }, - "showCircularDependencies": { - "type": "boolean", - "description": "Show circular dependency warnings on builds.", - "default": true - }, - "buildOptimizer": { - "type": "boolean", - "description": "Enables '@angular-devkit/build-optimizer' optimizations when using the 'aot' option.", - "default": false - }, - "namedChunks": { - "type": "boolean", - "description": "Use file name for lazy loaded chunks.", - "default": true - }, - "subresourceIntegrity": { - "type": "boolean", - "description": "Enables the use of subresource integrity validation.", - "default": false - }, - "serviceWorker": { - "type": "boolean", - "description": "Generates a service worker config for production builds.", - "default": false - }, - "ngswConfigPath": { - "type": "string", - "description": "Path to ngsw-config.json." - }, - "skipAppShell": { - "type": "boolean", - "description": "Flag to prevent building an app shell.", - "default": false, - "x-deprecated": true - }, - "index": { - "description": "Configures the generation of the application's HTML index.", - "oneOf": [ - { - "type": "string", - "description": "The path of a file to use for the application's HTML index. The filename of the specified path will be used for the generated file and will be created in the root of the application's configured output path." - }, - { - "type": "object", - "description": "", - "properties": { - "input": { - "type": "string", - "minLength": 1, - "description": "The path of a file to use for the application's generated HTML index." - }, - "output": { - "type": "string", - "minLength": 1, - "default": "index.html", - "description": "The output path of the application's generated HTML index file. The full provided path will be used and will be considered relative to the application's configured output path." - } - }, - "required": ["input"] - } - ] - }, - "statsJson": { - "type": "boolean", - "description": "Generates a 'stats.json' file which can be analyzed using tools such as 'webpack-bundle-analyzer'.", - "default": false - }, - "forkTypeChecker": { - "type": "boolean", - "description": "Run the TypeScript type checker in a forked process.", - "default": true - }, - "lazyModules": { - "description": "List of additional NgModule files that will be lazy loaded. Lazy router modules will be discovered automatically.", - "type": "array", - "items": { - "type": "string" - }, - "x-deprecated": "'SystemJsNgModuleLoader' is deprecated, and this is part of its usage. Use 'import()' syntax instead.", - "default": [] - }, - "budgets": { - "description": "Budget thresholds to ensure parts of your application stay within boundaries which you set.", - "type": "array", - "items": { - "$ref": "#/definitions/budget" - }, - "default": [] - }, - "profile": { - "type": "boolean", - "description": "Output profile events for Chrome profiler.", - "default": false, - "x-deprecated": "Use \"NG_BUILD_PROFILING\" environment variable instead." - }, - "es5BrowserSupport": { - "description": "Enables conditionally loaded ES2015 polyfills.", - "type": "boolean", - "x-deprecated": "This will be determined from the list of supported browsers specified in the 'browserslist' file." - }, - "rebaseRootRelativeCssUrls": { - "description": "Change root relative URLs in stylesheets to include base HREF and deploy URL. Use only for compatibility and transition. The behavior of this option is non-standard and will be removed in the next major release.", - "type": "boolean", - "default": false, - "x-deprecated": true - }, - "webWorkerTsConfig": { - "type": "string", - "description": "TypeScript configuration for Web Worker modules." - }, - "crossOrigin": { - "type": "string", - "description": "Define the crossorigin attribute setting of elements that provide CORS support.", - "default": "none", - "enum": [ - "none", - "anonymous", - "use-credentials" - ] - }, - "experimentalRollupPass": { - "type": "boolean", - "description": "Concatenate modules with Rollup before bundling them with Webpack.", - "default": false - } - }, - "additionalProperties": false, - "required": [ - "outputPath", - "index", - "main", - "tsConfig" - ], - "definitions": { - "assetPattern": { - "oneOf": [ - { - "type": "object", - "properties": { - "glob": { - "type": "string", - "description": "The pattern to match." - }, - "input": { - "type": "string", - "description": "The input directory path in which to apply 'glob'. Defaults to the project root." - }, - "ignore": { - "description": "An array of globs to ignore.", - "type": "array", - "items": { - "type": "string" - } - }, - "output": { - "type": "string", - "description": "Absolute path within the output." - } - }, - "additionalProperties": false, - "required": [ - "glob", - "input", - "output" - ] - }, - { - "type": "string" - } - ] - }, - "fileReplacement": { - "oneOf": [ - { - "type": "object", - "properties": { - "src": { - "type": "string" - }, - "replaceWith": { - "type": "string" - } - }, - "additionalProperties": false, - "required": [ - "src", - "replaceWith" - ] - }, - { - "type": "object", - "properties": { - "replace": { - "type": "string" - }, - "with": { - "type": "string" - } - }, - "additionalProperties": false, - "required": [ - "replace", - "with" - ] - } - ] - }, - "extraEntryPoint": { - "oneOf": [ - { - "type": "object", - "properties": { - "input": { - "type": "string", - "description": "The file to include." - }, - "bundleName": { - "type": "string", - "description": "The bundle name for this extra entry point." - }, - "lazy": { - "type": "boolean", - "description": "If the bundle will be lazy loaded.", - "default": false, - "x-deprecated": "Use 'inject' option with 'false' value instead." - }, - "inject": { - "type": "boolean", - "description": "If the bundle will be referenced in the HTML file.", - "default": true - } - }, - "additionalProperties": false, - "required": [ - "input" - ] - }, - { - "type": "string", - "description": "The file to include." - } - ] - }, - "budget": { - "type": "object", - "properties": { - "type": { - "type": "string", - "description": "The type of budget.", - "enum": [ - "all", - "allScript", - "any", - "anyScript", - "anyComponentStyle", - "bundle", - "initial" - ] - }, - "name": { - "type": "string", - "description": "The name of the bundle." - }, - "baseline": { - "type": "string", - "description": "The baseline size for comparison." - }, - "maximumWarning": { - "type": "string", - "description": "The maximum threshold for warning relative to the baseline." - }, - "maximumError": { - "type": "string", - "description": "The maximum threshold for error relative to the baseline." - }, - "minimumWarning": { - "type": "string", - "description": "The minimum threshold for warning relative to the baseline." - }, - "minimumError": { - "type": "string", - "description": "The minimum threshold for error relative to the baseline." - }, - "warning": { - "type": "string", - "description": "The threshold for warning relative to the baseline (min & max)." - }, - "error": { - "type": "string", - "description": "The threshold for error relative to the baseline (min & max)." - } - }, - "additionalProperties": false, - "required": [ - "type" - ] - } - } -} diff --git a/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts b/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts new file mode 100644 index 000000000000..f39d8da34114 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/app-shell/app-shell_spec.ts @@ -0,0 +1,201 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { normalize } from '@angular-devkit/core'; +import { createArchitect, host } from '../../testing/test-utils'; + +describe('AppShell Builder', () => { + const target = { project: 'app', target: 'app-shell' }; + let architect: Architect; + const originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + + beforeAll(() => { + jasmine.DEFAULT_TIMEOUT_INTERVAL = 100_000; + }); + + afterAll(() => { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + const appShellRouteFiles = { + 'src/styles.css': ` + p { color: #000 } + `, + 'src/app/app-shell/app-shell.component.html': ` +

+ app-shell works! +

+ `, + 'src/app/app-shell/app-shell.component.ts': ` + import { Component, OnInit } from '@angular/core'; + + @Component({ + selector: 'app-app-shell', + standalone: false, + templateUrl: './app-shell.component.html', + }) + export class AppShellComponent implements OnInit { + + constructor() { } + + ngOnInit() { + } + + } + `, + 'src/app/app.module.ts': ` + import { BrowserModule } from '@angular/platform-browser'; + import { NgModule } from '@angular/core'; + + import { AppRoutingModule } from './app-routing.module'; + import { AppComponent } from './app.component'; + import { RouterModule } from '@angular/router'; + + @NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + AppRoutingModule, + RouterModule + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + 'src/app/app.module.server.ts': ` + import { NgModule } from '@angular/core'; + import { ServerModule } from '@angular/platform-server'; + + import { AppModule } from './app.module'; + import { AppComponent } from './app.component'; + import { Routes, RouterModule } from '@angular/router'; + import { AppShellComponent } from './app-shell/app-shell.component'; + + const routes: Routes = [ { path: 'shell', component: AppShellComponent }]; + + @NgModule({ + imports: [ + AppModule, + ServerModule, + RouterModule.forRoot(routes), + ], + bootstrap: [AppComponent], + declarations: [AppShellComponent], + }) + export class AppServerModule {} + `, + 'src/main.ts': ` + import { platformBrowser } from '@angular/platform-browser'; + import { AppModule } from './app/app.module'; + + document.addEventListener('DOMContentLoaded', () => { + platformBrowser().bootstrapModule(AppModule) + .catch(err => console.log(err)); + }); + `, + 'src/app/app-routing.module.ts': ` + import { NgModule } from '@angular/core'; + import { Routes, RouterModule } from '@angular/router'; + + const routes: Routes = []; + + @NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] + }) + export class AppRoutingModule { } + `, + 'src/app/app.component.html': ` + + `, + }; + + it('works (basic)', async () => { + const run = await architect.scheduleTarget(target); + const output = await run.result; + await run.stop(); + + expect(output.success).toBe(true); + + const fileName = 'dist/index.html'; + const content = new TextDecoder().decode(host.scopedSync().read(normalize(fileName))); + expect(content).toMatch('Welcome to app'); + }); + + it('works with route', async () => { + host.writeMultipleFiles(appShellRouteFiles); + const overrides = { route: 'shell' }; + + const run = await architect.scheduleTarget(target, overrides); + const output = await run.result; + await run.stop(); + + expect(output.success).toBe(true); + const fileName = 'dist/index.html'; + const content = new TextDecoder().decode(host.scopedSync().read(normalize(fileName))); + expect(content).toContain('app-shell works!'); + }); + + it('critical CSS is inlined', async () => { + host.writeMultipleFiles(appShellRouteFiles); + const overrides = { + route: 'shell', + browserTarget: 'app:build:production,inline-critical-css', + }; + + const run = await architect.scheduleTarget(target, overrides); + const output = await run.result; + await run.stop(); + + expect(output.success).toBe(true); + const fileName = 'dist/index.html'; + const content = new TextDecoder().decode(host.scopedSync().read(normalize(fileName))); + + expect(content).toContain('app-shell works!'); + expect(content).toContain('p{color:#000}'); + expect(content).toMatch( + //, + ); + }); + + it('applies CSP nonce to critical CSS', async () => { + host.writeMultipleFiles(appShellRouteFiles); + host.replaceInFile('src/index.html', /p{color:#000}'); + expect(content).toContain(' +
{{ title }}
+ `, + './src/app/app.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + standalone: false, + templateUrl: './app.component.html', + styles: 'div { font-weight: 500; }', + }) + export class AppComponent { + title = 'app'; + } + `, + '.browserslistrc': ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + }); + + const { files } = await browserBuild(architect, host, target, { aot: true }); + + expect(await files['main.js']).toContain('-webkit-mask-composite'); + }); + + extensionsWithImportSupport.forEach((ext) => { + it(`supports imports in ${ext} files`, async () => { + host.writeMultipleFiles({ + [`src/styles.${ext}`]: ` + @import './imported-styles.${ext}'; + body { background-color: #00f; } + `, + [`src/imported-styles.${ext}`]: 'p { background-color: #f00; }', + [`src/app/app.component.${ext}`]: ` + @import './imported-component-styles.${ext}'; + .outer { + .inner { + background: #fff; + } + } + `, + [`src/app/imported-component-styles.${ext}`]: 'h1 { background: #000; }', + }); + + const matches: { [path: string]: RegExp } = { + 'styles.css': new RegExp( + // The global style should be there + /p\s*{\s*background-color: #f00;\s*}(.|\n|\r)*/.source + + // The global style via import should be there + /body\s*{\s*background-color: #00f;\s*}/.source, + ), + 'styles.css.map': /"mappings":".+"/, + 'main.js': new RegExp( + // The component style should be there + /h1(.|\n|\r)*background:\s*#000(.|\n|\r)*/.source + + // The component style via import should be there + /.outer(.|\n|\r)*.inner(.|\n|\r)*background:\s*#[fF]+/.source, + ), + }; + + const overrides = { + aot: true, + sourceMap: true, + styles: [`src/styles.${ext}`], + }; + + host.replaceInFile( + 'src/app/app.component.ts', + './app.component.css', + `./app.component.${ext}`, + ); + + const { files } = await browserBuild(architect, host, target, overrides); + for (const fileName of Object.keys(matches)) { + expect(await files[fileName]).toMatch(matches[fileName]); + } + }); + }); + + extensionsWithImportSupport.forEach((ext) => { + it(`supports material imports in ${ext} files`, async () => { + host.writeMultipleFiles({ + [`src/styles.${ext}`]: ` + @import "@angular/material/prebuilt-themes/indigo-pink.css"; + `, + [`src/app/app.component.${ext}`]: ` + @import "@angular/material/prebuilt-themes/indigo-pink.css"; + `, + }); + host.replaceInFile( + 'src/app/app.component.ts', + './app.component.css', + `./app.component.${ext}`, + ); + + const overrides = { + styles: [{ input: `src/styles.${ext}` }], + }; + await browserBuild(architect, host, target, overrides); + }); + }); + + extensionsWithVariableSupport.forEach((ext) => { + it(`supports ${ext} includePaths`, async () => { + let variableAssignment = ''; + let variablereference = ''; + if (ext === 'scss') { + variableAssignment = '$primary-color:'; + variablereference = '$primary-color'; + } else if (ext === 'less') { + variableAssignment = '@primary-color:'; + variablereference = '@primary-color'; + } + + host.writeMultipleFiles({ + [`src/style-paths/variables.${ext}`]: `${variableAssignment} #f00;`, + [`src/styles.${ext}`]: ` + @import 'variables'; + h1 { color: ${variablereference}; } + `, + [`src/app/app.component.${ext}`]: ` + @import 'variables'; + h2 { color: ${variablereference}; } + `, + }); + + const matches: { [path: string]: RegExp } = { + 'styles.css': /h1\s*{\s*color: #f00;\s*}/, + 'main.js': /h2\s*{\s*color: #f00;\s*}/, + }; + + host.replaceInFile( + 'src/app/app.component.ts', + './app.component.css', + `./app.component.${ext}`, + ); + + const overrides = { + styles: [`src/styles.${ext}`], + stylePreprocessorOptions: { + includePaths: ['src/style-paths'], + }, + }; + + const { files } = await browserBuild(architect, host, target, overrides); + for (const [fileName, match] of Object.entries(matches)) { + expect(await files[fileName]).toMatch(match); + } + }); + }); + + it(`supports font-awesome imports`, async () => { + // font-awesome mock to avoid having an extra dependency. + host.writeMultipleFiles({ + 'node_modules/font-awesome/scss/font-awesome.scss': ` + * { color: red } + `, + }); + + host.writeMultipleFiles({ + 'src/styles.scss': ` + @import "font-awesome/scss/font-awesome"; + `, + }); + + const overrides = { styles: [`src/styles.scss`] }; + await browserBuild(architect, host, target, overrides); + }); + + it(`uses autoprefixer`, async () => { + host.writeMultipleFiles({ + 'src/styles.css': tags.stripIndents` + @import url(imported-styles.css); + /* normal-comment */ + /*! important-comment */ + div { mask-composite: add; }`, + 'src/imported-styles.css': tags.stripIndents` + /* normal-comment */ + /*! important-comment */ + section { mask-composite: add; }`, + '.browserslistrc': ` + Safari 15.4 + Edge 104 + Firefox 91 + `, + }); + + const overrides = { optimization: false }; + const { files } = await browserBuild(architect, host, target, overrides); + const content = await files['styles.css']; + expect(content).toContain(tags.stripIndents` + /* normal-comment */ + /*! important-comment */ + section { -webkit-mask-composite: source-over; mask-composite: add; }`); + // Check separately because Webpack may add source file comments inbetween the rules + expect(content).toContain(tags.stripIndents` + /* normal-comment */ + /*! important-comment */ + div { -webkit-mask-composite: source-over; mask-composite: add; }`); + }); + + it(`minimizes css`, async () => { + host.writeMultipleFiles({ + 'src/styles.css': tags.stripIndents` + /* normal-comment */ + /*! important-comment */ + div { flex: 1 }`, + }); + + const overrides = { optimization: true }; + const { files } = await browserBuild(architect, host, target, overrides); + expect(await files['styles.css']).toContain('/*! important-comment */'); + }); + + // TODO: consider making this a unit test in the url processing plugins. + it( + `supports baseHref/deployUrl in resource urls`, + async () => { + // Use a large image for the relative ref so it cannot be inlined. + host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); + host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); + host.writeMultipleFiles({ + 'src/styles.css': ` + h1 { background: url('/assets/global-img-absolute.svg'); } + h2 { background: url('./assets/global-img-relative.png'); } + `, + 'src/app/app.component.css': ` + h3 { background: url('/assets/component-img-absolute.svg'); } + h4 { background: url('../assets/component-img-relative.png'); } + `, + 'src/assets/global-img-absolute.svg': imgSvg, + 'src/assets/component-img-absolute.svg': imgSvg, + }); + + let { files } = await browserBuild(architect, host, target, { aot: true }); + + // Check base paths are correctly generated. + let styles = await files['styles.css']; + let main = await files['main.js']; + + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(styles).toContain(`url('global-img-relative.png')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + expect(main).toContain(`url('component-img-relative.png')`); + + expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); + expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))).toBe(true); + expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( + true, + ); + expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))).toBe(true); + + // Check urls with deploy-url scheme are used as is. + files = ( + await browserBuild(architect, host, target, { + baseHref: '/base/', + deployUrl: 'http://deploy.url/', + }) + ).files; + + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + + // Check urls with base-href scheme are used as is (with deploy-url). + files = ( + await browserBuild(architect, host, target, { + baseHref: 'http://base.url/', + deployUrl: 'deploy/', + }) + ).files; + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + + // Check urls with deploy-url and base-href scheme only use deploy-url. + files = ( + await browserBuild(architect, host, target, { + baseHref: 'http://base.url/', + deployUrl: 'http://deploy.url/', + }) + ).files; + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + + // Check with schemeless base-href and deploy-url flags. + files = ( + await browserBuild(architect, host, target, { + baseHref: '/base/', + deployUrl: 'deploy/', + }) + ).files; + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + + // Check with identical base-href and deploy-url flags. + files = ( + await browserBuild(architect, host, target, { + baseHref: '/base/', + deployUrl: '/base/', + }) + ).files; + + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + + // Check with only base-href flag. + files = ( + await browserBuild(architect, host, target, { + baseHref: '/base/', + }) + ).files; + + styles = await files['styles.css']; + main = await files['main.js']; + expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); + expect(main).toContain(`url('/assets/component-img-absolute.svg')`); + // NOTE: Timeout for large amount of builds in test. Test should be split up when refactored. + }, + 4 * 60 * 1000, + ); + + it(`supports inline javascript in less`, async () => { + const overrides = { styles: [`src/styles.less`] }; + host.writeMultipleFiles({ + 'src/styles.less': ` + .myFunction() { + @functions: ~\`(function () { + return ''; + })()\`; + } + .myFunction(); + `, + }); + + await browserBuild(architect, host, target, overrides); + }); + + it('causes equal failure for tilde url()', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + body { + background-image: url('~does-not-exist.jpg'); + } + `, + }); + + const run = await architect.scheduleTarget(target, { optimization: true }); + await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); + await run.stop(); + }); + + it('causes equal failure for tilde-slash url()', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + body { + background-image: url('~/does-not-exist.jpg'); + } + `, + }); + + const run = await architect.scheduleTarget(target, { optimization: true }); + await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); + await run.stop(); + }); + + it('supports Protocol-relative Url', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + body { + background-image: url('//cdn.com/classic-bg.jpg'); + } + `, + }); + + const overrides = { optimization: true }; + const { files } = await browserBuild(architect, host, target, overrides); + expect(await files['styles.css']).toContain('background-image:url(//cdn.com/classic-bg.jpg)'); + }); + + it('supports fonts with space in filename', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + @font-face { + font-family: "Font Awesome"; + src: url("./assets/fa solid-900.woff2") format("woff2"); + } + + body { + font-family: "Font Awesome"; + } + `, + 'src/assets/fa solid-900.woff2': '', + }); + + const { output } = await browserBuild(architect, host, target); + expect(output.success).toBe(true); + }); + + extensionsWithImportSupport.forEach((ext) => { + it(`retains declarations order in ${ext} files when using @import`, async () => { + host.writeMultipleFiles({ + [`src/styles-one.${ext}`]: tags.stripIndents` + .one { + color: #fff; + } + `, + [`src/styles-two.${ext}`]: tags.stripIndents` + .two { + color: #fff; + } + `, + // LESS doesn't support css imports by default. + // See: https://github.com/less/less.js/issues/3188#issuecomment-374690630 + [`src/styles-three.${ext}`]: tags.stripIndents` + @import ${ + ext === 'less' ? ' (css) ' : '' + }url("https://fonts.googleapis.com/css?family=Roboto:400"); + .three { + color: #fff; + } + `, + }); + + const overrides = { + styles: [`src/styles-one.${ext}`, `src/styles-two.${ext}`, `src/styles-three.${ext}`], + }; + const { files } = await browserBuild(architect, host, target, overrides); + expect(await files['styles.css']).toMatch(/\.one(.|\n|\r)*\.two(.|\n|\r)*\.three/); + }); + + it(`adjusts relative resource URLs when using @import in ${ext} (global)`, async () => { + host.copyFile('src/spectrum.png', './src/more-styles/images/global-img-relative.png'); + host.writeMultipleFiles({ + [`src/styles-one.${ext}`]: tags.stripIndents` + @import "more-styles/styles-two.${ext}"; + `, + [`src/more-styles/styles-two.${ext}`]: tags.stripIndents` + .two { + background-image: url(images/global-img-relative.png); + } + `, + }); + + const overrides = { + sourceMap: false, + styles: [`src/styles-one.${ext}`], + }; + const { files } = await browserBuild(architect, host, target, overrides); + expect(await files['styles.css']).toContain("'global-img-relative.png'"); + }); + + it(`adjusts relative resource URLs when using @import in ${ext} (component)`, async () => { + host.copyFile('src/spectrum.png', './src/app/images/component-img-relative.png'); + host.writeMultipleFiles({ + [`src/app/styles/component-styles.${ext}`]: ` + div { background-image: url(../images/component-img-relative.png); } + `, + [`src/app/app.component.${ext}`]: ` + @import "styles/component-styles.${ext}"; + `, + }); + + host.replaceInFile( + 'src/app/app.component.ts', + './app.component.css', + `./app.component.${ext}`, + ); + + const overrides = { + sourceMap: false, + }; + await browserBuild(architect, host, target, overrides); + }); + }); + + it('should minify colors based on browser support', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + div { box-shadow: 0 3px 10px, rgba(0, 0, 0, 0.15); } + `, + }); + + let result = await browserBuild(architect, host, target, { optimization: true }); + expect(await result.files['styles.css']).toContain('#00000026'); + + await host.restore().toPromise(); + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + + // Edge 17 doesn't support #rrggbbaa colors + // https://github.com/angular/angular-cli/issues/21594#:~:text=%23rrggbbaa%20hex%20color%20notation + // While this browser is un-supported, this is used as a base case to test that the underlying + // logic to pass the list of supported browsers to the css optimizer works. + host.writeMultipleFiles({ + 'src/styles.css': ` + div { box-shadow: 0 3px 10px, rgba(0, 0, 0, 0.15); } + `, + '.browserslistrc': `edge 18`, + }); + + result = await browserBuild(architect, host, target, { optimization: true }); + + expect(await result.files['styles.css']).toContain('rgba(0,0,0,.15)'); + }, 80_000); + + it('works when using the same css file in `styles` and `stylesUrl`', async () => { + host.writeMultipleFiles({ + 'src/styles.css': ` + div { color: red } + `, + './src/app/app.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + standalone: false, + templateUrl: './app.component.html', + styleUrls: ['../styles.css'] + }) + export class AppComponent { + title = 'app'; + } + `, + }); + + await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); + }); + + it('works when Data URI has escaped quote', async () => { + const svgData = `"data:image/svg+xml;charset=utf-8,"`; + + host.writeMultipleFiles({ + 'src/styles.css': ` + div { background: url(${svgData}) } + `, + }); + + const result = await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); + expect(await result.files['styles.css']).toContain(svgData); + }); + + it('works when Data URI has parenthesis', async () => { + const svgData = + '"data:image/svg+xml;charset=utf-8,' + + `` + + '"'; + + host.writeMultipleFiles({ + 'src/styles.css': ` + div { background: url(${svgData}) } + `, + }); + + const result = await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); + expect(await result.files['styles.css']).toContain(svgData); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/svg_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/svg_spec.ts new file mode 100644 index 000000000000..4fe80e923b2e --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/svg_spec.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { join, normalize } from '@angular-devkit/core'; +import { createArchitect, host, outputPath } from '../../../testing/test-utils'; + +describe('Browser Builder allow svg', () => { + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('works with aot', async () => { + const svg = ` + + Hello World + `; + + host.writeMultipleFiles({ + './src/app/app.component.svg': svg, + './src/app/app.component.ts': ` + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-root', + standalone: false, + templateUrl: './app.component.svg', + styleUrls: [] + }) + export class AppComponent { + title = 'app'; + } + `, + }); + + const overrides = { aot: true }; + + const run = await architect.scheduleTarget(target, overrides); + + await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); + + const exists = host.scopedSync().exists(join(outputPath, 'main.js')); + expect(exists).toBe(true, '"main.js" should exist'); + + if (exists) { + const content = new TextDecoder().decode(host.scopedSync().read(join(outputPath, 'main.js'))); + + // Verify that the svg contents are present in the main bundle, + // e.g. as template instructions. + expect(content).toContain('Hello World'); + + // Verify that the svg contents are *not* present as a separate file. + expect(host.scopedSync().exists(normalize('dist/app.component.svg'))).toBe( + false, + 'should not copy app.component.svg to dist', + ); + } + + await run.stop(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/tsconfig-paths_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/tsconfig-paths_spec.ts new file mode 100644 index 000000000000..b097b7c078a0 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/tsconfig-paths_spec.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { normalize } from '@angular-devkit/core'; +import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; + +describe('Browser Builder tsconfig paths', () => { + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('should resolve basic tsconfig paths', async () => { + host.replaceInFile('src/app/app.module.ts', './app.component', '@root/app/app.component'); + + const tsconfigPath = normalize('tsconfig.json'); + const tsconfig = JSON.parse(new TextDecoder().decode(host.scopedSync().read(tsconfigPath))); + tsconfig.compilerOptions ??= {}; + tsconfig.compilerOptions.paths = { + '@root/*': ['./src/*'], + }; + host + .scopedSync() + .write(tsconfigPath, new TextEncoder().encode(JSON.stringify(tsconfig, null, 2)).buffer); + + await browserBuild(architect, host, target); + }); + + it('should resolve complex tsconfig paths with wildcards', async () => { + host.writeMultipleFiles({ + 'src/meaning-too.ts': 'export var meaning = 42;', + 'src/app/shared/meaning.ts': 'export var meaning = 42;', + 'src/app/shared/index.ts': `export * from './meaning'`, + }); + const tsconfigPath = normalize('tsconfig.json'); + const tsconfig = JSON.parse(new TextDecoder().decode(host.scopedSync().read(tsconfigPath))); + tsconfig.compilerOptions ??= {}; + tsconfig.compilerOptions.paths = { + '@shared': ['./src/app/shared'], + '@shared/*': ['./src/app/shared/*'], + '*': ['./*', './src/app/shared/*'], + }; + host + .scopedSync() + .write(tsconfigPath, new TextEncoder().encode(JSON.stringify(tsconfig, null, 2)).buffer); + + host.appendToFile( + 'src/app/app.component.ts', + ` + import { meaning } from 'src/app/shared/meaning'; + import { meaning as meaning2 } from '@shared'; + import { meaning as meaning3 } from '@shared/meaning'; + import { meaning as meaning4 } from 'meaning'; + import { meaning as meaning5 } from 'src/meaning-too'; + + // need to use imports otherwise they are ignored and + // no error is outputted, even if baseUrl/paths don't work + console.log(meaning) + console.log(meaning2) + console.log(meaning3) + console.log(meaning4) + console.log(meaning5) + `, + ); + + await browserBuild(architect, host, target); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts new file mode 100644 index 000000000000..fc66978d8114 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts @@ -0,0 +1,256 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { logging } from '@angular-devkit/core'; +import { debounceTime, take, tap } from 'rxjs'; +import { createArchitect, host } from '../../../testing/test-utils'; +import { BrowserBuilderOutput } from '../index'; + +describe('Browser Builder unused files warnings', () => { + const warningMessageSuffix = `is part of the TypeScript compilation but it's unused`; + const targetSpec = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('should not show warning when all files are used', async () => { + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); + const output = await run.result; + expect(output.success).toBe(true); + expect(logs.join().includes(warningMessageSuffix)).toBe(false); + + await run.stop(); + }); + + it('should show warning when some files are unused', async () => { + host.writeMultipleFiles({ + 'src/unused-file.ts': `export const unused = '1';`, + }); + + host.replaceInFile('src/tsconfig.app.json', '"main.ts"', '"main.ts", "unused-file.ts"'); + + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); + const output = await run.result; + expect(output.success).toBe(true); + expect(logs.join().includes(`unused-file.ts ${warningMessageSuffix}`)).toBe(true); + + await run.stop(); + }); + + it('should not show warning when excluded files are unused', async () => { + const ignoredFiles = { + 'src/file.d.ts': 'export type MyType = number;', + }; + + host.writeMultipleFiles(ignoredFiles); + + host.replaceInFile( + 'src/tsconfig.app.json', + '"main.ts"', + `"main.ts", ${Object.keys(ignoredFiles) + .map((f) => `"${f.replace('src/', '')}"`) + .join(',')}`, + ); + + host.replaceInFile( + 'src/tsconfig.app.json', + '"compilerOptions":', + '"angularCompilerOptions": { "strictTemplates": true }, "compilerOptions":', + ); + + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const run = await architect.scheduleTarget(targetSpec, { aot: true }, { logger }); + const output = await run.result; + expect(output.success).toBe(true); + expect(logs.join().includes(warningMessageSuffix)).toBe(false); + + await run.stop(); + }); + + it('should not show warning when type files are used', async () => { + host.writeMultipleFiles({ + 'src/app/type.ts': 'export type MyType = number;', + }); + + host.replaceInFile( + 'src/app/app.component.ts', + `'@angular/core';`, + `'@angular/core';\nimport { MyType } from './type';\n`, + ); + + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); + const output = await run.result; + expect(output.success).toBe(true); + expect(logs.join().includes(warningMessageSuffix)).toBe(false); + + await run.stop(); + }); + + it('should not show warning when type files are used transitively', async () => { + host.writeMultipleFiles({ + 'src/app/type.ts': `import {Myinterface} from './interface'; export type MyType = Myinterface;`, + 'src/app/interface.ts': 'export interface Myinterface {nbr: number;}', + }); + + host.replaceInFile( + 'src/app/app.component.ts', + `'@angular/core';`, + `'@angular/core';\nimport { MyType } from './type';\n`, + ); + + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); + const output = await run.result; + expect(output.success).toBe(true); + expect(logs.join().includes(warningMessageSuffix)).toBe(false); + + await run.stop(); + }); + + it('works for rebuilds', async () => { + host.replaceInFile('src/tsconfig.app.json', '"**/*.d.ts"', '"**/*.d.ts", "testing/**/*.ts"'); + + const logger = new logging.Logger(''); + let logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + let buildNumber = 0; + const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); + + await run.output + .pipe( + debounceTime(1000), + tap((buildEvent) => { + expect(buildEvent.success).toBe(true); + + buildNumber++; + switch (buildNumber) { + case 1: + // The first should not have unused files + expect(logs.join().includes(warningMessageSuffix)).toBe( + false, + `Case ${buildNumber} failed.`, + ); + + // Write a used file + host.writeMultipleFiles({ + 'src/testing/type.ts': 'export type MyType = number;', + }); + + // touch file to trigger build + host.replaceInFile( + 'src/app/app.component.ts', + `'@angular/core';`, + `'@angular/core';\n`, + ); + break; + + case 2: + // The second should have type.ts as unused + expect(logs.join().includes(`type.ts ${warningMessageSuffix}`)).toBe( + true, + `Case ${buildNumber} failed.`, + ); + + host.replaceInFile( + 'src/app/app.component.ts', + `'@angular/core';`, + `'@angular/core';\nimport { MyType } from '../testing/type';`, + ); + break; + + case 3: + // The third should not have any unused files + expect(logs.join().includes(warningMessageSuffix)).toBe( + false, + `Case ${buildNumber} failed.`, + ); + break; + } + + logs = []; + }), + take(3), + ) + .toPromise(); + await run.stop(); + }); + + it('should only show warning once per file', async () => { + host.replaceInFile('src/tsconfig.app.json', '"**/*.d.ts"', '"**/*.d.ts", "testing/**/*.ts"'); + + // Write a used file + host.writeMultipleFiles({ + 'src/testing/type.ts': 'export type MyType = number;', + }); + + const logger = new logging.Logger(''); + let logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + let buildNumber = 0; + const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); + + await run.output + .pipe( + debounceTime(1000), + tap((buildEvent) => { + expect(buildEvent.success).toBe(true); + + buildNumber++; + switch (buildNumber) { + case 1: + // The first should have type.ts as unused. + expect(logs.join().includes(`type.ts ${warningMessageSuffix}`)).toBe( + true, + `Case ${buildNumber} failed.`, + ); + + // touch a file to trigger a rebuild + host.appendToFile('src/main.ts', ''); + break; + case 2: + // The second should have type.ts as unused but shouldn't warn. + expect(logs.join().includes(warningMessageSuffix)).toBe( + false, + `Case ${buildNumber} failed.`, + ); + break; + } + + logs = []; + }), + take(2), + ) + .toPromise(); + await run.stop(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-chunk_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-chunk_spec.ts new file mode 100644 index 000000000000..8c6e9db94550 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-chunk_spec.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; + +describe('Browser Builder vendor chunk', () => { + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('works', async () => { + const { files } = await browserBuild(architect, host, target, { vendorChunk: true }); + expect('vendor.js' in files).toBe(true); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts new file mode 100644 index 000000000000..e1e8a1f86bd4 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import * as path from 'node:path'; +import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; + +// Following the naming conventions from +// https://sourcemaps.info/spec.html#h.ghqpj1ytqjbm +const IGNORE_LIST = 'x_google_ignoreList'; + +describe('Browser Builder external source map', () => { + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('works', async () => { + const overrides = { + sourceMap: { + scripts: true, + styles: true, + vendor: true, + }, + }; + + const { files } = await browserBuild(architect, host, target, overrides); + const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; + const hasTsSourcePaths = sourcePaths.some((p) => path.extname(p) == '.ts'); + expect(hasTsSourcePaths).toBe(true, `vendor.js.map should have '.ts' extentions`); + }); + + it('does not map sourcemaps from external library when disabled', async () => { + const overrides = { + sourceMap: { + scripts: true, + styles: true, + vendor: false, + }, + }; + + const { files } = await browserBuild(architect, host, target, overrides); + const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; + const hasTsSourcePaths = sourcePaths.some((p) => path.extname(p) == '.ts'); + expect(hasTsSourcePaths).toBe(false, `vendor.js.map not should have '.ts' extentions`); + }); +}); + +describe('Identifying third-party code in source maps', () => { + interface SourceMap { + sources: string[]; + [IGNORE_LIST]: number[]; + } + + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + it('specifies which sources are third party when vendor processing is disabled', async () => { + const overrides = { + sourceMap: { + scripts: true, + vendor: false, + }, + }; + + const { files } = await browserBuild(architect, host, target, overrides); + const mainMap: SourceMap = JSON.parse(await files['main.js.map']); + const polyfillsMap: SourceMap = JSON.parse(await files['polyfills.js.map']); + const runtimeMap: SourceMap = JSON.parse(await files['runtime.js.map']); + const vendorMap: SourceMap = JSON.parse(await files['vendor.js.map']); + + expect(mainMap[IGNORE_LIST]).not.toBeUndefined(); + expect(polyfillsMap[IGNORE_LIST]).not.toBeUndefined(); + expect(runtimeMap[IGNORE_LIST]).not.toBeUndefined(); + expect(vendorMap[IGNORE_LIST]).not.toBeUndefined(); + + expect(mainMap[IGNORE_LIST].length).toEqual(0); + expect(polyfillsMap[IGNORE_LIST].length).not.toEqual(0); + expect(runtimeMap[IGNORE_LIST].length).not.toEqual(0); + expect(vendorMap[IGNORE_LIST].length).not.toEqual(0); + + const thirdPartyInMain = mainMap.sources.some((s) => s.includes('node_modules')); + const thirdPartyInPolyfills = polyfillsMap.sources.some((s) => s.includes('node_modules')); + const thirdPartyInRuntime = runtimeMap.sources.some((s) => s.includes('webpack')); + const thirdPartyInVendor = vendorMap.sources.some((s) => s.includes('node_modules')); + expect(thirdPartyInMain).toBe(false, `main.js.map should not include any node modules`); + expect(thirdPartyInPolyfills).toBe(true, `polyfills.js.map should include some node modules`); + expect(thirdPartyInRuntime).toBe(true, `runtime.js.map should include some webpack code`); + expect(thirdPartyInVendor).toBe(true, `vendor.js.map should include some node modules`); + + // All sources in the main map are first-party. + const sources = mainMap.sources.filter((_, i) => !mainMap[IGNORE_LIST].includes(i)); + sources.sort(); + + expect(sources).toEqual([ + './src/app/app.component.css', + './src/app/app.component.ts', + './src/app/app.module.ts', + './src/main.ts', + ]); + + // Only some sources in the polyfills map are first-party. + expect(polyfillsMap.sources.filter((_, i) => !polyfillsMap[IGNORE_LIST].includes(i))).toEqual([ + './src/polyfills.ts', + ]); + + // None of the sources in the runtime and vendor maps are first-party. + expect(runtimeMap.sources.filter((_, i) => !runtimeMap[IGNORE_LIST].includes(i))).toEqual([]); + expect(vendorMap.sources.filter((_, i) => !vendorMap[IGNORE_LIST].includes(i))).toEqual([]); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts new file mode 100644 index 000000000000..65991dbcc42d --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts @@ -0,0 +1,182 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { join, logging } from '@angular-devkit/core'; +import { debounceTime, lastValueFrom, map, switchMap, takeWhile, tap, timer } from 'rxjs'; +import { browserBuild, createArchitect, host, outputPath } from '../../../testing/test-utils'; + +describe('Browser Builder Web Worker support', () => { + const target = { project: 'app', target: 'build' }; + let architect: Architect; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + }); + afterEach(async () => host.restore().toPromise()); + + const workerFiles: { [k: string]: string } = { + 'src/app/dep.ts': `export const foo = 'bar';`, + 'src/app/app.worker.ts': ` + /// + + import { foo } from './dep'; + console.log('hello from worker'); + addEventListener('message', ({ data }) => { + console.log('worker got message:', data); + if (data === 'hello') { + postMessage(foo); + } + }); + `, + 'src/main.ts': ` + import { platformBrowser } from '@angular/platform-browser'; + import { AppModule } from './app/app.module'; + platformBrowser().bootstrapModule(AppModule).catch(err => console.error(err)); + + const worker = new Worker(new URL('./app/app.worker', import.meta.url), { type: 'module' }); + worker.onmessage = ({ data }) => { + console.log('page got message:', data); + }; + worker.postMessage('hello'); + `, + // Make a new tsconfig for the *.worker.ts files. + // The final place for this tsconfig must take into consideration editor tooling, unit + // tests, and integration with other build targets. + './src/tsconfig.worker.json': ` + { + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/worker", + "lib": [ + "es2018", + "webworker" + ], + "types": [] + }, + "include": [ + "**/*.worker.ts", + ] + }`, + // Alter the app tsconfig to not include *.worker.ts files. + './src/tsconfig.app.json': ` + { + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/worker", + "types": [] + }, + "files": [ + "main.ts", + "polyfills.ts" + ] + }`, + }; + + it('bundles TS worker', async () => { + host.writeMultipleFiles(workerFiles); + + const logger = new logging.Logger(''); + const logs: string[] = []; + logger.subscribe((e) => logs.push(e.message)); + + const overrides = { webWorkerTsConfig: 'src/tsconfig.worker.json' }; + await browserBuild(architect, host, target, overrides, { logger }); + + // Worker bundle contains worker code. + const workerContent = new TextDecoder().decode( + host.scopedSync().read(join(outputPath, 'src_app_app_worker_ts.js')), + ); + expect(workerContent).toContain('hello from worker'); + expect(workerContent).toContain('bar'); + + // Main bundle references worker. + const mainContent = new TextDecoder().decode( + host.scopedSync().read(join(outputPath, 'main.js')), + ); + expect(mainContent).toContain('src_app_app_worker_ts'); + expect(logs.join().includes('Warning')).toBe(false, 'Should show no warnings.'); + }); + + it('minimizes and hashes worker', async () => { + host.writeMultipleFiles(workerFiles); + const overrides = { + webWorkerTsConfig: 'src/tsconfig.worker.json', + outputHashing: 'all', + optimization: true, + }; + await browserBuild(architect, host, target, overrides); + + // Worker bundle should have hash and minified code. + const workerBundle = host.fileMatchExists( + outputPath, + /src_app_app_worker_ts\.[0-9a-f]{16}\.js/, + ) as string; + expect(workerBundle).toBeTruthy('workerBundle should exist'); + const workerContent = new TextDecoder().decode( + host.scopedSync().read(join(outputPath, workerBundle)), + ); + expect(workerContent).toContain('hello from worker'); + expect(workerContent).toContain('bar'); + expect(workerContent).toContain('"hello"===e&&postMessage'); + + // Main bundle should reference hashed worker bundle. + const mainBundle = host.fileMatchExists(outputPath, /main\.[0-9a-f]{16}\.js/) as string; + expect(mainBundle).toBeTruthy('mainBundle should exist'); + const mainContent = new TextDecoder().decode( + host.scopedSync().read(join(outputPath, mainBundle)), + ); + expect(mainContent).toContain('src_app_app_worker_ts'); + }); + + it('rebuilds TS worker', async () => { + host.writeMultipleFiles(workerFiles); + const overrides = { + webWorkerTsConfig: 'src/tsconfig.worker.json', + watch: true, + }; + + let phase = 1; + const workerPath = join(outputPath, 'src_app_app_worker_ts.js'); + let workerContent = ''; + + // The current linux-based CI environments may not fully settled in regards to filesystem + // changes from previous tests which reuse the same directory and fileset. + // The initial delay helps mitigate false positive rebuild triggers in such scenarios. + const { run } = await lastValueFrom( + timer(1000).pipe( + switchMap(() => architect.scheduleTarget(target, overrides)), + switchMap((run) => run.output.pipe(map((output) => ({ run, output })))), + debounceTime(1000), + tap(({ output }) => expect(output.success).toBe(true, 'build should succeed')), + tap(() => { + switch (phase) { + case 1: + // Original worker content should be there. + workerContent = new TextDecoder().decode(host.scopedSync().read(workerPath)); + expect(workerContent).toContain('bar'); + // Change content of worker dependency. + host.writeMultipleFiles({ 'src/app/dep.ts': `export const foo = 'baz';` }); + phase = 2; + break; + + case 2: + workerContent = new TextDecoder().decode(host.scopedSync().read(workerPath)); + // Worker content should have changed. + expect(workerContent).toContain('baz'); + phase = 3; + break; + } + }), + takeWhile(() => phase < 3), + ), + ); + await run.stop(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/works_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/works_spec.ts new file mode 100644 index 000000000000..d5315b1b6257 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/works_spec.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { describeBuilder } from '../../../testing'; +import { buildWebpackBrowser } from '../index'; + +const BROWSER_BUILDER_INFO = { + name: '@angular-devkit/build-angular:browser', + schemaPath: __dirname + '/../schema.json', +}; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('basic test', () => { + it('works', async () => { + // Provide a target and options for builder execution + harness.useTarget('build', { + outputPath: 'dist', + index: 'src/index.html', + main: 'src/main.ts', + polyfills: 'src/polyfills.ts', + tsConfig: 'src/tsconfig.app.json', + progress: false, + vendorChunk: true, + assets: ['src/favicon.ico', 'src/assets'], + styles: ['src/styles.css'], + scripts: [], + }); + + // Execute builder with above provided project, target, and options + await harness.executeOnce(); + + // Default files should be in outputPath. + expect(harness.hasFile('dist/runtime.js')).toBeTrue(); + expect(harness.hasFile('dist/main.js')).toBeTrue(); + expect(harness.hasFile('dist/polyfills.js')).toBeTrue(); + expect(harness.hasFile('dist/vendor.js')).toBeTrue(); + expect(harness.hasFile('dist/favicon.ico')).toBeTrue(); + expect(harness.hasFile('dist/styles.css')).toBeTrue(); + expect(harness.hasFile('dist/index.html')).toBeTrue(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/browser-support_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/browser-support_spec.ts new file mode 100644 index 000000000000..f24c83f2d96b --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/browser-support_spec.ts @@ -0,0 +1,139 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "Browser support"', () => { + it('creates correct sourcemaps when downleveling async functions', async () => { + // Add a JavaScript file with async code + await harness.writeFile( + 'src/async-test.js', + 'async function testJs() { console.log("from-async-js-function"); }', + ); + + // Add an async function to the project as well as JavaScript file + // The type `Void123` is used as a unique identifier for the final sourcemap + // If sourcemaps are not properly propagated then it will not be in the final sourcemap + await harness.modifyFile( + 'src/main.ts', + (content) => + 'import "./async-test";\n' + + content + + '\ntype Void123 = void;' + + `\nasync function testApp(): Promise { console.log("from-async-app-function"); }`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + vendorChunk: true, + sourceMap: { + scripts: true, + }, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toMatch(/\sasync\s/); + harness.expectFile('dist/main.js.map').content.toContain('Promise'); + }); + + it('downlevels async functions ', async () => { + // Add an async function to the project + await harness.writeFile( + 'src/main.ts', + 'async function test(): Promise { console.log("from-async-function"); }', + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + vendorChunk: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toMatch(/\sasync\s/); + harness.expectFile('dist/main.js').content.toContain('"from-async-function"'); + }); + + it('warns when IE is present in browserslist', async () => { + await harness.writeFile( + '.browserslistrc', + ` + IE 9 + IE 11 + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(logs).toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringContaining('ES5 output is not supported'), + }), + ); + + // Don't duplicate the error. + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringContaining("fall outside Angular's browser support"), + }), + ); + }); + + it("warns when targeting a browser outside Angular's minimum support", async () => { + await harness.writeFile('.browserslistrc', 'Chrome >= 100'); + + harness.useTarget('build', BASE_OPTIONS); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + expect(logs).toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringContaining("fall outside Angular's browser support"), + }), + ); + }); + + it('downlevels "for await...of"', async () => { + // Add an async function to the project + await harness.writeFile( + 'src/main.ts', + ` + (async () => { + for await (const o of [1, 2, 3]) { + console.log("for await...of"); + } + })(); + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + vendorChunk: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toMatch(/\sawait\s/); + harness.expectFile('dist/main.js').content.toContain('"for await...of"'); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/index_watch_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/index_watch_spec.ts new file mode 100644 index 000000000000..a0b0b7fadb26 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/index_watch_spec.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "index is updated during watch mode"', () => { + it('index is watched in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/index.html').content.toContain('HelloWorldApp'); + harness.expectFile('dist/index.html').content.not.toContain('UpdatedPageTitle'); + + // Trigger rebuild + await harness.modifyFile('src/index.html', (s) => + s.replace('HelloWorldApp', 'UpdatedPageTitle'), + ); + }, + ({ result }) => { + expect(result?.success).toBe(true); + + harness.expectFile('dist/index.html').content.toContain('UpdatedPageTitle'); + }, + ]); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/localize_watch_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/localize_watch_spec.ts new file mode 100644 index 000000000000..2c39bf738b3a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/localize_watch_spec.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "localize works in watch mode"', () => { + beforeEach(() => { + harness.useProject('test', { + root: '.', + sourceRoot: 'src', + cli: { + cache: { + enabled: false, + }, + }, + i18n: { + locales: { + 'fr': 'src/locales/messages.fr.xlf', + }, + }, + }); + }); + + it('localize works in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + localize: true, + }); + + await harness.writeFile( + 'src/app/app.component.html', + ` +

Hello {{ title }}!

+ `, + ); + + await harness.writeFile('src/locales/messages.fr.xlf', TRANSLATION_FILE_CONTENT); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/fr/main.js').content.toContain('Bonjour'); + + // Trigger rebuild + await harness.appendToFile('src/app/app.component.html', '\n\n'); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/fr/main.js').content.toContain('Bonjour'); + }, + ]); + }); + }); +}); + +const TRANSLATION_FILE_CONTENT = ` + + + + + + Bonjour ! + + src/app/app.component.html + 2,3 + + An introduction header for this sample + + + + +`; diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/postcss_config_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/postcss_config_spec.ts new file mode 100644 index 000000000000..0ed245f18b44 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/postcss_config_spec.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "Postcss config file"', () => { + it('applies plugins from config file if one is present', async () => { + // See: + // https://github.com/postcss/postcss-plugin-boilerplate/blob/main/template/index.t.js + await harness.writeFile( + 'node_modules/my-postcss-plugin/index.cjs', + `module.exports = (opts = {}) => { + return { + postcssPlugin: 'my-postcss-plugin', + + Root(root, postcss) { + const newRule = new postcss.Rule({ + selector: '.my-postcss-plugin::before', + }); + newRule.append({ text: 'content: "from applied plugin";' }); + root.append(newRule); + }, + }; +}; + +module.exports.postcss = true; +`, + ); + + await harness.writeFile( + 'postcss.config.json', + JSON.stringify({ + plugins: { + 'my-postcss-plugin/index.cjs': {}, + }, + }), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/styles.css').content.toMatch(/from applied plugin/); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts new file mode 100644 index 000000000000..26cbe1144d2b --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts @@ -0,0 +1,311 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "Rebuild Error"', () => { + it('detects template errors with no AOT codegen or TS emit differences', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + aot: true, + watch: true, + }); + + const goodDirectiveContents = ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir { + @Input() foo!: number; + } + `; + + const typeErrorText = `Type 'number' is not assignable to type 'string'.`; + + // Create a directive and add to application + await harness.writeFile('src/app/dir.ts', goodDirectiveContents); + await harness.writeFile( + 'src/app/app.module.ts', + ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AppComponent } from './app.component'; + import { Dir } from './dir'; + @NgModule({ + declarations: [ + AppComponent, + Dir, + ], + imports: [ + BrowserModule + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + ); + + // Create app component that uses the directive + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core' + @Component({ + selector: 'app-root', + standalone: false, + template: '
', + }) + export class AppComponent { } + `, + ); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Update directive to use a different input type for 'foo' (number -> string) + // Should cause a template error + await harness.writeFile( + 'src/app/dir.ts', + ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir { + @Input() foo: string; + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Make an unrelated change to verify error cache was updated + // Should persist error in the next rebuild + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Revert the directive change that caused the error + // Should remove the error + await harness.writeFile('src/app/dir.ts', goodDirectiveContents); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Make an unrelated change to verify error cache was updated + // Should continue showing no error + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('detects template errors with AOT codegen differences', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + aot: true, + watch: true, + }); + + const typeErrorText = `Type 'number' is not assignable to type 'string'.`; + + // Create two directives and add to application + await harness.writeFile( + 'src/app/dir.ts', + ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir { + @Input() foo!: number; + } + `, + ); + + // Same selector with a different type on the `foo` property but initially no `@Input` + const goodDirectiveContents = ` + import { Directive } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir2 { + foo!: string; + } + `; + await harness.writeFile('src/app/dir2.ts', goodDirectiveContents); + + await harness.writeFile( + 'src/app/app.module.ts', + ` + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AppComponent } from './app.component'; + import { Dir } from './dir'; + import { Dir2 } from './dir2'; + @NgModule({ + declarations: [ + AppComponent, + Dir, + Dir2, + ], + imports: [ + BrowserModule + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + `, + ); + + // Create app component that uses the directive + await harness.writeFile( + 'src/app/app.component.ts', + ` + import { Component } from '@angular/core' + @Component({ + selector: 'app-root', + standalone: false, + template: '', + }) + export class AppComponent { } + `, + ); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + + // Update second directive to use string property `foo` as an Input + // Should cause a template error + await harness.writeFile( + 'src/app/dir2.ts', + ` + import { Directive, Input } from '@angular/core'; + @Directive({ selector: 'dir', standalone: false }) + export class Dir2 { + @Input() foo!: string; + } + `, + ); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Make an unrelated change to verify error cache was updated + // Should persist error in the next rebuild + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Revert the directive change that caused the error + // Should remove the error + await harness.writeFile('src/app/dir2.ts', goodDirectiveContents); + }, + async ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + + // Make an unrelated change to verify error cache was updated + // Should continue showing no error + await harness.modifyFile('src/main.ts', (content) => content + '\n'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(typeErrorText), + }), + ); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + + it('recovers from component stylesheet error', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: true, + aot: false, + }); + + await harness.executeWithCases( + [ + async ({ result }) => { + expect(result?.success).toBeTrue(); + await harness.writeFile('src/app/app.component.css', 'invalid-css-content'); + }, + async ({ result, logs }) => { + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('invalid-css-content'), + }), + ); + + await harness.writeFile('src/app/app.component.css', 'p { color: green }'); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('invalid-css-content'), + }), + ); + + harness.expectFile('dist/main.js').content.toContain('p { color: green }'); + }, + ], + { outputLogsOnFailure: false }, + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/styles_unsupported_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/styles_unsupported_spec.ts new file mode 100644 index 000000000000..3df11cafb163 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/styles_unsupported_spec.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Behavior: "Style Unsupported"', () => { + it('errors when importing a css file as an ECMA module (Webpack specific behaviour)', async () => { + await harness.writeFiles({ + 'src/test-style.css': '.test-a {color: red}', + 'src/main.ts': `import './test-style.css'`, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('./src/test-style.css:1:0 - Error'), + }), + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/allowed-common-js-dependencies_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/allowed-common-js-dependencies_spec.ts new file mode 100644 index 000000000000..b0e89583bb63 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/allowed-common-js-dependencies_spec.ts @@ -0,0 +1,151 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "allowedCommonJsDependencies"', () => { + describe('given option is not set', () => { + for (const aot of [true, false]) { + it(`should show warning when depending on a Common JS bundle in ${ + aot ? 'AOT' : 'JIT' + } Mode`, async () => { + // Add a Common JS dependency + await harness.appendToFile('src/app/app.component.ts', `import 'ajv';`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + aot, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching( + /Warning: .+app\.component\.ts depends on 'ajv'\. CommonJS or AMD dependencies/, + ), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('require-from-string'), + }), + 'Should not warn on transitive CommonJS packages which parent is also CommonJS.', + ); + }); + } + }); + + it('should not show warning when depending on a Common JS bundle which is allowed', async () => { + // Add a Common JS dependency + await harness.appendToFile( + 'src/app/app.component.ts', + ` + import 'ajv'; + import 'zone.js'; + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: ['ajv', 'zone.js'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/CommonJS or AMD dependencies/), + }), + ); + }); + + it('should not show warning when all dependencies are allowed by wildcard', async () => { + // Add a Common JS dependency + await harness.appendToFile( + 'src/app/app.component.ts', + ` + import 'ajv'; + import 'zone.js'; + `, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: ['*'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/CommonJS or AMD dependencies/), + }), + ); + }); + + it(`should not show warning when importing non global local data '@angular/common/locale/fr'`, async () => { + await harness.appendToFile( + 'src/app/app.component.ts', + `import '@angular/common/locales/fr';`, + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/CommonJS or AMD dependencies/), + }), + ); + }); + + it('should not show warning in JIT for templateUrl and styleUrl when using paths', async () => { + await harness.modifyFile('tsconfig.json', (content) => { + const tsconfig = JSON.parse(content); + tsconfig.compilerOptions ??= {}; + tsconfig.compilerOptions.paths = { + '@app/*': ['./src/app/*'], + }; + + return JSON.stringify(tsconfig, null, 2); + }); + + await harness.modifyFile('src/app/app.module.ts', (content) => + content.replace('./app.component', '@app/app.component'), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + allowedCommonJsDependencies: [], + aot: false, + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/CommonJS or AMD dependencies/), + }), + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts new file mode 100644 index 000000000000..1840cfd4c3ad --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts @@ -0,0 +1,460 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "assets"', () => { + beforeEach(async () => { + // Application code is not needed for asset tests + await harness.writeFile('src/main.ts', ''); + }); + + it('supports an empty array value', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('supports mixing shorthand and longhand syntax', async () => { + await harness.writeFile('src/files/test.svg', ''); + await harness.writeFile('src/files/another.file', 'asset file'); + await harness.writeFile('src/extra.file', 'extra file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/extra.file', { glob: '*', input: 'src/files', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.file').content.toBe('extra file'); + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + }); + + describe('shorthand syntax', () => { + it('copies a single asset', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/test.svg'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + }); + + it('copies multiple assets', async () => { + await harness.writeFile('src/test.svg', ''); + await harness.writeFile('src/another.file', 'asset file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/test.svg', 'src/another.file'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + }); + + it('copies an asset with directory and maintains directory in output', async () => { + await harness.writeFile('src/subdirectory/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/subdirectory/test.svg'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/subdirectory/test.svg').content.toBe(''); + }); + + it('does not fail if asset does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/test.svg'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').toNotExist(); + }); + + it('fail if asset path is not within project source root', async () => { + await harness.writeFile('test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['test.svg'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.error).toMatch('path must start with the project source root'); + + harness.expectFile('dist/test.svg').toNotExist(); + }); + }); + + describe('longhand syntax', () => { + it('copies a single asset', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + }); + + it('copies multiple assets as separate entries', async () => { + await harness.writeFile('src/test.svg', ''); + await harness.writeFile('src/another.file', 'asset file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { glob: 'test.svg', input: 'src', output: '.' }, + { glob: 'another.file', input: 'src', output: '.' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + }); + + it('copies multiple assets with a single entry glob pattern', async () => { + await harness.writeFile('src/test.svg', ''); + await harness.writeFile('src/another.file', 'asset file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '{test.svg,another.file}', input: 'src', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + }); + + it('copies multiple assets with a wildcard glob pattern', async () => { + await harness.writeFile('src/files/test.svg', ''); + await harness.writeFile('src/files/another.file', 'asset file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '*', input: 'src/files', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + }); + + it('copies multiple assets with a recursive wildcard glob pattern', async () => { + await harness.writeFiles({ + 'src/files/test.svg': '', + 'src/files/another.file': 'asset file', + 'src/files/nested/extra.file': 'extra file', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '**/*', input: 'src/files', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').content.toBe('asset file'); + harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); + }); + + it('automatically ignores "." prefixed files when using wildcard glob pattern', async () => { + await harness.writeFile('src/files/.gitkeep', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '*', input: 'src/files', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/.gitkeep').toNotExist(); + }); + + it('supports ignoring a specific file when using a glob pattern', async () => { + await harness.writeFiles({ + 'src/files/test.svg': '', + 'src/files/another.file': 'asset file', + 'src/files/nested/extra.file': 'extra file', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['another.file'] }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').toNotExist(); + harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); + }); + + it('supports ignoring with a glob pattern when using a glob pattern', async () => { + await harness.writeFiles({ + 'src/files/test.svg': '', + 'src/files/another.file': 'asset file', + 'src/files/nested/extra.file': 'extra file', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['**/*.file'] }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + harness.expectFile('dist/another.file').toNotExist(); + harness.expectFile('dist/nested/extra.file').toNotExist(); + }); + + it('copies an asset with directory and maintains directory in output', async () => { + await harness.writeFile('src/subdirectory/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'subdirectory/test.svg', input: 'src', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/subdirectory/test.svg').content.toBe(''); + }); + + it('does not fail if asset does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').toNotExist(); + }); + + it('uses project output path when output option is empty string', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + }); + + it('uses project output path when output option is "."', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + }); + + it('uses project output path when output option is "/"', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '/' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').content.toBe(''); + }); + + it('creates a project output sub-path when output option path does not exist', async () => { + await harness.writeFile('src/test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: 'subdirectory' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/subdirectory/test.svg').content.toBe(''); + }); + + it('fails if asset input option is outside workspace root (relative)', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '**/*', input: '../outside', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.error).toMatch('asset path must be within the workspace root'); + }); + + it('fails if asset input option is outside workspace root (absolute)', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: '**/*', input: '/tmp/outside-workspace', output: '.' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.error).toMatch('asset path must be within the workspace root'); + }); + + it('fails if output option is not within project output path', async () => { + await harness.writeFile('test.svg', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [{ glob: 'test.svg', input: 'src', output: '..' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.error).toMatch( + 'An asset cannot be written to a location outside of the output path', + ); + + harness.expectFile('dist/test.svg').toNotExist(); + }); + }); + + describe('symlinks and monorepo external assets', () => { + let externalDir: string; + + beforeEach(async () => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR must be set'); + externalDir = await fs.mkdtemp(path.join(baseTmpDir, 'angular-cli-asset-test-')); + await fs.mkdir(path.join(externalDir, 'nested'), { recursive: true }); + await fs.writeFile(path.join(externalDir, 'shared-root.txt'), 'shared root asset'); + await fs.writeFile( + path.join(externalDir, 'nested', 'shared-nested.txt'), + 'shared nested asset', + ); + }); + + afterEach(async () => { + await fs.rm(externalDir, { recursive: true, force: true }); + }); + + it('copies assets from a symlinked directory outside workspace root with followSymlinks: true', async () => { + const symlinkPath = harness.resolvePath('src/shared-assets'); + await fs.symlink(externalDir, symlinkPath, 'junction'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: [ + { glob: '**/*', input: 'src/shared-assets', output: 'assets', followSymlinks: true }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/assets/shared-root.txt').content.toBe('shared root asset'); + harness + .expectFile('dist/assets/nested/shared-nested.txt') + .content.toBe('shared nested asset'); + }); + + it('copies a symlinked file pointing outside the workspace root', async () => { + const symlinkPath = harness.resolvePath('src/external-file.txt'); + await fs.symlink(path.join(externalDir, 'shared-root.txt'), symlinkPath, 'file'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + assets: ['src/external-file.txt'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/external-file.txt').content.toBe('shared root asset'); + }); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/bundle-budgets_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/bundle-budgets_spec.ts new file mode 100644 index 000000000000..309cdfca1b2b --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/bundle-budgets_spec.ts @@ -0,0 +1,206 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { lazyModuleFiles, lazyModuleFnImport } from '../../../../testing/test-utils'; +import { buildWebpackBrowser } from '../../index'; +import { Type } from '../../schema'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + const CSS_EXTENSIONS = ['css', 'scss', 'less']; + const BUDGET_NOT_MET_REGEXP = /Budget .+ was not met by/; + + describe('Option: "bundleBudgets"', () => { + it(`should not warn when size is below threshold`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + budgets: [{ type: Type.All, maximumWarning: '100mb' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`should error when size is above 'maximumError' threshold`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + budgets: [{ type: Type.All, maximumError: '100b' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`should warn when size is above 'maximumWarning' threshold`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + budgets: [{ type: Type.All, maximumWarning: '100b' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`should warn when lazy bundle is above 'maximumWarning' threshold`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + budgets: [{ type: Type.Bundle, name: 'lazy-lazy-module', maximumWarning: '100b' }], + }); + + await harness.writeFiles(lazyModuleFiles); + await harness.writeFiles(lazyModuleFnImport); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringMatching('lazy-lazy-module exceeded maximum budget'), + }), + ); + }); + + CSS_EXTENSIONS.forEach((ext) => { + it(`shows warnings for large component ${ext} when using 'anyComponentStyle' when AOT`, async () => { + const cssContent = ` + .foo { color: white; padding: 1px; } + .buz { color: white; padding: 2px; } + .bar { color: white; padding: 3px; } + `; + + await harness.writeFiles({ + [`src/app/app.component.${ext}`]: cssContent, + [`src/assets/foo.${ext}`]: cssContent, + [`src/styles.${ext}`]: cssContent, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('app.component.css', `app.component.${ext}`), + ); + + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: true, + aot: true, + styles: [`src/styles.${ext}`], + budgets: [{ type: Type.AnyComponentStyle, maximumWarning: '1b' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'warn', + message: jasmine.stringMatching(new RegExp(`Warning.+app.component.${ext}`)), + }), + ); + }); + }); + + describe(`should ignore '.map' files`, () => { + it(`when 'bundle' budget`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + sourceMap: true, + optimization: true, + extractLicenses: true, + budgets: [{ type: Type.Bundle, name: 'main', maximumError: '1mb' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`when 'intial' budget`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + sourceMap: true, + optimization: true, + extractLicenses: true, + budgets: [{ type: Type.Initial, name: 'main', maximumError: '1mb' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`when 'all' budget`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + sourceMap: true, + optimization: true, + extractLicenses: true, + budgets: [{ type: Type.All, maximumError: '1mb' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + + it(`when 'any' budget`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + sourceMap: true, + optimization: true, + extractLicenses: true, + budgets: [{ type: Type.Any, maximumError: '1mb' }], + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBe(true); + expect(logs).not.toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), + }), + ); + }); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/extract-licenses_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/extract-licenses_spec.ts new file mode 100644 index 000000000000..59b42eb82f06 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/extract-licenses_spec.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "extractLicenses"', () => { + it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is true`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + extractLicenses: true, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); + }); + + it(`should not generate '3rdpartylicenses.txt' when 'extractLicenses' is false`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + extractLicenses: false, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/3rdpartylicenses.txt').toNotExist(); + }); + + it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is not set`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-critical_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-critical_spec.ts new file mode 100644 index 000000000000..678a30c670c7 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-critical_spec.ts @@ -0,0 +1,163 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "inlineCritical"', () => { + beforeEach(async () => { + await harness.writeFile('src/styles.css', 'body { color: #000 }'); + }); + + it(`should extract critical css when 'inlineCritical' is true`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: { + scripts: false, + styles: { + minify: true, + inlineCritical: true, + }, + fonts: false, + }, + styles: ['src/styles.css'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness + .expectFile('dist/index.html') + .content.toContain( + ``, + ); + harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); + }); + + it(`should extract critical css when 'optimization' is unset`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + optimization: undefined, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness + .expectFile('dist/index.html') + .content.toContain( + ``, + ); + harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); + }); + + it(`should extract critical css when 'optimization' is true`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + optimization: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness + .expectFile('dist/index.html') + .content.toContain( + ``, + ); + harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); + }); + + it(`should not extract critical css when 'optimization' is false`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + optimization: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.not.toContain(` { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + optimization: { + scripts: false, + styles: { + minify: false, + inlineCritical: false, + }, + fonts: false, + }, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.not.toContain(` { + harness.useTarget('build', { + ...BASE_OPTIONS, + deployUrl: 'http://cdn.com/', + optimization: { + scripts: false, + styles: { + minify: true, + inlineCritical: true, + }, + fonts: false, + }, + styles: ['src/styles.css'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness + .expectFile('dist/index.html') + .content.toContain( + ``, + ); + harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); + }); + + it(`should extract critical css when using '@media all {}' and 'minify' is set to true`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + optimization: { + scripts: false, + styles: { + minify: true, + inlineCritical: true, + }, + fonts: false, + }, + }); + + await harness.writeFile('src/styles.css', '@media all { body { color: #000 } }'); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness + .expectFile('dist/index.html') + .content.toContain( + ``, + ); + harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-style-language_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-style-language_spec.ts new file mode 100644 index 000000000000..eede6f2f8099 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-style-language_spec.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { InlineStyleLanguage } from '../../schema'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "inlineStyleLanguage"', () => { + beforeEach(async () => { + // Setup application component with inline style property + await harness.modifyFile('src/app/app.component.ts', (content) => { + return content + .replace('styleUrls', 'styles') + .replace('./app.component.css', '__STYLE_MARKER__'); + }); + }); + + for (const aot of [true, false]) { + describe(`[${aot ? 'AOT' : 'JIT'}]`, () => { + it('supports SCSS inline component styles when set to "scss"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + inlineStyleLanguage: InlineStyleLanguage.Scss, + aot, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('__STYLE_MARKER__', '$primary: indianred;\\nh1 { color: $primary; }'), + ); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.toContain('color: indianred'); + }); + + it('supports Sass inline component styles when set to "sass"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + inlineStyleLanguage: InlineStyleLanguage.Sass, + aot, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('__STYLE_MARKER__', '$primary: indianred\\nh1\\n\\tcolor: $primary'), + ); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.toContain('color: indianred'); + }); + + it('supports Less inline component styles when set to "less"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + inlineStyleLanguage: InlineStyleLanguage.Less, + aot, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('__STYLE_MARKER__', '@primary: indianred;\\nh1 { color: @primary; }'), + ); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.toContain('color: indianred'); + }); + + it('updates produced stylesheet in watch mode', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + main: 'src/main.ts', + inlineStyleLanguage: InlineStyleLanguage.Scss, + aot, + watch: true, + }); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace('__STYLE_MARKER__', '$primary: indianred;\\nh1 { color: $primary; }'), + ); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.toContain('color: indianred'); + harness.expectFile('dist/main.js').content.not.toContain('color: aqua'); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace( + '$primary: indianred;\\nh1 { color: $primary; }', + '$primary: aqua;\\nh1 { color: $primary; }', + ), + ); + }, + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toContain('color: indianred'); + harness.expectFile('dist/main.js').content.toContain('color: aqua'); + + await harness.modifyFile('src/app/app.component.ts', (content) => + content.replace( + '$primary: aqua;\\nh1 { color: $primary; }', + '$primary: blue;\\nh1 { color: $primary; }', + ), + ); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toContain('color: indianred'); + harness.expectFile('dist/main.js').content.not.toContain('color: aqua'); + harness.expectFile('dist/main.js').content.toContain('color: blue'); + }, + ]); + }); + }); + } + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/main_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/main_spec.ts new file mode 100644 index 000000000000..4c4839d933d0 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/main_spec.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "main"', () => { + it('uses a provided TypeScript file', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + main: 'src/main.ts', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/runtime.js').toExist(); + harness.expectFile('dist/main.js').toExist(); + harness.expectFile('dist/index.html').toExist(); + }); + + it('uses a provided JavaScript file', async () => { + await harness.writeFile('src/main.js', `console.log('main');`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + main: 'src/main.js', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/runtime.js').toExist(); + harness.expectFile('dist/main.js').toExist(); + harness.expectFile('dist/index.html').toExist(); + + harness.expectFile('dist/main.js').content.toContain(`console.log('main')`); + }); + + it('fails and shows an error when file does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + main: 'src/missing.ts', + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching('Module not found:') }), + ); + + harness.expectFile('dist/runtime.js').toNotExist(); + harness.expectFile('dist/main.js').toNotExist(); + harness.expectFile('dist/index.html').toNotExist(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/named-chunks_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/named-chunks_spec.ts new file mode 100644 index 000000000000..07d1ff5df2ab --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/named-chunks_spec.ts @@ -0,0 +1,69 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +const MAIN_OUTPUT = 'dist/main.js'; +const NAMED_LAZY_OUTPUT = 'dist/src_lazy-module_ts.js'; +const UNNAMED_LAZY_OUTPUT = 'dist/321.js'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "namedChunks"', () => { + beforeEach(async () => { + // Setup a lazy loaded chunk + await harness.writeFiles({ + 'src/lazy-module.ts': 'export const value = 42;', + 'src/main.ts': `import('./lazy-module');`, + }); + }); + + it('generates named files in output when true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + namedChunks: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile(MAIN_OUTPUT).toExist(); + harness.expectFile(NAMED_LAZY_OUTPUT).toExist(); + harness.expectFile(UNNAMED_LAZY_OUTPUT).toNotExist(); + }); + + it('does not generate named files in output when false', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + namedChunks: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile(MAIN_OUTPUT).toExist(); + harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); + harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); + }); + + it('does not generate named files in output when not present', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile(MAIN_OUTPUT).toExist(); + harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); + harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/output-hashing_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/output-hashing_spec.ts new file mode 100644 index 000000000000..26589c223498 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/output-hashing_spec.ts @@ -0,0 +1,169 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { OutputHashing } from '../../schema'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "outputHashing"', () => { + beforeEach(async () => { + // Application code is not needed for asset tests + await harness.writeFile('src/main.ts', ''); + await harness.writeFile('src/polyfills.ts', ''); + }); + + it('hashes all filenames when set to "all"', async () => { + await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + polyfills: 'src/polyfills.ts', + outputHashing: OutputHashing.All, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeTrue(); + }); + + it(`doesn't hash any filenames when not set`, async () => { + await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: 'src/polyfills.ts', + styles: ['src/styles.css'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); + }); + + it(`doesn't hash any filenames when set to "none"`, async () => { + await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + polyfills: 'src/polyfills.ts', + outputHashing: OutputHashing.None, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); + }); + + it(`hashes CSS resources filenames only when set to "media"`, async () => { + await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + polyfills: 'src/polyfills.ts', + outputHashing: OutputHashing.Media, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeTrue(); + }); + + it(`hashes bundles filenames only when set to "bundles"`, async () => { + await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + polyfills: 'src/polyfills.ts', + outputHashing: OutputHashing.Bundles, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeTrue(); + expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); + }); + + it('does not hash non injected styles', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + outputHashing: OutputHashing.All, + sourceMap: true, + styles: [ + { + input: 'src/styles.css', + inject: false, + }, + ], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.js$/)).toBeFalse(); + expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.js.map$/)).toBeFalse(); + harness.expectFile('dist/styles.css').toExist(); + harness.expectFile('dist/styles.css.map').toExist(); + }); + + it('does not override different files which has the same filenames when hashing is "none"', async () => { + await harness.writeFiles({ + 'src/styles.css': ` + h1 { background: url('./test.svg')} + h2 { background: url('./small/test.svg')} + `, + './src/test.svg': ` + Hello World + `, + './src/small/test.svg': ` + Hello World + `, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/styles.css'], + outputHashing: OutputHashing.None, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + + harness.expectFile('dist/test.svg').toExist(); + harness.expectFile('dist/small-test.svg').toExist(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/polyfills_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/polyfills_spec.ts new file mode 100644 index 000000000000..422cebb9ad0e --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/polyfills_spec.ts @@ -0,0 +1,69 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "polyfills"', () => { + it('uses a provided TypeScript file', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: 'src/polyfills.ts', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/polyfills.js').toExist(); + }); + + it('uses a provided JavaScript file', async () => { + await harness.writeFile('src/polyfills.js', `console.log('main');`); + + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: 'src/polyfills.js', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/polyfills.js').content.toContain(`console.log('main')`); + }); + + it('fails and shows an error when file does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: 'src/missing.ts', + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching('Module not found:') }), + ); + + harness.expectFile('dist/polyfills.js').toNotExist(); + }); + + it('resolves module specifiers in array', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + polyfills: ['zone.js', 'zone.js/testing'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('dist/polyfills.js').toExist(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts new file mode 100644 index 000000000000..f855f206a079 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts @@ -0,0 +1,438 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "scripts"', () => { + beforeEach(async () => { + // Application code is not needed for scripts tests + await harness.writeFile('src/main.ts', ''); + }); + + it('supports an empty array value', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + }); + + it('processes an empty script when optimizing', async () => { + await harness.writeFile('src/test-script-a.js', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + optimization: { + scripts: true, + }, + scripts: ['src/test-script-a.js'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').toExist(); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + describe('shorthand syntax', () => { + it('processes a single script into a single output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: ['src/test-script-a.js'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple scripts into a single output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + await harness.writeFile('src/test-script-b.js', 'console.log("b");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: ['src/test-script-a.js', 'src/test-script-b.js'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); + harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('preserves order of multiple scripts in single output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + await harness.writeFile('src/test-script-b.js', 'console.log("b");'); + await harness.writeFile('src/test-script-c.js', 'console.log("c");'); + await harness.writeFile('src/test-script-d.js', 'console.log("d");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [ + 'src/test-script-c.js', + 'src/test-script-d.js', + 'src/test-script-b.js', + 'src/test-script-a.js', + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/scripts.js') + .content.toMatch( + /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, + ); + }); + + it('fails and shows an error if script does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: ['src/test-script-a.js'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(`Can't resolve 'src/test-script-a.js'`), + }), + ); + + harness.expectFile('dist/scripts.js').toNotExist(); + }); + + it('shows the output script as a chunk entry in the logging output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: ['src/test-script-a.js'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), + ); + }); + }); + + describe('longhand syntax', () => { + it('processes a single script into a single output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes a single script into a single output named with bundleName', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('uses default bundleName when bundleName is empty string', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js', bundleName: '' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple scripts with no bundleName into a single output', async () => { + await harness.writeFiles({ + 'src/test-script-a.js': 'console.log("a");', + 'src/test-script-b.js': 'console.log("b");', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js' }, { input: 'src/test-script-b.js' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); + harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple scripts with same bundleName into a single output', async () => { + await harness.writeFiles({ + 'src/test-script-a.js': 'console.log("a");', + 'src/test-script-b.js': 'console.log("b");', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [ + { input: 'src/test-script-a.js', bundleName: 'extra' }, + { input: 'src/test-script-b.js', bundleName: 'extra' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); + harness.expectFile('dist/extra.js').content.toContain('console.log("b")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple scripts with different bundleNames into separate outputs', async () => { + await harness.writeFiles({ + 'src/test-script-a.js': 'console.log("a");', + 'src/test-script-b.js': 'console.log("b");', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [ + { input: 'src/test-script-a.js', bundleName: 'extra' }, + { input: 'src/test-script-b.js', bundleName: 'other' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); + harness.expectFile('dist/other.js').content.toContain('console.log("b")'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('preserves order of multiple scripts in single output', async () => { + await harness.writeFiles({ + 'src/test-script-a.js': 'console.log("a");', + 'src/test-script-b.js': 'console.log("b");', + 'src/test-script-c.js': 'console.log("c");', + 'src/test-script-d.js': 'console.log("d");', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [ + { input: 'src/test-script-c.js' }, + { input: 'src/test-script-d.js' }, + { input: 'src/test-script-b.js' }, + { input: 'src/test-script-a.js' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/scripts.js') + .content.toMatch( + /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, + ); + }); + + it('preserves order of multiple scripts with different bundleNames', async () => { + await harness.writeFiles({ + 'src/test-script-a.js': 'console.log("a");', + 'src/test-script-b.js': 'console.log("b");', + 'src/test-script-c.js': 'console.log("c");', + 'src/test-script-d.js': 'console.log("d");', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [ + { input: 'src/test-script-c.js', bundleName: 'other' }, + { input: 'src/test-script-d.js', bundleName: 'extra' }, + { input: 'src/test-script-b.js', bundleName: 'extra' }, + { input: 'src/test-script-a.js', bundleName: 'other' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/other.js') + .content.toMatch(/console\.log\("c"\)[;\s]+console\.log\("a"\)/); + harness + .expectFile('dist/extra.js') + .content.toMatch(/console\.log\("d"\)[;\s]+console\.log\("b"\)/); + harness + .expectFile('dist/index.html') + .content.toMatch( + /'); + }); + + it('does not add script element to index when inject is false', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js', inject: false }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + // `inject: false` causes the bundleName to be the input file name + harness.expectFile('dist/test-script-a.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.not.toContain(''); + }); + + it('does not add script element to index with bundleName when inject is false', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra', inject: false }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); + harness + .expectFile('dist/index.html') + .content.not.toContain(''); + }); + + it('shows the output script as a chunk entry in the logging output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js' }], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), + ); + }); + + it('shows the output script as a chunk entry with bundleName in the logging output', async () => { + await harness.writeFile('src/test-script-a.js', 'console.log("a");'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.js.+\d+ bytes/) }), + ); + }); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/stats-json_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/stats-json_spec.ts new file mode 100644 index 000000000000..609e21fcef5a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/stats-json_spec.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "statsJson"', () => { + beforeEach(async () => { + // Application code is not needed for stat JSON tests + await harness.writeFile('src/main.ts', ''); + }); + + it('generates a Webpack Stats file in output when true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + statsJson: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + if (harness.expectFile('dist/stats.json').toExist()) { + const content = harness.readFile('dist/stats.json'); + expect(() => JSON.parse(content)) + .withContext('Expected Webpack Stats file to be valid JSON.') + .not.toThrow(); + } + }); + + // TODO: Investigate why this profiling object is no longer present in Webpack 5.90.3+ and if this should even be tested + xit('includes Webpack profiling information', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + statsJson: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + if (harness.expectFile('dist/stats.json').toExist()) { + const stats = JSON.parse(harness.readFile('dist/stats.json')); + expect(stats?.chunks?.[0]?.modules?.[0]?.profile?.building).toBeDefined(); + } + }); + + it('does not generate a Webpack Stats file in output when false', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + statsJson: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/stats.json').toNotExist(); + }); + + it('does not generate a Webpack Stats file in output when not present', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/stats.json').toNotExist(); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts new file mode 100644 index 000000000000..343f024f403a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts @@ -0,0 +1,435 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "styles"', () => { + beforeEach(async () => { + // Application code is not needed for styles tests + await harness.writeFile('src/main.ts', ''); + }); + + it('supports an empty array value', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').toNotExist(); + }); + + it('does not create an output styles file when option is not present', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').toNotExist(); + }); + + describe('shorthand syntax', () => { + it('processes a single style into a single output', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/test-style-a.css'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple styles into a single output', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/test-style-a.css', 'src/test-style-b.css'], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness.expectFile('dist/styles.css').content.toContain('.test-b {color: green}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('preserves order of multiple styles in single output', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + 'src/test-style-c.css': '.test-c {color: blue}', + 'src/test-style-d.css': '.test-d {color: yellow}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [ + 'src/test-style-c.css', + 'src/test-style-d.css', + 'src/test-style-b.css', + 'src/test-style-a.css', + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/styles.css') + .content.toMatch( + /\.test-c {color: blue}[\s|\S]+\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}[\s|\S]+\.test-a {color: red}/m, + ); + }); + + it('fails and shows an error if style does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/test-style-a.css'], + }); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + level: 'error', + message: jasmine.stringMatching(`Can't resolve 'src/test-style-a.css'`), + }), + ); + + harness.expectFile('dist/styles.css').toNotExist(); + }); + + it('shows the output style as a chunk entry in the logging output', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: ['src/test-style-a.css'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ kB/) }), + ); + }); + }); + + describe('longhand syntax', () => { + it('processes a single style into a single output', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes a single style into a single output named with bundleName', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('uses default bundleName when bundleName is empty string', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', bundleName: '' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple styles with no bundleName into a single output', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css' }, { input: 'src/test-style-b.css' }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness.expectFile('dist/styles.css').content.toContain('.test-b {color: green}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple styles with same bundleName into a single output', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [ + { input: 'src/test-style-a.css', bundleName: 'extra' }, + { input: 'src/test-style-b.css', bundleName: 'extra' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); + harness.expectFile('dist/extra.css').content.toContain('.test-b {color: green}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('processes multiple styles with different bundleNames into separate outputs', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [ + { input: 'src/test-style-a.css', bundleName: 'extra' }, + { input: 'src/test-style-b.css', bundleName: 'other' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); + harness.expectFile('dist/other.css').content.toContain('.test-b {color: green}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('preserves order of multiple styles in single output', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + 'src/test-style-c.css': '.test-c {color: blue}', + 'src/test-style-d.css': '.test-d {color: yellow}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [ + { input: 'src/test-style-c.css' }, + { input: 'src/test-style-d.css' }, + { input: 'src/test-style-b.css' }, + { input: 'src/test-style-a.css' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/styles.css') + .content.toMatch( + /\.test-c {color: blue}[\s|\S]+\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}[\s|\S]+\.test-a {color: red}/, + ); + }); + + it('preserves order of multiple styles with different bundleNames', async () => { + await harness.writeFiles({ + 'src/test-style-a.css': '.test-a {color: red}', + 'src/test-style-b.css': '.test-b {color: green}', + 'src/test-style-c.css': '.test-c {color: blue}', + 'src/test-style-d.css': '.test-d {color: yellow}', + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [ + { input: 'src/test-style-c.css', bundleName: 'other' }, + { input: 'src/test-style-d.css', bundleName: 'extra' }, + { input: 'src/test-style-b.css', bundleName: 'extra' }, + { input: 'src/test-style-a.css', bundleName: 'other' }, + ], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness + .expectFile('dist/other.css') + .content.toMatch(/\.test-c {color: blue}[\s|\S]+\.test-a {color: red}/); + harness + .expectFile('dist/extra.css') + .content.toMatch(/\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}/); + harness + .expectFile('dist/index.html') + .content.toMatch( + /\s*/, + ); + }); + + it('adds link element to index when inject is true', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', inject: true }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.toContain(''); + }); + + it('does not add link element to index when inject is false', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', inject: false }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + // `inject: false` causes the bundleName to be the input file name + harness.expectFile('dist/test-style-a.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.not.toContain(''); + }); + + it('does not add link element to index with bundleName when inject is false', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', bundleName: 'extra', inject: false }], + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); + harness + .expectFile('dist/index.html') + .content.not.toContain(''); + }); + + it('shows the output style as a chunk entry in the logging output', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css' }], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ kB/) }), + ); + }); + + it('shows the output style as a chunk entry with bundleName in the logging output', async () => { + await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); + + harness.useTarget('build', { + ...BASE_OPTIONS, + styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.css.+\d+ kB/) }), + ); + }); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/subresource-integrity_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/subresource-integrity_spec.ts new file mode 100644 index 000000000000..1fcf6b34a826 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/subresource-integrity_spec.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "subresourceIntegrity"', () => { + it(`does not add integrity attribute when not present`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.not.toContain('integrity='); + }); + + it(`does not add integrity attribute when 'false'`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + subresourceIntegrity: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.not.toContain('integrity='); + }); + + it(`does add integrity attribute when 'true'`, async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + subresourceIntegrity: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.toMatch(/integrity="\w+-[A-Za-z0-9/+=]+"/); + }); + + it(`does not issue a warning when 'true' and 'scripts' is set.`, async () => { + await harness.writeFile('src/script.js', ''); + + harness.useTarget('build', { + ...BASE_OPTIONS, + subresourceIntegrity: true, + scripts: ['src/script.js'], + }); + + const { result, logs } = await harness.executeOnce(); + + expect(result?.success).toBe(true); + harness.expectFile('dist/index.html').content.toMatch(/integrity="\w+-[A-Za-z0-9/+=]+"/); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/subresource-integrity/), + }), + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/tsconfig_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/tsconfig_spec.ts new file mode 100644 index 000000000000..ebef4da04110 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/tsconfig_spec.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "tsConfig"', () => { + it('throws an exception when TypeScript Configuration file does not exist', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + tsConfig: 'src/missing.json', + }); + + const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); + + expect(result).toBeUndefined(); + expect(error).toEqual( + jasmine.objectContaining({ + message: jasmine.stringMatching('no such file or directory'), + }), + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/verbose_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/verbose_spec.ts new file mode 100644 index 000000000000..c74af39557ed --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/verbose_spec.ts @@ -0,0 +1,148 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { logging } from '@angular-devkit/core'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +// The below plugin is only enabled when verbose option is set to true. +const VERBOSE_LOG_TEXT = 'LOG from webpack.'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "verbose"', () => { + beforeEach(async () => { + // Application code is not needed for verbose output + await harness.writeFile('src/main.ts', ''); + }); + + it('should include verbose logs when true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: true, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(VERBOSE_LOG_TEXT), + }), + ); + }); + + it('should not include verbose logs when undefined', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: undefined, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(VERBOSE_LOG_TEXT), + }), + ); + }); + + it('should not include verbose logs when false', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: false, + }); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(VERBOSE_LOG_TEXT), + }), + ); + }); + + it('should list modified files when verbose is set to true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: true, + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBeTrue(); + // Amend file + await harness.appendToFile('/src/main.ts', ' '); + }, + ({ result, logs }) => { + expect(result?.success).toBeTrue(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching( + /angular\.watch-files-logs-plugin\n\s+Modified files:\n.+main\.ts/, + ), + }), + ); + }, + ]); + }); + + it('should not include error stacktraces when false', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: false, + styles: ['./src/styles.scss'], + }); + + // Create a compilatation error. + await harness.writeFile('./src/styles.scss', `@import 'invalid-module';`); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(`Can't find stylesheet to import`), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('styles.scss.webpack'), + }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('at Object.loader'), + }), + ); + }); + + it('should include error stacktraces when true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + verbose: true, + styles: ['./src/styles.scss'], + }); + + // Create a compilatation error. + await harness.writeFile('./src/styles.scss', `@import 'invalid-module';`); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('styles.scss.webpack'), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('at Object.loader'), + }), + ); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/options/watch_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/watch_spec.ts new file mode 100644 index 000000000000..d61290aa0b7c --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/options/watch_spec.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { timeout } from 'rxjs'; +import { buildWebpackBrowser } from '../../index'; +import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; + +describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { + describe('Option: "watch"', () => { + beforeEach(async () => { + // Application code is not needed for these tests + await harness.writeFile('src/main.ts', ''); + }); + + it('does not wait for file changes when false', (done) => { + harness.useTarget('build', { + ...BASE_OPTIONS, + watch: false, + }); + + // If the build waits then it will timeout with the custom timeout. + // A single build should not take more than 15 seconds. + let count = 0; + harness + .execute() + .pipe(timeout(15000)) + .subscribe({ + complete() { + expect(count).toBe(1); + done(); + }, + next({ result }) { + count++; + expect(result?.success).toBe(true); + }, + error(error) { + done.fail(error); + }, + }); + }); + + it('does not wait for file changes when not present', (done) => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + // If the build waits then it will timeout with the custom timeout. + // A single build should not take more than 15 seconds. + let count = 0; + harness + .execute() + .pipe(timeout(15000)) + .subscribe({ + complete() { + expect(count).toBe(1); + done(); + }, + next({ result }) { + count++; + expect(result?.success).toBe(true); + }, + error(error) { + done.fail(error); + }, + }); + }); + + it('watches for file changes when true', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + main: 'src/main.ts', + watch: true, + }); + + await harness.executeWithCases([ + async ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.not.toContain('abcd1234'); + + await harness.modifyFile( + 'src/main.ts', + (content) => content + 'console.log("abcd1234");', + ); + }, + ({ result }) => { + expect(result?.success).toBe(true); + harness.expectFile('dist/main.js').content.toContain('abcd1234'); + }, + ]); + }); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/browser/tests/setup.ts b/packages/angular_devkit/build_angular/src/builders/browser/tests/setup.ts new file mode 100644 index 000000000000..b14bba897987 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/browser/tests/setup.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Schema } from '../schema'; + +export { describeBuilder } from '../../../testing'; + +export const BROWSER_BUILDER_INFO = Object.freeze({ + name: '@angular-devkit/build-angular:browser', + schemaPath: __dirname + '/../schema.json', +}); + +/** + * Contains all required browser builder fields. + * Also disables progress reporting to minimize logging output. + */ +export const BASE_OPTIONS = Object.freeze({ + index: 'src/index.html', + main: 'src/main.ts', + outputPath: 'dist', + tsConfig: 'src/tsconfig.app.json', + progress: false, + + // Disable optimizations + optimization: false, + buildOptimizer: false, +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/builder.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/builder.ts new file mode 100644 index 000000000000..1e03eef28ef0 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/builder.ts @@ -0,0 +1,228 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { DevServerBuilderOutput } from '@angular/build'; +import { type IndexHtmlTransform, checkPort, purgeStaleBuildCache } from '@angular/build/private'; +import type { BuilderContext } from '@angular-devkit/architect'; +import type { Plugin } from 'esbuild'; +import type http from 'node:http'; +import { EMPTY, Observable, defer, switchMap } from 'rxjs'; +import type { ExecutionTransformer } from '../../transforms'; +import { isEsbuildBased, normalizeOptions } from './options'; +import type { Schema as DevServerBuilderOptions } from './schema'; + +/** + * A Builder that executes a development server based on the provided browser target option. + * + * Usage of the `transforms` and/or `extensions` parameters is NOT supported and may cause + * unexpected build output or build failures. + * + * @param options Dev Server options. + * @param context The build context. + * @param transforms A map of transforms that can be used to hook into some logic (such as + * transforming webpack configuration before passing it to webpack). + * @param extensions An optional object containing an array of build plugins (esbuild-based) + * and/or HTTP request middleware. + * + * @experimental Direct usage of this function is considered experimental. + */ +export function execute( + options: DevServerBuilderOptions, + context: BuilderContext, + transforms: { + webpackConfiguration?: ExecutionTransformer; + logging?: import('@angular-devkit/build-webpack').WebpackLoggingCallback; + indexHtml?: IndexHtmlTransform; + } = {}, + extensions?: { + buildPlugins?: Plugin[]; + middleware?: (( + req: http.IncomingMessage, + res: http.ServerResponse, + next: (err?: unknown) => void, + ) => void)[]; + builderSelector?: (info: BuilderSelectorInfo, logger: BuilderContext['logger']) => string; + }, +): Observable { + // Determine project name from builder context target + const projectName = context.target?.project; + if (!projectName) { + context.logger.error(`The "dev-server" builder requires a target to be specified.`); + + return EMPTY; + } + + context.logger.warn( + 'The "@angular-devkit/build-angular:dev-server" builder is deprecated as part of Angular\'s Webpack support deprecation. ' + + 'Use "@angular/build:dev-server" instead. For more information, see https://angular.dev/tools/cli/build-system-migration.', + ); + + return defer(() => initialize(options, projectName, context, extensions?.builderSelector)).pipe( + switchMap(({ builderName, normalizedOptions }) => { + // Use vite-based development server for esbuild-based builds + if (isEsbuildBased(builderName)) { + if (transforms?.logging || transforms?.webpackConfiguration) { + throw new Error( + `The "application" and "browser-esbuild" builders do not support Webpack transforms.`, + ); + } + + if (options.publicHost) { + context.logger.warn( + `The "publicHost" option will not be used because it is not supported by the "${builderName}" builder.`, + ); + } + + if (options.disableHostCheck) { + context.logger.warn( + `The "disableHostCheck" option will not be used because it is not supported by the "${builderName}" builder.`, + ); + } + + // New build system defaults hmr option to the value of liveReload + normalizedOptions.hmr ??= normalizedOptions.liveReload; + + // New build system uses Vite's allowedHost option convention of true for disabling host checks + if (normalizedOptions.disableHostCheck) { + (normalizedOptions as unknown as { allowedHosts: true }).allowedHosts = true; + } else { + normalizedOptions.allowedHosts ??= []; + } + + return defer(() => + Promise.all([import('@angular/build/private'), import('../browser-esbuild')]), + ).pipe( + switchMap(([{ serveWithVite, buildApplicationInternal }, { convertBrowserOptions }]) => + serveWithVite( + normalizedOptions as typeof normalizedOptions & { + hmr: boolean; + allowedHosts: true | string[]; + define: { [key: string]: string } | undefined; + }, + builderName, + (options, context, codePlugins) => { + return builderName === '@angular-devkit/build-angular:browser-esbuild' + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + buildApplicationInternal(convertBrowserOptions(options as any), context, { + codePlugins, + }) + : buildApplicationInternal(options, context, { codePlugins }); + }, + context, + transforms, + extensions, + ), + ), + ); + } + + // Warn if the initial options provided by the user enable prebundling with Webpack-based builders + if (options.prebundle) { + context.logger.warn( + `Prebundling has been configured but will not be used because it is not supported by the "${builderName}" builder.`, + ); + } + + if (extensions?.buildPlugins?.length) { + throw new Error('Only the "application" and "browser-esbuild" builders support plugins.'); + } + if (extensions?.middleware?.length) { + throw new Error( + 'Only the "application" and "browser-esbuild" builders support middleware.', + ); + } + + // Webpack based build systems default to false for hmr option + normalizedOptions.hmr ??= false; + + // Use Webpack for all other browser targets + return defer(() => import('./webpack-server')).pipe( + switchMap(({ serveWebpackBrowser }) => + serveWebpackBrowser(normalizedOptions, builderName, context, transforms), + ), + ); + }), + ); +} + +async function initialize( + initialOptions: DevServerBuilderOptions, + projectName: string, + context: BuilderContext, + builderSelector = defaultBuilderSelector, +) { + // Purge old build disk cache. + await purgeStaleBuildCache(context); + + const normalizedOptions = await normalizeOptions(context, projectName, initialOptions); + const builderName = builderSelector( + { + builderName: await context.getBuilderNameForTarget(normalizedOptions.buildTarget), + forceEsbuild: !!normalizedOptions.forceEsbuild, + }, + context.logger, + ); + + if ( + !normalizedOptions.disableHostCheck && + !/^127\.\d+\.\d+\.\d+/g.test(normalizedOptions.host) && + normalizedOptions.host !== 'localhost' + ) { + context.logger.warn(` +Warning: This is a simple server for use in testing or debugging Angular applications +locally. It hasn't been reviewed for security issues. + +Binding this server to an open connection can result in compromising your application or +computer. Using a different host than the one passed to the "--host" flag might result in +websocket connection issues. You might need to use "--disable-host-check" if that's the +case. + `); + } + + if (normalizedOptions.disableHostCheck) { + context.logger.warn( + 'Warning: Running a server with --disable-host-check is a security risk. ' + + 'See https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a for more information.', + ); + } + + normalizedOptions.port = await checkPort(normalizedOptions.port, normalizedOptions.host); + + return { + builderName, + normalizedOptions, + }; +} + +interface BuilderSelectorInfo { + builderName: string; + forceEsbuild: boolean; +} + +function defaultBuilderSelector( + info: BuilderSelectorInfo, + logger: BuilderContext['logger'], +): string { + if (isEsbuildBased(info.builderName)) { + return info.builderName; + } + + if (info.forceEsbuild) { + if (!info.builderName.startsWith('@angular-devkit/build-angular:')) { + logger.warn( + 'Warning: Forcing the use of the esbuild-based build system with third-party builders' + + ' may cause unexpected behavior and/or build failures.', + ); + } + + // The compatibility builder should be used if esbuild is force enabled. + return '@angular-devkit/build-angular:browser-esbuild'; + } + + return info.builderName; +} diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/index.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/index.ts new file mode 100644 index 000000000000..cd61c8e6c31a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/index.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { DevServerBuilderOutput } from '@angular/build'; +import { createBuilder } from '@angular-devkit/architect'; +import { execute } from './builder'; +import { Schema as DevServerBuilderOptions } from './schema'; + +export { + type DevServerBuilderOptions, + type DevServerBuilderOutput, + execute as executeDevServerBuilder, +}; +export default createBuilder(execute); + +// Temporary export to support specs +export { execute as executeDevServer }; diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/options.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/options.ts new file mode 100644 index 000000000000..80cd22dff4e2 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/options.ts @@ -0,0 +1,154 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { BuilderContext, targetFromTargetString } from '@angular-devkit/architect'; +import path from 'node:path'; +import { normalizeCacheOptions } from '../../utils/normalize-cache'; +import { normalizeOptimization } from '../../utils/normalize-optimization'; +import { Schema as DevServerOptions } from './schema'; + +export type NormalizedDevServerOptions = Awaited>; + +export function isEsbuildBased( + builderName: string, +): builderName is + | '@angular/build:application' + | '@angular-devkit/build-angular:application' + | '@angular-devkit/build-angular:browser-esbuild' { + if ( + builderName === '@angular/build:application' || + builderName === '@angular-devkit/build-angular:application' || + builderName === '@angular-devkit/build-angular:browser-esbuild' + ) { + return true; + } + + return false; +} + +/** + * Normalize the user provided options by creating full paths for all path based options + * and converting multi-form options into a single form that can be directly used + * by the build process. + * + * @param context The context for current builder execution. + * @param projectName The name of the project for the current execution. + * @param options An object containing the options to use for the build. + * @returns An object containing normalized options required to perform the build. + */ +export async function normalizeOptions( + context: BuilderContext, + projectName: string, + options: DevServerOptions, +) { + const { workspaceRoot, logger } = context; + const projectMetadata = await context.getProjectMetadata(projectName); + const projectRoot = path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? ''); + + const cacheOptions = normalizeCacheOptions(projectMetadata, workspaceRoot); + + // Target specifier defaults to the current project's build target using a development configuration + const buildTargetSpecifier = options.buildTarget ?? `::development`; + const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build'); + + // Get the application builder options. + const browserBuilderName = await context.getBuilderNameForTarget(buildTarget); + const rawBuildOptions = await context.getTargetOptions(buildTarget); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const buildOptions = (await context.validateOptions(rawBuildOptions, browserBuilderName)) as any; + const optimization = normalizeOptimization(buildOptions.optimization); + + if (options.prebundle !== false && isEsbuildBased(browserBuilderName)) { + if (!cacheOptions.enabled) { + // Warn if the initial options provided by the user enable prebundling but caching is disabled + logger.warn( + 'Prebundling has been configured but will not be used because caching has been disabled.', + ); + } else if (optimization.scripts) { + // Warn if the initial options provided by the user enable prebundling but script optimization is enabled. + logger.warn( + 'Prebundling has been configured but will not be used because scripts optimization is enabled.', + ); + } + } + + let inspect: false | { host?: string; port?: number } = false; + const inspectRaw = options.inspect; + if (inspectRaw === true || inspectRaw === '' || inspectRaw === 'true') { + inspect = { + host: undefined, + port: undefined, + }; + } else if (typeof inspectRaw === 'string' && inspectRaw !== 'false') { + const port = +inspectRaw; + if (isFinite(port)) { + inspect = { + host: undefined, + port, + }; + } else { + const [host, port] = inspectRaw.split(':'); + inspect = { + host, + port: isNaN(+port) ? undefined : +port, + }; + } + } + + // Initial options to keep + const { + host, + port, + poll, + open, + verbose, + watch, + allowedHosts, + disableHostCheck, + liveReload, + hmr, + headers, + proxyConfig, + servePath, + publicHost, + ssl, + sslCert, + sslKey, + forceEsbuild, + prebundle, + } = options; + + // Return all the normalized options + return { + buildTarget, + host: host ?? 'localhost', + port: port ?? 4200, + poll, + open, + verbose, + watch, + liveReload: !!liveReload, + hmr, + headers, + workspaceRoot, + projectRoot, + cacheOptions, + allowedHosts, + disableHostCheck, + proxyConfig, + servePath, + publicHost, + ssl, + sslCert: sslCert && path.resolve(workspaceRoot, sslCert), + sslKey: sslKey && path.resolve(workspaceRoot, sslKey), + forceEsbuild, + // Prebundling defaults to true but requires caching to function + prebundle: cacheOptions.enabled && !optimization.scripts && (prebundle ?? true), + inspect, + }; +} diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json b/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json new file mode 100644 index 000000000000..495f244b1722 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json @@ -0,0 +1,135 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "Dev Server Target", + "description": "Dev Server target options for Build Facade.", + "type": "object", + "properties": { + "buildTarget": { + "type": "string", + "description": "A build builder target to serve in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", + "pattern": "^[^:\\s]*:[^:\\s]*(:[^\\s]+)?$" + }, + "port": { + "type": "number", + "description": "Port to listen on.", + "default": 4200 + }, + "host": { + "type": "string", + "description": "Host to listen on.", + "default": "localhost" + }, + "proxyConfig": { + "type": "string", + "description": "Proxy configuration file. For more information, see https://angular.dev/tools/cli/serve#proxying-to-a-backend-server." + }, + "ssl": { + "type": "boolean", + "description": "Serve using HTTPS.", + "default": false + }, + "sslKey": { + "type": "string", + "description": "SSL key to use for serving HTTPS." + }, + "sslCert": { + "type": "string", + "description": "SSL certificate to use for serving HTTPS." + }, + "headers": { + "type": "object", + "description": "Custom HTTP headers to be added to all responses.", + "propertyNames": { + "pattern": "^[-_A-Za-z0-9]+$" + }, + "additionalProperties": { + "type": "string" + } + }, + "open": { + "type": "boolean", + "description": "Opens the url in default browser.", + "default": false, + "alias": "o" + }, + "verbose": { + "type": "boolean", + "description": "Adds more details to output logging." + }, + "liveReload": { + "type": "boolean", + "description": "Whether to reload the page on change, using live-reload.", + "default": true + }, + "publicHost": { + "type": "string", + "description": "The URL that the browser client (or live-reload client, if enabled) should use to connect to the development server. Use for a complex dev server setup, such as one with reverse proxies. This option has no effect when using the 'application' or other esbuild-based builders." + }, + "allowedHosts": { + "type": "array", + "description": "List of hosts that are allowed to access the dev server.", + "default": [], + "items": { + "type": "string" + } + }, + "servePath": { + "type": "string", + "description": "The pathname where the application will be served." + }, + "disableHostCheck": { + "type": "boolean", + "description": "Don't verify connected clients are part of allowed hosts.", + "default": false + }, + "hmr": { + "type": "boolean", + "description": "Enable hot module replacement." + }, + "watch": { + "type": "boolean", + "description": "Rebuild on change.", + "default": true + }, + "poll": { + "type": "number", + "description": "Enable and define the file watching poll time period in milliseconds." + }, + "inspect": { + "default": false, + "description": "Activate debugging inspector. This option only has an effect when 'SSR' or 'SSG' are enabled.", + "oneOf": [ + { + "type": "string", + "description": "Activate the inspector on host and port in the format of `[[host:]port]`. See the security warning in https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure regarding the host parameter usage." + }, + { "type": "boolean" } + ] + }, + "forceEsbuild": { + "type": "boolean", + "description": "Force the development server to use the 'browser-esbuild' builder when building.", + "default": false + }, + "prebundle": { + "description": "Enable and control the Vite-based development server's prebundling capabilities. To enable prebundling, the Angular CLI cache must also be enabled. This option has no effect when using the 'browser' or other Webpack-based builders.", + "oneOf": [ + { "type": "boolean" }, + { + "type": "object", + "properties": { + "exclude": { + "description": "List of package imports that should not be prebundled by the development server. The packages will be bundled into the application code itself.", + "type": "array", + "items": { "type": "string" } + } + }, + "additionalProperties": false, + "required": ["exclude"] + } + ] + } + }, + "additionalProperties": false, + "required": ["buildTarget"] +} diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts new file mode 100644 index 000000000000..ef273285ff39 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts @@ -0,0 +1,193 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect, BuilderRun } from '@angular-devkit/architect'; +import path from 'node:path'; +// eslint-disable-next-line import/no-extraneous-dependencies +import puppeteer, { Browser, Page } from 'puppeteer'; +import { debounceTime, switchMap, take } from 'rxjs'; +import { createArchitect, host } from '../../../testing/test-utils'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +declare const document: any; +declare const getComputedStyle: any; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +describe('Dev Server Builder HMR', () => { + const target = { project: 'app', target: 'serve' }; + const overrides = { hmr: true, watch: true, port: 0 }; + let architect: Architect; + let browser: Browser; + let page: Page; + let logs: string[] = []; + let runs: BuilderRun[]; + + beforeAll(async () => { + browser = await puppeteer.launch({ + args: ['--no-sandbox', '--disable-gpu'], + executablePath: process.env.CHROME_BIN + ? path.resolve(path.join(process.cwd(), '..', '..', '..'), process.env.CHROME_BIN) + : undefined, + }); + }); + + afterAll(async () => { + await browser.close(); + }); + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + + logs = []; + runs = []; + page = await browser.newPage(); + page.on('console', (msg) => logs.push(msg.text())); + + host.writeMultipleFiles({ + 'src/app/app.component.html': ` +

{{title}}

+ + + + + + + `, + }); + }); + + afterEach(async () => { + await host.restore().toPromise(); + await page.close(); + await Promise.all(runs.map((r) => r.stop())); + }); + + it('works for CSS changes', async () => { + const run = await architect.scheduleTarget(target, overrides); + runs.push(run); + + let buildCount = 0; + await run.output + .pipe( + debounceTime(1000), + switchMap(async (buildEvent) => { + expect(buildEvent.success).toBe(true); + const url = buildEvent.baseUrl as string; + switch (buildCount) { + case 0: + await page.goto(url); + host.writeMultipleFiles({ + 'src/styles.css': 'p { color: rgb(255, 255, 0) }', + }); + break; + case 1: + expect(logs).toContain('[webpack-dev-server] Hot updated 1 modules.'); + expect(logs).toContain(`[HMR] css reload %s ${url}styles.css`); + expect(logs).toContain('[webpack-dev-server] App is up to date.'); + + const pTagColor = await page.evaluate(() => { + const el = document.querySelector('p'); + + return getComputedStyle(el).color; + }); + + expect(pTagColor).toBe('rgb(255, 255, 0)'); + break; + } + + logs = []; + buildCount++; + }), + take(2), + ) + .toPromise(); + }); + + it('works for TS changes', async () => { + const run = await architect.scheduleTarget(target, overrides); + runs.push(run); + + let buildCount = 0; + await run.output + .pipe( + debounceTime(1000), + switchMap(async (buildEvent) => { + expect(buildEvent.success).toBe(true); + const url = buildEvent.baseUrl as string; + + switch (buildCount) { + case 0: + await page.goto(url); + host.replaceInFile('src/app/app.component.ts', `'app'`, `'app-hmr'`); + break; + case 1: + expect(logs).toContain('[webpack-dev-server] Hot updated 3 modules.'); + expect(logs).toContain('[webpack-dev-server] App is up to date.'); + + const innerText = await page.evaluate(() => document.querySelector('p').innerText); + expect(innerText).toBe('app-hmr'); + break; + } + + logs = []; + buildCount++; + }), + take(2), + ) + .toPromise(); + }); + + it('restores input and select values', async () => { + const run = await architect.scheduleTarget(target, overrides); + runs.push(run); + + let buildCount = 0; + await run.output + .pipe( + debounceTime(1000), + switchMap(async (buildEvent) => { + expect(buildEvent.success).toBe(true); + const url = buildEvent.baseUrl as string; + switch (buildCount) { + case 0: + await page.goto(url); + await page.evaluate(() => { + document.querySelector('input.visible').value = 'input value'; + document.querySelector('select').value = 'two'; + }); + + host.replaceInFile('src/app/app.component.ts', `'app'`, `'app-hmr'`); + break; + case 1: + expect(logs).toContain('[webpack-dev-server] Hot updated 3 modules.'); + expect(logs).toContain('[webpack-dev-server] App is up to date.'); + expect(logs).toContain('[NG HMR] Restoring input/textarea values.'); + expect(logs).toContain('[NG HMR] Restoring selected options.'); + + const inputValue = await page.evaluate( + () => document.querySelector('input.visible').value, + ); + expect(inputValue).toBe('input value'); + + const selectValue = await page.evaluate(() => document.querySelector('select').value); + expect(selectValue).toBe('two'); + break; + } + + logs = []; + buildCount++; + }), + take(2), + ) + .toPromise(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts new file mode 100644 index 000000000000..cfcc01980f78 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { workspaces } from '@angular-devkit/core'; +import { createArchitect, host } from '../../../testing/test-utils'; +import { DevServerBuilderOutput } from '../index'; + +describe('Dev Server Builder index', () => { + const targetSpec = { project: 'app', target: 'serve' }; + + beforeEach(async () => host.initialize().toPromise()); + afterEach(async () => host.restore().toPromise()); + + it('sets HTML lang attribute with the active locale', async () => { + const locale = 'fr'; + const { workspace } = await workspaces.readWorkspace( + host.root(), + workspaces.createWorkspaceHost(host), + ); + const app = workspace.projects.get('app'); + if (!app) { + fail('Test application "app" not found.'); + + return; + } + + app.extensions['i18n'] = { + locales: { + [locale]: [], + }, + }; + + const target = app.targets.get('build'); + if (!target) { + fail('Test application "app" target "build" not found.'); + + return; + } + if (!target.options) { + target.options = {}; + } + target.options.localize = [locale]; + + await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); + + const architect = (await createArchitect(host.root())).architect; + const run = await architect.scheduleTarget(targetSpec, { port: 0 }); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + const response = await fetch(output.baseUrl); + expect(await response.text()).toContain(`lang="${locale}"`); + await run.stop(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts new file mode 100644 index 000000000000..87ff4b6f13ec --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts @@ -0,0 +1,90 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect, BuilderRun } from '@angular-devkit/architect'; +import { tags } from '@angular-devkit/core'; +import { Agent, fetch } from 'undici'; +import { createArchitect, host } from '../../../testing/test-utils'; +import { DevServerBuilderOutput } from '../index'; + +describe('Dev Server Builder ssl', () => { + const target = { project: 'app', target: 'serve' }; + let architect: Architect; + // We use runs like this to ensure it WILL stop the servers at the end of each tests. + let runs: BuilderRun[]; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + runs = []; + }); + afterEach(async () => { + await host.restore().toPromise(); + await Promise.all(runs.map((r) => r.stop())); + }); + + it('works', async () => { + const run = await architect.scheduleTarget(target, { ssl: true, port: 0 }); + runs.push(run); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + expect(output.baseUrl).toMatch(/^https:\/\/localhost:\d+\//); + + const response = await fetch(output.baseUrl, { + dispatcher: new Agent({ + connect: { rejectUnauthorized: false }, + }), + }); + expect(await response.text()).toContain('HelloWorldApp'); + }); + + it('supports key and cert', async () => { + host.writeMultipleFiles({ + 'ssl/server.key': tags.stripIndents` + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgEpythQjrJo9bm8GM + LFacGutCqc/XxDZ3dDkSMYZYZ2ehRANCAARvwtZ3OwP1uLhrcLp7nemvaWqkA+FN + NDjOA3OZKhyVHYog1jNTawJJjwk66upbXGFL8622yU1INWbZFxvrSANl + -----END PRIVATE KEY----- + `, + 'ssl/server.crt': tags.stripIndents` + -----BEGIN CERTIFICATE----- + MIIBfzCCASWgAwIBAgIUUoRhwzxAE3y5nrOW8de+cJEIVvQwCgYIKoZIzj0EAwIw + FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTAxOTA4NTUyNVoYDzIxMjYwOTI1 + MDg1NTI1WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO + PQMBBwNCAARvwtZ3OwP1uLhrcLp7nemvaWqkA+FNNDjOA3OZKhyVHYog1jNTawJJ + jwk66upbXGFL8622yU1INWbZFxvrSANlo1MwUTAdBgNVHQ4EFgQUWyqB1QeFcs6L + LL7Utsybm6+XFvIwHwYDVR0jBBgwFoAUWyqB1QeFcs6LLL7Utsybm6+XFvIwDwYD + VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBazry25W+Qewb/WzadhmdY + YDGdshNZCk0g0DI3ctNjlgIhAKm2X8pmqdkM38Yh8QDN0cHBsAcDfRYffDnjJ3tP + dpnU + -----END CERTIFICATE----- + `, + }); + + const overrides = { + ssl: true, + sslKey: 'ssl/server.key', + sslCert: 'ssl/server.crt', + port: 0, + }; + + const run = await architect.scheduleTarget(target, overrides); + runs.push(run); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + expect(output.baseUrl).toMatch(/^https:\/\/localhost:\d+\//); + + const response = await fetch(output.baseUrl, { + dispatcher: new Agent({ + connect: { rejectUnauthorized: false }, + }), + }); + expect(await response.text()).toContain('HelloWorldApp'); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts new file mode 100644 index 000000000000..14290fc4e5db --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect, BuilderRun } from '@angular-devkit/architect'; +import { EmittedFiles } from '@angular-devkit/build-webpack'; +import { normalize } from '@angular-devkit/core'; +import { createArchitect, host } from '../../../testing/test-utils'; +import { DevServerBuilderOutput } from '../index'; + +describe('Dev Server Builder', () => { + const target = { project: 'app', target: 'serve' }; + let architect: Architect; + let runs: BuilderRun[] = []; + + beforeEach(async () => { + await host.initialize().toPromise(); + architect = (await createArchitect(host.root())).architect; + runs = []; + }); + afterEach(async () => { + await host.restore().toPromise(); + await Promise.all(runs.map((r) => r.stop())); + }); + + it(`doesn't serve files on the cwd directly`, async () => { + const run = await architect.scheduleTarget(target); + runs.push(run); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + + // When webpack-dev-server doesn't have `contentBase: false`, this will serve the repo README. + const response = await fetch(`http://localhost:${output.port}/README.md`, { + headers: { + 'Accept': 'text/html', + }, + }); + + const res = await response.text(); + expect(res).not.toContain('This file is automatically generated during release.'); + expect(res).toContain('HelloWorldApp'); + }); + + it('should not generate sourcemaps when running prod build', async () => { + // Production builds have sourcemaps turned off. + const run = await architect.scheduleTarget( + { ...target, configuration: 'production' }, + { port: 0 }, + ); + runs.push(run); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + const hasSourceMaps = + output.emittedFiles && output.emittedFiles.some((f: EmittedFiles) => f.extension === '.map'); + expect(hasSourceMaps).toBe(false, `Expected emitted files not to contain '.map' files.`); + }); + + it('serves custom headers', async () => { + const run = await architect.scheduleTarget(target, { + headers: { 'X-Header': 'Hello World' }, + port: 0, + }); + runs.push(run); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + const response = await fetch(output.baseUrl); + expect(response.headers.get('X-Header')).toBe('Hello World'); + }); + + it('uses source locale when not localizing', async () => { + const config = host.scopedSync().read(normalize('angular.json')); + const jsonConfig = JSON.parse(new TextDecoder().decode(config)); + const applicationProject = jsonConfig.projects.app; + + applicationProject.i18n = { sourceLocale: 'fr' }; + + host.writeMultipleFiles({ + 'angular.json': JSON.stringify(jsonConfig), + }); + + const architect = (await createArchitect(host.root())).architect; + const run = await architect.scheduleTarget(target, { port: 0 }); + const output = (await run.result) as DevServerBuilderOutput; + expect(output.success).toBe(true); + + const indexResponse = await fetch(output.baseUrl); + expect(await indexResponse.text()).toContain('lang="fr"'); + const vendorResponse = await fetch(output.baseUrl + 'vendor.js'); + const vendorText = await vendorResponse.text(); + expect(vendorText).toContain('fr'); + expect(vendorText).toContain('octobre'); + + await run.stop(); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-assets_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-assets_spec.ts new file mode 100644 index 000000000000..f104bcaa0025 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-assets_spec.ts @@ -0,0 +1,125 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { executeDevServer } from '../../index'; +import { executeOnceAndFetch } from '../execute-fetch'; +import { describeServeBuilder } from '../jasmine-helpers'; +import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; + +describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isVite) => { + const javascriptFileContent = + "import {foo} from 'unresolved'; /* a comment */const foo = `bar`;\n\n\n"; + + describe('Behavior: "browser builder assets"', () => { + it('serves a project JavaScript asset unmodified', async () => { + await harness.writeFile('src/extra.js', javascriptFileContent); + + setupTarget(harness, { + assets: ['src/extra.js'], + optimization: { + scripts: true, + }, + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, 'extra.js'); + + expect(result?.success).toBeTrue(); + expect(await response?.text()).toContain(javascriptFileContent); + }); + + it('serves a project TypeScript asset unmodified', async () => { + await harness.writeFile('src/extra.ts', javascriptFileContent); + + setupTarget(harness, { + assets: ['src/extra.ts'], + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, 'extra.ts'); + + expect(result?.success).toBeTrue(); + expect(await response?.text()).toContain(javascriptFileContent); + }); + + it('should return 404 for non existing assets', async () => { + setupTarget(harness, { + assets: [], + optimization: { + scripts: true, + }, + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, 'does-not-exist.js'); + + expect(result?.success).toBeTrue(); + expect(await response?.status).toBe(404); + }); + + it(`should return the asset that matches 'index.html' when path has a trailing '/'`, async () => { + await harness.writeFile( + 'src/login/index.html', + '

Login page

', + ); + + setupTarget(harness, { + assets: ['src/login'], + optimization: { + scripts: true, + }, + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, 'login/'); + + expect(result?.success).toBeTrue(); + expect(await response?.status).toBe(200); + expect(await response?.text()).toContain('

Login page

'); + }); + + (isVite ? it : xit)( + `should return the asset that matches '.html' when path has no trailing '/'`, + async () => { + await harness.writeFile( + 'src/login/new.html', + '

Login page

', + ); + + setupTarget(harness, { + assets: ['src/login'], + optimization: { + scripts: true, + }, + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, 'login/new'); + + expect(result?.success).toBeTrue(); + expect(await response?.status).toBe(200); + expect(await response?.text()).toContain('

Login page

'); + }, + ); + }); +}); diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-base-href_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-base-href_spec.ts new file mode 100644 index 000000000000..813796079b17 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/tests/behavior/build-base-href_spec.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { executeDevServer } from '../../index'; +import { executeOnceAndFetch } from '../execute-fetch'; +import { describeServeBuilder } from '../jasmine-helpers'; +import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; + +describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { + describe('Behavior: "buildTarget baseHref"', () => { + beforeEach(async () => { + setupTarget(harness, { + baseHref: '/test/', + }); + + // Application code is not needed for these tests + await harness.writeFile('src/main.ts', 'console.log("foo");'); + }); + + it('uses the baseHref defined in the "buildTarget" options as the serve path', async () => { + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, '/test/main.js'); + + expect(result?.success).toBeTrue(); + const baseUrl = new URL(`${result?.baseUrl}/`); + expect(baseUrl.pathname).toBe('/test/'); + expect(await response?.text()).toContain('console.log'); + }); + + it('serves the application from baseHref location without trailing slash', async () => { + harness.useTarget('serve', { + ...BASE_OPTIONS, + }); + + const { result, response } = await executeOnceAndFetch(harness, '/test'); + + expect(result?.success).toBeTrue(); + expect(await response?.text()).toContain(' + + + + + %SCRIPTS% + + + + + + diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-debug.html b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-debug.html new file mode 100644 index 000000000000..dc58d8e6ee60 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma-debug.html @@ -0,0 +1,46 @@ + + + + + %X_UA_COMPATIBLE% + Karma DEBUG RUNNER + + + + + + + + + + + + + + + + %SCRIPTS% + + + + + + diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts new file mode 100644 index 000000000000..07aac6f8b9d2 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/karma/karma.ts @@ -0,0 +1,202 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/* eslint-disable */ +// TODO: cleanup this file, it's copied as is from Angular CLI. +import type { IncomingMessage, ServerResponse } from 'node:http'; +import * as path from 'node:path'; +import type { Compiler } from 'webpack'; +import webpackDevMiddleware from 'webpack-dev-middleware'; + +import { statsErrorsToString } from '../../utils/stats'; +import { logging } from '@angular-devkit/core'; +import { BuildOptions } from '../../../../utils/build-options'; +import { normalizeSourceMaps } from '../../../../utils/index'; + +let webpackMiddleware: webpackDevMiddleware.API; + +const init: any = (config: any, emitter: any) => { + if (!config.buildWebpack) { + throw new Error( + `The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to` + + ` be used from within Angular CLI and will not work correctly outside of it.`, + ); + } + const options = config.buildWebpack.options as BuildOptions; + const logger: logging.Logger = config.buildWebpack.logger; + + // Add a reporter that fixes sourcemap urls. + if (normalizeSourceMaps(options.sourceMap).scripts) { + config.reporters.unshift('@angular-devkit/build-angular--sourcemap-reporter'); + + // Code taken from https://github.com/tschaub/karma-source-map-support. + // We can't use it directly because we need to add it conditionally in this file, and karma + // frameworks cannot be added dynamically. + const smsPath = path.dirname(require.resolve('source-map-support')); + const ksmsPath = path.dirname(require.resolve('karma-source-map-support')); + + config.files.unshift( + { + pattern: path.join(smsPath, 'browser-source-map-support.js'), + included: true, + served: true, + watched: false, + }, + { pattern: path.join(ksmsPath, 'client.js'), included: true, served: true, watched: false }, + ); + } + + // When using code-coverage, auto-add karma-coverage. + if ( + options.codeCoverage && + !config.reporters.some((r: string) => r === 'coverage' || r === 'coverage-istanbul') + ) { + config.reporters.push('coverage'); + } + + const compiler = config.buildWebpack.compiler as Compiler; + const webpackMiddlewareConfig = { + // Hide webpack output because its noisy. + stats: false, + }; + + config.webpackMiddleware = { ...webpackMiddlewareConfig, ...config.webpackMiddleware }; + + // Our custom context and debug files list the webpack bundles directly instead of using + // the karma files array. + config.customContextFile = `${__dirname}/karma-context.html`; + config.customDebugFile = `${__dirname}/karma-debug.html`; + + // Add the webpack server fallback. + config.middleware = config.middleware || []; + config.middleware.push('@angular-devkit/build-angular--fallback'); + + webpackMiddleware = webpackDevMiddleware(compiler, webpackMiddlewareConfig); + emitter.on('exit', (done: any) => { + webpackMiddleware.close(() => compiler.close(() => done())); + }); + + let lastCompilationHash: string | undefined; + + return new Promise((resolve) => { + compiler.hooks.done.tap('karma', (stats) => { + if (stats.hasErrors()) { + lastCompilationHash = undefined; + + // Only generate needed JSON stats and when needed. + const statsJson = stats.toJson({ + all: false, + children: true, + errors: true, + warnings: true, + }); + + logger.error(statsErrorsToString(statsJson, { colors: true })); + + if (config.singleRun) { + // Notify potential listeners of the compile error. + emitter.emit('load_error'); + } + + // Finish Karma run early in case of compilation error. + emitter.emit('run_complete', [], { exitCode: 1 }); + } else if (stats.hash != lastCompilationHash) { + // Refresh karma only when there are no webpack errors, and if the compilation changed. + lastCompilationHash = stats.hash; + emitter.refreshFiles(); + } + + // This is needed to block Karma from launching browsers before Webpack writes the assets in memory. + // See the below: + // https://github.com/karma-runner/karma-chrome-launcher/issues/154#issuecomment-986661937 + // https://github.com/angular/angular-cli/issues/22495 + resolve(); + }); + }); +}; + +init.$inject = ['config', 'emitter']; + +// Copied from "karma-jasmine-diff-reporter" source code: +// In case, when multiple reporters are used in conjunction +// with initSourcemapReporter, they both will show repetitive log +// messages when displaying everything that supposed to write to terminal. +// So just suppress any logs from initSourcemapReporter by doing nothing on +// browser log, because it is an utility reporter, +// unless it's alone in the "reporters" option and base reporter is used. +function muteDuplicateReporterLogging(context: any, config: any) { + context.writeCommonMsg = () => {}; + const reporterName = '@angular/cli'; + const hasTrailingReporters = config.reporters.slice(-1).pop() !== reporterName; + + if (hasTrailingReporters) { + context.writeCommonMsg = () => {}; + } +} + +// Strip the server address and webpack scheme (webpack://) from error log. +const sourceMapReporter: any = function (this: any, baseReporterDecorator: any, config: any) { + baseReporterDecorator(this); + muteDuplicateReporterLogging(this, config); + + const urlRegexp = /http:\/\/localhost:\d+\/(webpack:\/)?/gi; + + this.onSpecComplete = function (_browser: any, result: any) { + if (!result.success) { + result.log = result.log.map((l: string) => l.replace(urlRegexp, '')); + } + }; + + // avoid duplicate complete message + this.onRunComplete = () => {}; + + // avoid duplicate failure message + this.specFailure = () => {}; +}; + +sourceMapReporter.$inject = ['baseReporterDecorator', 'config']; + +/** + * List of files that are always served by the webpack server. + */ +const alwaysServe: ReadonlySet = new Set([ + '/runtime.js', + '/polyfills.js', + '/scripts.js', + '/styles.css', + '/vendor.js', +]); + +// When a request is not found in the karma server, try looking for it from the webpack server root. +function fallbackMiddleware() { + return function ( + request: IncomingMessage, + response: ServerResponse, + next: (err?: unknown) => void, + ) { + if (!webpackMiddleware) { + next(); + return; + } + + webpackMiddleware(request, response, () => { + if (request.url && alwaysServe.has(request.url)) { + response.statusCode = 200; + response.end(); + } else { + next(); + } + }); + }; +} + +module.exports = { + 'framework:@angular-devkit/build-angular': ['factory', init], + 'reporter:@angular-devkit/build-angular--sourcemap-reporter': ['type', sourceMapReporter], + 'middleware:@angular-devkit/build-angular--fallback': ['factory', fallbackMiddleware], +}; diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/named-chunks-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/named-chunks-plugin.ts new file mode 100644 index 000000000000..417d11484ef7 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/named-chunks-plugin.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { AsyncDependenciesBlock, Chunk, Compiler, Template, dependencies } from 'webpack'; + +// `ImportDependency` is not part of Webpack's depenencies typings. +const ImportDependency: typeof dependencies.ModuleDependency = require('webpack/lib/dependencies/import/ImportDependency'); + +const PLUGIN_NAME = 'named-chunks-plugin'; + +/** + * Webpack will not populate the chunk `name` property unless `webpackChunkName` magic comment is used. + * This however will also effect the filename which is not desired when using `deterministic` chunkIds. + * This plugin will populate the chunk `name` which is mainly used so that users can set bundle budgets on lazy chunks. + */ +export class NamedChunksPlugin { + apply(compiler: Compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.chunkAsset.tap(PLUGIN_NAME, (chunk) => { + if (chunk.name) { + return; + } + + if ([...chunk.files.values()].every((f) => f.endsWith('.css'))) { + // If all chunk files are CSS files skip. + // This happens when using `import('./styles.css')` in a lazy loaded module. + return undefined; + } + + const name = this.generateName(chunk); + if (name) { + chunk.name = name; + } + }); + }); + } + + private generateName(chunk: Chunk): string | undefined { + for (const group of chunk.groupsIterable) { + const [block] = group.getBlocks(); + if (!(block instanceof AsyncDependenciesBlock)) { + continue; + } + + if (block.groupOptions.name) { + // Ignore groups which have been named already. + return undefined; + } + + for (const dependency of block.dependencies) { + if (dependency instanceof ImportDependency) { + return Template.toPath(dependency.request); + } + } + } + + return undefined; + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/occurrences-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/occurrences-plugin.ts new file mode 100644 index 000000000000..0357b267071a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/occurrences-plugin.ts @@ -0,0 +1,98 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Compiler } from 'webpack'; + +const PLUGIN_NAME = 'angular-occurrences-plugin'; + +export interface OccurrencesPluginOptions { + aot?: boolean; + scriptsOptimization?: boolean; +} + +export class OccurrencesPlugin { + constructor(private options: OccurrencesPluginOptions) {} + + apply(compiler: Compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.processAssets.tapPromise( + { + name: PLUGIN_NAME, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, + }, + async (compilationAssets) => { + for (const assetName of Object.keys(compilationAssets)) { + if (!assetName.endsWith('.js')) { + continue; + } + + const scriptAsset = compilation.getAsset(assetName); + if (!scriptAsset || scriptAsset.source.size() <= 0) { + continue; + } + + const src = scriptAsset.source.source().toString('utf-8'); + + let ngComponentCount = 0; + + if (!this.options.aot) { + // Count the number of `Component({` strings (case sensitive), which happens in __decorate(). + ngComponentCount += this.countOccurrences(src, 'Component({'); + } + + if (this.options.scriptsOptimization) { + // for ascii_only true + ngComponentCount += this.countOccurrences(src, '.\\u0275cmp', false); + } else { + // For Ivy we just count ɵcmp.src + ngComponentCount += this.countOccurrences(src, '.ɵcmp', true); + } + + compilation.updateAsset( + assetName, + (s) => s, + (assetInfo) => ({ + ...assetInfo, + ngComponentCount, + }), + ); + } + }, + ); + }); + } + + private countOccurrences(source: string, match: string, wordBreak = false): number { + let count = 0; + + // We condition here so branch prediction happens out of the loop, not in it. + if (wordBreak) { + const re = /\w/; + for (let pos = source.lastIndexOf(match); pos >= 0; pos = source.lastIndexOf(match, pos)) { + if (!(re.test(source[pos - 1] || '') || re.test(source[pos + match.length] || ''))) { + count++; // 1 match, AH! AH! AH! 2 matches, AH! AH! AH! + } + + pos -= match.length; + if (pos < 0) { + break; + } + } + } else { + for (let pos = source.lastIndexOf(match); pos >= 0; pos = source.lastIndexOf(match, pos)) { + count++; // 1 match, AH! AH! AH! 2 matches, AH! AH! AH! + pos -= match.length; + if (pos < 0) { + break; + } + } + } + + return count; + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/postcss-cli-resources.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/postcss-cli-resources.ts new file mode 100644 index 000000000000..37ee30b5f9bf --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/postcss-cli-resources.ts @@ -0,0 +1,212 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { interpolateName } from 'loader-utils'; +import * as path from 'node:path'; +import * as url from 'node:url'; +import { Declaration, Plugin } from 'postcss'; +import { assertIsError } from '../../../utils/error'; + +function wrapUrl(url: string): string { + let wrappedUrl; + const hasSingleQuotes = url.indexOf("'") >= 0; + + if (hasSingleQuotes) { + wrappedUrl = `"${url}"`; + } else { + wrappedUrl = `'${url}'`; + } + + return `url(${wrappedUrl})`; +} + +export interface PostcssCliResourcesOptions { + baseHref?: string; + deployUrl?: string; + resourcesOutputPath?: string; + rebaseRootRelative?: boolean; + + /** CSS is extracted to a `.css` or is embedded in a `.js` file. */ + extracted?: boolean; + filename: (resourcePath: string) => string; + loader: import('webpack').LoaderContext; + emitFile: boolean; +} + +async function resolve( + file: string, + base: string, + resolver: (file: string, base: string) => Promise, +): Promise { + try { + return await resolver('./' + file, base); + } catch { + return resolver(file, base); + } +} + +export const postcss = true; + +export default function (options?: PostcssCliResourcesOptions): Plugin { + if (!options) { + throw new Error('No options were specified to "postcss-cli-resources".'); + } + + const { + deployUrl = '', + resourcesOutputPath = '', + filename, + loader, + emitFile, + extracted, + } = options; + + const process = async (inputUrl: string, context: string, resourceCache: Map) => { + // If root-relative, absolute or protocol relative url, leave as is + if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) { + return inputUrl; + } + + if (/^\//.test(inputUrl)) { + return inputUrl; + } + + // If starts with a caret, remove and return remainder + // this supports bypassing asset processing + if (inputUrl.startsWith('^')) { + return inputUrl.slice(1); + } + + const cacheKey = path.resolve(context, inputUrl); + const cachedUrl = resourceCache.get(cacheKey); + if (cachedUrl) { + return cachedUrl; + } + + if (inputUrl.startsWith('~')) { + inputUrl = inputUrl.slice(1); + } + + const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/')); + const resolver = (file: string, base: string) => + new Promise((resolve, reject) => { + loader.resolve(base, decodeURI(file), (err, result) => { + if (err) { + reject(err); + + return; + } + resolve(result as string); + }); + }); + + const result = await resolve(pathname as string, context, resolver); + + return new Promise((resolve, reject) => { + loader.fs.readFile(result, (err, content) => { + if (err) { + reject(err); + + return; + } + + let outputPath = interpolateName( + // TODO: Revisit. Previously due to lack of type safety, this object + // was fine, but in practice it doesn't match the type of the loader context. + { resourcePath: result } as Parameters[0], + filename(result), + { + content, + context: loader.context || loader.rootContext, + }, + ).replace(/\\|\//g, '-'); + + if (resourcesOutputPath) { + outputPath = path.posix.join(resourcesOutputPath, outputPath); + } + + loader.addDependency(result); + if (emitFile) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + loader.emitFile(outputPath, content!, undefined, { sourceFilename: result }); + } + + let outputUrl = outputPath.replace(/\\/g, '/'); + if (hash || search) { + outputUrl = url.format({ pathname: outputUrl, hash, search }); + } + + if (deployUrl && !extracted) { + outputUrl = url.resolve(deployUrl, outputUrl); + } + + resourceCache.set(cacheKey, outputUrl); + resolve(outputUrl); + }); + }); + }; + + const resourceCache = new Map(); + const processed = Symbol('postcss-cli-resources'); + + return { + postcssPlugin: 'postcss-cli-resources', + async Declaration(decl) { + if (!decl.value.includes('url') || processed in decl) { + return; + } + + const value = decl.value; + const urlRegex = /url(?:\(\s*(['"]?))(.*?)(?:\1\s*\))/g; + const segments: string[] = []; + + let match; + let lastIndex = 0; + let modified = false; + + // We want to load it relative to the file that imports + const inputFile = decl.source && decl.source.input.file; + const context = (inputFile && path.dirname(inputFile)) || loader.context; + + while ((match = urlRegex.exec(value))) { + const originalUrl = match[2]; + let processedUrl; + try { + processedUrl = await process(originalUrl, context, resourceCache); + } catch (err) { + assertIsError(err); + loader.emitError(decl.error(err.message, { word: originalUrl })); + continue; + } + + if (lastIndex < match.index) { + segments.push(value.slice(lastIndex, match.index)); + } + + if (!processedUrl || originalUrl === processedUrl) { + segments.push(match[0]); + } else { + segments.push(wrapUrl(processedUrl)); + modified = true; + } + + lastIndex = match.index + match[0].length; + } + + if (lastIndex < value.length) { + segments.push(value.slice(lastIndex)); + } + + if (modified) { + decl.value = segments.join(''); + } + + (decl as Declaration & { [processed]: boolean })[processed] = true; + }, + }; +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/progress-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/progress-plugin.ts new file mode 100644 index 000000000000..823220eb796e --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/progress-plugin.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { ProgressPlugin as WebpackProgressPlugin } from 'webpack'; +import { Spinner } from '../../../utils/spinner'; + +export class ProgressPlugin extends WebpackProgressPlugin { + constructor(platform: 'server' | 'browser') { + const platformCapitalFirst = platform.replace(/^\w/, (s) => s.toUpperCase()); + const spinner = new Spinner(); + spinner.start(`Generating ${platform} application bundles (phase: setup)...`); + + super({ + handler: (percentage: number, message: string) => { + const phase = message ? ` (phase: ${message})` : ''; + spinner.text = `Generating ${platform} application bundles${phase}...`; + + switch (percentage) { + case 1: + if (spinner.isSpinning) { + spinner.succeed(`${platformCapitalFirst} application bundle generation complete.`); + } + break; + case 0: + if (!spinner.isSpinning) { + spinner.start(); + } + break; + } + }, + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/remove-hash-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/remove-hash-plugin.ts new file mode 100644 index 000000000000..f4b8c3311689 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/remove-hash-plugin.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Compiler } from 'webpack'; +import { HashFormat } from '../utils/helpers'; + +export interface RemoveHashPluginOptions { + chunkNames: string[]; + hashFormat: HashFormat; +} + +export class RemoveHashPlugin { + constructor(private options: RemoveHashPluginOptions) {} + + apply(compiler: Compiler): void { + compiler.hooks.compilation.tap('remove-hash-plugin', (compilation) => { + const assetPath = (path: string, data: { chunk?: { name?: string | null } }) => { + const chunkName = data.chunk?.name; + const { chunkNames, hashFormat } = this.options; + + if (chunkName && chunkNames?.includes(chunkName)) { + // Replace hash formats with empty strings. + return path.replace(hashFormat.chunk, '').replace(hashFormat.extract, ''); + } + + return path; + }; + + compilation.hooks.assetPath.tap('remove-hash-plugin', assetPath); + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/scripts-webpack-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/scripts-webpack-plugin.ts new file mode 100644 index 000000000000..10d7d2d245bb --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/scripts-webpack-plugin.ts @@ -0,0 +1,211 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { interpolateName } from 'loader-utils'; +import * as path from 'node:path'; +import { Chunk, Compilation, Compiler, sources as webpackSources } from 'webpack'; +import { assertIsError } from '../../../utils/error'; +import { addError } from '../../../utils/webpack-diagnostics'; + +const Entrypoint = require('webpack/lib/Entrypoint'); + +/** + * The name of the plugin provided to Webpack when tapping Webpack compiler hooks. + */ +const PLUGIN_NAME = 'scripts-webpack-plugin'; + +export interface ScriptsWebpackPluginOptions { + name: string; + sourceMap?: boolean; + scripts: string[]; + filename: string; + basePath: string; +} + +interface ScriptOutput { + filename: string; + source: webpackSources.CachedSource; +} + +function addDependencies(compilation: Compilation, scripts: string[]): void { + for (const script of scripts) { + compilation.fileDependencies.add(script); + } +} + +export class ScriptsWebpackPlugin { + private _lastBuildTime?: number; + private _cachedOutput?: ScriptOutput; + + constructor(private options: ScriptsWebpackPluginOptions) {} + + async shouldSkip(compilation: Compilation, scripts: string[]): Promise { + if (this._lastBuildTime == undefined) { + this._lastBuildTime = Date.now(); + + return false; + } + + for (const script of scripts) { + const scriptTime = await new Promise((resolve, reject) => { + compilation.fileSystemInfo.getFileTimestamp(script, (error, entry) => { + if (error) { + reject(error); + + return; + } + + resolve(entry && typeof entry !== 'string' ? entry.safeTime : undefined); + }); + }); + + if (!scriptTime || scriptTime > this._lastBuildTime) { + this._lastBuildTime = Date.now(); + + return false; + } + } + + return true; + } + + private _insertOutput( + compilation: Compilation, + { filename, source }: ScriptOutput, + cached = false, + ) { + const chunk = new Chunk(this.options.name); + chunk.rendered = !cached; + chunk.id = this.options.name; + chunk.ids = [chunk.id]; + chunk.files.add(filename); + + const entrypoint = new Entrypoint(this.options.name); + entrypoint.pushChunk(chunk); + chunk.addGroup(entrypoint); + compilation.entrypoints.set(this.options.name, entrypoint); + compilation.chunks.add(chunk); + + compilation.assets[filename] = source; + compilation.hooks.chunkAsset.call(chunk, filename); + } + + apply(compiler: Compiler): void { + if (this.options.scripts.length === 0) { + return; + } + + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + // Use the resolver from the compilation instead of compiler. + // Using the latter will causes a lot of `DescriptionFileUtils.loadDescriptionFile` calls. + // See: https://github.com/angular/angular-cli/issues/24634#issuecomment-1425782668 + const resolver = compilation.resolverFactory.get('normal', { + preferRelative: true, + useSyncFileSystemCalls: true, + // Caching must be disabled because it causes the resolver to become async after a rebuild. + cache: false, + }); + + const scripts: string[] = []; + + for (const script of this.options.scripts) { + try { + const resolvedPath = resolver.resolveSync({}, this.options.basePath, script); + if (resolvedPath) { + scripts.push(resolvedPath); + } else { + addError(compilation, `Cannot resolve '${script}'.`); + } + } catch (error) { + assertIsError(error); + addError(compilation, error.message); + } + } + + compilation.hooks.additionalAssets.tapPromise(PLUGIN_NAME, async () => { + if (await this.shouldSkip(compilation, scripts)) { + if (this._cachedOutput) { + this._insertOutput(compilation, this._cachedOutput, true); + } + + addDependencies(compilation, scripts); + + return; + } + + const sourceGetters = scripts.map((fullPath) => { + return new Promise((resolve, reject) => { + compilation.inputFileSystem.readFile( + fullPath, + (err?: Error | null, data?: string | Buffer) => { + if (err) { + reject(err); + + return; + } + + const content = data?.toString() ?? ''; + + let source; + if (this.options.sourceMap) { + // TODO: Look for source map file (for '.min' scripts, etc.) + + let adjustedPath = fullPath; + if (this.options.basePath) { + adjustedPath = path.relative(this.options.basePath, fullPath); + } + source = new webpackSources.OriginalSource(content, adjustedPath); + } else { + source = new webpackSources.RawSource(content); + } + + resolve(source); + }, + ); + }); + }); + + const sources = await Promise.all(sourceGetters); + const concatSource = new webpackSources.ConcatSource(); + sources.forEach((source) => { + concatSource.add(source); + concatSource.add('\n;'); + }); + + const combinedSource = new webpackSources.CachedSource(concatSource); + + const output = { filename: this.options.filename, source: combinedSource }; + this._insertOutput(compilation, output); + this._cachedOutput = output; + addDependencies(compilation, scripts); + }); + compilation.hooks.processAssets.tapPromise( + { + name: PLUGIN_NAME, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, + }, + async () => { + const assetName = this.options.filename; + const asset = compilation.getAsset(assetName); + if (asset) { + const interpolatedFilename = interpolateName( + // TODO: Revisit. Previously due to lack of type safety, this object + // was fine, but in practice it doesn't match the type of the loader context. + { resourcePath: 'scripts.js' } as Parameters[0], + assetName, + { content: asset.source.source() }, + ); + if (assetName !== interpolatedFilename) { + compilation.renameAsset(assetName, interpolatedFilename); + } + } + }, + ); + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/service-worker-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/service-worker-plugin.ts new file mode 100644 index 000000000000..8b49d4d817f6 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/service-worker-plugin.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { augmentAppWithServiceWorker } from '@angular/build/private'; +import type { Compiler } from 'webpack'; + +export interface ServiceWorkerPluginOptions { + projectRoot: string; + root: string; + baseHref?: string; + ngswConfigPath?: string; +} + +export class ServiceWorkerPlugin { + constructor(private readonly options: ServiceWorkerPluginOptions) {} + + apply(compiler: Compiler) { + compiler.hooks.done.tapPromise('angular-service-worker', async (stats) => { + if (stats.hasErrors()) { + // Don't generate a service worker if the compilation has errors. + // When there are errors some files will not be emitted which would cause other errors down the line such as readdir failures. + return; + } + + const { projectRoot, root, baseHref = '', ngswConfigPath } = this.options; + const { compilation } = stats; + // We use the output path from the compilation instead of build options since during + // localization the output path is modified to a temp directory. + // See: https://github.com/angular/angular-cli/blob/7e64b1537d54fadb650559214fbb12707324cd75/packages/angular_devkit/build_angular/src/utils/i18n-options.ts#L251-L252 + const outputPath = compilation.outputOptions.path; + + if (!outputPath) { + throw new Error('Compilation output path cannot be empty.'); + } + + try { + await augmentAppWithServiceWorker( + projectRoot, + root, + outputPath, + baseHref, + ngswConfigPath, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (compiler.inputFileSystem as any).promises, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (compiler.outputFileSystem as any).promises, + ); + } catch (error) { + compilation.errors.push( + new compilation.compiler.webpack.WebpackError( + `Failed to generate service worker - ${error instanceof Error ? error.message : error}`, + ), + ); + } + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/styles-webpack-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/styles-webpack-plugin.ts new file mode 100644 index 000000000000..38555f56a093 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/styles-webpack-plugin.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import type { Compilation, Compiler } from 'webpack'; +import { assertIsError } from '../../../utils/error'; +import { addError } from '../../../utils/webpack-diagnostics'; + +export interface StylesWebpackPluginOptions { + preserveSymlinks?: boolean; + root: string; + entryPoints: Record; +} + +/** + * The name of the plugin provided to Webpack when tapping Webpack compiler hooks. + */ +const PLUGIN_NAME = 'styles-webpack-plugin'; + +export class StylesWebpackPlugin { + private compilation: Compilation | undefined; + + constructor(private readonly options: StylesWebpackPluginOptions) {} + + apply(compiler: Compiler): void { + const { entryPoints, preserveSymlinks, root } = this.options; + const resolver = compiler.resolverFactory.get('global-styles', { + conditionNames: ['sass', 'less', 'style'], + mainFields: ['sass', 'less', 'style', 'main', '...'], + extensions: ['.scss', '.sass', '.less', '.css'], + restrictions: [/\.((le|sa|sc|c)ss)$/i], + preferRelative: true, + useSyncFileSystemCalls: true, + symlinks: !preserveSymlinks, + fileSystem: compiler.inputFileSystem ?? undefined, + }); + + const webpackOptions = compiler.options; + compiler.hooks.environment.tap(PLUGIN_NAME, () => { + const entry = + typeof webpackOptions.entry === 'function' ? webpackOptions.entry() : webpackOptions.entry; + + webpackOptions.entry = async () => { + const entrypoints = await entry; + + for (const [bundleName, paths] of Object.entries(entryPoints)) { + entrypoints[bundleName] ??= {}; + const entryImport = (entrypoints[bundleName].import ??= []); + + for (const path of paths) { + try { + const resolvedPath = resolver.resolveSync({}, root, path); + if (resolvedPath) { + entryImport.push(`${resolvedPath}?ngGlobalStyle`); + } else { + assert(this.compilation, 'Compilation cannot be undefined.'); + addError(this.compilation, `Cannot resolve '${path}'.`); + } + } catch (error) { + assert(this.compilation, 'Compilation cannot be undefined.'); + assertIsError(error); + addError(this.compilation, error.message); + } + } + } + + return entrypoints; + }; + }); + + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + this.compilation = compilation; + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/suppress-entry-chunks-webpack-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/suppress-entry-chunks-webpack-plugin.ts new file mode 100644 index 000000000000..aae12361dd5a --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/suppress-entry-chunks-webpack-plugin.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * Remove .js files from entry points consisting entirely of stylesheets. + * To be used together with mini-css-extract-plugin. + */ +export class SuppressExtractedTextChunksWebpackPlugin { + apply(compiler: import('webpack').Compiler): void { + compiler.hooks.compilation.tap('SuppressExtractedTextChunks', (compilation) => { + compilation.hooks.chunkAsset.tap('SuppressExtractedTextChunks', (chunk, filename) => { + // Remove only JavaScript assets + if (!filename.endsWith('.js')) { + return; + } + + // Only chunks with a css asset should have JavaScript assets removed + let hasCssFile = false; + for (const file of chunk.files) { + if (file.endsWith('.css')) { + hasCssFile = true; + break; + } + } + + if (!hasCssFile) { + return; + } + + // Only chunks with all CSS entry dependencies should have JavaScript assets removed + let cssOnly = false; + const entryModules = compilation.chunkGraph.getChunkEntryModulesIterable(chunk); + for (const module of entryModules) { + cssOnly = module.dependencies.every( + (dependency: {}) => dependency.constructor.name === 'CssDependency', + ); + + if (!cssOnly) { + break; + } + } + + if (cssOnly) { + chunk.files.delete(filename); + compilation.deleteAsset(filename); + } + }); + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/transfer-size-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/transfer-size-plugin.ts new file mode 100644 index 000000000000..77122667452f --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/transfer-size-plugin.ts @@ -0,0 +1,66 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { promisify } from 'node:util'; +import { brotliCompress } from 'node:zlib'; +import { Compiler } from 'webpack'; +import { addWarning } from '../../../utils/webpack-diagnostics'; + +const brotliCompressAsync = promisify(brotliCompress); + +const PLUGIN_NAME = 'angular-transfer-size-estimator'; + +export class TransferSizePlugin { + constructor() {} + + apply(compiler: Compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.processAssets.tapPromise( + { + name: PLUGIN_NAME, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, + }, + async (compilationAssets) => { + const actions = []; + for (const assetName of Object.keys(compilationAssets)) { + if (!assetName.endsWith('.js') && !assetName.endsWith('.css')) { + continue; + } + + const scriptAsset = compilation.getAsset(assetName); + if (!scriptAsset || scriptAsset.source.size() <= 0) { + continue; + } + + actions.push( + brotliCompressAsync(scriptAsset.source.source()) + .then((result) => { + compilation.updateAsset( + assetName, + (s) => s, + (assetInfo) => ({ + ...assetInfo, + estimatedTransferSize: result.length, + }), + ); + }) + .catch((error) => { + addWarning( + compilation, + `Unable to calculate estimated transfer size for '${assetName}'. Reason: ${error.message}`, + ); + }), + ); + } + + await Promise.all(actions); + }, + ); + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/typescript.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/typescript.ts new file mode 100644 index 000000000000..129c869036d2 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/typescript.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { CompilerOptions } from '@angular/compiler-cli'; +import { AngularWebpackPlugin } from '@ngtools/webpack'; +import { ScriptTarget } from 'typescript'; +import { WebpackConfigOptions } from '../../../utils/build-options'; + +export function createIvyPlugin( + wco: WebpackConfigOptions, + aot: boolean, + tsconfig: string, +): AngularWebpackPlugin { + const { buildOptions, tsConfig } = wco; + const optimize = buildOptions.optimization.scripts; + + const compilerOptions: CompilerOptions = { + sourceMap: buildOptions.sourceMap.scripts, + declaration: false, + declarationMap: false, + // Disable removing of comments as TS is quite aggressive with these and can + // remove important annotations, such as /* @__PURE__ */. + removeComments: false, + }; + + if (tsConfig.options.target === undefined || tsConfig.options.target < ScriptTarget.ES2022) { + compilerOptions.target = ScriptTarget.ES2022; + // If 'useDefineForClassFields' is already defined in the users project leave the value as is. + // Otherwise fallback to false due to https://github.com/microsoft/TypeScript/issues/45995 + // which breaks the deprecated `@Effects` NGRX decorator and potentially other existing code as well. + compilerOptions.useDefineForClassFields ??= false; + + wco.logger.warn( + 'TypeScript compiler options "target" and "useDefineForClassFields" are set to "ES2022" and ' + + '"false" respectively by the Angular CLI. To control ECMA version and features use the Browserslist configuration. ' + + 'For more information, see https://angular.dev/tools/cli/build#configuring-browser-compatibility\n' + + `NOTE: You can set the "target" to "ES2022" in the project's tsconfig to remove this warning.`, + ); + } + + if (buildOptions.preserveSymlinks !== undefined) { + compilerOptions.preserveSymlinks = buildOptions.preserveSymlinks; + } + + const fileReplacements: Record = {}; + if (buildOptions.fileReplacements) { + for (const replacement of buildOptions.fileReplacements) { + fileReplacements[replacement.replace] = replacement.with; + } + } + + return new AngularWebpackPlugin({ + tsconfig, + compilerOptions, + fileReplacements, + jitMode: !aot, + emitNgModuleScope: !optimize, + inlineStyleFileExtension: buildOptions.inlineStyleLanguage ?? 'css', + }); +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/plugins/watch-files-logs-plugin.ts b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/watch-files-logs-plugin.ts new file mode 100644 index 000000000000..d56e0e53db32 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/plugins/watch-files-logs-plugin.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Compiler } from 'webpack'; + +const PLUGIN_NAME = 'angular.watch-files-logs-plugin'; + +export class WatchFilesLogsPlugin { + apply(compiler: Compiler) { + compiler.hooks.watchRun.tap(PLUGIN_NAME, ({ modifiedFiles, removedFiles }) => { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const logger = compilation.getLogger(PLUGIN_NAME); + if (modifiedFiles?.size) { + logger.log(`Modified files:\n${[...modifiedFiles].join('\n')}\n`); + } + + if (removedFiles?.size) { + logger.log(`Removed files:\n${[...removedFiles].join('\n')}\n`); + } + }); + }); + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/utils/async-chunks.ts b/packages/angular_devkit/build_angular/src/tools/webpack/utils/async-chunks.ts new file mode 100644 index 000000000000..00eb0740fb11 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/utils/async-chunks.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { StatsChunk, StatsCompilation } from 'webpack'; +import { NormalizedEntryPoint } from './helpers'; + +/** + * Webpack stats may incorrectly mark extra entry points `initial` chunks, when + * they are actually loaded asynchronously and thus not in the main bundle. This + * function finds extra entry points in Webpack stats and corrects this value + * whereever necessary. Does not modify {@param webpackStats}. + */ +export function markAsyncChunksNonInitial( + webpackStats: StatsCompilation, + extraEntryPoints: NormalizedEntryPoint[], +): StatsChunk[] { + const { chunks = [], entrypoints: entryPoints = {} } = webpackStats; + + // Find all Webpack chunk IDs not injected into the main bundle. We don't have + // to worry about transitive dependencies because extra entry points cannot be + // depended upon in Webpack, thus any extra entry point with `inject: false`, + // **cannot** be loaded in main bundle. + const asyncChunkIds = extraEntryPoints + .filter((entryPoint) => !entryPoint.inject && entryPoints[entryPoint.bundleName]) + .flatMap((entryPoint) => + entryPoints[entryPoint.bundleName].chunks?.filter((n) => n !== 'runtime'), + ); + + // Find chunks for each ID. + const asyncChunks = asyncChunkIds.map((chunkId) => { + const chunk = chunks.find((chunk) => chunk.id === chunkId); + if (!chunk) { + throw new Error(`Failed to find chunk (${chunkId}) in set:\n${JSON.stringify(chunks)}`); + } + + return chunk; + }); + + // A chunk is considered `initial` only if Webpack already belives it to be initial + // and the application developer did not mark it async via an extra entry point. + return chunks.map((chunk) => { + return asyncChunks.find((asyncChunk) => asyncChunk === chunk) + ? { + ...chunk, + initial: false, + } + : chunk; + }); +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts b/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts new file mode 100644 index 000000000000..e359597ab45e --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/utils/helpers.ts @@ -0,0 +1,325 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ObjectPattern } from 'copy-webpack-plugin'; +import { createHash } from 'node:crypto'; +import { createRequire } from 'node:module'; +import * as path from 'node:path'; +import { globSync } from 'tinyglobby'; +import type { Configuration, WebpackOptionsNormalized } from 'webpack'; +import { + AssetPatternClass, + OutputHashing, + ScriptElement, + StyleElement, +} from '../../../builders/browser/schema'; +import { WebpackConfigOptions } from '../../../utils/build-options'; +import { VERSION } from '../../../utils/package-version'; + +export interface HashFormat { + chunk: string; + extract: string; + file: string; + script: string; +} + +export type WebpackStatsOptions = Exclude; + +export function getOutputHashFormat(outputHashing = OutputHashing.None, length = 20): HashFormat { + const hashTemplate = `.[contenthash:${length}]`; + + switch (outputHashing) { + case 'media': + return { + chunk: '', + extract: '', + file: hashTemplate, + script: '', + }; + case 'bundles': + return { + chunk: hashTemplate, + extract: hashTemplate, + file: '', + script: hashTemplate, + }; + case 'all': + return { + chunk: hashTemplate, + extract: hashTemplate, + file: hashTemplate, + script: hashTemplate, + }; + case 'none': + default: + return { + chunk: '', + extract: '', + file: '', + script: '', + }; + } +} + +export type NormalizedEntryPoint = Required>; + +export function normalizeExtraEntryPoints( + extraEntryPoints: (ScriptElement | StyleElement)[], + defaultBundleName: string, +): NormalizedEntryPoint[] { + return extraEntryPoints.map((entry) => { + if (typeof entry === 'string') { + return { input: entry, inject: true, bundleName: defaultBundleName }; + } + + const { inject = true, ...newEntry } = entry; + let bundleName; + if (entry.bundleName) { + bundleName = entry.bundleName; + } else if (!inject) { + // Lazy entry points use the file name as bundle name. + bundleName = path.parse(entry.input).name; + } else { + bundleName = defaultBundleName; + } + + return { ...newEntry, inject, bundleName }; + }); +} + +export function assetNameTemplateFactory(hashFormat: HashFormat): (resourcePath: string) => string { + const visitedFiles = new Map(); + + return (resourcePath: string) => { + if (hashFormat.file) { + // File names are hashed therefore we don't need to handle files with the same file name. + return `[name]${hashFormat.file}.[ext]`; + } + + const filename = path.basename(resourcePath); + // Check if the file with the same name has already been processed. + const visited = visitedFiles.get(filename); + if (!visited) { + // Not visited. + visitedFiles.set(filename, resourcePath); + + return filename; + } else if (visited === resourcePath) { + // Same file. + return filename; + } + + // File has the same name but it's in a different location. + return '[path][name].[ext]'; + }; +} + +export function getInstrumentationExcludedPaths( + root: string, + excludedPaths: string[], +): Set { + const excluded = new Set(); + + for (const excludeGlob of excludedPaths) { + const excludePath = excludeGlob[0] === '/' ? excludeGlob.slice(1) : excludeGlob; + globSync(excludePath, { cwd: root }).forEach((p) => excluded.add(path.join(root, p))); + } + + return excluded; +} + +export function normalizeGlobalStyles(styleEntrypoints: StyleElement[]): { + entryPoints: Record; + noInjectNames: string[]; +} { + const entryPoints: Record = {}; + const noInjectNames: string[] = []; + + if (styleEntrypoints.length === 0) { + return { entryPoints, noInjectNames }; + } + + for (const style of normalizeExtraEntryPoints(styleEntrypoints, 'styles')) { + // Add style entry points. + entryPoints[style.bundleName] ??= []; + entryPoints[style.bundleName].push(style.input); + + // Add non injected styles to the list. + if (!style.inject) { + noInjectNames.push(style.bundleName); + } + } + + return { entryPoints, noInjectNames }; +} + +export function getCacheSettings( + wco: WebpackConfigOptions, + angularVersion: string, +): WebpackOptionsNormalized['cache'] { + const { enabled, path: cacheDirectory } = wco.buildOptions.cache; + if (enabled) { + return { + type: 'filesystem', + profile: wco.buildOptions.verbose, + cacheDirectory: path.join(cacheDirectory, 'angular-webpack'), + maxMemoryGenerations: 1, + // We use the versions and build options as the cache name. The Webpack configurations are too + // dynamic and shared among different build types: test, build and serve. + // None of which are "named". + name: createHash('sha1') + .update(angularVersion) + .update(VERSION) + .update(wco.projectRoot) + .update(JSON.stringify(wco.tsConfig)) + .update( + JSON.stringify({ + ...wco.buildOptions, + // Needed because outputPath changes on every build when using i18n extraction + // https://github.com/angular/angular-cli/blob/736a5f89deaca85f487b78aec9ff66d4118ceb6a/packages/angular_devkit/build_angular/src/utils/i18n-options.ts#L264-L265 + outputPath: undefined, + }), + ) + .digest('hex'), + }; + } + + if (wco.buildOptions.watch) { + return { + type: 'memory', + maxGenerations: 1, + }; + } + + return false; +} + +export function globalScriptsByBundleName( + scripts: ScriptElement[], +): { bundleName: string; inject: boolean; paths: string[] }[] { + return normalizeExtraEntryPoints(scripts, 'scripts').reduce( + (prev: { bundleName: string; paths: string[]; inject: boolean }[], curr) => { + const { bundleName, inject, input } = curr; + + const existingEntry = prev.find((el) => el.bundleName === bundleName); + if (existingEntry) { + if (existingEntry.inject && !inject) { + // All entries have to be lazy for the bundle to be lazy. + throw new Error(`The ${bundleName} bundle is mixing injected and non-injected scripts.`); + } + + existingEntry.paths.push(input); + } else { + prev.push({ + bundleName, + inject, + paths: [input], + }); + } + + return prev; + }, + [], + ); +} + +export function assetPatterns(root: string, assets: AssetPatternClass[]) { + return assets.map((asset: AssetPatternClass, index: number): ObjectPattern => { + // Resolve input paths relative to workspace root and add slash at the end. + // eslint-disable-next-line prefer-const + let { input, output = '', ignore = [], glob } = asset; + input = path.resolve(root, input).replace(/\\/g, '/'); + input = input.endsWith('/') ? input : input + '/'; + output = output.endsWith('/') ? output : output + '/'; + + if (output.startsWith('..')) { + throw new Error('An asset cannot be written to a location outside of the output path.'); + } + + return { + context: input, + // Now we remove starting slash to make Webpack place it from the output root. + to: output.replace(/^\//, ''), + from: glob, + noErrorOnMissing: true, + force: true, + globOptions: { + dot: true, + followSymbolicLinks: !!asset.followSymlinks, + ignore: [ + '.gitkeep', + '**/.DS_Store', + '**/Thumbs.db', + // Negate patterns needs to be absolute because copy-webpack-plugin uses absolute globs which + // causes negate patterns not to match. + // See: https://github.com/webpack-contrib/copy-webpack-plugin/issues/498#issuecomment-639327909 + ...ignore, + ].map((i) => path.posix.join(input, i)), + }, + priority: index, + }; + }); +} + +export function getStatsOptions(verbose = false): WebpackStatsOptions { + const webpackOutputOptions: WebpackStatsOptions = { + all: false, // Fallback value for stats options when an option is not defined. It has precedence over local webpack defaults. + colors: true, + hash: true, // required by custom stat output + timings: true, // required by custom stat output + chunks: true, // required by custom stat output + builtAt: true, // required by custom stat output + warnings: true, + errors: true, + assets: true, // required by custom stat output + cachedAssets: true, // required for bundle size calculators + + // Needed for markAsyncChunksNonInitial. + ids: true, + entrypoints: true, + }; + + const verboseWebpackOutputOptions: WebpackStatsOptions = { + // The verbose output will most likely be piped to a file, so colors just mess it up. + colors: false, + usedExports: true, + optimizationBailout: true, + reasons: true, + children: true, + assets: true, + version: true, + chunkModules: true, + errorDetails: true, + errorStack: true, + moduleTrace: true, + logging: 'verbose', + modulesSpace: Infinity, + }; + + return verbose + ? { ...webpackOutputOptions, ...verboseWebpackOutputOptions } + : webpackOutputOptions; +} + +/** + * Checks if a specified package is installed in the given workspace. + * + * @param root - The root directory of the workspace. + * @param name - The name of the package to check for. + * @returns `true` if the package is installed, `false` otherwise. + */ +export function isPackageInstalled(root: string, name: string): boolean { + try { + const resolve = createRequire(root + '/').resolve; + resolve(name); + + return true; + } catch { + return false; + } +} diff --git a/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts b/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts new file mode 100644 index 000000000000..3bd046cbae15 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/tools/webpack/utils/stats.ts @@ -0,0 +1,367 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { + BudgetCalculatorResult, + BundleStats, + generateBuildStatsTable, +} from '@angular/build/private'; +import { WebpackLoggingCallback } from '@angular-devkit/build-webpack'; +import { logging } from '@angular-devkit/core'; +import assert from 'node:assert'; +import * as path from 'node:path'; +import { Configuration, StatsCompilation } from 'webpack'; +import { Schema as BrowserBuilderOptions } from '../../../builders/browser/schema'; +import { normalizeOptimization } from '../../../utils'; +import { colors as ansiColors } from '../../../utils/color'; +import { markAsyncChunksNonInitial } from './async-chunks'; +import { WebpackStatsOptions, getStatsOptions, normalizeExtraEntryPoints } from './helpers'; + +function getBuildDuration(webpackStats: StatsCompilation): number { + assert(webpackStats.builtAt, 'buildAt cannot be undefined'); + assert(webpackStats.time, 'time cannot be undefined'); + + return Date.now() - webpackStats.builtAt + webpackStats.time; +} + +function generateBundleStats(info: { + rawSize?: number; + estimatedTransferSize?: number; + files?: string[]; + names?: string[]; + initial?: boolean; + rendered?: boolean; +}): BundleStats { + const rawSize = typeof info.rawSize === 'number' ? info.rawSize : '-'; + const estimatedTransferSize = + typeof info.estimatedTransferSize === 'number' ? info.estimatedTransferSize : '-'; + const files = + info.files + ?.filter((f) => !f.endsWith('.map')) + .map((f) => path.basename(f)) + .join(', ') ?? ''; + const names = info.names?.length ? info.names.join(', ') : '-'; + const initial = !!info.initial; + + return { + initial, + stats: [files, names, rawSize, estimatedTransferSize], + }; +} + +// We use this cache because we can have multiple builders running in the same process, +// where each builder has different output path. + +// Ideally, we should create the logging callback as a factory, but that would need a refactoring. +const runsCache = new Set(); + +function statsToString( + json: StatsCompilation, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + statsConfig: any, + budgetFailures?: BudgetCalculatorResult[], +): string { + if (!json.chunks?.length) { + return ''; + } + + const colors = statsConfig.colors; + const rs = (x: string) => (colors ? ansiColors.reset(x) : x); + const w = (x: string) => (colors ? ansiColors.bold.white(x) : x); + + const changedChunksStats: BundleStats[] = []; + let hasEstimatedTransferSizes = false; + + const isFirstRun = !runsCache.has(json.outputPath || ''); + + for (const chunk of json.chunks) { + // During first build we want to display unchanged chunks + // but unchanged cached chunks are always marked as not rendered. + if (!isFirstRun && !chunk.rendered) { + continue; + } + + const assets = json.assets?.filter((asset) => chunk.files?.includes(asset.name)); + let rawSize = 0; + let estimatedTransferSize; + if (assets) { + for (const asset of assets) { + if (asset.name.endsWith('.map')) { + continue; + } + + rawSize += asset.size; + + if (typeof asset.info.estimatedTransferSize === 'number') { + if (estimatedTransferSize === undefined) { + estimatedTransferSize = 0; + hasEstimatedTransferSizes = true; + } + estimatedTransferSize += asset.info.estimatedTransferSize; + } + } + } + changedChunksStats.push(generateBundleStats({ ...chunk, rawSize, estimatedTransferSize })); + } + const unchangedChunkNumber = json.chunks.length - changedChunksStats.length; + + runsCache.add(json.outputPath || ''); + + const statsTable = generateBuildStatsTable( + changedChunksStats, + colors, + unchangedChunkNumber === 0, + hasEstimatedTransferSizes, + budgetFailures, + ); + + // In some cases we do things outside of webpack context + // Such us index generation, service worker augmentation etc... + // This will correct the time and include these. + const time = getBuildDuration(json); + + return rs( + `\n${statsTable}\n\n` + + (unchangedChunkNumber > 0 ? `${unchangedChunkNumber} unchanged chunks\n\n` : '') + + `Build at: ${w(new Date().toISOString())} - Hash: ${w(json.hash || '')} - Time: ${w('' + time)}ms`, + ); +} + +export function statsWarningsToString( + json: StatsCompilation, + statsConfig: WebpackStatsOptions, +): string { + const colors = statsConfig.colors; + const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x); + const y = (x: string) => (colors ? ansiColors.reset.yellow(x) : x); + const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x); + + const warnings = json.warnings ? [...json.warnings] : []; + if (json.children) { + warnings.push(...json.children.map((c) => c.warnings ?? []).reduce((a, b) => [...a, ...b], [])); + } + + let output = ''; + for (const warning of warnings) { + if (typeof warning === 'string') { + output += yb(`Warning: ${warning}\n\n`); + } else { + let file = warning.file || warning.moduleName; + // Clean up warning paths + // Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js.... + // to ./src/app/styles.scss.webpack + if (file && !statsConfig.errorDetails) { + const webpackPathIndex = file.indexOf('.webpack['); + if (webpackPathIndex !== -1) { + file = file.substring(0, webpackPathIndex); + } + } + + if (file) { + output += c(file); + if (warning.loc) { + output += ':' + yb(warning.loc); + } + output += ' - '; + } + if (!/^warning/i.test(warning.message)) { + output += y('Warning: '); + } + output += `${warning.message}\n\n`; + } + } + + return output ? '\n' + output : output; +} + +export function statsErrorsToString( + json: StatsCompilation, + statsConfig: WebpackStatsOptions, +): string { + const colors = statsConfig.colors; + const c = (x: string) => (colors ? ansiColors.reset.cyan(x) : x); + const yb = (x: string) => (colors ? ansiColors.reset.yellowBright(x) : x); + const r = (x: string) => (colors ? ansiColors.reset.redBright(x) : x); + + const errors = json.errors ? [...json.errors] : []; + if (json.children) { + errors.push(...json.children.map((c) => c?.errors || []).reduce((a, b) => [...a, ...b], [])); + } + + let output = ''; + for (const error of errors) { + if (typeof error === 'string') { + output += r(`Error: ${error}\n\n`); + } else { + let file = error.file || error.moduleName; + // Clean up error paths + // Ex: ./src/app/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js.... + // to ./src/app/styles.scss.webpack + if (file && !statsConfig.errorDetails) { + const webpackPathIndex = file.indexOf('.webpack['); + if (webpackPathIndex !== -1) { + file = file.substring(0, webpackPathIndex); + } + } + + if (file) { + output += c(file); + if (error.loc) { + output += ':' + yb(error.loc); + } + output += ' - '; + } + + // In most cases webpack will add stack traces to error messages. + // This below cleans up the error from stacks. + // See: https://github.com/webpack/webpack/issues/15980 + const index = error.message.search(/[\n\s]+at /); + let message = + statsConfig.errorStack || index === -1 ? error.message : error.message.substring(0, index); + + // Clean up error message paths when not verbose + // Ex: Execution of module code from module graph (./src/styles.scss.webpack[javascript/auto]!=!...) failed + // to Execution of module code from module graph (./src/styles.scss) failed + if (message && !statsConfig.errorDetails) { + message = message.replace(/([^(\s]+)\.webpack\[[^\]]+\]!=![^\s)]+/g, '$1'); + } + + if (!/^error/i.test(message)) { + output += r('Error: '); + } + output += `${message}\n\n`; + } + } + + return output ? '\n' + output : output; +} + +export function statsHasErrors(json: StatsCompilation): boolean { + return !!(json.errors?.length || json.children?.some((c) => c.errors?.length)); +} + +export function statsHasWarnings(json: StatsCompilation): boolean { + return !!(json.warnings?.length || json.children?.some((c) => c.warnings?.length)); +} + +export function createWebpackLoggingCallback( + options: BrowserBuilderOptions, + logger: logging.LoggerApi, +): WebpackLoggingCallback { + const { verbose = false, scripts = [], styles = [] } = options; + const extraEntryPoints = [ + ...normalizeExtraEntryPoints(styles, 'styles'), + ...normalizeExtraEntryPoints(scripts, 'scripts'), + ]; + + return (stats, config) => { + if (verbose && config.stats !== false) { + const statsOptions = config.stats === true ? undefined : config.stats; + logger.info(stats.toString(statsOptions)); + } + + const rawStats = stats.toJson(getStatsOptions(false)); + const webpackStats = { + ...rawStats, + chunks: markAsyncChunksNonInitial(rawStats, extraEntryPoints), + }; + + webpackStatsLogger(logger, webpackStats, config); + }; +} + +export interface BuildEventStats { + aot: boolean; + optimization: boolean; + allChunksCount: number; + lazyChunksCount: number; + initialChunksCount: number; + changedChunksCount?: number; + durationInMs: number; + cssSizeInBytes: number; + jsSizeInBytes: number; + ngComponentCount: number; +} + +export function generateBuildEventStats( + webpackStats: StatsCompilation, + browserBuilderOptions: BrowserBuilderOptions, +): BuildEventStats { + const { chunks = [], assets = [] } = webpackStats; + + let jsSizeInBytes = 0; + let cssSizeInBytes = 0; + let initialChunksCount = 0; + let ngComponentCount = 0; + let changedChunksCount = 0; + + const allChunksCount = chunks.length; + const isFirstRun = !runsCache.has(webpackStats.outputPath || ''); + + const chunkFiles = new Set(); + for (const chunk of chunks) { + if (!isFirstRun && chunk.rendered) { + changedChunksCount++; + } + + if (chunk.initial) { + initialChunksCount++; + } + + for (const file of chunk.files ?? []) { + chunkFiles.add(file); + } + } + + for (const asset of assets) { + if (asset.name.endsWith('.map') || !chunkFiles.has(asset.name)) { + continue; + } + + if (asset.name.endsWith('.js')) { + jsSizeInBytes += asset.size; + ngComponentCount += asset.info.ngComponentCount ?? 0; + } else if (asset.name.endsWith('.css')) { + cssSizeInBytes += asset.size; + } + } + + return { + optimization: !!normalizeOptimization(browserBuilderOptions.optimization).scripts, + aot: browserBuilderOptions.aot !== false, + allChunksCount, + lazyChunksCount: allChunksCount - initialChunksCount, + initialChunksCount, + changedChunksCount, + durationInMs: getBuildDuration(webpackStats), + cssSizeInBytes, + jsSizeInBytes, + ngComponentCount, + }; +} + +export function webpackStatsLogger( + logger: logging.LoggerApi, + json: StatsCompilation, + config: Configuration, + budgetFailures?: BudgetCalculatorResult[], +): void { + logger.info(statsToString(json, config.stats, budgetFailures)); + + if (typeof config.stats !== 'object') { + throw new Error('Invalid Webpack stats configuration.'); + } + + if (statsHasWarnings(json)) { + logger.warn(statsWarningsToString(json, config.stats)); + } + + if (statsHasErrors(json)) { + logger.error(statsErrorsToString(json, config.stats)); + } +} diff --git a/packages/angular_devkit/build_angular/src/transforms.ts b/packages/angular_devkit/build_angular/src/transforms.ts index c724aedab646..6ae0678cd2da 100644 --- a/packages/angular_devkit/build_angular/src/transforms.ts +++ b/packages/angular_devkit/build_angular/src/transforms.ts @@ -1,8 +1,9 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + export type ExecutionTransformer = (input: T) => T | Promise; diff --git a/packages/angular_devkit/build_angular/src/tslint/index.ts b/packages/angular_devkit/build_angular/src/tslint/index.ts deleted file mode 100644 index 0801bb0c514a..000000000000 --- a/packages/angular_devkit/build_angular/src/tslint/index.ts +++ /dev/null @@ -1,254 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; -import { json } from '@angular-devkit/core'; -import { readFileSync } from 'fs'; -import * as glob from 'glob'; -import { Minimatch } from 'minimatch'; -import * as path from 'path'; -import * as tslint from 'tslint'; // tslint:disable-line:no-implicit-dependencies -import { Program } from 'typescript'; -import { stripBom } from '../angular-cli-files/utilities/strip-bom'; -import { Schema as RealTslintBuilderOptions } from './schema'; - - -type TslintBuilderOptions = RealTslintBuilderOptions & json.JsonObject; -interface LintResult extends tslint.LintResult { - fileNames: string[]; -} - -async function _loadTslint() { - let tslint; - try { - tslint = await import('tslint'); // tslint:disable-line:no-implicit-dependencies - } catch { - throw new Error('Unable to find TSLint. Ensure TSLint is installed.'); - } - - const version = tslint.Linter.VERSION && tslint.Linter.VERSION.split('.'); - if ( - !version || version.length < 2 - || (Number(version[0]) === 5 && Number(version[1]) < 5) // 5.5+ - || Number(version[0]) < 5 // 6.0+ - ) { - throw new Error('TSLint must be version 5.5 or higher.'); - } - - return tslint; -} - - -async function _run( - options: TslintBuilderOptions, - context: BuilderContext, -): Promise { - const systemRoot = context.workspaceRoot; - process.chdir(context.currentDirectory); - const projectName = (context.target && context.target.project) || ''; - - // Print formatter output only for non human-readable formats. - const printInfo = - ['prose', 'verbose', 'stylish'].includes(options.format || '') && !options.silent; - - context.reportStatus(`Linting ${JSON.stringify(projectName)}...`); - if (printInfo) { - context.logger.info(`Linting ${JSON.stringify(projectName)}...`); - } - - if (!options.tsConfig && options.typeCheck) { - throw new Error('A "project" must be specified to enable type checking.'); - } - - const projectTslint = await _loadTslint(); - const tslintConfigPath = options.tslintConfig - ? path.resolve(systemRoot, options.tslintConfig) - : null; - const Linter = projectTslint.Linter; - - let result: undefined | LintResult = undefined; - if (options.tsConfig) { - const tsConfigs = Array.isArray(options.tsConfig) ? options.tsConfig : [options.tsConfig]; - context.reportProgress(0, tsConfigs.length); - const allPrograms = tsConfigs.map(tsConfig => { - return Linter.createProgram(path.resolve(systemRoot, tsConfig)); - }); - - let i = 0; - for (const program of allPrograms) { - const partial = await _lint( - projectTslint, - systemRoot, - tslintConfigPath, - options, - program, - allPrograms, - ); - if (result === undefined) { - result = partial; - } else { - result.failures = result.failures - .filter(curr => { - return !partial.failures.some(prev => curr.equals(prev)); - }) - .concat(partial.failures); - - // we are not doing much with 'errorCount' and 'warningCount' - // apart from checking if they are greater than 0 thus no need to dedupe these. - result.errorCount += partial.errorCount; - result.warningCount += partial.warningCount; - result.fileNames = [...new Set([...result.fileNames, ...partial.fileNames])]; - - if (partial.fixes) { - result.fixes = result.fixes ? result.fixes.concat(partial.fixes) : partial.fixes; - } - } - - context.reportProgress(++i, allPrograms.length); - } - } else { - result = await _lint(projectTslint, systemRoot, tslintConfigPath, options); - } - - if (result == undefined) { - throw new Error('Invalid lint configuration. Nothing to lint.'); - } - - if (!options.silent) { - const Formatter = projectTslint.findFormatter(options.format || ''); - if (!Formatter) { - throw new Error(`Invalid lint format "${options.format}".`); - } - const formatter = new Formatter(); - - const output = formatter.format(result.failures, result.fixes, result.fileNames); - if (output.trim()) { - context.logger.info(output); - } - } - - if (result.warningCount > 0 && printInfo) { - context.logger.warn('Lint warnings found in the listed files.'); - } - - if (result.errorCount > 0 && printInfo) { - context.logger.error('Lint errors found in the listed files.'); - } - - if (result.warningCount === 0 && result.errorCount === 0 && printInfo) { - context.logger.info('All files pass linting.'); - } - - return { - success: options.force || result.errorCount === 0, - }; -} - - -export default createBuilder(_run); - - -async function _lint( - projectTslint: typeof tslint, - systemRoot: string, - tslintConfigPath: string | null, - options: TslintBuilderOptions, - program?: Program, - allPrograms?: Program[], -): Promise { - const Linter = projectTslint.Linter; - const Configuration = projectTslint.Configuration; - - const files = getFilesToLint(systemRoot, options, Linter, program); - const lintOptions = { - fix: !!options.fix, - formatter: options.format, - }; - - const linter = new Linter(lintOptions, program); - - let lastDirectory: string | undefined = undefined; - let configLoad; - const lintedFiles: string[] = []; - for (const file of files) { - if (program && allPrograms) { - // If it cannot be found in ANY program, then this is an error. - if (allPrograms.every(p => p.getSourceFile(file) === undefined)) { - throw new Error( - `File ${JSON.stringify(file)} is not part of a TypeScript project '${options.tsConfig}'.`, - ); - } else if (program.getSourceFile(file) === undefined) { - // The file exists in some other programs. We will lint it later (or earlier) in the loop. - continue; - } - } - - const contents = getFileContents(file); - - // Only check for a new tslint config if the path changes. - const currentDirectory = path.dirname(file); - if (currentDirectory !== lastDirectory) { - configLoad = Configuration.findConfiguration(tslintConfigPath, file); - lastDirectory = currentDirectory; - } - - if (configLoad) { - // Give some breathing space to other promises that might be waiting. - await Promise.resolve(); - linter.lint(file, contents, configLoad.results); - lintedFiles.push(file); - } - } - - return { - ...linter.getResult(), - fileNames: lintedFiles, - }; -} - -function getFilesToLint( - root: string, - options: TslintBuilderOptions, - linter: typeof tslint.Linter, - program?: Program, -): string[] { - const ignore = options.exclude; - const files = options.files || []; - - if (files.length > 0) { - return files - .map(file => glob.sync(file, { cwd: root, ignore, nodir: true })) - .reduce((prev, curr) => prev.concat(curr), []) - .map(file => path.join(root, file)); - } - - if (!program) { - return []; - } - - let programFiles = linter.getFileNames(program); - - if (ignore && ignore.length > 0) { - // normalize to support ./ paths - const ignoreMatchers = ignore - .map(pattern => new Minimatch(path.normalize(pattern), { dot: true })); - - programFiles = programFiles - .filter(file => !ignoreMatchers.some(matcher => matcher.match(path.relative(root, file)))); - } - - return programFiles; -} - -function getFileContents(file: string): string { - // NOTE: The tslint CLI checks for and excludes MPEG transport streams; this does not. - try { - return stripBom(readFileSync(file, 'utf-8')); - } catch { - throw new Error(`Could not read file '${file}'.`); - } -} diff --git a/packages/angular_devkit/build_angular/src/tslint/schema.json b/packages/angular_devkit/build_angular/src/tslint/schema.json deleted file mode 100644 index cbe1d6779bff..000000000000 --- a/packages/angular_devkit/build_angular/src/tslint/schema.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "title": "TSlint Target", - "description": "TSlint target options for Build Facade.", - "type": "object", - "properties": { - "tslintConfig": { - "type": "string", - "description": "The name of the TSLint configuration file." - }, - "tsConfig": { - "description": "The name of the TypeScript configuration file.", - "oneOf": [ - { "type": "string" }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "fix": { - "type": "boolean", - "description": "Fixes linting errors (may overwrite linted files).", - "default": false - }, - "typeCheck": { - "type": "boolean", - "description": "Controls the type check for linting.", - "default": false - }, - "force": { - "type": "boolean", - "description": "Succeeds even if there was linting errors.", - "default": false - }, - "silent": { - "type": "boolean", - "description": "Show output text.", - "default": false - }, - "format": { - "type": "string", - "description": "Output format (prose, json, stylish, verbose, pmd, msbuild, checkstyle, vso, fileslist).", - "default": "prose", - "anyOf": [ - { - "enum": [ - "checkstyle", - "codeFrame", - "filesList", - "json", - "junit", - "msbuild", - "pmd", - "prose", - "stylish", - "tap", - "verbose", - "vso" - ] - }, - { "minLength": 1 } - ] - }, - "exclude": { - "type": "array", - "description": "Files to exclude from linting.", - "default": [], - "items": { - "type": "string" - } - }, - "files": { - "type": "array", - "description": "Files to include in linting.", - "default": [], - "items": { - "type": "string" - } - } - }, - "additionalProperties": false, - "required": [] -} \ No newline at end of file diff --git a/packages/angular_devkit/build_angular/src/utils/action-cache.ts b/packages/angular_devkit/build_angular/src/utils/action-cache.ts deleted file mode 100644 index bb8f9695201e..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/action-cache.ts +++ /dev/null @@ -1,171 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { createHash } from 'crypto'; -import * as fs from 'fs'; -import { copyFile } from './copy-file'; -import { manglingDisabled } from './environment-options'; -import { CacheKey, ProcessBundleOptions, ProcessBundleResult } from './process-bundle'; - -const cacache = require('cacache'); -const packageVersion = require('../../package.json').version; - -export interface CacheEntry { - path: string; - size: number; - integrity?: string; -} - -export class BundleActionCache { - constructor(private readonly cachePath: string, private readonly integrityAlgorithm?: string) {} - - static copyEntryContent(entry: CacheEntry | string, dest: fs.PathLike): void { - copyFile(typeof entry === 'string' ? entry : entry.path, dest); - - if (process.platform !== 'win32') { - // The cache writes entries as readonly and when using copyFile the permissions will also be copied. - // See: https://github.com/npm/cacache/blob/073fbe1a9f789ba42d9a41de7b8429c93cf61579/lib/util/move-file.js#L36 - fs.chmodSync(dest, 0o644); - } - } - - generateBaseCacheKey(content: string): string { - // Create base cache key with elements: - // * package version - different build-angular versions cause different final outputs - // * code length/hash - ensure cached version matches the same input code - const algorithm = this.integrityAlgorithm || 'sha1'; - const codeHash = createHash(algorithm) - .update(content) - .digest('base64'); - let baseCacheKey = `${packageVersion}|${content.length}|${algorithm}-${codeHash}`; - if (manglingDisabled) { - baseCacheKey += '|MD'; - } - - return baseCacheKey; - } - - generateCacheKeys(action: ProcessBundleOptions): string[] { - const baseCacheKey = this.generateBaseCacheKey(action.code); - - // Postfix added to sourcemap cache keys when vendor sourcemaps are present - // Allows non-destructive caching of both variants - const SourceMapVendorPostfix = !!action.sourceMaps && action.vendorSourceMaps ? '|vendor' : ''; - - // Determine cache entries required based on build settings - const cacheKeys = []; - - // If optimizing and the original is not ignored, add original as required - if ((action.optimize || action.optimizeOnly) && !action.ignoreOriginal) { - cacheKeys[CacheKey.OriginalCode] = baseCacheKey + '|orig'; - - // If sourcemaps are enabled, add original sourcemap as required - if (action.sourceMaps) { - cacheKeys[CacheKey.OriginalMap] = baseCacheKey + SourceMapVendorPostfix + '|orig-map'; - } - } - // If not only optimizing, add downlevel as required - if (!action.optimizeOnly) { - cacheKeys[CacheKey.DownlevelCode] = baseCacheKey + '|dl'; - - // If sourcemaps are enabled, add downlevel sourcemap as required - if (action.sourceMaps) { - cacheKeys[CacheKey.DownlevelMap] = baseCacheKey + SourceMapVendorPostfix + '|dl-map'; - } - } - - return cacheKeys; - } - - async getCacheEntries(cacheKeys: (string | null)[]): Promise<(CacheEntry | null)[] | false> { - // Attempt to get required cache entries - const cacheEntries = []; - for (const key of cacheKeys) { - if (key) { - const entry = await cacache.get.info(this.cachePath, key); - if (!entry) { - return false; - } - cacheEntries.push({ - path: entry.path, - size: entry.size, - integrity: entry.metadata && entry.metadata.integrity, - }); - } else { - cacheEntries.push(null); - } - } - - return cacheEntries; - } - - async getCachedBundleResult(action: ProcessBundleOptions): Promise { - const entries = action.cacheKeys && await this.getCacheEntries(action.cacheKeys); - if (!entries) { - return null; - } - - const result: ProcessBundleResult = { name: action.name }; - - let cacheEntry = entries[CacheKey.OriginalCode]; - if (cacheEntry) { - result.original = { - filename: action.filename, - size: cacheEntry.size, - integrity: cacheEntry.integrity, - }; - - BundleActionCache.copyEntryContent(cacheEntry, result.original.filename); - - cacheEntry = entries[CacheKey.OriginalMap]; - if (cacheEntry) { - result.original.map = { - filename: action.filename + '.map', - size: cacheEntry.size, - }; - - BundleActionCache.copyEntryContent(cacheEntry, result.original.filename + '.map'); - } - } else if (!action.ignoreOriginal) { - // If the original wasn't processed (and therefore not cached), add info - result.original = { - filename: action.filename, - size: Buffer.byteLength(action.code, 'utf8'), - map: - action.map === undefined - ? undefined - : { - filename: action.filename + '.map', - size: Buffer.byteLength(action.map, 'utf8'), - }, - }; - } - - cacheEntry = entries[CacheKey.DownlevelCode]; - if (cacheEntry) { - result.downlevel = { - filename: action.filename.replace('es2015', 'es5'), - size: cacheEntry.size, - integrity: cacheEntry.integrity, - }; - - BundleActionCache.copyEntryContent(cacheEntry, result.downlevel.filename); - - cacheEntry = entries[CacheKey.DownlevelMap]; - if (cacheEntry) { - result.downlevel.map = { - filename: action.filename.replace('es2015', 'es5') + '.map', - size: cacheEntry.size, - }; - - BundleActionCache.copyEntryContent(cacheEntry, result.downlevel.filename + '.map'); - } - } - - return result; - } -} diff --git a/packages/angular_devkit/build_angular/src/utils/action-executor.ts b/packages/angular_devkit/build_angular/src/utils/action-executor.ts index 4e589af63de6..716729fe86ed 100644 --- a/packages/angular_devkit/build_angular/src/utils/action-executor.ts +++ b/packages/angular_devkit/build_angular/src/utils/action-executor.ts @@ -1,153 +1,72 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import JestWorker from 'jest-worker'; -import * as os from 'os'; -import * as path from 'path'; -import * as v8 from 'v8'; -import { BundleActionCache } from './action-cache'; -import { I18nOptions } from './i18n-options'; -import { InlineOptions, ProcessBundleOptions, ProcessBundleResult } from './process-bundle'; -const hasThreadSupport = (() => { - try { - require('worker_threads'); +import Piscina from 'piscina'; +import { InlineOptions } from './bundle-inline-options'; +import { maxWorkers } from './environment-options'; +import { I18nOptions } from './i18n-webpack'; - return true; - } catch { - return false; - } -})(); - -// This is used to normalize serialization messaging across threads and processes -// Threads use the structured clone algorithm which handles more types -// Processes use JSON which is much more limited -const serialize = ((v8 as unknown) as { serialize(value: unknown): Buffer }).serialize; - -let workerFile = require.resolve('./process-bundle'); -workerFile = - path.extname(workerFile) === '.ts' - ? require.resolve('./process-bundle-bootstrap') - : workerFile; +const workerFile = require.resolve('./process-bundle'); export class BundleActionExecutor { - private largeWorker?: JestWorker; - private smallWorker?: JestWorker; - private cache?: BundleActionCache; - - constructor( - private workerOptions: { cachePath?: string; i18n: I18nOptions }, - integrityAlgorithm?: string, - private readonly sizeThreshold = 32 * 1024, - ) { - if (workerOptions.cachePath) { - this.cache = new BundleActionCache(workerOptions.cachePath, integrityAlgorithm); - } - } - - private static executeMethod(worker: JestWorker, method: string, input: unknown): Promise { - return ((worker as unknown) as Record Promise>)[method](input); - } - - private ensureLarge(): JestWorker { - if (this.largeWorker) { - return this.largeWorker; - } - - // larger files are processed in a separate process to limit memory usage in the main process - return (this.largeWorker = new JestWorker(workerFile, { - exposedMethods: ['process', 'inlineLocales'], - setupArgs: [[...serialize(this.workerOptions)]], - })); - } - - private ensureSmall(): JestWorker { - if (this.smallWorker) { - return this.smallWorker; - } + private workerPool?: Piscina; - // small files are processed in a limited number of threads to improve speed - // The limited number also prevents a large increase in memory usage for an otherwise short operation - return (this.smallWorker = new JestWorker(workerFile, { - exposedMethods: ['process', 'inlineLocales'], - setupArgs: hasThreadSupport ? [this.workerOptions] : [[...serialize(this.workerOptions)]], - numWorkers: os.cpus().length < 2 ? 1 : 2, - enableWorkerThreads: hasThreadSupport, - })); - } + constructor(private workerOptions: { i18n: I18nOptions }) {} - private executeAction(method: string, action: { code: string }): Promise { - // code.length is not an exact byte count but close enough for this - if (action.code.length > this.sizeThreshold) { - return BundleActionExecutor.executeMethod(this.ensureLarge(), method, action); - } else { - return BundleActionExecutor.executeMethod(this.ensureSmall(), method, action); + private ensureWorkerPool(): Piscina { + if (this.workerPool) { + return this.workerPool; } - } - async process(action: ProcessBundleOptions): Promise { - if (this.cache) { - const cacheKeys = this.cache.generateCacheKeys(action); - action.cacheKeys = cacheKeys; + this.workerPool = new Piscina({ + filename: workerFile, + name: 'inlineLocales', + workerData: this.workerOptions, + maxThreads: maxWorkers, + recordTiming: false, + }); - // Try to get cached data, if it fails fallback to processing - try { - const cachedResult = await this.cache.getCachedBundleResult(action); - if (cachedResult) { - return cachedResult; - } - } catch {} - } - - return this.executeAction('process', action); - } - - processAll(actions: Iterable): AsyncIterable { - return BundleActionExecutor.executeAll(actions, action => this.process(action)); + return this.workerPool; } async inline( action: InlineOptions, ): Promise<{ file: string; diagnostics: { type: string; message: string }[]; count: number }> { - return this.executeAction('inlineLocales', action); + return this.ensureWorkerPool().run(action, { name: 'inlineLocales' }); } inlineAll(actions: Iterable) { - return BundleActionExecutor.executeAll(actions, action => this.inline(action)); + return BundleActionExecutor.executeAll(actions, (action) => this.inline(action)); } private static async *executeAll( actions: Iterable, executor: (action: I) => Promise, ): AsyncIterable { - const executions = new Map, Promise>(); + const executions = new Map, Promise<[Promise, O]>>(); for (const action of actions) { const execution = executor(action); executions.set( execution, - execution.then(result => { - executions.delete(execution); - - return result; - }), + execution.then((result) => [execution, result]), ); } while (executions.size > 0) { - yield Promise.race(executions.values()); + const [execution, result] = await Promise.race(executions.values()); + executions.delete(execution); + yield result; } } stop(): void { - if (this.largeWorker) { - this.largeWorker.end(); - } - if (this.smallWorker) { - this.smallWorker.end(); + if (this.workerPool) { + void this.workerPool.destroy(); } } } diff --git a/packages/angular_devkit/build_angular/src/utils/build-browser-features.ts b/packages/angular_devkit/build_angular/src/utils/build-browser-features.ts deleted file mode 100644 index cfd3e58dda4c..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/build-browser-features.ts +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import * as browserslist from 'browserslist'; -import { feature, features } from 'caniuse-lite'; -import * as ts from 'typescript'; - -export class BuildBrowserFeatures { - private readonly _supportedBrowsers: string[]; - private readonly _es6TargetOrLater: boolean; - - constructor( - private projectRoot: string, - private scriptTarget: ts.ScriptTarget, - ) { - this._supportedBrowsers = browserslist(undefined, { path: this.projectRoot }); - this._es6TargetOrLater = this.scriptTarget > ts.ScriptTarget.ES5; - } - - /** - * True, when one or more browsers requires ES5 - * support and the scirpt target is ES2015 or greater. - */ - isDifferentialLoadingNeeded(): boolean { - return this._es6TargetOrLater && this.isEs5SupportNeeded(); - } - - /** - * True, when one or more browsers requires ES5 support - */ - isEs5SupportNeeded(): boolean { - return !this.isFeatureSupported('es6-module'); - } - - /** - * Safari 10.1 and iOS Safari 10.3 supports modules, - * but does not support the `nomodule` attribute. - * While return `true`, when support for Safari 10.1 and iOS Safari 10.3 - * is required and in differential loading is enabled. - */ - isNoModulePolyfillNeeded(): boolean { - if (!this.isDifferentialLoadingNeeded()) { - return false; - } - - const safariBrowsers = [ - 'safari 10.1', - 'ios_saf 10.3', - ]; - - return this._supportedBrowsers.some(browser => safariBrowsers.includes(browser)); - } - - /** - * True, when a browser feature is supported partially or fully. - */ - isFeatureSupported(featureId: string): boolean { - // y: feature is fully available - // n: feature is unavailable - // a: feature is partially supported - // x: feature is prefixed - const criteria = [ - 'y', - 'a', - ]; - - const data = feature(features[featureId]); - - return !this._supportedBrowsers - .some(browser => { - const [agentId, version] = browser.split(' '); - - const browserData = data.stats[agentId]; - const featureStatus = (browserData && browserData[version]) as string | undefined; - - // We are only interested in the first character - // Ex: when 'a #4 #5', we only need to check for 'a' - // as for such cases we should polyfill these features as needed - return !featureStatus || !criteria.includes(featureStatus.charAt(0)); - }); - } -} diff --git a/packages/angular_devkit/build_angular/src/utils/build-browser-features_spec.ts b/packages/angular_devkit/build_angular/src/utils/build-browser-features_spec.ts deleted file mode 100644 index 0f111b563e1d..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/build-browser-features_spec.ts +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - - -import { TestProjectHost } from '@angular-devkit/architect/testing'; -import { getSystemPath, join } from '@angular-devkit/core'; -import { ScriptTarget } from 'typescript'; -import { BuildBrowserFeatures } from './build-browser-features'; - -const devkitRoot = (global as any)._DevKitRoot; // tslint:disable-line:no-any -const workspaceRoot = join( - devkitRoot, - 'tests/angular_devkit/build_angular/hello-world-app/'); - -const host = new TestProjectHost(workspaceRoot); - -describe('BuildBrowserFeatures', () => { - let workspaceRootSysPath = ''; - beforeEach(async () => { - await host.initialize().toPromise(); - workspaceRootSysPath = getSystemPath(host.root()); - }); - - afterEach(async () => host.restore().toPromise()); - - describe('isDifferentialLoadingNeeded', () => { - it('should be true for for IE 9-11 and ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': 'IE 9-11', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isDifferentialLoadingNeeded()).toBe(true); - }); - - it('should be false for Chrome and ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': 'last 1 chrome version', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isDifferentialLoadingNeeded()).toBe(false); - }); - - it('detects no need for differential loading for target is ES5', () => { - host.writeMultipleFiles({ - 'browserslist': 'last 1 chrome version', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES5, - ); - expect(buildBrowserFeatures.isDifferentialLoadingNeeded()).toBe(false); - }); - - it('should be false for Safari 10.1 when target is ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari 10.1', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isDifferentialLoadingNeeded()).toBe(false); - }); - }); - - describe('isFeatureSupported', () => { - it('should be true for es6-module and Safari 10.1', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari 10.1', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isFeatureSupported('es6-module')).toBe(true); - }); - - it('should be false for es6-module and IE9', () => { - host.writeMultipleFiles({ - 'browserslist': 'IE 9', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isFeatureSupported('es6-module')).toBe(false); - }); - - it('should be true for es6-module and last 1 chrome version', () => { - host.writeMultipleFiles({ - 'browserslist': 'last 1 chrome version', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isFeatureSupported('es6-module')).toBe(true); - }); - - it('should be true for es6-module and Edge 18', () => { - host.writeMultipleFiles({ - 'browserslist': 'Edge 18', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isFeatureSupported('es6-module')).toBe(true); - }); - }); - - describe('isNoModulePolyfillNeeded', () => { - it('should be false for Safari 10.1 when target is ES5', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari 10.1', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES5, - ); - expect(buildBrowserFeatures.isNoModulePolyfillNeeded()).toBe(false); - }); - - it('should be false for Safari 10.1 when target is ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari 10.1', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isNoModulePolyfillNeeded()).toBe(false); - }); - - it('should be true for Safari 9+ when target is ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari >= 9', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isNoModulePolyfillNeeded()).toBe(true); - }); - - it('should be false for Safari 9+ when target is ES5', () => { - host.writeMultipleFiles({ - 'browserslist': 'Safari >= 9', - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES5, - ); - expect(buildBrowserFeatures.isNoModulePolyfillNeeded()).toBe(false); - }); - - it('should be false when not supporting Safari 10.1 target is ES2015', () => { - host.writeMultipleFiles({ - 'browserslist': ` - Edge 18 - IE 9 - `, - }); - - const buildBrowserFeatures = new BuildBrowserFeatures( - workspaceRootSysPath, - ScriptTarget.ES2015, - ); - expect(buildBrowserFeatures.isNoModulePolyfillNeeded()).toBe(false); - }); - }); -}); diff --git a/packages/angular_devkit/build_angular/src/utils/build-options.ts b/packages/angular_devkit/build_angular/src/utils/build-options.ts new file mode 100644 index 000000000000..9ffd13f517d3 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/build-options.ts @@ -0,0 +1,90 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ParsedConfiguration } from '@angular/compiler-cli'; +import { logging } from '@angular-devkit/core'; +import { + AssetPatternClass, + Budget, + CrossOrigin, + I18NTranslation, + IndexUnion, + InlineStyleLanguage, + Localize, + OutputHashing, + ScriptElement, + SourceMapClass, + StyleElement, +} from '../builders/browser/schema'; +import { Schema as DevServerSchema } from '../builders/dev-server/schema'; +import { NormalizedCachedOptions } from './normalize-cache'; +import { NormalizedFileReplacement } from './normalize-file-replacements'; +import { NormalizedOptimizationOptions } from './normalize-optimization'; + +export interface BuildOptions { + optimization: NormalizedOptimizationOptions; + environment?: string; + outputPath: string; + resourcesOutputPath?: string; + aot?: boolean; + sourceMap: SourceMapClass; + vendorChunk?: boolean; + commonChunk?: boolean; + baseHref?: string; + deployUrl?: string; + verbose?: boolean; + progress?: boolean; + localize?: Localize; + i18nMissingTranslation?: I18NTranslation; + externalDependencies?: string[]; + watch?: boolean; + outputHashing?: OutputHashing; + poll?: number; + index?: IndexUnion; + deleteOutputPath?: boolean; + preserveSymlinks?: boolean; + extractLicenses?: boolean; + buildOptimizer?: boolean; + namedChunks?: boolean; + crossOrigin?: CrossOrigin; + subresourceIntegrity?: boolean; + serviceWorker?: boolean; + webWorkerTsConfig?: string; + statsJson: boolean; + hmr?: boolean; + main: string; + polyfills: string[]; + budgets: Budget[]; + assets: AssetPatternClass[]; + scripts: ScriptElement[]; + styles: StyleElement[]; + stylePreprocessorOptions?: { includePaths: string[] }; + platform?: 'browser' | 'server'; + fileReplacements: NormalizedFileReplacement[]; + inlineStyleLanguage?: InlineStyleLanguage; + allowedCommonJsDependencies?: string[]; + cache: NormalizedCachedOptions; + codeCoverage?: boolean; + codeCoverageExclude?: string[]; + supportedBrowsers?: string[]; +} + +export interface WebpackDevServerOptions + extends BuildOptions, + Omit {} + +export interface WebpackConfigOptions { + root: string; + logger: logging.Logger; + projectRoot: string; + sourceRoot?: string; + buildOptions: T; + tsConfig: ParsedConfiguration; + tsConfigPath: string; + projectName: string; +} diff --git a/packages/angular_devkit/build_angular/src/utils/bundle-inline-options.ts b/packages/angular_devkit/build_angular/src/utils/bundle-inline-options.ts new file mode 100644 index 000000000000..68c53b06777c --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/bundle-inline-options.ts @@ -0,0 +1,16 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 interface InlineOptions { + filename: string; + code: string; + map?: string; + outputPath: string; + missingTranslation?: 'warning' | 'error' | 'ignore'; + setLocale?: boolean; +} diff --git a/packages/angular_devkit/build_angular/src/utils/cache-path.ts b/packages/angular_devkit/build_angular/src/utils/cache-path.ts deleted file mode 100644 index a6eeffdd7495..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/cache-path.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as findCacheDirectory from 'find-cache-dir'; -import { tmpdir } from 'os'; -import { resolve } from 'path'; -import { cachingBasePath } from './environment-options'; - -export function findCachePath(name: string): string { - if (cachingBasePath) { - return resolve(cachingBasePath, name); - } - - return findCacheDirectory({ name }) || tmpdir(); -} diff --git a/packages/angular_devkit/build_angular/src/utils/color.ts b/packages/angular_devkit/build_angular/src/utils/color.ts new file mode 100644 index 000000000000..3e6eac3c63c8 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/color.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 ansiColors from 'ansi-colors'; +import { WriteStream } from 'node:tty'; + +function supportColor(): boolean { + if (process.env.FORCE_COLOR !== undefined) { + // 2 colors: FORCE_COLOR = 0 (Disables colors), depth 1 + // 16 colors: FORCE_COLOR = 1, depth 4 + // 256 colors: FORCE_COLOR = 2, depth 8 + // 16,777,216 colors: FORCE_COLOR = 3, depth 16 + // See: https://nodejs.org/dist/latest-v12.x/docs/api/tty.html#tty_writestream_getcolordepth_env + // and https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/tty.js#L106; + switch (process.env.FORCE_COLOR) { + case '': + case 'true': + case '1': + case '2': + case '3': + return true; + default: + return false; + } + } + + if (process.stdout instanceof WriteStream) { + return process.stdout.hasColors(); + } + + return false; +} + +// Create a separate instance to prevent unintended global changes to the color configuration +const colors = ansiColors.create(); +colors.enabled = supportColor(); + +export { colors }; diff --git a/packages/angular_devkit/build_angular/src/utils/copy-assets.ts b/packages/angular_devkit/build_angular/src/utils/copy-assets.ts index 17e2fdd64c20..a525cab99b34 100644 --- a/packages/angular_devkit/build_angular/src/utils/copy-assets.ts +++ b/packages/angular_devkit/build_angular/src/utils/copy-assets.ts @@ -1,36 +1,39 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as fs from 'fs'; -import * as glob from 'glob'; -import * as path from 'path'; -import { copyFile } from './copy-file'; - -function globAsync(pattern: string, options: glob.IOptions) { - return new Promise((resolve, reject) => - glob(pattern, options, (e, m) => (e ? reject(e) : resolve(m))), - ); -} + +import fs from 'node:fs'; +import path from 'node:path'; +import { glob } from 'tinyglobby'; export async function copyAssets( - entries: { glob: string; ignore?: string[]; input: string; output: string; flatten?: boolean }[], + entries: { + glob: string; + ignore?: string[]; + input: string; + output: string; + flatten?: boolean; + followSymlinks?: boolean; + }[], basePaths: Iterable, root: string, changed?: Set, ) { const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db']; + const outputFiles: { source: string; destination: string }[] = []; + for (const entry of entries) { const cwd = path.resolve(root, entry.input); - const files = await globAsync(entry.glob, { + const files = await glob(entry.glob, { cwd, dot: true, - nodir: true, ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore, + followSymbolicLinks: entry.followSymlinks ?? false, }); const directoryExists = new Set(); @@ -42,6 +45,9 @@ export async function copyAssets( } const filePath = entry.flatten ? path.basename(file) : file; + + outputFiles.push({ source: src, destination: path.join(entry.output, filePath) }); + for (const base of basePaths) { const dest = path.join(base, entry.output, filePath); const dir = path.dirname(dest); @@ -51,8 +57,10 @@ export async function copyAssets( } directoryExists.add(dir); } - copyFile(src, dest); + fs.copyFileSync(src, dest, fs.constants.COPYFILE_FICLONE); } } } + + return outputFiles; } diff --git a/packages/angular_devkit/build_angular/src/utils/copy-file.ts b/packages/angular_devkit/build_angular/src/utils/copy-file.ts deleted file mode 100644 index f935599fe95f..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/copy-file.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as fs from 'fs'; - -// Workaround Node.js issue prior to 10.16 with copyFile on macOS -// https://github.com/angular/angular-cli/issues/15544 & https://github.com/nodejs/node/pull/27241 -let copyFileWorkaround = false; -if (process.platform === 'darwin') { - const version = process.versions.node.split('.').map(part => Number(part)); - if (version[0] < 10 || version[0] === 11 || (version[0] === 10 && version[1] < 16)) { - copyFileWorkaround = true; - } -} - -export function copyFile(src: fs.PathLike, dest: fs.PathLike): void { - if (copyFileWorkaround) { - try { - fs.unlinkSync(dest); - } catch {} - } - - fs.copyFileSync(src, dest, fs.constants.COPYFILE_FICLONE); -} diff --git a/packages/angular_devkit/build_angular/src/utils/default-progress.ts b/packages/angular_devkit/build_angular/src/utils/default-progress.ts index 258412b460f1..a924a2fa9689 100644 --- a/packages/angular_devkit/build_angular/src/utils/default-progress.ts +++ b/packages/angular_devkit/build_angular/src/utils/default-progress.ts @@ -1,9 +1,9 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ export function defaultProgress(progress: boolean | undefined): boolean { diff --git a/packages/angular_devkit/build_angular/src/utils/delete-output-dir.ts b/packages/angular_devkit/build_angular/src/utils/delete-output-dir.ts deleted file mode 100644 index bb8c648a1220..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/delete-output-dir.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { resolve } from 'path'; -import * as rimraf from 'rimraf'; - -/** - * Delete an output directory, but error out if it's the root of the project. - */ -export function deleteOutputDir(root: string, outputPath: string) { - const resolvedOutputPath = resolve(root, outputPath); - if (resolvedOutputPath === root) { - throw new Error('Output path MUST not be project root directory!'); - } - - rimraf.sync(resolvedOutputPath); -} diff --git a/packages/angular_devkit/build_angular/src/utils/empty.js b/packages/angular_devkit/build_angular/src/utils/empty.js deleted file mode 100644 index 8b137891791f..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/empty.js +++ /dev/null @@ -1 +0,0 @@ - diff --git a/packages/angular_devkit/build_angular/src/utils/environment-options.ts b/packages/angular_devkit/build_angular/src/utils/environment-options.ts index 7d9e6b1931f2..9d53be82ce79 100644 --- a/packages/angular_devkit/build_angular/src/utils/environment-options.ts +++ b/packages/angular_devkit/build_angular/src/utils/environment-options.ts @@ -1,30 +1,98 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as path from 'path'; -const mangleVariable = process.env['NG_BUILD_MANGLE']; -export const manglingDisabled = - !!mangleVariable && (mangleVariable === '0' || mangleVariable.toLowerCase() === 'false'); - -const cacheVariable = process.env['NG_BUILD_CACHE']; -export const cachingDisabled = - !!cacheVariable && (cacheVariable === '0' || cacheVariable.toLowerCase() === 'false'); -export const cachingBasePath = (() => { - if ( - cachingDisabled || - !cacheVariable || - (cacheVariable === '1' || cacheVariable.toLowerCase() === 'true') - ) { - return null; +import { availableParallelism } from 'node:os'; + +function isDisabled(variable: string): boolean { + return variable === '0' || variable.toLowerCase() === 'false'; +} + +function isEnabled(variable: string): boolean { + return variable === '1' || variable.toLowerCase() === 'true'; +} + +function isPresent(variable: string | undefined): variable is string { + return typeof variable === 'string' && variable !== ''; +} + +// Optimization and mangling +const debugOptimizeVariable = process.env['NG_BUILD_DEBUG_OPTIMIZE']; +const debugOptimize = (() => { + if (!isPresent(debugOptimizeVariable) || isDisabled(debugOptimizeVariable)) { + return { + mangle: true, + minify: true, + beautify: false, + }; } - if (!path.isAbsolute(cacheVariable)) { - throw new Error('NG_BUILD_CACHE path value must be absolute.'); + + const debugValue = { + mangle: false, + minify: false, + beautify: true, + }; + + if (isEnabled(debugOptimizeVariable)) { + return debugValue; + } + + for (const part of debugOptimizeVariable.split(',')) { + switch (part.trim().toLowerCase()) { + case 'mangle': + debugValue.mangle = true; + break; + case 'minify': + debugValue.minify = true; + break; + case 'beautify': + debugValue.beautify = true; + break; + } } - return cacheVariable; + return debugValue; })(); + +const mangleVariable = process.env['NG_BUILD_MANGLE']; +export const allowMangle = isPresent(mangleVariable) + ? !isDisabled(mangleVariable) + : debugOptimize.mangle; + +export const shouldBeautify = debugOptimize.beautify; +export const allowMinify = debugOptimize.minify; + +/** + * Some environments, like CircleCI which use Docker report a number of CPUs by the host and not the count of available. + * This cause `Error: Call retries were exceeded` errors when trying to use them. + * + * @see https://github.com/nodejs/node/issues/28762 + * @see https://github.com/webpack-contrib/terser-webpack-plugin/issues/143 + * @see https://ithub.com/angular/angular-cli/issues/16860#issuecomment-588828079 + * + */ +const maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS']; +export const maxWorkers = isPresent(maxWorkersVariable) + ? +maxWorkersVariable + : Math.min(4, Math.max(availableParallelism() - 1, 1)); + +const parallelTsVariable = process.env['NG_BUILD_PARALLEL_TS']; +export const useParallelTs = !isPresent(parallelTsVariable) || !isDisabled(parallelTsVariable); + +const debugPerfVariable = process.env['NG_BUILD_DEBUG_PERF']; +export const debugPerformance = isPresent(debugPerfVariable) && isEnabled(debugPerfVariable); + +const watchRootVariable = process.env['NG_BUILD_WATCH_ROOT']; +export const shouldWatchRoot = isPresent(watchRootVariable) && isEnabled(watchRootVariable); + +const typeCheckingVariable = process.env['NG_BUILD_TYPE_CHECK']; +export const useTypeChecking = + !isPresent(typeCheckingVariable) || !isDisabled(typeCheckingVariable); + +const buildLogsJsonVariable = process.env['NG_BUILD_LOGS_JSON']; +export const useJSONBuildLogs = + isPresent(buildLogsJsonVariable) && isEnabled(buildLogsJsonVariable); diff --git a/packages/angular_devkit/build_angular/src/utils/error.ts b/packages/angular_devkit/build_angular/src/utils/error.ts new file mode 100644 index 000000000000..0ca77c331d2d --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/error.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; + +export function assertIsError(value: unknown): asserts value is Error & { code?: string } { + const isError = + value instanceof Error || + // The following is needing to identify errors coming from RxJs. + (typeof value === 'object' && value && 'name' in value && 'message' in value); + assert(isError, 'catch clause variable is not an Error instance'); +} diff --git a/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts b/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts index 57b52ca35c2f..9f639f16cb21 100644 --- a/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts +++ b/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts @@ -1,27 +1,30 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { BuilderContext } from '@angular-devkit/architect'; import { EmittedFiles } from '@angular-devkit/build-webpack'; -import * as fs from 'fs'; -import * as path from 'path'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; import { BundleActionExecutor } from './action-executor'; +import { InlineOptions } from './bundle-inline-options'; import { copyAssets } from './copy-assets'; -import { I18nOptions } from './i18n-options'; -import { InlineOptions } from './process-bundle'; +import { assertIsError } from './error'; +import { I18nOptions } from './i18n-webpack'; +import { Spinner } from './spinner'; function emittedFilesToInlineOptions( emittedFiles: EmittedFiles[], scriptsEntryPointName: string[], emittedPath: string, outputPath: string, - es5: boolean, missingTranslation: 'error' | 'warning' | 'ignore' | undefined, -): { options: InlineOptions[]; originalFiles: string[] } { + context: BuilderContext, +): { options: InlineOptions[]; originalFiles: string[] } { const options: InlineOptions[] = []; const originalFiles: string[] = []; for (const emittedFile of emittedFiles) { @@ -37,10 +40,9 @@ function emittedFilesToInlineOptions( const action: InlineOptions = { filename: emittedFile.file, code: fs.readFileSync(originalPath, 'utf8'), - es5, outputPath, missingTranslation, - setLocale: emittedFile.name === 'main' || emittedFile.name === 'vendor', + setLocale: emittedFile.name === 'main', }; originalFiles.push(originalPath); @@ -49,11 +51,14 @@ function emittedFilesToInlineOptions( action.map = fs.readFileSync(originalMapPath, 'utf8'); originalFiles.push(originalMapPath); } catch (err) { + assertIsError(err); if (err.code !== 'ENOENT') { throw err; } } + context.logger.debug(`i18n file queued for processing: ${action.filename}`); + options.push(action); } @@ -68,29 +73,35 @@ export async function i18nInlineEmittedFiles( outputPaths: string[], scriptsEntryPointName: string[], emittedPath: string, - es5: boolean, missingTranslation: 'error' | 'warning' | 'ignore' | undefined, ): Promise { const executor = new BundleActionExecutor({ i18n }); let hasErrors = false; + const spinner = new Spinner(); + spinner.start('Generating localized bundles...'); + try { const { options, originalFiles: processedFiles } = emittedFilesToInlineOptions( emittedFiles, scriptsEntryPointName, emittedPath, baseOutputPath, - es5, missingTranslation, + context, ); for await (const result of executor.inlineAll(options)) { + context.logger.debug(`i18n file processed: ${result.file}`); + for (const diagnostic of result.diagnostics) { + spinner.stop(); if (diagnostic.type === 'error') { hasErrors = true; context.logger.error(diagnostic.message); } else { context.logger.warn(diagnostic.message); } + spinner.start(); } } @@ -101,14 +112,15 @@ export async function i18nInlineEmittedFiles( glob: '**/*', input: emittedPath, output: '', - ignore: [...processedFiles].map(f => path.relative(emittedPath, f)), + ignore: [...processedFiles].map((f) => path.relative(emittedPath, f)), }, ], outputPaths, '', ); } catch (err) { - context.logger.error('Localized bundle generation failed: ' + err.message); + assertIsError(err); + spinner.fail('Localized bundle generation failed: ' + err.message); return false; } finally { @@ -116,9 +128,9 @@ export async function i18nInlineEmittedFiles( } if (hasErrors) { - context.logger.error('Localized bundle generation failed.'); + spinner.fail('Localized bundle generation failed.'); } else { - context.logger.info('Localized bundle generation complete.'); + spinner.succeed('Localized bundle generation complete.'); } return !hasErrors; diff --git a/packages/angular_devkit/build_angular/src/utils/i18n-options.ts b/packages/angular_devkit/build_angular/src/utils/i18n-options.ts deleted file mode 100644 index 06d5d551a536..000000000000 --- a/packages/angular_devkit/build_angular/src/utils/i18n-options.ts +++ /dev/null @@ -1,292 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext } from '@angular-devkit/architect'; -import { json } from '@angular-devkit/core'; -import * as fs from 'fs'; -import * as os from 'os'; -import * as path from 'path'; -import * as rimraf from 'rimraf'; -import { readTsconfig } from '../angular-cli-files/utilities/read-tsconfig'; -import { Schema as BrowserBuilderSchema } from '../browser/schema'; -import { Schema as ServerBuilderSchema } from '../server/schema'; -import { createTranslationLoader } from './load-translations'; - -export interface I18nOptions { - inlineLocales: Set; - sourceLocale: string; - locales: Record< - string, - { file: string; format?: string; translation?: unknown; dataPath?: string } - >; - flatOutput?: boolean; - readonly shouldInline: boolean; - veCompatLocale?: string; -} - -export function createI18nOptions( - metadata: json.JsonObject, - inline?: boolean | string[], -): I18nOptions { - if ( - metadata.i18n !== undefined && - (typeof metadata.i18n !== 'object' || !metadata.i18n || Array.isArray(metadata.i18n)) - ) { - throw new Error('Project i18n field is malformed. Expected an object.'); - } - metadata = metadata.i18n || {}; - - if (metadata.sourceLocale !== undefined && typeof metadata.sourceLocale !== 'string') { - throw new Error('Project i18n sourceLocale field is malformed. Expected a string.'); - } - - const i18n: I18nOptions = { - inlineLocales: new Set(), - // en-US is the default locale added to Angular applications (https://angular.io/guide/i18n#i18n-pipes) - sourceLocale: metadata.sourceLocale || 'en-US', - locales: {}, - get shouldInline() { - return this.inlineLocales.size > 0; - }, - }; - - if ( - metadata.locales !== undefined && - (!metadata.locales || typeof metadata.locales !== 'object' || Array.isArray(metadata.locales)) - ) { - throw new Error('Project i18n locales field is malformed. Expected an object.'); - } else if (metadata.locales) { - for (const [locale, translationFile] of Object.entries(metadata.locales)) { - if (typeof translationFile !== 'string') { - throw new Error( - `Project i18n locales field value for '${locale}' is malformed. Expected a string.`, - ); - } - - if (locale === i18n.sourceLocale) { - throw new Error( - `An i18n locale identifier ('${locale}') cannot both be a source locale and provide a translation.`, - ); - } - - i18n.locales[locale] = { - file: translationFile, - }; - } - } - - if (inline === true) { - i18n.inlineLocales.add(i18n.sourceLocale); - Object.keys(i18n.locales).forEach(locale => i18n.inlineLocales.add(locale)); - } else if (inline) { - for (const locale of inline) { - if (!i18n.locales[locale] && i18n.sourceLocale !== locale) { - throw new Error(`Requested locale '${locale}' is not defined for the project.`); - } - - i18n.inlineLocales.add(locale); - } - } - - return i18n; -} - -export async function configureI18nBuild( - context: BuilderContext, - options: T, -): Promise<{ - buildOptions: T; - i18n: I18nOptions; -}> { - if (!context.target) { - throw new Error('The builder requires a target.'); - } - - const buildOptions = { ...options }; - const tsConfig = readTsconfig(buildOptions.tsConfig, context.workspaceRoot); - const usingIvy = tsConfig.options.enableIvy !== false; - const metadata = await context.getProjectMetadata(context.target); - const i18n = createI18nOptions(metadata, buildOptions.localize); - - // Until 11.0, support deprecated i18n options when not using new localize option - // i18nFormat is automatically calculated - if (buildOptions.localize === undefined && usingIvy) { - mergeDeprecatedI18nOptions(i18n, buildOptions.i18nLocale, buildOptions.i18nFile); - } else if (buildOptions.localize !== undefined && !usingIvy) { - if ( - buildOptions.localize === true || - (Array.isArray(buildOptions.localize) && buildOptions.localize.length > 1) - ) { - throw new Error( - `Localization with multiple locales in one build is not supported with View Engine.`, - ); - } - - for (const deprecatedOption of ['i18nLocale', 'i18nFormat', 'i18nFile']) { - // tslint:disable-next-line: no-any - if (typeof (buildOptions as any)[deprecatedOption] !== 'undefined') { - context.logger.warn( - `Option 'localize' and deprecated '${deprecatedOption}' found. Using 'localize'.`, - ); - } - } - - if ( - buildOptions.localize === false || - (Array.isArray(buildOptions.localize) && buildOptions.localize.length === 0) - ) { - buildOptions.i18nFile = undefined; - buildOptions.i18nLocale = undefined; - buildOptions.i18nFormat = undefined; - } - } - - // Clear deprecated options when using Ivy to prevent unintended behavior - if (usingIvy) { - buildOptions.i18nFile = undefined; - buildOptions.i18nFormat = undefined; - buildOptions.i18nLocale = undefined; - } - - if (i18n.inlineLocales.size > 0) { - const projectRoot = path.join(context.workspaceRoot, (metadata.root as string) || ''); - const localeDataBasePath = findLocaleDataBasePath(projectRoot); - if (!localeDataBasePath) { - throw new Error( - `Unable to find locale data within '@angular/common'. Please ensure '@angular/common' is installed.`, - ); - } - - // Load locales - const loader = await createTranslationLoader(); - const usedFormats = new Set(); - for (const [locale, desc] of Object.entries(i18n.locales)) { - if (i18n.inlineLocales.has(locale) && desc.file) { - const result = loader(path.join(projectRoot, desc.file)); - - for (const diagnostics of result.diagnostics.messages) { - if (diagnostics.type === 'error') { - throw new Error( - `Error parsing translation file '${desc.file}': ${diagnostics.message}`, - ); - } else { - context.logger.warn(`WARNING [${desc.file}]: ${diagnostics.message}`); - } - } - - usedFormats.add(result.format); - if (usedFormats.size > 1 && tsConfig.options.enableI18nLegacyMessageIdFormat !== false) { - // This limitation is only for legacy message id support (defaults to true as of 9.0) - throw new Error( - 'Localization currently only supports using one type of translation file format for the entire application.', - ); - } - - desc.format = result.format; - desc.translation = result.translation; - - const localeDataPath = findLocaleDataPath(locale, localeDataBasePath); - if (!localeDataPath) { - context.logger.warn( - `Locale data for '${locale}' cannot be found. No locale data will be included for this locale.`, - ); - } else { - desc.dataPath = localeDataPath; - } - } - } - - // Legacy message id's require the format of the translations - if (usedFormats.size > 0) { - buildOptions.i18nFormat = [...usedFormats][0]; - } - - // Provide support for using the Ivy i18n options with VE - if (!usingIvy) { - i18n.veCompatLocale = buildOptions.i18nLocale = [...i18n.inlineLocales][0]; - - if (buildOptions.i18nLocale !== i18n.sourceLocale) { - buildOptions.i18nFile = i18n.locales[buildOptions.i18nLocale].file; - } - - // Clear inline locales to prevent any new i18n related processing - i18n.inlineLocales.clear(); - - // Update the output path to include the locale to mimic Ivy localize behavior - buildOptions.outputPath = path.join(buildOptions.outputPath, buildOptions.i18nLocale); - } - } - - // If inlining store the output in a temporary location to facilitate post-processing - if (i18n.shouldInline) { - const tempPath = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-i18n-')); - buildOptions.outputPath = tempPath; - - // Remove temporary directory used for i18n processing - process.on('exit', () => { - try { - rimraf.sync(tempPath); - } catch {} - }); - } - - return { buildOptions, i18n }; -} - -function mergeDeprecatedI18nOptions( - i18n: I18nOptions, - i18nLocale: string | undefined, - i18nFile: string | undefined, -): I18nOptions { - if (i18nFile !== undefined && i18nLocale === undefined) { - throw new Error(`Option 'i18nFile' cannot be used without the 'i18nLocale' option.`); - } - - if (i18nLocale !== undefined) { - i18n.inlineLocales.clear(); - i18n.inlineLocales.add(i18nLocale); - - if (i18nFile !== undefined) { - i18n.locales[i18nLocale] = { file: i18nFile }; - } else { - // If no file, treat the locale as the source locale - // This mimics deprecated behavior - i18n.sourceLocale = i18nLocale; - } - - i18n.flatOutput = true; - } - - return i18n; -} - -function findLocaleDataBasePath(projectRoot: string): string | null { - try { - const commonPath = path.dirname( - require.resolve('@angular/common/package.json', { paths: [projectRoot] }), - ); - const localesPath = path.join(commonPath, 'locales/global'); - - if (!fs.existsSync(localesPath)) { - return null; - } - - return localesPath; - } catch { - return null; - } -} - -function findLocaleDataPath(locale: string, basePath: string): string | null { - const localeDataPath = path.join(basePath, locale + '.js'); - - if (!fs.existsSync(localeDataPath)) { - return null; - } - - return localeDataPath; -} diff --git a/packages/angular_devkit/build_angular/src/utils/i18n-webpack.ts b/packages/angular_devkit/build_angular/src/utils/i18n-webpack.ts new file mode 100644 index 000000000000..ef0fd1dc2207 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/i18n-webpack.ts @@ -0,0 +1,145 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { + type I18nOptions, + createI18nOptions, + createTranslationLoader, + loadTranslations, +} from '@angular/build/private'; +import { BuilderContext } from '@angular-devkit/architect'; +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { Schema as BrowserBuilderSchema } from '../builders/browser/schema'; +import { Schema as ServerBuilderSchema } from '../builders/server/schema'; +import { readTsconfig } from '../utils/read-tsconfig'; + +/** + * The base module location used to search for locale specific data. + */ +const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; + +// Re-export for use within Webpack related builders +export { I18nOptions, loadTranslations }; + +export async function configureI18nBuild( + context: BuilderContext, + options: T, +): Promise<{ + buildOptions: T; + i18n: I18nOptions; +}> { + if (!context.target) { + throw new Error('The builder requires a target.'); + } + + const buildOptions = { ...options }; + const tsConfig = await readTsconfig(buildOptions.tsConfig, context.workspaceRoot); + const metadata = await context.getProjectMetadata(context.target); + const i18n = createI18nOptions(metadata, buildOptions.localize, context.logger); + + // No additional processing needed if no inlining requested and no source locale defined. + if (!i18n.shouldInline && !i18n.hasDefinedSourceLocale) { + return { buildOptions, i18n }; + } + + const projectRoot = path.join(context.workspaceRoot, (metadata.root as string) || ''); + // The trailing slash is required to signal that the path is a directory and not a file. + const projectRequire = createRequire(projectRoot + '/'); + const localeResolver = (locale: string) => + projectRequire.resolve(path.join(LOCALE_DATA_BASE_MODULE, locale)); + + // Load locale data and translations (if present) + let loader; + const usedFormats = new Set(); + for (const [locale, desc] of Object.entries(i18n.locales)) { + if (!i18n.inlineLocales.has(locale) && locale !== i18n.sourceLocale) { + continue; + } + + let localeDataPath = findLocaleDataPath(locale, localeResolver); + if (!localeDataPath) { + const [first] = locale.split('-'); + if (first) { + localeDataPath = findLocaleDataPath(first.toLowerCase(), localeResolver); + if (localeDataPath) { + context.logger.warn( + `Locale data for '${locale}' cannot be found. Using locale data for '${first}'.`, + ); + } + } + } + if (!localeDataPath) { + context.logger.warn( + `Locale data for '${locale}' cannot be found. No locale data will be included for this locale.`, + ); + } else { + desc.dataPath = localeDataPath; + } + + if (!desc.files.length) { + continue; + } + + loader ??= await createTranslationLoader(); + + loadTranslations( + locale, + desc, + context.workspaceRoot, + loader, + { + warn(message) { + context.logger.warn(message); + }, + error(message) { + throw new Error(message); + }, + }, + usedFormats, + buildOptions.i18nDuplicateTranslation, + ); + + if (usedFormats.size > 1 && tsConfig.options.enableI18nLegacyMessageIdFormat !== false) { + // This limitation is only for legacy message id support (defaults to true as of 9.0) + throw new Error( + 'Localization currently only supports using one type of translation file format for the entire application.', + ); + } + } + + // If inlining store the output in a temporary location to facilitate post-processing + if (i18n.shouldInline) { + // TODO: we should likely save these in the .angular directory in the next major version. + // We'd need to do a migration to add the temp directory to gitignore. + const tempPath = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-i18n-')); + buildOptions.outputPath = tempPath; + + process.on('exit', () => { + try { + fs.rmSync(tempPath, { force: true, recursive: true, maxRetries: 3 }); + } catch {} + }); + } + + return { buildOptions, i18n }; +} + +function findLocaleDataPath(locale: string, resolver: (locale: string) => string): string | null { + // Remove private use subtags + const scrubbedLocale = locale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, ''); + + try { + return resolver(scrubbedLocale); + } catch { + // fallback to known existing en-US locale data as of 14.0 + return scrubbedLocale === 'en-US' ? findLocaleDataPath('en', resolver) : null; + } +} diff --git a/packages/angular_devkit/build_angular/src/utils/index.ts b/packages/angular_devkit/build_angular/src/utils/index.ts index 8cd7670f0a9b..da07543fafa8 100644 --- a/packages/angular_devkit/build_angular/src/utils/index.ts +++ b/packages/angular_devkit/build_angular/src/utils/index.ts @@ -1,17 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -export * from './build-browser-features'; export * from './default-progress'; -export * from './delete-output-dir'; -export * from './run-module-as-observable-fork'; +export { deleteOutputDir, loadProxyConfiguration } from '@angular/build/private'; export * from './normalize-file-replacements'; export * from './normalize-asset-patterns'; export * from './normalize-source-maps'; export * from './normalize-optimization'; export * from './normalize-builder-schema'; +export * from './url'; diff --git a/packages/angular_devkit/build_angular/src/utils/inline-critical-css.ts b/packages/angular_devkit/build_angular/src/utils/inline-critical-css.ts new file mode 100644 index 000000000000..cd58ea795480 --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/inline-critical-css.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; + +export interface InlineCriticalCssProcessorOptions { + minify?: boolean; + deployUrl?: string; + readAsset?: (path: string) => Promise; + autoCsp?: boolean; + outputPath?: string; +} + +export class InlineCriticalCssProcessor { + constructor(protected readonly options: InlineCriticalCssProcessorOptions) {} + + async process(html: string): Promise<{ content: string; warnings: string[]; errors: string[] }> { + const warnings: string[] = []; + const errors: string[] = []; + const { outputPath, deployUrl, minify = false, readAsset } = this.options; + + const { default: Beasties } = await import('beasties'); + + const beasties = new Beasties({ + logger: { + warn: (s: string) => warnings.push(s), + error: (s: string) => errors.push(s), + info: () => {}, + }, + logLevel: 'warn', + path: outputPath, + publicPath: deployUrl, + compress: minify, + pruneSource: false, + reduceInlineStyles: false, + mergeStylesheets: false, + preload: 'media-script', + nonce: (document) => { + const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]'); + const cspNonce = + nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce'); + + return cspNonce ?? undefined; + }, + noscriptFallback: true, + inlineFonts: true, + }); + + beasties.readFile = (path) => { + return readAsset ? readAsset(path) : readFile(path, 'utf-8'); + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const beastiesInternal = beasties as any; + const initialEmbedLinkedStylesheet = + beastiesInternal.embedLinkedStylesheet.bind(beastiesInternal); + beastiesInternal.embedLinkedStylesheet = async (link: unknown, document: unknown) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const linkEl = link as any; + const beastiesMedia = linkEl.getAttribute('data-beasties-media'); + if (beastiesMedia) { + linkEl.removeAttribute('data-beasties-media'); + linkEl.setAttribute('media', beastiesMedia); + if (linkEl.next?.name === 'noscript') { + linkEl.next.remove?.(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (document as any).querySelectorAll('script').forEach((script: any) => { + if (script.textContent?.includes('data-beasties-media')) { + script.remove?.(); + } + }); + } + + return initialEmbedLinkedStylesheet(link, document); + }; + const content = await beasties.process(html); + + return { + // Clean up value from value less attributes. + // This is caused because parse5 always requires attributes to have a string value. + // nomodule="" defer="" -> nomodule defer. + content: content.replace(/(\s(?:defer|nomodule))=""/g, '$1'), + errors, + warnings, + }; + } +} diff --git a/packages/angular_devkit/build_angular/src/utils/inline-critical-css_spec.ts b/packages/angular_devkit/build_angular/src/utils/inline-critical-css_spec.ts new file mode 100644 index 000000000000..a5a49baec26b --- /dev/null +++ b/packages/angular_devkit/build_angular/src/utils/inline-critical-css_spec.ts @@ -0,0 +1,178 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { tags } from '@angular-devkit/core'; +import { InlineCriticalCssProcessor } from './inline-critical-css'; + +describe('InlineCriticalCssProcessor', () => { + const styles: Record = { + '/dist/styles.css': ` + body { margin: 0; } + html { color: white; } + `, + '/dist/theme.css': ` + span { color: blue; } + p { color: blue; } + `, + }; + + const readAsset = async (file: string): Promise => { + const content = styles[file]; + if (content) { + return content; + } + + throw new Error('Cannot read asset.'); + }; + + const getContent = (deployUrl: string, bodyContent = ''): string => { + return ` + + + + + + ${bodyContent} + `; + }; + + it('should inline critical css', async () => { + const inlineFontsProcessor = new InlineCriticalCssProcessor({ + readAsset, + outputPath: '/dist/', + }); + + const { content } = await inlineFontsProcessor.process(getContent('')); + + expect(content).toContain( + ``, + ); + expect(content).toContain( + ``, + ); + expect(content).not.toContain('color: blue'); + expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` + `); + }); + + it('should inline critical css when using deployUrl', async () => { + const inlineFontsProcessor = new InlineCriticalCssProcessor({ + readAsset, + outputPath: '/dist/', + deployUrl: 'http://cdn.com', + }); + + const { content } = await inlineFontsProcessor.process(getContent('http://cdn.com/')); + + expect(content).toContain( + ``, + ); + expect(content).toContain( + ``, + ); + expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` + `); + }); + + it('should compress inline critical css when minify is enabled', async () => { + const inlineFontsProcessor = new InlineCriticalCssProcessor({ + readAsset, + minify: true, + outputPath: '/dist/', + }); + + const { content } = await inlineFontsProcessor.process(getContent('')); + + expect(content).toContain( + ``, + ); + expect(content).toContain( + ``, + ); + expect(content).toContain(''); + }); + + it(`should process the inline 'onload' handlers if a 'autoCsp' is true`, async () => { + const inlineCssProcessor = new InlineCriticalCssProcessor({ + readAsset, + autoCsp: true, + outputPath: '/dist/', + }); + + const { content } = await inlineCssProcessor.process(getContent('')); + + expect(content).toContain( + '', + ); + expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` + `); + }); + + it('should process the inline `onload` handlers if a CSP nonce is specified', async () => { + const inlineCssProcessor = new InlineCriticalCssProcessor({ + readAsset, + outputPath: '/dist/', + }); + + const { content } = await inlineCssProcessor.process( + getContent('', ''), + ); + + expect(content).toContain( + '', + ); + expect(content).toContain( + '', + ); + // Nonces shouldn't be added inside the `noscript` tags. + expect(content).toContain(''); + expect(content).toContain('` + - `` + - `` + - `` + - ``, - ); - await run.stop(); - }); - - it('works with anonymous', async () => { - const overrides = { crossOrigin: CrossOrigin.Anonymous }; - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `` + - `` + - `` + - `` + - `` + - `` + - ``, - ); - await run.stop(); - }); - - it('works with none', async () => { - const overrides = { crossOrigin: CrossOrigin.None }; - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `` + - `` + - `` + - `` + - `` + - `` + - ``, - ); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/deploy-url_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/deploy-url_spec_large.ts deleted file mode 100644 index 019798fc4126..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/deploy-url_spec_large.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { BrowserBuilderOutput } from '../../src/browser'; -import { createArchitect, host } from '../utils'; - - -describe('Browser Builder deploy url', () => { - const targetSpec = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('uses deploy url for bundles urls and runtime', async () => { - const overrides = { deployUrl: 'deployUrl/' }; - const overrides2 = { deployUrl: 'http://example.com/some/path/' }; - - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(output.outputPath).not.toBeUndefined(); - const outputPath = normalize(output.outputPath); - - const fileName = join(outputPath, 'index.html'); - const runtimeFileName = join(outputPath, 'runtime.js'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toContain('deployUrl/main.js'); - const runtimeContent = virtualFs.fileBufferToString( - await host.read(normalize(runtimeFileName)).toPromise(), - ); - expect(runtimeContent).toContain('deployUrl/'); - - const run2 = await architect.scheduleTarget(targetSpec, overrides2); - const output2 = await run2.result as BrowserBuilderOutput; - expect(output2.outputPath).toEqual(outputPath); // These should be the same. - - const content2 = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content2).toContain('http://example.com/some/path/main.js'); - - await run.stop(); - await run2.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/differential_loading_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/differential_loading_spec_large.ts deleted file mode 100644 index 48e5460b6ee2..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/differential_loading_spec_large.ts +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect/src/index'; -import { PathFragment } from '@angular-devkit/core'; -import { browserBuild, createArchitect, host } from '../utils'; - -describe('Browser Builder with differential loading', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - // to trigger differential loading we need an non ever green browser - host.writeMultipleFiles({ - browserslist: 'IE 10', - }); - - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(async () => host.restore().toPromise()); - - it('emits all the neccessary files', async () => { - const { files } = await browserBuild(architect, host, target); - - const expectedOutputs = [ - 'favicon.ico', - 'index.html', - - 'main-es2015.js', - 'main-es2015.js.map', - 'main-es5.js', - 'main-es5.js.map', - - 'polyfills-es2015.js', - 'polyfills-es2015.js.map', - 'polyfills-es5.js', - 'polyfills-es5.js.map', - - 'runtime-es2015.js', - 'runtime-es2015.js.map', - 'runtime-es5.js', - 'runtime-es5.js.map', - - 'styles-es2015.js', - 'styles-es2015.js.map', - 'styles-es5.js', - 'styles-es5.js.map', - - 'vendor-es2015.js', - 'vendor-es2015.js.map', - 'vendor-es5.js', - 'vendor-es5.js.map', - ] as PathFragment[]; - - expect(Object.keys(files)).toEqual(jasmine.arrayWithExactContents(expectedOutputs)); - }); - - it('deactivates differential loading for watch mode', async () => { - const { files } = await browserBuild(architect, host, target, { watch: true }); - - const expectedOutputs = [ - 'favicon.ico', - 'index.html', - - 'main.js', - 'main.js.map', - - 'polyfills.js', - 'polyfills.js.map', - - 'runtime.js', - 'runtime.js.map', - - 'styles.js', - 'styles.js.map', - - 'vendor.js', - 'vendor.js.map', - ] as PathFragment[]; - - expect(Object.keys(files)).toEqual(jasmine.arrayWithExactContents(expectedOutputs)); - }); - - it('emits the right ES formats', async () => { - if (!process.env['NG_BUILD_FULL_DIFFERENTIAL']) { - // The test fails depending on the order of previously executed tests - // The wrong data is being read from the filesystem. - pending('Incredibly flaky outside full build differential loading'); - } - const { files } = await browserBuild(architect, host, target, { optimization: true }); - expect(await files['main-es5.js']).not.toContain('class'); - expect(await files['main-es2015.js']).toContain('class'); - }); - - it('uses the right zone.js variant', async () => { - const { files } = await browserBuild(architect, host, target, { optimization: false }); - expect(await files['polyfills-es5.js']).toContain('zone.js/dist/zone-legacy'); - expect(await files['polyfills-es5.js']).toContain('registerElementPatch'); - expect(await files['polyfills-es5.js']).toContain('zone.js/dist/zone-evergreen'); - expect(await files['polyfills-es2015.js']).toContain('zone.js/dist/zone-evergreen'); - expect(await files['polyfills-es2015.js']).not.toContain('zone.js/dist/zone-legacy'); - expect(await files['polyfills-es2015.js']).not.toContain('registerElementPatch'); - }); - - it('adds `type="module"` when differential loading is needed', async () => { - host.writeMultipleFiles({ - browserslist: ` - last 1 chrome version - IE 9 - `, - }); - - const { files } = await browserBuild(architect, host, target, { watch: true }); - expect(await files['index.html']).toContain( - '' + - '' + - '' + - '' + - '', - ); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/errors_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/errors_spec_large.ts deleted file mode 100644 index 75000540b54a..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/errors_spec_large.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { logging } from '@angular-devkit/core'; -import { createArchitect, host, veEnabled } from '../utils'; - -describe('Browser Builder errors', () => { - const targetSpec = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('shows error when files are not part of the compilation', async () => { - host.replaceInFile( - 'src/tsconfig.app.json', - /,\r?\n?\s*"polyfills\.ts"/, - '', - ); - host.replaceInFile( - 'src/tsconfig.app.json', - '"**/*.ts"', - '"**/*.d.ts"', - ); - const logger = new logging.Logger(''); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(targetSpec, {}, { logger }); - const output = await run.result; - expect(output.success).toBe(false); - expect(logs.join()).toContain('polyfills.ts is missing from the TypeScript'); - await run.stop(); - }); - - it('shows TS syntax errors', async () => { - host.appendToFile('src/app/app.component.ts', ']]]'); - const logger = new logging.Logger(''); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(targetSpec, {}, { logger }); - const output = await run.result; - expect(output.success).toBe(false); - expect(logs.join()).toContain('Declaration or statement expected'); - await run.stop(); - }); - - it('shows static analysis errors', async () => { - host.replaceInFile('src/app/app.component.ts', `'app-root'`, `(() => 'app-root')()`); - const logger = new logging.Logger(''); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(targetSpec, { aot: true }, { logger }); - const output = await run.result; - expect(output.success).toBe(false); - if (!veEnabled) { - expect(logs.join()).toContain('selector must be a string'); - } else { - expect(logs.join()).toContain('Function expressions are not supported in'); - } - await run.stop(); - }); - - it('shows missing export errors', async () => { - host.writeMultipleFiles({ - 'src/not-main.js': ` - import { missingExport } from 'rxjs'; - console.log(missingExport); - `, - }); - const overrides = { main: 'src/not-main.js' }; - const logger = new logging.Logger(''); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(targetSpec, overrides, { logger }); - const output = await run.result; - expect(output.success).toBe(false); - expect(logs.join()).toContain(`export 'missingExport' was not found in 'rxjs'`); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/i18n_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/i18n_spec_large.ts deleted file mode 100644 index 30bdec4c58ff..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/i18n_spec_large.ts +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { BrowserBuilderOutput } from '../../src/browser'; -import { createArchitect, host, veEnabled } from '../utils'; - -// DISABLED_FOR_IVY - These should pass but are currently not supported -(veEnabled ? describe : xdescribe)('Browser Builder i18n', () => { - const emptyTranslationFile = ` - - - - - - - `; - - const targetSpec = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('uses translations', async () => { - host.writeMultipleFiles({ - 'src/locale/messages.fr.xlf': ` - - - - - - Hello i18n! - Bonjour i18n! - An introduction header for this sample - - - - - `, - }); - - host.appendToFile( - 'src/app/app.component.html', - '

Hello i18n!

', - ); - - const overrides = { - aot: true, - i18nFile: 'src/locale/messages.fr.xlf', - i18nFormat: 'true', - i18nLocale: 'fr', - }; - - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - const outputPath = output.outputPath; - const fileName = join(normalize(outputPath), 'main.js'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toMatch(/Bonjour i18n!/); - - await run.stop(); - }); - - it('ignores missing translations', async () => { - const overrides = { - aot: true, - i18nFile: 'src/locale/messages.fr.xlf', - i18nFormat: 'true', - i18nLocale: 'fr', - i18nMissingTranslation: 'ignore', - }; - - host.writeMultipleFiles({ 'src/locale/messages.fr.xlf': emptyTranslationFile }); - host.appendToFile('src/app/app.component.html', '

Other content

'); - - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - const outputPath = output.outputPath; - const fileName = join(normalize(outputPath), 'main.js'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toMatch(/Other content/); - - await run.stop(); - }); - - it('reports errors for missing translations', async () => { - const overrides = { - aot: true, - i18nFile: 'src/locale/messages.fr.xlf', - i18nFormat: 'true', - i18nLocale: 'fr', - i18nMissingTranslation: 'error', - }; - - host.writeMultipleFiles({ 'src/locale/messages.fr.xlf': emptyTranslationFile }); - host.appendToFile('src/app/app.component.html', '

Other content

'); - - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(false); - - await run.stop(); - }); - - it('register locales', async () => { - const overrides = { aot: true, i18nLocale: 'fr_FR' }; - - const run = await architect.scheduleTarget(targetSpec, overrides); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - const outputPath = output.outputPath; - const fileName = join(normalize(outputPath), 'main.js'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toMatch(/registerLocaleData/); - expect(content).toMatch(/angular_common_locales_fr/); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/index_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/index_spec_large.ts deleted file mode 100644 index 9da24721f57c..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/index_spec_large.ts +++ /dev/null @@ -1,240 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, tags, virtualFs, workspaces } from '@angular-devkit/core'; -import { BrowserBuilderOutput } from '../../src/browser'; -import { createArchitect, host } from '../utils'; - -// tslint:disable-next-line:no-big-function -describe('Browser Builder index HTML processing', () => { - const targetSpec = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works with UTF-8 BOM', async () => { - host.writeMultipleFiles({ - 'src/index.html': Buffer.from( - '\ufeff', - 'utf8'), - }); - - const run = await architect.scheduleTarget(targetSpec); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `` - + `` - + `` - + ``, - ); - await run.stop(); - }); - - // todo: enable when utf16 is supported - xit('works with UTF16 LE BOM', async () => { - host.writeMultipleFiles({ - 'src/index.html': Buffer.from( - '\ufeff', - 'utf16le'), - }); - - const run = await architect.scheduleTarget(targetSpec); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `` - + `` - + `` - + ``, - ); - await run.stop(); - }); - - it('keeps escaped charaters', async () => { - host.writeMultipleFiles({ - 'src/index.html': tags.oneLine` - í - - `, - }); - - const run = await architect.scheduleTarget(targetSpec); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `í ` - + `` - + `` - + ``, - ); - await run.stop(); - }); - - it('keeps custom template charaters', async () => { - host.writeMultipleFiles({ - 'src/index.html': tags.oneLine` - <%= csrf_meta_tags %> - - `, - }); - - const run = await architect.scheduleTarget(targetSpec); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - const fileName = join(normalize(output.outputPath), 'index.html'); - const content = virtualFs.fileBufferToString(await host.read(normalize(fileName)).toPromise()); - expect(content).toBe( - `<%= csrf_meta_tags %> ` - + `` - + `` - + ``, - ); - await run.stop(); - }); - - it('uses the input value from the index option longform', async () => { - const { workspace } = await workspaces.readWorkspace(host.root(), workspaces.createWorkspaceHost(host)); - const app = workspace.projects.get('app'); - if (!app) { - fail('Test application "app" not found.'); - - return; - } - const target = app.targets.get('build'); - if (!target) { - fail('Test application "app" target "build" not found.'); - - return; - } - if (!target.options) { - target.options = {}; - } - target.options.index = { input: 'src/index-2.html' }; - await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); - - host.writeMultipleFiles({ - 'src/index-2.html': tags.oneLine` - <%= csrf_meta_tags %> - - `, - }); - await host.delete(join(host.root(), normalize('src/index.html'))).toPromise(); - - // Recreate architect to use update angular.json - architect = (await createArchitect(host.root())).architect; - - const run = await architect.scheduleTarget(targetSpec); - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - const outputIndexPath = join(host.root(), 'dist', 'index.html'); - const content = await host.read(normalize(outputIndexPath)).toPromise(); - expect(virtualFs.fileBufferToString(content)).toBe( - `<%= csrf_meta_tags %> ` - + `` - + `` - + ``, - ); - }); - - it('uses the output value from the index option longform', async () => { - const { workspace } = await workspaces.readWorkspace(host.root(), workspaces.createWorkspaceHost(host)); - const app = workspace.projects.get('app'); - if (!app) { - fail('Test application "app" not found.'); - - return; - } - const target = app.targets.get('build'); - if (!target) { - fail('Test application "app" target "build" not found.'); - - return; - } - if (!target.options) { - target.options = {}; - } - target.options.index = { input: 'src/index.html', output: 'main.html' }; - await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); - - host.writeMultipleFiles({ - 'src/index.html': tags.oneLine` - - - `, - }); - - // Recreate architect to use update angular.json - architect = (await createArchitect(host.root())).architect; - - const run = await architect.scheduleTarget(targetSpec); - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - const outputIndexPath = join(host.root(), 'dist', 'main.html'); - const content = await host.read(normalize(outputIndexPath)).toPromise(); - expect(virtualFs.fileBufferToString(content)).toBe( - ` ` - + `` - + `` - + ``, - ); - }); - - it('creates subdirectories for output value from the index option longform', async () => { - const { workspace } = await workspaces.readWorkspace(host.root(), workspaces.createWorkspaceHost(host)); - const app = workspace.projects.get('app'); - if (!app) { - fail('Test application "app" not found.'); - - return; - } - const target = app.targets.get('build'); - if (!target) { - fail('Test application "app" target "build" not found.'); - - return; - } - if (!target.options) { - target.options = {}; - } - target.options.index = { input: 'src/index.html', output: 'extra/main.html' }; - await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); - - host.writeMultipleFiles({ - 'src/index.html': tags.oneLine` - - - `, - }); - - // Recreate architect to use update angular.json - architect = (await createArchitect(host.root())).architect; - - const run = await architect.scheduleTarget(targetSpec); - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - const outputIndexPath = join(host.root(), 'dist', 'extra', 'main.html'); - const content = await host.read(normalize(outputIndexPath)).toPromise(); - expect(virtualFs.fileBufferToString(content)).toBe( - ` ` - + `` - + `` - + ``, - ); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/lazy-module_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/lazy-module_spec_large.ts deleted file mode 100644 index 0822372967fb..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/lazy-module_spec_large.ts +++ /dev/null @@ -1,278 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { TestLogger, TestProjectHost } from '@angular-devkit/architect/testing'; -import { take, tap, timeout } from 'rxjs/operators'; -import { - browserBuild, - createArchitect, - host, - lazyModuleFiles, - lazyModuleFnImport, - lazyModuleStringImport, - veEnabled, -} from '../utils'; - -// tslint:disable-next-line:no-big-function -describe('Browser Builder lazy modules', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - function addLazyLoadedModulesInTsConfig(host: TestProjectHost, lazyModuleFiles: Record) { - const files = [ - ...Object.keys(lazyModuleFiles), - 'main.ts', - ] - .map(f => '"' + f.replace('src/', '') + '"') - .join(', '); - - host.replaceInFile( - 'src/tsconfig.app.json', - '"main.ts"', - `${files}`, - ); - } - - function hasMissingModuleError(logger: TestLogger) { - // TS type error when using import(). - return logger.includes('Cannot find module') || - // Webpack error when using import() on a rebuild. - // There is no TS error because the type checker is forked on rebuilds. - logger.includes('Module not found'); - } - - const cases: [string, Record][] = [ - ['string', lazyModuleStringImport], - ['function', lazyModuleFnImport], - ]; - for (const [name, imports] of cases) { - describe(`Load children ${name} syntax`, () => { - it('supports lazy bundle for lazy routes with JIT', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(imports); - - if (name === 'string') { - addLazyLoadedModulesInTsConfig(host, lazyModuleFiles); - } - - const { files } = await browserBuild(architect, host, target); - expect('lazy-lazy-module.js' in files).toBe(true); - }); - - it('supports lazy bundle for lazy routes with AOT', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(imports); - addLazyLoadedModulesInTsConfig(host, lazyModuleFiles); - - const { files } = await browserBuild(architect, host, target, { aot: true }); - if (!veEnabled) { - const data = await files['lazy-lazy-module.js']; - expect(data).not.toBeUndefined('Lazy module output bundle does not exist'); - expect(data).toContain('LazyModule.ɵmod'); - } else { - expect(files['lazy-lazy-module-ngfactory.js']).not.toBeUndefined(); - } - }); - }); - } - - // Errors for missing lazy routes are only supported with function syntax. - // `ngProgram.listLazyRoutes` will ignore invalid lazy routes in the route map. - describe(`Load children errors with function syntax`, () => { - it('should show error when lazy route is invalid', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - host.replaceInFile('src/app/app.module.ts', 'lazy.module', 'invalid.module'); - - const logger = new TestLogger('build-lazy-errors'); - const run = await architect.scheduleTarget(target, {}, { logger }); - const output = await run.result; - expect(output.success).toBe(false); - expect(hasMissingModuleError(logger)).toBe(true, 'Should show missing module error'); - }); - - it('should show error when lazy route is invalid on watch mode AOT', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - - let buildNumber = 0; - const logger = new TestLogger('rebuild-lazy-errors'); - const overrides = { watch: true, aot: true }; - const run = await architect.scheduleTarget(target, overrides, { logger }); - await run.output - .pipe( - timeout(15000), - tap(buildEvent => { - buildNumber++; - switch (buildNumber) { - case 1: - expect(buildEvent.success).toBe(true); - host.replaceInFile('src/app/app.module.ts', 'lazy.module', 'invalid.module'); - logger.clear(); - break; - case 2: - expect(buildEvent.success).toBe(false); - break; - } - }), - take(2), - ) - .toPromise(); - await run.stop(); - }); - }); - - it(`supports lazy bundle for import() calls`, async () => { - host.writeMultipleFiles({ - 'src/lazy-module.ts': 'export const value = 42;', - 'src/main.ts': `import('./lazy-module');`, - }); - // Using `import()` in TS require targetting `esnext` modules. - host.replaceInFile('src/tsconfig.app.json', `"module": "es2015"`, `"module": "esnext"`); - - const { files } = await browserBuild(architect, host, target); - expect(files['lazy-module.js']).not.toBeUndefined(); - }); - - it(`supports lazy bundle for dynamic import() calls`, async () => { - host.writeMultipleFiles({ - 'src/lazy-module.ts': 'export const value = 42;', - 'src/main.ts': ` - const lazyFileName = 'module'; - import(/*webpackChunkName: '[request]'*/'./lazy-' + lazyFileName); - `, - }); - host.replaceInFile('src/tsconfig.app.json', `"module": "es2015"`, `"module": "esnext"`); - - const { files } = await browserBuild(architect, host, target); - expect(files['lazy-module.js']).not.toBeUndefined(); - }); - - it(`supports lazy bundle for System.import() calls`, async () => { - const lazyfiles = { - 'src/lazy-module.ts': 'export const value = 42;', - 'src/main.ts': `declare var System: any; System.import('./lazy-module');`, - }; - - host.writeMultipleFiles(lazyfiles); - addLazyLoadedModulesInTsConfig(host, lazyfiles); - - const { files } = await browserBuild(architect, host, target); - expect(files['lazy-module.js']).not.toBeUndefined(); - }); - - it(`supports hiding lazy bundle module name`, async () => { - host.writeMultipleFiles({ - 'src/lazy-module.ts': 'export const value = 42;', - 'src/main.ts': `const lazyFileName = 'module'; import('./lazy-' + lazyFileName);`, - }); - host.replaceInFile('src/tsconfig.app.json', `"module": "es2015"`, `"module": "esnext"`); - - const { files } = await browserBuild(architect, host, target, { namedChunks: false }); - expect(files['0.js']).not.toBeUndefined(); - }); - - it(`supports making a common bundle for shared lazy modules`, async () => { - host.writeMultipleFiles({ - 'src/one.ts': `import * as http from '@angular/common/http'; console.log(http);`, - 'src/two.ts': `import * as http from '@angular/common/http'; console.log(http);`, - 'src/main.ts': `import('./one'); import('./two');`, - }); - - const { files } = await browserBuild(architect, host, target); - expect(files['one.js']).not.toBeUndefined(); - expect(files['two.js']).not.toBeUndefined(); - // TODO: the chunk with common modules used to be called `common`, see why that changed. - expect(files['default~one~two.js']).not.toBeUndefined(); - }); - - it(`supports disabling the common bundle`, async () => { - host.writeMultipleFiles({ - 'src/one.ts': `import * as http from '@angular/common/http'; console.log(http);`, - 'src/two.ts': `import * as http from '@angular/common/http'; console.log(http);`, - 'src/main.ts': `import('./one'); import('./two');`, - }); - - const { files } = await browserBuild(architect, host, target, { commonChunk: false }); - expect(files['one.js']).not.toBeUndefined(); - expect(files['two.js']).not.toBeUndefined(); - expect(files['common.js']).toBeUndefined(); - }); - - it(`supports extra lazy modules array in JIT`, async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles({ - 'src/app/app.component.ts': ` - import { Component, SystemJsNgModuleLoader } from '@angular/core'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'], - }) - export class AppComponent { - title = 'app'; - constructor(loader: SystemJsNgModuleLoader) { - // Module will be split at build time and loaded when requested below - loader.load('src/app/lazy/lazy.module#LazyModule') - .then((factory) => { /* Use factory here */ }); - } - }`, - }); - host.replaceInFile('src/tsconfig.app.json', `"module": "es2015"`, `"module": "esnext"`); - addLazyLoadedModulesInTsConfig(host, lazyModuleFiles); - - const { files } = await browserBuild(architect, host, target, { - lazyModules: ['src/app/lazy/lazy.module'], - }); - expect(files['src-app-lazy-lazy-module.js']).not.toBeUndefined(); - }); - - it(`supports extra lazy modules array in AOT`, async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles({ - 'src/app/app.component.ts': ` - import { Component, SystemJsNgModuleLoader } from '@angular/core'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'], - }) - export class AppComponent { - title = 'app'; - constructor(loader: SystemJsNgModuleLoader) { - // Module will be split at build time and loaded when requested below - loader.load('src/app/lazy/lazy.module#LazyModule') - .then((factory) => { /* Use factory here */ }); - } - }`, - }); - host.replaceInFile('src/tsconfig.app.json', `"module": "es2015"`, `"module": "esnext"`); - addLazyLoadedModulesInTsConfig(host, lazyModuleFiles); - const { files } = await browserBuild(architect, host, target, { - lazyModules: ['src/app/lazy/lazy.module'], - aot: true, - }); - - if (!veEnabled) { - const data = await files['src-app-lazy-lazy-module.js']; - expect(data).not.toBeUndefined('Lazy module output bundle does not exist'); - expect(data).toContain('LazyModule.ɵmod'); - } else { - expect(files['src-app-lazy-lazy-module-ngfactory.js']).not.toBeUndefined(); - } - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/license-extraction_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/license-extraction_spec_large.ts deleted file mode 100644 index ee15546581ce..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/license-extraction_spec_large.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder license extraction', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - // Ignored because license works when trying manually on a project, but doesn't work here. - it('works', async () => { - // TODO: make license extraction independent from optimization level. - const overrides = { extractLicenses: true, optimization: true }; - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['3rdpartylicenses.txt']).not.toBeUndefined(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/no-entry-module_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/no-entry-module_spec_large.ts deleted file mode 100644 index 70ab4e64dc9b..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/no-entry-module_spec_large.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { browserBuild, createArchitect, host, veEnabled } from '../utils'; - -describe('Browser Builder no entry module', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - // Remove the bootstrap but keep a reference to AppModule so the import is not elided. - host.replaceInFile('src/main.ts', /platformBrowserDynamic.*?bootstrapModule.*?;/, ''); - host.appendToFile('src/main.ts', 'console.log(AppModule);'); - - await browserBuild(architect, host, target, { baseHref: '/myUrl' }); - }); - - it('reports warning when no bootstrap code', async () => { - if (!veEnabled) { - pending('Does not apply to Ivy.'); - - return; - } - - host.replaceInFile('src/main.ts', /./g, ''); - host.appendToFile('src/main.ts', `import './app/app.module';`); - - const logger = new TestLogger('no-bootstrap'); - await browserBuild(architect, host, target, { baseHref: '/myUrl' }, { logger }); - expect(logger.includes('Lazy routes discovery is not enabled')).toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/optimization-level_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/optimization-level_spec_large.ts deleted file mode 100644 index b37c9dc9afaf..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/optimization-level_spec_large.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder optimization level', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const overrides = { optimization: true }; - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js']).not.toContain('AppComponent'); - }); - - it('tsconfig target changes optimizations to use ES2015', async () => { - host.replaceInFile('tsconfig.json', '"target": "es5"', '"target": "es2015"'); - - const overrides = { optimization: true }; - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['vendor.js']).toMatch(/class \w{constructor\(\){/); - }); - - it('supports styles only optimizations', async () => { - const overrides = { - optimization: { - styles: true, - scripts: false, - }, - aot: true, - extractCss: true, - styles: ['src/styles.css'], - }; - - host.appendToFile('src/main.ts', '/** js comment should not be dropped */'); - host.appendToFile('src/app/app.component.css', 'div { color: white }'); - host.writeMultipleFiles({ - 'src/styles.css': `div { color: white }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js']).toContain('js comment should not be dropped'); - expect(await files['main.js']).toContain('color:#fff'); - expect(await files['styles.css']).toContain('color:#fff'); - }); - - it('supports scripts only optimizations', async () => { - const overrides = { - optimization: { - styles: false, - scripts: true, - }, - aot: true, - extractCss: true, - styles: ['src/styles.css'], - }; - - host.appendToFile('src/main.ts', '/** js comment should be dropped */'); - host.appendToFile('src/app/app.component.css', 'div { color: white }'); - host.writeMultipleFiles({ - 'src/styles.css': `div { color: white }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js']).not.toContain('js comment should be dropped'); - expect(await files['main.js']).toContain('color: white'); - expect(await files['styles.css']).toContain('color: white'); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/output-hashing_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/output-hashing_spec_large.ts deleted file mode 100644 index d81ef71eeda5..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/output-hashing_spec_large.ts +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { normalize } from '@angular-devkit/core'; -import { - browserBuild, - createArchitect, - host, - lazyModuleFiles, - lazyModuleFnImport, -} from '../utils'; - -describe('Browser Builder output hashing', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('updates hash as content changes', async () => { - const OUTPUT_RE = /(main|styles|lazy\.module)\.([a-z0-9]+)\.(chunk|bundle)\.(js|css)$/; - - function generateFileHashMap(): Map { - const hashes = new Map(); - - host - .scopedSync() - .list(normalize('./dist')) - .forEach(name => { - const matches = name.match(OUTPUT_RE); - if (matches) { - const [, module, hash] = matches; - hashes.set(module, hash); - } - }); - - return hashes; - } - - function validateHashes( - oldHashes: Map, - newHashes: Map, - shouldChange: Array, - ): void { - newHashes.forEach((hash, module) => { - if (hash == oldHashes.get(module)) { - if (shouldChange.includes(module)) { - throw new Error( - `Module "${module}" did not change hash (${hash}), but was expected to.`, - ); - } - } else if (!shouldChange.includes(module)) { - throw new Error(`Module "${module}" changed hash (${hash}), but was not expected to.`); - } - }); - } - - let oldHashes: Map; - let newHashes: Map; - - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - - const overrides = { outputHashing: 'all', extractCss: true }; - - // We must do several builds instead of a single one in watch mode, so that the output - // path is deleted on each run and only contains the most recent files. - await browserBuild(architect, host, target, overrides); - - // Save the current hashes. - oldHashes = generateFileHashMap(); - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - - await browserBuild(architect, host, target, overrides); - newHashes = generateFileHashMap(); - validateHashes(oldHashes, newHashes, []); - oldHashes = newHashes; - host.writeMultipleFiles({ 'src/styles.css': 'body { background: blue; }' }); - - // Style hash should change. - await browserBuild(architect, host, target, overrides); - newHashes = generateFileHashMap(); - validateHashes(oldHashes, newHashes, ['styles']); - oldHashes = newHashes; - host.writeMultipleFiles({ 'src/app/app.component.css': 'h1 { margin: 10px; }' }); - - // Main hash should change, since inline styles go in the main bundle. - await browserBuild(architect, host, target, overrides); - newHashes = generateFileHashMap(); - validateHashes(oldHashes, newHashes, ['main']); - oldHashes = newHashes; - host.appendToFile('src/app/lazy/lazy.module.ts', `console.log(1);`); - - // Lazy loaded bundle should change, and so should inline. - await browserBuild(architect, host, target, overrides); - newHashes = generateFileHashMap(); - validateHashes(oldHashes, newHashes, ['lazy.module']); - oldHashes = newHashes; - host.appendToFile('src/main.ts', ''); - - // Nothing should have changed. - await browserBuild(architect, host, target, overrides); - newHashes = generateFileHashMap(); - validateHashes(oldHashes, newHashes, []); - }); - - it('supports options', async () => { - host.writeMultipleFiles({ 'src/styles.css': `h1 { background: url('./spectrum.png')}` }); - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - - // We must do several builds instead of a single one in watch mode, so that the output - // path is deleted on each run and only contains the most recent files. - // 'all' should hash everything. - await browserBuild(architect, host, target, { outputHashing: 'all', extractCss: true }); - - expect(host.fileMatchExists('dist', /runtime\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /main\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /polyfills\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /vendor\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.css/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /spectrum\.[0-9a-f]{20}\.png/)).toBeTruthy(); - - // 'none' should hash nothing. - await browserBuild(architect, host, target, { outputHashing: 'none', extractCss: true }); - - expect(host.fileMatchExists('dist', /runtime\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /main\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /polyfills\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /vendor\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.css/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /spectrum\.[0-9a-f]{20}\.png/)).toBeFalsy(); - - // 'media' should hash css resources only. - await browserBuild(architect, host, target, { outputHashing: 'media', extractCss: true }); - - expect(host.fileMatchExists('dist', /runtime\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /main\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /polyfills\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /vendor\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.css/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /spectrum\.[0-9a-f]{20}\.png/)).toBeTruthy(); - - // 'bundles' should hash bundles only. - await browserBuild(architect, host, target, { outputHashing: 'bundles', extractCss: true }); - expect(host.fileMatchExists('dist', /runtime\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /main\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /polyfills\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /vendor\.[0-9a-f]{20}\.js/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.css/)).toBeTruthy(); - expect(host.fileMatchExists('dist', /spectrum\.[0-9a-f]{20}\.png/)).toBeFalsy(); - }); - - it('does not hash non injected styles', async () => { - const overrides = { - outputHashing: 'all', - extractCss: true, - styles: [{ input: 'src/styles.css', inject: false }], - }; - - await browserBuild(architect, host, target, overrides); - - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.js.map/)).toBeFalsy(); - expect(host.scopedSync().exists(normalize('dist/styles.css'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/styles.css.map'))).toBe(true); - }); - - it('does not hash non injected styles when optimization is enabled', async () => { - const overrides = { - outputHashing: 'all', - extractCss: true, - optimization: true, - styles: [{ input: 'src/styles.css', inject: false }], - }; - - await browserBuild(architect, host, target, overrides); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.js/)).toBeFalsy(); - expect(host.fileMatchExists('dist', /styles\.[0-9a-f]{20}\.js.map/)).toBeFalsy(); - expect(host.scopedSync().exists(normalize('dist/styles.css'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/styles.css.map'))).toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/output-path_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/output-path_spec_large.ts deleted file mode 100644 index f661a9cecade..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/output-path_spec_large.ts +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { getSystemPath, join, virtualFs } from '@angular-devkit/core'; -import * as fs from 'fs'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder output path', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('deletes output path', async () => { - // Write a file to the output path to later verify it was deleted. - await host.write( - join(host.root(), 'dist/file.txt'), - virtualFs.stringToFileBuffer('file'), - ).toPromise(); - - // Delete an app file to force a failed compilation. - // Failed compilations still delete files, but don't output any. - await host.delete(join(host.root(), 'src', 'app', 'app.component.ts')).toPromise(); - - const run = await architect.scheduleTarget(target); - const output = await run.result; - expect(output.success).toBe(false); - expect(await host.exists(join(host.root(), 'dist')).toPromise()).toBe(false); - await run.stop(); - }); - - it('deletes output path and unlink symbolic link', async () => { - // Write a file to the output path to later verify it was deleted. - host.writeMultipleFiles({ - 'src-link/dummy.txt': '', - 'dist/file.txt': virtualFs.stringToFileBuffer('file'), - }); - - const distLinked = join(host.root(), 'dist', 'linked'); - - // create symbolic link - fs.symlinkSync( - getSystemPath(join(host.root(), 'src-link')), - getSystemPath(distLinked), - 'junction', - ); - - expect(await host.exists(distLinked).toPromise()).toBe(true); - - // Delete an app file to force a failed compilation. - // Failed compilations still delete files, but don't output any. - await host.delete(join(host.root(), 'src', 'app', 'app.component.ts')).toPromise(); - const run = await architect.scheduleTarget(target); - const output = await run.result; - expect(output.success).toBe(false); - - expect(await host.exists(join(host.root(), 'dist')).toPromise()).toBe(false); - expect(await host.exists(join(host.root(), 'src-link')).toPromise()).toBe(true); - }); - - it('does not allow output path to be project root', async () => { - const overrides = { outputPath: './' }; - const run = await architect.scheduleTarget(target, overrides); - try { - await run.result; - expect('THE ABOVE LINE SHOULD THROW').toBe(''); - } catch { } - await run.stop(); - }); - - it('works with absolute outputPath', async () => { - const overrides = { - outputPath: getSystemPath(join(host.root(), 'dist')), - }; - const { files } = await browserBuild(architect, host, target, overrides); - expect('main.js' in files).toBe(true); - expect('index.html' in files).toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/poll_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/poll_spec_large.ts deleted file mode 100644 index 32859c66f38a..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/poll_spec_large.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { debounceTime, take, tap } from 'rxjs/operators'; -import { createArchitect, host } from '../utils'; - - -describe('Browser Builder poll', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const overrides = { watch: true, poll: 10000 }; - const intervals: number[] = []; - let startTime: number | undefined; - - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - // Debounce 1s, otherwise changes are too close together and polling doesn't work. - debounceTime(1000), - tap((buildEvent) => { - expect(buildEvent.success).toBe(true); - if (startTime != undefined) { - intervals.push(Date.now() - startTime - 1000); - } - startTime = Date.now(); - host.appendToFile('src/main.ts', 'console.log(1);'); - }), - take(4), - ).toPromise(); - - intervals.sort(); - const median = intervals[Math.trunc(intervals.length / 2)]; - expect(median).toBeGreaterThan(3000); - expect(median).toBeLessThan(12000); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/profile_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/profile_spec_large.ts deleted file mode 100644 index 4be69f531df2..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/profile_spec_large.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { BrowserBuilderOutput } from '../../src/browser'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder profile', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { profile: true }); - const output = await run.result as BrowserBuilderOutput; - - expect(output.success).toBe(true); - - const speedMeasureLogPath = normalize('speed-measure-plugin.json'); - expect(host.scopedSync().exists(normalize('chrome-profiler-events.json'))).toBe(true); - expect(host.scopedSync().exists(speedMeasureLogPath)).toBe(true); - - const content = virtualFs.fileBufferToString(host.scopedSync().read(speedMeasureLogPath)); - expect(content).toContain('plugins'); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/rebuild_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/rebuild_spec_large.ts deleted file mode 100644 index 56b23dabbd15..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/rebuild_spec_large.ts +++ /dev/null @@ -1,545 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { join, logging, normalize, virtualFs } from '@angular-devkit/core'; -import { debounceTime, take, takeWhile, tap } from 'rxjs/operators'; -import { - createArchitect, - host, - lazyModuleFiles, - lazyModuleFnImport, - outputPath, - veEnabled, -} from '../utils'; - -describe('Browser Builder rebuilds', () => { - const target = { project: 'app', target: 'build' }; - // Rebuild tests are especially sensitive to time between writes due to file watcher - // behaviour. Give them a while. - const rebuildDebounceTime = 3000; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('rebuilds on TS file changes', async () => { - const goldenValueFiles: { [path: string]: string } = { - 'src/app/app.module.ts': ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - - console.log('$$_E2E_GOLDEN_VALUE_1'); - export let X = '$$_E2E_GOLDEN_VALUE_2'; - `, - 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; - import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } - - platformBrowserDynamic().bootstrapModule(AppModule); - - import * as m from './app/app.module'; - console.log(m.X); - console.log('$$_E2E_GOLDEN_VALUE_3'); - `, - }; - - const overrides = { watch: true }; - - let phase = 1; - const run = await architect.scheduleTarget(target, overrides); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(result => { - expect(result.success).toBe(true, 'build should succeed'); - const hasLazyChunk = host.scopedSync().exists(normalize('dist/lazy-lazy-module.js')); - switch (phase) { - case 1: - // No lazy chunk should exist. - if (!hasLazyChunk) { - phase = 2; - host.writeMultipleFiles({ ...lazyModuleFiles, ...lazyModuleFnImport }); - } - break; - - case 2: - // A lazy chunk should have been with the filename. - if (hasLazyChunk) { - phase = 3; - host.writeMultipleFiles(goldenValueFiles); - } - break; - - case 3: - // The golden values should be present and in the right order. - const re = new RegExp( - /\$\$_E2E_GOLDEN_VALUE_1(.|\n|\r)*/.source + - /\$\$_E2E_GOLDEN_VALUE_2(.|\n|\r)*/.source + - /\$\$_E2E_GOLDEN_VALUE_3/.source, - ); - const fileName = './dist/main.js'; - const content = virtualFs.fileBufferToString( - host.scopedSync().read(normalize(fileName)), - ); - - if (re.test(content)) { - phase = 4; - } - break; - } - }), - takeWhile(() => phase < 4), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds on CSS changes', async () => { - const overrides = { watch: true }; - - const run = await architect.scheduleTarget(target, overrides); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => expect(buildEvent.success).toBe(true)), - tap(() => host.appendToFile('src/app/app.component.css', ':host { color: blue; }')), - take(2), - ) - .toPromise(); - await run.stop(); - }); - - it('type checks on rebuilds', async () => { - host.writeMultipleFiles({ - 'src/funky2.ts': `export const funky2 = (value: string) => value + 'hello';`, - 'src/funky.ts': `export * from './funky2';`, - }); - host.appendToFile( - 'src/main.ts', - ` - import { funky2 } from './funky'; - console.log(funky2('town')); - `, - ); - - const overrides = { watch: true, forkTypeChecker: false }; - const logger = new TestLogger('rebuild-type-errors'); - const typeError = `is not assignable to parameter of type 'number'`; - let buildNumber = 0; - - const run = await architect.scheduleTarget(target, overrides, { logger }); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => { - buildNumber += 1; - switch (buildNumber) { - case 1: - expect(buildEvent.success).toBe(true); - // Make an invalid version of the file. - // Should trigger a rebuild, this time an error is expected. - host.writeMultipleFiles({ - 'src/funky2.ts': `export const funky2 = (value: number) => value + 1;`, - }); - break; - - case 2: - // The second build should error out with a type error on the type of an argument. - expect(buildEvent.success).toBe(false); - expect(logger.includes(typeError)).toBe(true); - logger.clear(); - // Change an UNRELATED file and the error should still happen. - // Should trigger a rebuild, this time an error is also expected. - host.appendToFile('src/app/app.module.ts', `console.log(1);`); - break; - - case 3: - // The third build should have the same error as the first. - expect(buildEvent.success).toBe(false); - expect(logger.includes(typeError)).toBe(true); - logger.clear(); - // Fix the error. - host.writeMultipleFiles({ - 'src/funky2.ts': `export const funky2 = (value: string) => value + 'hello';`, - }); - break; - - default: - expect(buildEvent.success).toBe(true); - break; - } - }), - take(4), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds on type changes', async () => { - host.writeMultipleFiles({ 'src/type.ts': `export type MyType = number;` }); - host.appendToFile('src/main.ts', `import { MyType } from './type';`); - - const overrides = { watch: true }; - const run = await architect.scheduleTarget(target, overrides); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => expect(buildEvent.success).toBe(true)), - tap(() => host.writeMultipleFiles({ 'src/type.ts': `export type MyType = string;` })), - take(2), - ) - .toPromise(); - }); - - it('rebuilds after errors in JIT', async () => { - const origContent = virtualFs.fileBufferToString( - host.scopedSync().read(normalize('src/app/app.component.ts')), - ); - host.appendToFile('./src/app/app.component.ts', `console.logg('error')`); - - const overrides = { watch: true, aot: false }; - let buildNumber = 0; - const logger = new logging.Logger(''); - let logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(target, overrides, { logger }); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => { - buildNumber++; - switch (buildNumber) { - case 1: - // The first build should error out with an error. - expect(buildEvent.success).toBe(false); - expect(logs.join()).toContain(`Property 'logg' does not exist on type 'Console'`); - logs = []; - // Fix the error. - host.writeMultipleFiles({ - 'src/app/app.component.ts': ` - ${origContent} - console.errorr('error'); - `, - }); - break; - - case 2: - // The second build should have everything fixed. - expect(buildEvent.success).toBe(true); - expect(logs.join()).not.toContain('Module build failed'); - break; - } - }), - take(2), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds after errors in AOT', async () => { - // DISABLED_FOR_IVY - These should pass but are currently not supported - if (!veEnabled) { - pending('Broken in Ivy: https://github.com/angular/angular/issues/32214'); - - return; - } - - // Save the original contents of `./src/app/app.component.ts`. - const origContent = virtualFs.fileBufferToString( - host.scopedSync().read(normalize('src/app/app.component.ts')), - ); - // Add a major static analysis error on a non-main file to the initial build. - host.replaceInFile('./src/app/app.component.ts', `'app-root'`, `(() => 'app-root')()`); - - const overrides = { watch: true, aot: true }; - const logger = new TestLogger('rebuild-aot-errors'); - const staticAnalysisError = !veEnabled - ? 'selector must be a string' - : 'Function expressions are not supported in decorators'; - const syntaxError = 'Declaration or statement expected.'; - let buildNumber = 0; - - const run = await architect.scheduleTarget(target, overrides, { logger }); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => { - buildNumber += 1; - switch (buildNumber) { - case 1: - // The first build should error out with a static analysis error. - expect(buildEvent.success).toBe(false); - expect(logger.includes(staticAnalysisError)).toBe(true); - logger.clear(); - // Fix the static analysis error. - host.writeMultipleFiles({ 'src/app/app.component.ts': origContent }); - break; - - case 2: - expect(buildEvent.success).toBe(true); - expect(logger.includes(staticAnalysisError)).toBe(false); - logger.clear(); - // Add an syntax error to a non-main file. - host.appendToFile('src/app/app.component.ts', `]]]`); - break; - - case 3: - // The third build should have TS syntax error. - expect(buildEvent.success).toBe(false); - expect(logger.includes(syntaxError)).toBe(true); - expect(logger.includes(staticAnalysisError)).toBe(false); - logger.clear(); - // Fix the syntax error, but add the static analysis error again. - host.writeMultipleFiles({ - 'src/app/app.component.ts': origContent.replace( - `'app-root'`, - `(() => 'app-root')()`, - ), - }); - break; - - case 4: - expect(buildEvent.success).toBe(false); - expect(logger.includes(syntaxError)).toBe(false); - expect(logger.includes(staticAnalysisError)).toBe(true); - logger.clear(); - // Restore the file to a error-less state. - host.writeMultipleFiles({ 'src/app/app.component.ts': origContent }); - break; - - case 5: - // The fifth build should have everything fixed.. - expect(buildEvent.success).toBe(true); - expect(logger.includes(syntaxError)).toBe(false); - expect(logger.includes(staticAnalysisError)).toBe(false); - break; - } - }), - take(5), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds AOT factories', async () => { - host.writeMultipleFiles({ - 'src/app/app.component.css': ` - @import './imported-styles.css'; - body {background-color: #00f;} - `, - 'src/app/imported-styles.css': 'p {color: #f00;}', - }); - - const overrides = { watch: true, aot: true }; - let buildNumber = 0; - - const run = await architect.scheduleTarget(target, overrides); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => { - buildNumber += 1; - const fileName = './dist/main.js'; - let content; - switch (buildNumber) { - case 1: - // Trigger a few rebuilds first. - // The AOT compiler is still optimizing rebuilds on the first rebuilds. - expect(buildEvent.success).toBe(true); - host.appendToFile('src/main.ts', 'console.log(1);'); - break; - - case 2: - expect(buildEvent.success).toBe(true); - host.appendToFile('src/main.ts', 'console.log(1);'); - break; - - case 3: - // Change the component html. - expect(buildEvent.success).toBe(true); - host.appendToFile('src/app/app.component.html', '

HTML_REBUILD_STRING

'); - break; - - case 4: - // Check if html changes are added to factories. - expect(buildEvent.success).toBe(true); - content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - expect(content).toContain('HTML_REBUILD_STRING'); - // Change the component css. - host.appendToFile('src/app/app.component.css', 'CSS_REBUILD_STRING {color: #f00;}'); - break; - - case 5: - // Check if css changes are added to factories. - expect(buildEvent.success).toBe(true); - content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - expect(content).toContain('CSS_REBUILD_STRING'); - // Change the component css import. - host.appendToFile( - 'src/app/app.component.css', - 'CSS_DEP_REBUILD_STRING {color: #f00;}', - ); - break; - - case 6: - // Check if css import changes are added to factories. - expect(buildEvent.success).toBe(true); - content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - expect(content).toContain('CSS_DEP_REBUILD_STRING'); - // Change the component itself. - host.replaceInFile( - 'src/app/app.component.ts', - 'app-root', - 'app-root-FACTORY_REBUILD_STRING', - ); - break; - - case 7: - // Check if component changes are added to factories. - expect(buildEvent.success).toBe(true); - content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - expect(content).toContain('FACTORY_REBUILD_STRING'); - break; - } - }), - take(7), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds on changes in barrel file dependency', async () => { - host.writeMultipleFiles({ - 'src/index.ts': `export * from './interface'`, - 'src/interface.ts': `export interface Foo { bar: boolean };`, - }); - host.appendToFile( - 'src/main.ts', - ` - import { Foo } from './index'; - const x: Foo = { bar: true }; - `, - ); - - const overrides = { watch: true, aot: false }; - let buildNumber = 0; - const run = await architect.scheduleTarget(target, overrides); - await run.output - .pipe( - debounceTime(rebuildDebounceTime), - tap(buildEvent => { - buildNumber += 1; - switch (buildNumber) { - case 1: - expect(buildEvent.success).toBe(true); - host.writeMultipleFiles({ - 'src/interface.ts': `export interface Foo { - bar: boolean; - baz?: string; - };`, - }); - break; - - case 2: - expect(buildEvent.success).toBe(true); - break; - } - }), - take(2), - ) - .toPromise(); - await run.stop(); - }); - - it('rebuilds AOT on CSS changes', async () => { - const overrides = { watch: true, aot: true }; - - let buildCount = 1; - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - debounceTime(rebuildDebounceTime), - tap(() => { - const content = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - - switch (buildCount) { - case 1: - expect(content).not.toContain('color: green'); - host.appendToFile('src/app/app.component.css', 'h1 { color: green; }'); - break; - case 2: - expect(content).toContain('color: green'); - break; - } - - buildCount++; - }), - tap((buildEvent) => expect(buildEvent.success).toBe(true)), - take(2), - ).toPromise(); - await run.stop(); - }); - - it('rebuilds AOT on HTML changes', async () => { - const overrides = { watch: true, aot: true }; - - let buildCount = 1; - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - debounceTime(rebuildDebounceTime), - tap(() => { - const content = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - - switch (buildCount) { - case 1: - expect(content).not.toContain('New Updated Content'); - host.appendToFile('src/app/app.component.html', 'New Updated Content'); - break; - case 2: - expect(content).toContain('New Updated Content'); - break; - } - - buildCount++; - }), - tap((buildEvent) => expect(buildEvent.success).toBe(true)), - take(2), - ).toPromise(); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/replacements_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/replacements_spec_large.ts deleted file mode 100644 index 49e852738ea4..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/replacements_spec_large.ts +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { normalize, virtualFs } from '@angular-devkit/core'; -import { of, race } from 'rxjs'; -import { delay, filter, map, take, takeUntil, takeWhile, tap, timeout } from 'rxjs/operators'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder file replacements', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - beforeEach(() => host.writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 42;', - 'src/meaning.ts': `export var meaning = 10;`, - - 'src/main.ts': ` - import { meaning } from './meaning'; - - console.log(meaning); - `, - })); - - it('allows file replacements', async () => { - const overrides = { - fileReplacements: [ - { - replace: normalize('/src/meaning.ts'), - with: normalize('/src/meaning-too.ts'), - }, - ], - }; - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js']).toMatch(/meaning\s*=\s*42/); - expect(await files['main.js']).not.toMatch(/meaning\s*=\s*10/); - }); - - it(`allows file replacements with deprecated format`, async () => { - const overrides = { - fileReplacements: [ - { - src: normalize('/src/meaning.ts'), - replaceWith: normalize('/src/meaning-too.ts'), - }, - ], - }; - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js']).toMatch(/meaning\s*=\s*42/); - expect(await files['main.js']).not.toMatch(/meaning\s*=\s*10/); - }); - - it(`fails compilation with missing 'replace' file`, async () => { - const overrides = { - fileReplacements: [ - { - replace: normalize('/src/meaning.ts'), - with: normalize('/src/meaning-three.ts'), - }, - ], - }; - - const run = await architect.scheduleTarget(target, overrides); - try { - await run.result; - expect('THE ABOVE LINE SHOULD THROW').toBe(''); - } catch {} - await run.stop(); - }); - - it(`fails compilation with missing 'with' file`, async () => { - const overrides = { - fileReplacements: [ - { - replace: normalize('/src/meaning-three.ts'), - with: normalize('/src/meaning-too.ts'), - }, - ], - }; - - const run = await architect.scheduleTarget(target, overrides); - try { - await run.result; - expect('THE ABOVE LINE SHOULD THROW').toBe(''); - } catch {} - await run.stop(); - }); - - it('file replacements work with watch mode', async () => { - const overrides = { - fileReplacements: [ - { - replace: normalize('/src/meaning.ts'), - with: normalize('/src/meaning-too.ts'), - }, - ], - watch: true, - }; - - let buildCount = 0; - let phase = 1; - - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - timeout(30000), - tap((result) => { - expect(result.success).toBe(true, 'build should succeed'); - - const fileName = normalize('dist/main.js'); - const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName)); - const has42 = /meaning\s*=\s*42/.test(content); - buildCount++; - switch (phase) { - case 1: - const has10 = /meaning\s*=\s*10/.test(content); - - if (has42 && !has10) { - phase = 2; - host.writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 84;', - }); - } - break; - - case 2: - const has84 = /meaning\s*=\s*84/.test(content); - - if (has84 && !has42) { - phase = 3; - } else { - // try triggering a rebuild again - host.writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 84;', - }); - } - break; - } - }), - takeWhile(() => phase < 3), - ).toPromise().catch(() => { - throw new Error(`stuck at phase ${phase} [builds: ${buildCount}]`); - }); - - await run.stop(); - }); - - it('file replacements work with forked type checker on watch mode', async () => { - host.writeMultipleFiles({ - 'src/file-replaced.ts': 'export var obj = { one: 1, two: 2 };', - 'src/file.ts': `export var obj = { one: 1 };`, - 'src/main.ts': ` - import { obj } from './file'; - console.log(obj.two); - `, - }); - - const overrides = { - fileReplacements: [{ - replace: normalize('/src/file.ts'), - with: normalize('/src/file-replaced.ts'), - }], - watch: true, - }; - - const unexpectedError = `Property 'two' does not exist on type '{ one: number; }'`; - const expectedError = `Property 'prop' does not exist on type '{}'`; - const logger = new TestLogger('rebuild-type-errors'); - - // Race between a timeout and the expected log entry. - const stop$ = race( - of(null).pipe(delay(45000 * 2 / 3)), - logger.pipe( - filter(entry => entry.message.includes(expectedError)), - map(entry => entry.message), - take(1), - ), - ); - - let errorAdded = false; - const run = await architect.scheduleTarget(target, overrides, { logger }); - run.output.pipe( - tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')), - tap(() => { - // Introduce a known type error to detect in the logger filter. - if (!errorAdded) { - host.appendToFile('src/main.ts', 'console.log({}.prop);'); - errorAdded = true; - } - }), - takeUntil(stop$), - ).subscribe(); - - const res = await stop$.toPromise(); - expect(res).not.toBe(null, 'Test timed out.'); - expect(res).not.toContain(unexpectedError); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/resolve-json-module_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/resolve-json-module_spec_large.ts deleted file mode 100644 index 369032e49145..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/resolve-json-module_spec_large.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { join, virtualFs } from '@angular-devkit/core'; -import { take, tap } from 'rxjs/operators'; -import { createArchitect, host, outputPath } from '../utils'; - - -describe('Browser Builder resolve json module', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works with watch', async () => { - host.writeMultipleFiles({ - 'src/my-json-file.json': `{"foo": "1"}`, - 'src/main.ts': `import * as a from './my-json-file.json'; console.log(a);`, - }); - - host.replaceInFile( - 'tsconfig.json', - '"target": "es2015"', - '"target": "es5", "resolveJsonModule": true', - ); - - const overrides = { watch: true }; - - let buildCount = 1; - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - tap(() => { - const content = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - - switch (buildCount) { - case 1: - expect(content).toContain('\\"foo\\":\\"1\\"'); - host.writeMultipleFiles({ - 'src/my-json-file.json': `{"foo": "2"}`, - }); - break; - case 2: - expect(content).toContain('\\"foo\\":\\"2\\"'); - break; - } - - buildCount++; - }), - tap((buildEvent) => expect(buildEvent.success).toBe(true)), - take(2), - ).toPromise(); - }); - -}); diff --git a/packages/angular_devkit/build_angular/test/browser/resources-output-path_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/resources-output-path_spec_large.ts deleted file mode 100644 index b70abccfb927..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/resources-output-path_spec_large.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -import { Architect } from '@angular-devkit/architect'; -import { normalize } from '@angular-devkit/core'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder styles resources output path', () => { - const imgSvg = ` - - - - `; - - function writeFiles() { - // Use a large image for the relative ref so it cannot be inlined. - host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); - host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); - host.writeMultipleFiles({ - 'src/styles.css': ` - h1 { background: url('/assets/global-img-absolute.svg'); } - h2 { background: url('./assets/global-img-relative.png'); } - `, - 'src/app/app.component.css': ` - h3 { background: url('/assets/component-img-absolute.svg'); } - h4 { background: url('../assets/component-img-relative.png'); } - `, - 'src/assets/global-img-absolute.svg': imgSvg, - 'src/assets/component-img-absolute.svg': imgSvg, - }); - } - - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it(`supports resourcesOutputPath in resource urls`, async () => { - writeFiles(); - // Check base paths are correctly generated. - const overrides = { - aot: true, - extractCss: true, - resourcesOutputPath: 'out-assets', - }; - - const { files } = await browserBuild(architect, host, target, overrides); - const styles = await files['styles.css']; - const main = await files['main.js']; - - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(styles).toContain(`url('out-assets/global-img-relative.png')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - expect(main).toContain(`url('out-assets/component-img-relative.png')`); - - expect(host.scopedSync() - .exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); - expect(host.scopedSync() - .exists(normalize('dist/out-assets/global-img-relative.png'))).toBe(true); - expect(host.scopedSync() - .exists(normalize('dist/assets/component-img-absolute.svg'))).toBe(true); - expect(host.scopedSync() - .exists(normalize('dist/out-assets/component-img-relative.png'))).toBe(true); - }); - - it(`supports blank resourcesOutputPath`, async () => { - writeFiles(); - - // Check base paths are correctly generated. - const overrides = { aot: true, extractCss: true }; - const { files } = await browserBuild(architect, host, target, overrides); - const styles = await files['styles.css']; - const main = await files['main.js']; - - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(styles).toContain(`url('global-img-relative.png')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - expect(main).toContain(`url('component-img-relative.png')`); - expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))) - .toBe(true); - expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))) - .toBe(true); - expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))) - .toBe(true); - expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))) - .toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/rollup_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/rollup_spec_large.ts deleted file mode 100644 index 55e96781e284..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/rollup_spec_large.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { - BrowserBuildOutput, - browserBuild, - createArchitect, - host, - lazyModuleFiles, - lazyModuleFnImport, -} from '../utils'; - - -describe('Browser Builder Rollup Concatenation test', () => { - const target = { project: 'app', target: 'build' }; - const overrides = { - experimentalRollupPass: true, - // JIT Rollup bundles will include require calls to .css and .html file, that have lost their - // path context. AOT code already inlines resources so that's not a problem. - aot: true, - // Webpack can't separate rolled-up modules into chunks. - vendorChunk: false, - commonChunk: false, - namedChunks: false, - }; - const prodOverrides = { - // Usual prod options. - fileReplacements: [{ - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }], - optimization: true, - sourceMap: false, - extractCss: true, - namedChunks: false, - aot: true, - extractLicenses: true, - vendorChunk: false, - buildOptimizer: true, - // Extra prod options we need for experimentalRollupPass. - commonChunk: false, - // Just for convenience. - outputHashing: 'none', - }; - const rollupProdOverrides = { - ...prodOverrides, - experimentalRollupPass: true, - }; - let architect: Architect; - - const getOutputSize = async (output: BrowserBuildOutput) => - (await Promise.all( - Object.keys(output.files) - .filter(name => name.endsWith('.js') && - // These aren't concatenated by Rollup so no point comparing. - !['runtime.js', 'polyfills.js'].includes(name)) - .map(name => output.files[name]), - )) - .map(content => content.length) - .reduce((acc, curr) => acc + curr, 0); - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - await browserBuild(architect, host, target, overrides); - }); - - it('works with lazy modules', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - await browserBuild(architect, host, target, overrides); - }); - - it('creates smaller or same size bundles for app without lazy bundles', async () => { - const prodOutput = await browserBuild(architect, host, target, prodOverrides); - const prodSize = await getOutputSize(prodOutput); - const rollupProdOutput = await browserBuild(architect, host, target, rollupProdOverrides); - const rollupProd = await getOutputSize(rollupProdOutput); - expect(prodSize).toBeGreaterThan(rollupProd); - }); - - it('creates smaller bundles for apps with lazy bundles', async () => { - host.writeMultipleFiles(lazyModuleFiles); - host.writeMultipleFiles(lazyModuleFnImport); - const prodOutput = await browserBuild(architect, host, target, prodOverrides); - const prodSize = await getOutputSize(prodOutput); - const rollupProdOutput = await browserBuild(architect, host, target, rollupProdOverrides); - const rollupProd = await getOutputSize(rollupProdOutput); - expect(prodSize).toBeGreaterThan(rollupProd); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/scripts-array_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/scripts-array_spec_large.ts deleted file mode 100644 index da0129c9fb5b..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/scripts-array_spec_large.ts +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { logging } from '@angular-devkit/core'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder scripts array', () => { - const scripts: { [path: string]: string } = { - 'src/input-script.js': 'console.log(\'input-script\'); var number = 1+1;', - 'src/zinput-script.js': 'console.log(\'zinput-script\');', - 'src/finput-script.js': 'console.log(\'finput-script\');', - 'src/uinput-script.js': 'console.log(\'uinput-script\');', - 'src/binput-script.js': 'console.log(\'binput-script\');', - 'src/ainput-script.js': 'console.log(\'ainput-script\');', - 'src/cinput-script.js': 'console.log(\'cinput-script\');', - 'src/lazy-script.js': 'console.log(\'lazy-script\');', - 'src/pre-rename-script.js': 'console.log(\'pre-rename-script\');', - 'src/pre-rename-lazy-script.js': 'console.log(\'pre-rename-lazy-script\');', - }; - const getScriptsOption = () => [ - 'src/input-script.js', - 'src/zinput-script.js', - 'src/finput-script.js', - 'src/uinput-script.js', - 'src/binput-script.js', - 'src/ainput-script.js', - 'src/cinput-script.js', - { input: 'src/lazy-script.js', bundleName: 'lazy-script', inject: false }, - { input: 'src/pre-rename-script.js', bundleName: 'renamed-script' }, - { input: 'src/pre-rename-lazy-script.js', bundleName: 'renamed-lazy-script', inject: false }, - ]; - - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const matches: Record = { - 'scripts.js': 'input-script', - 'lazy-script.js': 'lazy-script', - 'renamed-script.js': 'pre-rename-script', - 'renamed-lazy-script.js': 'pre-rename-lazy-script', - 'main.js': 'input-script', - 'index.html': '' - + '' - + '' - + '' - + '' - + '', - }; - - host.writeMultipleFiles(scripts); - host.appendToFile('src/main.ts', '\nimport \'./input-script.js\';'); - - // Remove styles so we don't have to account for them in the index.html order check. - const { files } = await browserBuild(architect, host, target, { - styles: [], - scripts: getScriptsOption(), - } as {}); - - for (const [fileName, content] of Object.entries(matches)) { - expect(await files[fileName]).toMatch(content); - } - }); - - it('works in watch mode with differential loading', async () => { - const matches: Record = { - 'scripts.js': 'input-script', - 'lazy-script.js': 'lazy-script', - 'renamed-script.js': 'pre-rename-script', - 'renamed-lazy-script.js': 'pre-rename-lazy-script', - 'main.js': 'input-script', - 'index.html': '' - + '' - + '' - + '' - + '' - + '', - }; - - host.writeMultipleFiles(scripts); - host.appendToFile('src/main.ts', '\nimport \'./input-script.js\';'); - - // Enable differential loading - host.appendToFile('browserslist', '\nIE 10'); - - // Remove styles so we don't have to account for them in the index.html order check. - const { files } = await browserBuild(architect, host, target, { - styles: [], - scripts: getScriptsOption(), - watch: true, - } as {}); - - for (const [fileName, content] of Object.entries(matches)) { - expect(await files[fileName]).toMatch(content); - } - }); - - it('uglifies, uses sourcemaps, and adds hashes', async () => { - host.writeMultipleFiles(scripts); - - const { files } = await browserBuild(architect, host, target, { - optimization: true, - sourceMap: true, - outputHashing: 'all', - scripts: getScriptsOption(), - } as {}); - - const fileNames = Object.keys(files); - const scriptsBundle = fileNames.find(n => /scripts\.[0-9a-f]{20}\.js/.test(n)); - expect(scriptsBundle).toBeTruthy(); - expect(await files[scriptsBundle || '']).toMatch('var number=2;'); - - expect(fileNames.some(n => /scripts\.[0-9a-f]{20}\.js\.map/.test(n))).toBeTruthy(); - expect(fileNames.some(n => /renamed-script\.[0-9a-f]{20}\.js/.test(n))).toBeTruthy(); - expect(fileNames.some(n => /renamed-script\.[0-9a-f]{20}\.js\.map/.test(n))).toBeTruthy(); - expect(fileNames.some(n => /script\.[0-9a-f]{20}\.js/.test(n))).toBeTruthy(); - expect(await files['lazy-script.js']).not.toBeUndefined(); - expect(await files['lazy-script.js.map']).not.toBeUndefined(); - expect(await files['renamed-lazy-script.js']).not.toBeUndefined(); - expect(await files['renamed-lazy-script.js.map']).not.toBeUndefined(); - }); - - it('preserves script order', async () => { - host.writeMultipleFiles(scripts); - - const { files } = await browserBuild(architect, host, target, { - scripts: getScriptsOption(), - } as {}); - - expect(await files['scripts.js']).toMatch(new RegExp( - /.*['"]input-script['"](.|\n|\r)*/.source - + /['"]zinput-script['"](.|\n|\r)*/.source - + /['"]finput-script['"](.|\n|\r)*/.source - + /['"]uinput-script['"](.|\n|\r)*/.source - + /['"]binput-script['"](.|\n|\r)*/.source - + /['"]ainput-script['"](.|\n|\r)*/.source - + /['"]cinput-script['"]/.source, - )); - }); - - it('chunk in entry', async () => { - host.writeMultipleFiles(scripts); - - const logger = new logging.Logger('build-script-chunk-entry'); - const logs: string[] = []; - logger.subscribe(({ message }) => { - logs.push(message); - }); - - await browserBuild( - architect, - host, - target, - { - scripts: getScriptsOption(), - } as {}, - { logger }, - ); - - expect(logs.join('\n')).toMatch(/\(lazy-script\) 69 bytes.*\[entry].*\[rendered]/); - expect(logs.join('\n')).toMatch(/\(renamed-script\) 78 bytes.*\[entry].*\[rendered]/); - expect(logs.join('\n')).toMatch(/\(renamed-lazy-script\) 88 bytes.*\[entry].*\[rendered]/); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/service-worker_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/service-worker_spec_large.ts deleted file mode 100644 index 3b70f2e5f477..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/service-worker_spec_large.ts +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { normalize, virtualFs } from '@angular-devkit/core'; -import { createArchitect, host } from '../utils'; - -describe('Browser Builder service worker', () => { - const manifest = { - index: '/index.html', - assetGroups: [ - { - name: 'app', - installMode: 'prefetch', - resources: { - files: [ - '/favicon.ico', - '/index.html', - '/*.bundle.css', - '/*.bundle.js', - '/*.chunk.js', - ], - }, - }, - { - name: 'assets', - installMode: 'lazy', - updateMode: 'prefetch', - resources: { - files: [ - '/assets/**', - '/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)', - ], - }, - }, - ], - }; - - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('errors if no ngsw-config.json is present', async () => { - const overrides = { serviceWorker: true }; - - const run = await architect.scheduleTarget(target, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); - - await run.stop(); - }); - - it('works with service worker', async () => { - host.writeMultipleFiles({ - 'src/ngsw-config.json': JSON.stringify(manifest), - 'src/assets/folder-asset.txt': 'folder-asset.txt', - 'src/styles.css': `body { background: url(./spectrum.png); }`, - }); - - const overrides = { serviceWorker: true }; - const run = await architect.scheduleTarget(target, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - expect(host.scopedSync().exists(normalize('dist/ngsw.json'))); - const ngswJson = JSON.parse(virtualFs.fileBufferToString( - host.scopedSync().read(normalize('dist/ngsw.json')))); - // Verify index and assets are there. - expect(ngswJson).toEqual(jasmine.objectContaining({ - configVersion: 1, - index: '/index.html', - navigationUrls: [ - { positive: true, regex: '^\\\/.*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*\\.[^\/]*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*__[^\/]*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*__[^\/]*\\\/.*$' }, - ], - assetGroups: [ - { - name: 'app', - installMode: 'prefetch', - updateMode: 'prefetch', - urls: [ - '/favicon.ico', - '/index.html', - ], - patterns: [], - }, - { - name: 'assets', - installMode: 'lazy', - updateMode: 'prefetch', - urls: [ - '/assets/folder-asset.txt', - '/spectrum.png', - ], - patterns: [], - }, - ], - dataGroups: [], - hashTable: { - '/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01', - '/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4', - '/index.html': 'f95e7a84949070c4984069b592be7969bc3187a0', - '/spectrum.png': '8d048ece46c0f3af4b598a95fd8e4709b631c3c0', - }, - })); - - await run.stop(); - }); - - it('works with service worker and baseHref', async () => { - host.writeMultipleFiles({ - 'src/ngsw-config.json': JSON.stringify(manifest), - 'src/assets/folder-asset.txt': 'folder-asset.txt', - }); - - const overrides = { serviceWorker: true, baseHref: '/foo/bar' }; - const run = await architect.scheduleTarget(target, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - expect(host.scopedSync().exists(normalize('dist/ngsw.json'))); - const ngswJson = JSON.parse(virtualFs.fileBufferToString( - host.scopedSync().read(normalize('dist/ngsw.json')))); - // Verify index and assets include the base href. - expect(ngswJson).toEqual(jasmine.objectContaining({ - configVersion: 1, - index: '/foo/bar/index.html', - navigationUrls: [ - { positive: true, regex: '^\\\/.*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*\\.[^\/]*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*__[^\/]*$' }, - { positive: false, regex: '^\\\/(?:.+\\\/)?[^\/]*__[^\/]*\\\/.*$' }, - ], - assetGroups: [ - { - name: 'app', - installMode: 'prefetch', - updateMode: 'prefetch', - urls: [ - '/foo/bar/favicon.ico', - '/foo/bar/index.html', - ], - patterns: [], - }, - { - name: 'assets', - installMode: 'lazy', - updateMode: 'prefetch', - urls: [ - '/foo/bar/assets/folder-asset.txt', - ], - patterns: [], - }, - ], - dataGroups: [], - hashTable: { - '/foo/bar/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01', - '/foo/bar/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4', - '/foo/bar/index.html': 'a5359e8e1a516683b32bbb2f9e8bf402dae4738e', - }, - })); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/source-map_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/source-map_spec_large.ts deleted file mode 100644 index df9688e1d3b1..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/source-map_spec_large.ts +++ /dev/null @@ -1,170 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { OutputHashing } from '../../src/browser/schema'; -import { browserBuild, createArchitect, host } from '../utils'; - -// tslint:disable-next-line:no-big-function -describe('Browser Builder source map', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const overrides = { - sourceMap: true, - extractCss: true, - styles: ['src/styles.css'], - }; - - host.writeMultipleFiles({ - 'src/styles.css': `div { flex: 1 }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['main.js.map']).not.toBeUndefined(); - expect(await files['styles.css.map']).not.toBeUndefined(); - }); - - it(`sourcemaps sources should not start with '/'`, async () => { - // If sourcemaps sources start with a '/' it will break VS code breakpoints - // Unless 'sourceMapPathOverrides' are provided - const overrides = { - sourceMap: true, - }; - - const { files } = await browserBuild(architect, host, target, overrides); - const mainJSMap = await files['main.js.map']; - expect(mainJSMap).not.toBeUndefined(); - - const sources: string[] = JSON.parse(mainJSMap).sources; - for (const source of sources) { - expect(source.startsWith('/')).toBe(false, `${source} started with an '/'.`); - } - }); - - it('works with outputHashing', async () => { - const { files } = await browserBuild(architect, host, target, { - sourceMap: true, - outputHashing: OutputHashing.All, - }); - - expect(Object.keys(files).some(name => /main\.[0-9a-f]{20}\.js.map/.test(name))).toBeTruthy(); - }); - - it('does not output source map when disabled', async () => { - const { files } = await browserBuild(architect, host, target, { - sourceMap: false, - }); - - expect(files['main.js.map']).toBeUndefined(); - }); - - it('supports eval source map', async () => { - const { files } = await browserBuild(architect, host, target, { - sourceMap: true, evalSourceMap: true, - }); - - expect(files['main.js.map']).toBeUndefined(); - expect(await files['main.js']).toContain('eval("function webpackEmptyAsyncContext'); - }); - - it('supports hidden sourcemaps', async () => { - const overrides = { - sourceMap: { - hidden: true, - styles: true, - scripts: true, - }, - extractCss: true, - styles: ['src/styles.scss'], - }; - - host.writeMultipleFiles({ - 'src/styles.scss': `div { flex: 1 }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect('main.js.map' in files).toBe(true); - expect('styles.css.map' in files).toBe(true); - expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); - expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); - }); - - it('supports styles only sourcemaps', async () => { - const overrides = { - sourceMap: { - styles: true, - scripts: false, - }, - extractCss: true, - styles: ['src/styles.scss'], - }; - - host.writeMultipleFiles({ - 'src/styles.scss': `div { flex: 1 }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect('main.js.map' in files).toBe(false); - expect('styles.css.map' in files).toBe(true); - expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); - expect(await files['styles.css']).toContain('sourceMappingURL=styles.css.map'); - }); - - it('supports scripts only sourcemaps', async () => { - const overrides = { - sourceMap: { - styles: false, - scripts: true, - }, - extractCss: true, - styles: ['src/styles.scss'], - }; - - host.writeMultipleFiles({ - 'src/styles.scss': `div { flex: 1 }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect('main.js.map' in files).toBe(true); - expect('styles.css.map' in files).toBe(false); - expect(await files['main.js']).toContain('sourceMappingURL=main.js.map'); - expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); - }); - - it('should not inline component styles sourcemaps when hidden', async () => { - const overrides = { - sourceMap: { - hidden: true, - styles: true, - scripts: true, - }, - extractCss: true, - styles: ['src/styles.scss'], - }; - - host.writeMultipleFiles({ - 'src/styles.scss': `div { flex: 1 }`, - 'src/app/app.component.css': `p { color: red; }`, - }); - - const { files } = await browserBuild(architect, host, target, overrides); - expect('main.js.map' in files).toBe(true); - expect('styles.css.map' in files).toBe(true); - expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); - expect(await files['main.js']).not.toContain('sourceMappingURL=data:application/json'); - expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); - expect(await files['styles.css']).not.toContain('sourceMappingURL=data:application/json'); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/stats-json_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/stats-json_spec_large.ts deleted file mode 100644 index 5da908348cd2..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/stats-json_spec_large.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder stats json', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const { files } = await browserBuild(architect, host, target, { statsJson: true }); - expect('stats.json' in files).toBe(true); - }); - - it('works with profile flag', async () => { - const { files } = await browserBuild(architect, host, target, { statsJson: true }); - expect('stats.json' in files).toBe(true); - const stats = JSON.parse(await files['stats.json']); - expect(stats.chunks[0].modules[0].profile.building).toBeDefined(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/styles_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/styles_spec_large.ts deleted file mode 100644 index 5e5e5fe9cf04..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/styles_spec_large.ts +++ /dev/null @@ -1,607 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function - -import { Architect } from '@angular-devkit/architect'; -import { logging, normalize, tags } from '@angular-devkit/core'; -import { browserBuild, createArchitect, host } from '../utils'; - -describe('Browser Builder styles', () => { - const extensionsWithImportSupport = ['css', 'scss', 'less', 'styl']; - const extensionsWithVariableSupport = ['scss', 'less', 'styl']; - const imgSvg = ` - - - - `; - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('supports global styles', async () => { - const styles = [ - 'src/input-style.css', - { input: 'src/lazy-style.css', bundleName: 'lazy-style', inject: false }, - { input: 'src/pre-rename-style.css', bundleName: 'renamed-style' }, - { input: 'src/pre-rename-lazy-style.css', bundleName: 'renamed-lazy-style', inject: false }, - ] as {}; - const cssMatches: { [path: string]: string } = { - 'styles.css': '.input-style', - 'lazy-style.css': '.lazy-style', - 'renamed-style.css': '.pre-rename-style', - 'renamed-lazy-style.css': '.pre-rename-lazy-style', - }; - const cssIndexMatches: { [path: string]: string } = { - 'index.html': - '' + - '', - }; - const jsMatches: { [path: string]: string } = { - 'styles.js': '.input-style', - 'lazy-style.js': '.lazy-style', - 'renamed-style.js': '.pre-rename-style', - 'renamed-lazy-style.js': '.pre-rename-lazy-style', - }; - const jsIndexMatches: { [path: string]: string } = { - 'index.html': - '' + - '' + - '' + - '' + - '' + - '', - }; - - host.writeMultipleFiles({ - 'src/string-style.css': '.string-style { color: red }', - 'src/input-style.css': '.input-style { color: red }', - 'src/lazy-style.css': '.lazy-style { color: red }', - 'src/pre-rename-style.css': '.pre-rename-style { color: red }', - 'src/pre-rename-lazy-style.css': '.pre-rename-lazy-style { color: red }', - }); - - let { files } = await browserBuild(architect, host, target, { extractCss: true, styles }); - // Check css files were created. - for (const cssFileName of Object.keys(cssMatches)) { - expect(await files[cssFileName]).toMatch(cssMatches[cssFileName]); - } - // Check no js files are created. - for (const jsFileName of Object.keys(jsMatches)) { - expect(jsFileName in files).toBe(false); - } - - // Check check index has styles in the right order. - for (const cssIndexFileName of Object.keys(cssIndexMatches)) { - expect(await files[cssIndexFileName]).toMatch(cssIndexMatches[cssIndexFileName]); - } - - // Also test with extractCss false. - files = (await browserBuild(architect, host, target, { extractCss: false, styles })).files; - - // Check js files were created. - for (const jsFileName of Object.keys(jsMatches)) { - expect(await files[jsFileName]).toMatch(jsMatches[jsFileName]); - } - - // Check no css files are created. - for (const cssFileName of Object.keys(cssMatches)) { - expect(cssFileName in files).toBe(false); - } - - // Check check index has styles in the right order. - for (const jsIndexFileName of Object.keys(jsIndexMatches)) { - expect(await files[jsIndexFileName]).toMatch(jsIndexMatches[jsIndexFileName]); - } - }); - - it('supports empty styleUrls in components', async () => { - host.writeMultipleFiles({ - './src/app/app.component.ts': ` - import { Component } from '@angular/core'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: [] - }) - export class AppComponent { - title = 'app'; - } - `, - }); - - await browserBuild(architect, host, target, { extractCss: true }); - }); - - extensionsWithImportSupport.forEach(ext => { - it(`supports imports in ${ext} files`, async () => { - host.writeMultipleFiles({ - [`src/styles.${ext}`]: ` - @import './imported-styles.${ext}'; - body { background-color: #00f; } - `, - [`src/imported-styles.${ext}`]: 'p { background-color: #f00; }', - [`src/app/app.component.${ext}`]: ` - @import './imported-component-styles.${ext}'; - .outer { - .inner { - background: #fff; - } - } - `, - [`src/app/imported-component-styles.${ext}`]: 'h1 { background: #000; }', - }); - - const matches: { [path: string]: RegExp } = { - 'styles.css': new RegExp( - // The global style should be there - /p\s*{\s*background-color: #f00;\s*}(.|\n|\r)*/.source + - // The global style via import should be there - /body\s*{\s*background-color: #00f;\s*}/.source, - ), - 'styles.css.map': /"mappings":".+"/, - 'main.js': new RegExp( - // The component style should be there - /h1(.|\n|\r)*background:\s*#000(.|\n|\r)*/.source + - // The component style via import should be there - /.outer(.|\n|\r)*.inner(.|\n|\r)*background:\s*#[fF]+/.source, - ), - }; - - const overrides = { - extractCss: true, - sourceMap: true, - styles: [`src/styles.${ext}`], - }; - - host.replaceInFile( - 'src/app/app.component.ts', - './app.component.css', - `./app.component.${ext}`, - ); - - const { files } = await browserBuild(architect, host, target, overrides); - for (const fileName of Object.keys(matches)) { - expect(await files[fileName]).toMatch(matches[fileName]); - } - }); - }); - - extensionsWithImportSupport.forEach(ext => { - it(`supports material imports in ${ext} files`, async () => { - host.writeMultipleFiles({ - [`src/styles.${ext}`]: ` - @import "~@angular/material/prebuilt-themes/indigo-pink.css"; - @import "@angular/material/prebuilt-themes/indigo-pink.css"; - `, - [`src/app/app.component.${ext}`]: ` - @import "~@angular/material/prebuilt-themes/indigo-pink.css"; - @import "@angular/material/prebuilt-themes/indigo-pink.css"; - `, - }); - host.replaceInFile( - 'src/app/app.component.ts', - './app.component.css', - `./app.component.${ext}`, - ); - - const overrides = { - extractCss: true, - styles: [{ input: `src/styles.${ext}` }], - }; - await browserBuild(architect, host, target, overrides); - }); - }); - - extensionsWithVariableSupport.forEach(ext => { - it(`supports ${ext} includePaths`, async () => { - let variableAssignment = ''; - let variablereference = ''; - if (ext === 'scss') { - variableAssignment = '$primary-color:'; - variablereference = '$primary-color'; - } else if (ext === 'styl') { - variableAssignment = '$primary-color ='; - variablereference = '$primary-color'; - } else if (ext === 'less') { - variableAssignment = '@primary-color:'; - variablereference = '@primary-color'; - } - - host.writeMultipleFiles({ - [`src/style-paths/variables.${ext}`]: `${variableAssignment} #f00;`, - [`src/styles.${ext}`]: ` - @import 'variables'; - h1 { color: ${variablereference}; } - `, - [`src/app/app.component.${ext}`]: ` - @import 'variables'; - h2 { color: ${variablereference}; } - `, - }); - - const matches: { [path: string]: RegExp } = { - 'styles.css': /h1\s*{\s*color: #f00;\s*}/, - 'main.js': /h2.*{.*color: #f00;.*}/, - }; - - host.replaceInFile( - 'src/app/app.component.ts', - './app.component.css', - `./app.component.${ext}`, - ); - - const overrides = { - extractCss: true, - styles: [`src/styles.${ext}`], - stylePreprocessorOptions: { - includePaths: ['src/style-paths'], - }, - }; - - const { files } = await browserBuild(architect, host, target, overrides); - for (const fileName of Object.keys(matches)) { - expect(await files[fileName]).toMatch(matches[fileName]); - } - }); - }); - - it(`supports font-awesome imports`, async () => { - host.writeMultipleFiles({ - 'src/styles.scss': ` - $fa-font-path: "~font-awesome/fonts"; - @import "~font-awesome/scss/font-awesome"; - `, - }); - - const overrides = { extractCss: true, styles: [`src/styles.scss`] }; - await browserBuild(architect, host, target, overrides); - }, 30000); - - it(`supports font-awesome imports without extractCss`, async () => { - host.writeMultipleFiles({ - 'src/styles.scss': ` - @import "~font-awesome/css/font-awesome.css"; - `, - }); - - const overrides = { extractCss: false, styles: [`src/styles.scss`] }; - await browserBuild(architect, host, target, overrides); - }, 30000); - - it(`uses autoprefixer`, async () => { - host.writeMultipleFiles({ - 'src/styles.css': tags.stripIndents` - /* normal-comment */ - /*! important-comment */ - div { flex: 1 }`, - browserslist: 'IE 10', - }); - - const overrides = { extractCss: true, optimization: false }; - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['styles.css']).toContain(tags.stripIndents` - /* normal-comment */ - /*! important-comment */ - div { -ms-flex: 1; flex: 1 }`); - }); - - it(`minimizes css`, async () => { - host.writeMultipleFiles({ - 'src/styles.css': tags.stripIndents` - /* normal-comment */ - /*! important-comment */ - div { flex: 1 }`, - }); - - const overrides = { extractCss: true, optimization: true }; - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['styles.css']).toContain('/*! important-comment */div{flex:1}'); - }); - - // TODO: consider making this a unit test in the url processing plugins. - it(`supports baseHref/deployUrl in resource urls without rebaseRootRelativeCssUrls`, async () => { - // Use a large image for the relative ref so it cannot be inlined. - host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); - host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); - host.writeMultipleFiles({ - 'src/styles.css': ` - h1 { background: url('/assets/global-img-absolute.svg'); } - h2 { background: url('./assets/global-img-relative.png'); } - `, - 'src/app/app.component.css': ` - h3 { background: url('/assets/component-img-absolute.svg'); } - h4 { background: url('../assets/component-img-relative.png'); } - `, - 'src/assets/global-img-absolute.svg': imgSvg, - 'src/assets/component-img-absolute.svg': imgSvg, - }); - - let { files } = await browserBuild(architect, host, target, { aot: true, extractCss: true }); - - // Check base paths are correctly generated. - let styles = await files['styles.css']; - let main = await files['main.js']; - - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(styles).toContain(`url('global-img-relative.png')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - expect(main).toContain(`url('component-img-relative.png')`); - - expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( - true, - ); - expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))).toBe(true); - - // Check urls with deploy-url scheme are used as is. - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: '/base/', - deployUrl: 'http://deploy.url/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - - // Check urls with base-href scheme are used as is (with deploy-url). - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: 'http://base.url/', - deployUrl: 'deploy/', - })).files; - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - - // Check urls with deploy-url and base-href scheme only use deploy-url. - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: 'http://base.url/', - deployUrl: 'http://deploy.url/', - })).files; - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - - // Check with schemeless base-href and deploy-url flags. - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: '/base/', - deployUrl: 'deploy/', - })).files; - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - - // Check with identical base-href and deploy-url flags. - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: '/base/', - deployUrl: '/base/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - - // Check with only base-href flag. - files = (await browserBuild(architect, host, target, { - extractCss: true, - baseHref: '/base/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - }, 90000); - - it(`supports baseHref/deployUrl in resource urls with rebaseRootRelativeCssUrls`, async () => { - // Use a large image for the relative ref so it cannot be inlined. - host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); - host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); - host.writeMultipleFiles({ - 'src/styles.css': ` - h1 { background: url('/assets/global-img-absolute.svg'); } - h2 { background: url('./assets/global-img-relative.png'); } - `, - 'src/app/app.component.css': ` - h3 { background: url('/assets/component-img-absolute.svg'); } - h4 { background: url('../assets/component-img-relative.png'); } - `, - 'src/assets/global-img-absolute.svg': imgSvg, - 'src/assets/component-img-absolute.svg': imgSvg, - }); - - // Check base paths are correctly generated. - const overrides = { - extractCss: true, - rebaseRootRelativeCssUrls: true, - }; - let { files } = await browserBuild(architect, host, target, { - ...overrides, - aot: true, - }); - - let styles = await files['styles.css']; - let main = await files['main.js']; - expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); - expect(styles).toContain(`url('global-img-relative.png')`); - expect(main).toContain(`url('/assets/component-img-absolute.svg')`); - expect(main).toContain(`url('component-img-relative.png')`); - expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))).toBe(true); - expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( - true, - ); - expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))).toBe(true); - - // Check urls with deploy-url scheme are used as is. - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: '/base/', - deployUrl: 'http://deploy.url/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('http://deploy.url/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('http://deploy.url/assets/component-img-absolute.svg')`); - - // Check urls with base-href scheme are used as is (with deploy-url). - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: 'http://base.url/', - deployUrl: 'deploy/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('http://base.url/deploy/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('http://base.url/deploy/assets/component-img-absolute.svg')`); - - // Check urls with deploy-url and base-href scheme only use deploy-url. - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: 'http://base.url/', - deployUrl: 'http://deploy.url/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('http://deploy.url/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('http://deploy.url/assets/component-img-absolute.svg')`); - - // Check with schemeless base-href and deploy-url flags. - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: '/base/', - deployUrl: 'deploy/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/base/deploy/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/base/deploy/assets/component-img-absolute.svg')`); - - // Check with identical base-href and deploy-url flags. - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: '/base/', - deployUrl: '/base/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/base/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/base/assets/component-img-absolute.svg')`); - - // Check with only base-href flag. - files = (await browserBuild(architect, host, target, { - ...overrides, - baseHref: '/base/', - })).files; - - styles = await files['styles.css']; - main = await files['main.js']; - expect(styles).toContain(`url('/base/assets/global-img-absolute.svg')`); - expect(main).toContain(`url('/base/assets/component-img-absolute.svg')`); - }, 90000); - - it(`supports bootstrap@4`, async () => { - const overrides = { - extractCss: true, - styles: ['../../../../node_modules/bootstrap/dist/css/bootstrap.css'], - scripts: ['../../../../node_modules/bootstrap/dist/js/bootstrap.js'], - }; - - await browserBuild(architect, host, target, overrides); - }); - - it(`supports inline javascript in less`, async () => { - const overrides = { styles: [`src/styles.less`] }; - host.writeMultipleFiles({ - 'src/styles.less': ` - .myFunction() { - @functions: ~\`(function () { - return ''; - })()\`; - } - .myFunction(); - `, - }); - - await browserBuild(architect, host, target, overrides); - }); - - it('supports Protocol-relative Url', async () => { - host.writeMultipleFiles({ - 'src/styles.css': ` - body { - background-image: url('//cdn.com/classic-bg.jpg'); - } - `, - }); - - const overrides = { extractCss: true, optimization: true }; - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['styles.css']).toContain('background-image:url(//cdn.com/classic-bg.jpg)'); - }); - - it('supports fonts with space in filename', async () => { - host.writeMultipleFiles({ - 'src/styles.css': ` - @font-face { - font-family: "Font Awesome"; - src: url("./assets/fa solid-900.woff2") format("woff2"); - } - - body { - font-family: "Font Awesome"; - } - `, - 'src/assets/fa solid-900.woff2': '', - }); - - const overrides = { extractCss: true }; - const { output } = await browserBuild(architect, host, target, overrides); - expect(output.success).toBe(true); - }); - - it('supports font names with spaces', async () => { - host.writeMultipleFiles({ - 'src/styles.css': ` - body { - font: 10px "Font Awesome"; - } - `, - }); - - const overrides = { extractCss: true, optimization: true }; - const logger = new logging.Logger('font-name-spaces'); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const { output } = await browserBuild(architect, host, target, overrides, { logger }); - expect(output.success).toBe(true); - expect(logs.join()).not.toContain('WARNING in Invalid font values '); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/subresource-integrity_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/subresource-integrity_spec_large.ts deleted file mode 100644 index 6e8478439b5e..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/subresource-integrity_spec_large.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder subresource integrity', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - host.writeMultipleFiles({ - 'src/my-js-file.js': `console.log(1); export const a = 2;`, - 'src/main.ts': `import { a } from './my-js-file'; console.log(a);`, - }); - - const overrides = { subresourceIntegrity: true }; - const { files } = await browserBuild(architect, host, target, overrides); - expect(await files['index.html']).toMatch(/integrity="\w+-[A-Za-z0-9\/\+=]+"/); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/svg_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/svg_spec_large.ts deleted file mode 100644 index 49d7480fe7ab..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/svg_spec_large.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { createArchitect, host, outputPath, veEnabled } from '../utils'; - -describe('Browser Builder allow svg', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works with aot', async () => { - const svg = ` - - Hello World - `; - - host.writeMultipleFiles({ - './src/app/app.component.svg': svg, - './src/app/app.component.ts': ` - import { Component } from '@angular/core'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.svg', - styleUrls: [] - }) - export class AppComponent { - title = 'app'; - } - `, - }); - - const overrides = { aot: true }; - - const run = await architect.scheduleTarget(target, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - const exists = host.scopedSync().exists(join(outputPath, 'main.js')); - expect(exists).toBe(true, '"main.js" should exist'); - - if (exists) { - const content = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - - if (!veEnabled) { - expect(content).toContain('ɵɵnamespaceSVG'); - } else { - expect(content).toContain('":svg:svg"'); - } - expect(host.scopedSync().exists(normalize('dist/app.component.svg'))).toBe( - false, - 'should not copy app.component.svg to dist', - ); - } - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/tsconfig-paths_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/tsconfig-paths_spec_large.ts deleted file mode 100644 index 73553d31130b..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/tsconfig-paths_spec_large.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder tsconfig paths', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - host.replaceInFile('src/app/app.module.ts', './app.component', '@root/app/app.component'); - host.replaceInFile('tsconfig.json', /"baseUrl": ".\/",/, ` - "baseUrl": "./", - "paths": { - "@root/*": [ - "./src/*" - ] - }, - `); - - await browserBuild(architect, host, target); - }); - - it('works', async () => { - host.writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 42;', - 'src/app/shared/meaning.ts': 'export var meaning = 42;', - 'src/app/shared/index.ts': `export * from './meaning'`, - }); - host.replaceInFile('tsconfig.json', /"baseUrl": ".\/",/, ` - "baseUrl": "./", - "paths": { - "@shared": [ - "src/app/shared" - ], - "@shared/*": [ - "src/app/shared/*" - ], - "*": [ - "*", - "src/app/shared/*" - ] - }, - `); - host.appendToFile('src/app/app.component.ts', ` - import { meaning } from 'src/app/shared/meaning'; - import { meaning as meaning2 } from '@shared'; - import { meaning as meaning3 } from '@shared/meaning'; - import { meaning as meaning4 } from 'meaning'; - import { meaning as meaning5 } from 'src/meaning-too'; - - // need to use imports otherwise they are ignored and - // no error is outputted, even if baseUrl/paths don't work - console.log(meaning) - console.log(meaning2) - console.log(meaning3) - console.log(meaning4) - console.log(meaning5) - `); - - await browserBuild(architect, host, target); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/unused-files-warning_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/unused-files-warning_spec_large.ts deleted file mode 100644 index a8079e9b4f30..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/unused-files-warning_spec_large.ts +++ /dev/null @@ -1,281 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { debounceTime, take, tap } from 'rxjs/operators'; -import { BrowserBuilderOutput } from '../../src/browser/index'; -import { createArchitect, host, veEnabled } from '../utils'; - -// tslint:disable-next-line:no-big-function -describe('Browser Builder unused files warnings', () => { - const warningMessageSuffix = `is part of the TypeScript compilation but it's unused`; - const targetSpec = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('should not show warning when all files are used', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - const logger = new TestLogger('unused-files-warnings'); - const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(logger.includes(warningMessageSuffix)).toBe(false); - logger.clear(); - - await run.stop(); - }); - - it('should show warning when some files are unused', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - host.replaceInFile( - 'src/tsconfig.app.json', - '"main.ts"', - '"main.ts", "environments/environment.prod.ts"', - ); - - const logger = new TestLogger('unused-files-warnings'); - const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(logger.includes(`environment.prod.ts ${warningMessageSuffix}`)).toBe(true); - logger.clear(); - - await run.stop(); - }); - - it('should not show warning when excluded files are unused', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - const ignoredFiles = { - 'src/file.d.ts': 'export type MyType = number;', - 'src/file.ngsummary.ts': 'export const hello = 42;', - 'src/file.ngfactory.ts': 'export const hello = 42;', - 'src/file.ngstyle.ts': 'export const hello = 42;', - 'src/file.ng_typecheck__.ts': 'export const hello = 42;', - }; - - host.writeMultipleFiles(ignoredFiles); - - host.replaceInFile( - 'src/tsconfig.app.json', - '"main.ts"', - `"main.ts", ${Object.keys(ignoredFiles).map(f => `"${f.replace('src/', '')}"`).join(',')}`, - ); - - const logger = new TestLogger('unused-files-warnings'); - const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(logger.includes(warningMessageSuffix)).toBe(false); - logger.clear(); - - await run.stop(); - }); - - it('should not show warning when type files are used', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - host.writeMultipleFiles({ - 'src/app/type.ts': 'export type MyType = number;', - }); - - host.replaceInFile( - 'src/app/app.component.ts', - `'@angular/core';`, - `'@angular/core';\nimport { MyType } from './type';\n`, - ); - - const logger = new TestLogger('unused-files-warnings'); - const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(logger.includes(warningMessageSuffix)).toBe(false); - logger.clear(); - - await run.stop(); - }); - - it('should not show warning when type files are used transitively', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - host.writeMultipleFiles({ - 'src/app/type.ts': - `import {Myinterface} from './interface'; export type MyType = Myinterface;`, - 'src/app/interface.ts': 'export interface Myinterface {nbr: number;}', - }); - - host.replaceInFile( - 'src/app/app.component.ts', - `'@angular/core';`, - `'@angular/core';\nimport { MyType } from './type';\n`, - ); - - const logger = new TestLogger('unused-files-warnings'); - const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); - const output = await run.result as BrowserBuilderOutput; - expect(output.success).toBe(true); - expect(logger.includes(warningMessageSuffix)).toBe(false); - logger.clear(); - - await run.stop(); - }); - - it('works for rebuilds', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - host.replaceInFile( - 'src/tsconfig.app.json', - '"**/*.d.ts"', - '"**/*.d.ts", "testing/**/*.ts"', - ); - - const logger = new TestLogger('unused-files-warnings'); - let buildNumber = 0; - const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); - - await run.output - .pipe( - debounceTime(1000), - tap(buildEvent => { - expect(buildEvent.success).toBe(true); - - buildNumber ++; - switch (buildNumber) { - case 1: - // The first should not have unused files - expect(logger.includes(warningMessageSuffix)).toBe(false, `Case ${buildNumber} failed.`); - - // Write a used file - host.writeMultipleFiles({ - 'src/testing/type.ts': 'export type MyType = number;', - }); - - // touch file to trigger build - host.replaceInFile( - 'src/app/app.component.ts', - `'@angular/core';`, - `'@angular/core';\n`, - ); - break; - - case 2: - // The second should have type.ts as unused - expect(logger.includes(`type.ts ${warningMessageSuffix}`)).toBe(true, `Case ${buildNumber} failed.`); - - host.replaceInFile( - 'src/app/app.component.ts', - `'@angular/core';`, - `'@angular/core';\nimport { MyType } from '../testing/type';`, - ); - break; - - case 3: - // The third should not have any unused files - expect(logger.includes(warningMessageSuffix)).toBe(false, `Case ${buildNumber} failed.`); - break; - } - - logger.clear(); - }), - take(3), - ) - .toPromise(); - await run.stop(); - }); - - it('should only show warning once per file', async () => { - if (veEnabled) { - // TODO: https://github.com/angular/angular-cli/issues/15056 - pending('Only supported in Ivy.'); - - return; - } - - host.replaceInFile( - 'src/tsconfig.app.json', - '"**/*.d.ts"', - '"**/*.d.ts", "testing/**/*.ts"', - ); - - // Write a used file - host.writeMultipleFiles({ - 'src/testing/type.ts': 'export type MyType = number;', - }); - - const logger = new TestLogger('unused-files-warnings'); - let buildNumber = 0; - const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); - - await run.output - .pipe( - debounceTime(1000), - tap(buildEvent => { - expect(buildEvent.success).toBe(true); - - buildNumber ++; - switch (buildNumber) { - case 1: - // The first should have type.ts as unused. - expect(logger.includes(`type.ts ${warningMessageSuffix}`)).toBe(true, `Case ${buildNumber} failed.`); - - // touch a file to trigger a rebuild - host.appendToFile('src/main.ts', ''); - break; - case 2: - // The second should should have type.ts as unused but shouldn't warn. - expect(logger.includes(warningMessageSuffix)).toBe(false, `Case ${buildNumber} failed.`); - break; - } - - logger.clear(); - }), - take(2), - ) - .toPromise(); - await run.stop(); - }); - -}); diff --git a/packages/angular_devkit/build_angular/test/browser/vendor-chunk_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/vendor-chunk_spec_large.ts deleted file mode 100644 index 51155b63490f..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/vendor-chunk_spec_large.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder vendor chunk', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const { files } = await browserBuild(architect, host, target, { vendorChunk: true }); - expect('vendor.js' in files).toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/vendor-source-map_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/vendor-source-map_spec_large.ts deleted file mode 100644 index 7d479a525b40..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/vendor-source-map_spec_large.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import * as path from 'path'; -import { browserBuild, createArchitect, host, veEnabled } from '../utils'; - -describe('Browser Builder external source map', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - const overrides = { - sourceMap: { - scripts: true, - styles: true, - vendor: true, - }, - }; - - const { files } = await browserBuild(architect, host, target, overrides); - const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; - const hasTsSourcePaths = sourcePaths.some(p => path.extname(p) == '.ts'); - expect(hasTsSourcePaths).toBe(true, `vendor.js.map should have '.ts' extentions`); - }); - - it(`works when using deprecated 'vendorSourceMap'`, async () => { - const overrides = { - sourceMap: { - scripts: true, - styles: true, - }, - vendorSourceMap: true, - }; - - const { files } = await browserBuild(architect, host, target, overrides); - const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; - const hasTsSourcePaths = sourcePaths.some(p => path.extname(p) == '.ts'); - expect(hasTsSourcePaths).toBe(true, `vendor.js.map should have '.ts' extentions`); - }); - - it('does not map sourcemaps from external library when disabled', async () => { - const overrides = { - sourceMap: { - scripts: true, - styles: true, - vendor: false, - }, - }; - - const { files } = await browserBuild(architect, host, target, overrides); - const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; - const hasTsSourcePaths = sourcePaths.some(p => path.extname(p) == '.ts'); - expect(hasTsSourcePaths).toBe(false, `vendor.js.map not should have '.ts' extentions`); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/web-worker_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/web-worker_spec_large.ts deleted file mode 100644 index 208618272b82..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/web-worker_spec_large.ts +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { join, virtualFs } from '@angular-devkit/core'; -import { debounceTime, takeWhile, tap } from 'rxjs/operators'; -import { browserBuild, createArchitect, host, outputPath } from '../utils'; - - -describe('Browser Builder Web Worker support', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - const workerFiles: { [k: string]: string } = { - 'src/app/dep.ts': `export const foo = 'bar';`, - 'src/app/app.worker.ts': ` - /// - - import { foo } from './dep'; - console.log('hello from worker'); - addEventListener('message', ({ data }) => { - console.log('worker got message:', data); - if (data === 'hello') { - postMessage(foo); - } - }); - `, - 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; - import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - if (environment.production) { enableProdMode(); } - platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err)); - - const worker = new Worker('./app/app.worker', { type: 'module' }); - worker.onmessage = ({ data }) => { - console.log('page got message:', data); - }; - worker.postMessage('hello'); - `, - // Make a new tsconfig for the *.worker.ts files. - // The final place for this tsconfig must take into consideration editor tooling, unit - // tests, and integration with other build targets. - './src/tsconfig.worker.json': ` - { - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/worker", - "lib": [ - "es2018", - "webworker" - ], - "types": [] - }, - "include": [ - "**/*.worker.ts", - ] - }`, - // Alter the app tsconfig to not include *.worker.ts files. - './src/tsconfig.app.json': ` - { - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/worker", - "types": [] - }, - "files": [ - "main.ts", - "polyfills.ts" - ] - }`, - }; - - it('bundles TS worker', async () => { - host.writeMultipleFiles(workerFiles); - const logger = new TestLogger('worker-warnings'); - const overrides = { webWorkerTsConfig: 'src/tsconfig.worker.json' }; - await browserBuild(architect, host, target, overrides, { logger }); - - // Worker bundle contains worker code. - const workerContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, '0.worker.js'))); - expect(workerContent).toContain('hello from worker'); - expect(workerContent).toContain('bar'); - - // Main bundle references worker. - const mainContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js'))); - expect(mainContent).toContain('0.worker.js'); - expect(logger.includes('WARNING')).toBe(false, 'Should show no warnings.'); - }); - - it('minimizes and hashes worker', async () => { - host.writeMultipleFiles(workerFiles); - const overrides = { - webWorkerTsConfig: 'src/tsconfig.worker.json', - outputHashing: 'all', - optimization: true, - }; - await browserBuild(architect, host, target, overrides); - - // Worker bundle should have hash and minified code. - const workerBundle = host.fileMatchExists(outputPath, /0\.[0-9a-f]{20}\.worker\.js/) as string; - expect(workerBundle).toBeTruthy('workerBundle should exist'); - const workerContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, workerBundle))); - expect(workerContent).toContain('hello from worker'); - expect(workerContent).toContain('bar'); - expect(workerContent).toContain('"hello"===e&&postMessage'); - - // Main bundle should reference hashed worker bundle. - const mainBundle = host.fileMatchExists(outputPath, /main\.[0-9a-f]{20}\.js/) as string; - expect(mainBundle).toBeTruthy('mainBundle should exist'); - const mainContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, mainBundle))); - expect(mainContent).toContain(workerBundle); - }); - - it('rebuilds TS worker', async () => { - host.writeMultipleFiles(workerFiles); - const overrides = { - webWorkerTsConfig: 'src/tsconfig.worker.json', - watch: true, - }; - - let phase = 1; - const workerPath = join(outputPath, '0.worker.js'); - let workerContent = ''; - - const run = await architect.scheduleTarget(target, overrides); - await run.output.pipe( - // Wait for files to be written to disk. - // FIXME: Not quite sure why such a long 'debounceTime' is needed. - // Anything under `2500` is a constant failure locally when using - // 'fdescribe' and this tests doesn't run as first one and is also rather flaky on CI. - // It seems that the outputted files contents don't get updated in time. - debounceTime(2500), - tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')), - tap(() => { - switch (phase) { - case 1: - // Original worker content should be there. - workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath)); - expect(workerContent).toContain('bar'); - // Change content of worker dependency. - host.writeMultipleFiles({ 'src/app/dep.ts': `export const foo = 'baz';` }); - phase = 2; - break; - - case 2: - workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath)); - // Worker content should have changed. - expect(workerContent).toContain('baz'); - phase = 3; - break; - } - }), - takeWhile(() => phase < 3), - ).toPromise(); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/browser/works_spec_large.ts b/packages/angular_devkit/build_angular/test/browser/works_spec_large.ts deleted file mode 100644 index 37013244745a..000000000000 --- a/packages/angular_devkit/build_angular/test/browser/works_spec_large.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { normalize } from '@angular-devkit/core'; -import { browserBuild, createArchitect, host } from '../utils'; - - -describe('Browser Builder basic test', () => { - const target = { project: 'app', target: 'build' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(async () => host.restore().toPromise()); - - it('works', async () => { - await browserBuild(architect, host, target); - - // Default files should be in outputPath. - expect(await host.scopedSync().exists(normalize('dist/runtime.js'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/main.js'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/polyfills.js'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/styles.js'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/vendor.js'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/favicon.ico'))).toBe(true); - expect(await host.scopedSync().exists(normalize('dist/index.html'))).toBe(true); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/allowed-hosts_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/allowed-hosts_spec_large.ts deleted file mode 100644 index 3b6767c9abf2..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/allowed-hosts_spec_large.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder allowed host', () => { - // We have to spoof the host to a non-numeric one because Webpack Dev Server does not - // check the hosts anymore when requests come from numeric IP addresses. - const headers = { host: 'spoofy.mcspoofface' }; - - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - // We use runs like this to ensure it WILL stop the servers at the end of each tests. - let runs: BuilderRun[]; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { allowedHosts: ['spoofy.mcspoofface'] }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch(`${output.baseUrl}`, { headers }); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/budgets_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/budgets_spec_large.ts deleted file mode 100644 index 154912995861..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/budgets_spec_large.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { normalize, virtualFs } from '@angular-devkit/core'; -import { createArchitect, host } from '../utils'; - -describe('Dev Server Builder bundle budgets', () => { - const targetSpec = { project: 'app', target: 'serve' }; - - beforeEach(async () => host.initialize().toPromise()); - afterEach(async () => host.restore().toPromise()); - - it('should ignore budgets', async () => { - const config = host.scopedSync().read(normalize('angular.json')); - const jsonConfig = JSON.parse(virtualFs.fileBufferToString(config)); - const buildOptions = jsonConfig.projects.app.targets.build.options; - - buildOptions.budgets = [{ type: 'all', maximumError: '100b' }], - buildOptions.optimization = true; - - host.writeMultipleFiles({ - 'angular.json': JSON.stringify(jsonConfig), - }); - - const architect = (await createArchitect(host.root())).architect; - const run = await architect.scheduleTarget(targetSpec); - const output = await run.result; - expect(output.success).toBe(true); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/deploy-url_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/deploy-url_spec_large.ts deleted file mode 100644 index 505997e6d943..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/deploy-url_spec_large.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Deploy Url', () => { - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - let runs: BuilderRun[] = []; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { deployUrl: 'test/' }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/test'); - - const response = await fetch(`${output.baseUrl}/polyfills.js`); - expect(await response.text()).toContain('window["webpackJsonp"]'); - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/index_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/index_spec_large.ts deleted file mode 100644 index 22aca8912431..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/index_spec_large.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { workspaces } from '@angular-devkit/core'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server/index'; -import { createArchitect, host } from '../utils'; - -describe('Dev Server Builder index', () => { - const targetSpec = { project: 'app', target: 'serve' }; - - beforeEach(async () => host.initialize().toPromise()); - afterEach(async () => host.restore().toPromise()); - - it(`adds 'type="module"' when differential loading is needed`, async () => { - host.writeMultipleFiles({ - browserslist: ` - last 1 chrome version - IE 10 - `, - }); - - const architect = (await createArchitect(host.root())).architect; - const run = await architect.scheduleTarget(targetSpec); - const output = (await run.result) as DevServerBuilderOutput; - expect(output.success).toBe(true); - const response = await fetch('http://localhost:4200/index.html'); - expect(await response.text()).toContain( - '' + - '' + - '' + - '' + - '', - ); - await run.stop(); - }); - - it(`does not add 'type="module"' to custom scripts when differential loading is needed`, async () => { - host.writeMultipleFiles({ - browserslist: ` - last 1 chrome version - IE 10 - `, - 'test.js': 'console.log("test");', - }); - - const { workspace } = await workspaces.readWorkspace(host.root(), workspaces.createWorkspaceHost(host)); - const app = workspace.projects.get('app'); - if (!app) { - fail('Test application "app" not found.'); - - return; - } - const target = app.targets.get('build'); - if (!target) { - fail('Test application "app" target "build" not found.'); - - return; - } - if (!target.options) { - target.options = {}; - } - target.options.scripts = ['test.js']; - await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); - - const architect = (await createArchitect(host.root())).architect; - const run = await architect.scheduleTarget(targetSpec); - const output = (await run.result) as DevServerBuilderOutput; - expect(output.success).toBe(true); - const response = await fetch('http://localhost:4200/index.html'); - expect(await response.text()).toContain( - '' + - '' + - '' + - '' + - '' + - '', - ); - await run.stop(); - }); - - it(`doesn't 'type="module"' when differential loading is not needed`, async () => { - host.writeMultipleFiles({ - browserslist: ` - last 1 chrome version - `, - }); - - const architect = (await createArchitect(host.root())).architect; - const run = await architect.scheduleTarget(targetSpec); - const output = (await run.result) as DevServerBuilderOutput; - expect(output.success).toBe(true); - const response = await fetch('http://localhost:4200/index.html'); - expect(await response.text()).toContain( - '' + - '' + - '' + - '' + - '', - ); - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/proxy_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/proxy_spec_large.ts deleted file mode 100644 index 7ac09c879aa6..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/proxy_spec_large.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import * as express from 'express'; // tslint:disable-line:no-implicit-dependencies -import * as http from 'http'; -import { AddressInfo } from 'net'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { Schema as DevServerBuilderOptions } from '../../src/dev-server/schema'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder proxy', () => { - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - // We use runs like this to ensure it WILL stop the servers at the end of each tests. - let runs: BuilderRun[]; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - // Create an express app that serves as a proxy. - const app = express(); - const server = http.createServer(app); - server.listen(0); - - app.set('port', (server.address() as AddressInfo).port); - app.get('/api/test', function (_req, res) { - res.send('TEST_API_RETURN'); - }); - - const backendHost = 'localhost'; - // cast is safe, the HTTP server is not using a pipe or UNIX domain socket - const backendPort = (server.address() as AddressInfo).port; - const proxyServerUrl = `http://${backendHost}:${backendPort}`; - - host.writeMultipleFiles({ - 'proxy.config.json': `{ "/api/*": { "target": "${proxyServerUrl}" } }`, - }); - - const run = await architect.scheduleTarget(target, { proxyConfig: 'proxy.config.json' }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch('http://localhost:4200/api/test'); - expect(await response.text()).toContain('TEST_API_RETURN'); - server.close(); - }, 30000); - - it('errors out with a missing proxy file', async () => { - const run = await architect.scheduleTarget(target, { proxyConfig: 'INVALID.json' }); - runs.push(run); - - try { - await run.result; - expect('THE ABOVE LINE SHOULD THROW').toBe('true'); - } catch { - // Success! - } - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/public-host_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/public-host_spec_large.ts deleted file mode 100644 index 4f021d6b5624..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/public-host_spec_large.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder public host', () => { - // We have to spoof the host to a non-numeric one because Webpack Dev Server does not - // check the hosts anymore when requests come from numeric IP addresses. - const headers = { host: 'spoofy.mcspoofface' }; - - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - // We use runs like this to ensure it WILL stop the servers at the end of each tests. - let runs: BuilderRun[]; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(target); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch(`${output.baseUrl}`, { headers }); - expect(await response.text()).toContain('Invalid Host header'); - }, 30000); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { publicHost: headers.host }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch(`${output.baseUrl}`, { headers }); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { disableHostCheck: true }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch(`${output.baseUrl}`, { headers }); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/serve-path_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/serve-path_spec_large.ts deleted file mode 100644 index 21e7e11ec112..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/serve-path_spec_large.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder serve path', () => { - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - // We use runs like this to ensure it WILL stop the servers at the end of each tests. - let runs: BuilderRun[]; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('uses the servePath option when specified', async () => { - const run = await architect.scheduleTarget(target, { servePath: 'test/' }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/test'); - - const response = await fetch(`${output.baseUrl}/polyfills.js`); - expect(await response.text()).toContain('window["webpackJsonp"]'); - }, 30000); - - it('does not fallback when request is outside serve path', async () => { - const run = await architect.scheduleTarget(target, { servePath: 'test/' }); - - await expectAsync(run.result).toBeResolvedTo( - jasmine.objectContaining({ success: true, baseUrl: 'http://localhost:4200/test' }), - ); - - // fallback processing requires an accept header - await expectAsync( - fetch('http://localhost:4200', { headers: { 'accept': 'text/html' } }), - ).toBeResolvedTo(jasmine.objectContaining({ status: 404 })); - - await expectAsync( - fetch('http://localhost:4200/api/', { headers: { 'accept': 'text/html' } }), - ).toBeResolvedTo(jasmine.objectContaining({ status: 404 })); - - await run.stop(); - }, 30000); - - it('does fallback when request is inside serve path', async () => { - const run = await architect.scheduleTarget(target, { servePath: 'test/' }); - - await expectAsync(run.result).toBeResolvedTo( - jasmine.objectContaining({ success: true, baseUrl: 'http://localhost:4200/test' }), - ); - - // fallback processing requires an accept header - await expectAsync( - fetch('http://localhost:4200/test/nothere', { headers: { 'accept': 'text/html' } }), - ).toBeResolvedTo(jasmine.objectContaining({ status: 200 })); - - await run.stop(); - }, 30000); - -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/ssl_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/ssl_spec_large.ts deleted file mode 100644 index e4a2abba6db0..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/ssl_spec_large.ts +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import { tags } from '@angular-devkit/core'; -import * as https from 'https'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder ssl', () => { - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - // We use runs like this to ensure it WILL stop the servers at the end of each tests. - let runs: BuilderRun[]; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(target, { ssl: true }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('https://localhost:4200/'); - - const response = await fetch('https://localhost:4200/index.html', { - agent: new https.Agent({ rejectUnauthorized: false }), - }); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); - - it('supports key and cert', async () => { - host.writeMultipleFiles({ - 'ssl/server.key': tags.stripIndents` - -----BEGIN RSA PRIVATE KEY----- - MIIEpAIBAAKCAQEA0+kOHdfpsPNUguCtai27DJ+DuOfVw4gw1P3BgYhNG8qoukaW - gdDLowj59+cXXgn9ZnQ8PdvZXhCEQcP3wjd1cBPuGQzO7BekoKEgzfGE/zjrrIeL - Q7tHYx9ddCPotQX4OJu4FZFJyS1Ar7zDDpQ9fSw6qmsXWN6I18fIGSVvbDbVB9rw - iAsLGe2jWadjXAjSqVOy6aT+CKJgnRnxudNZGP1LRC1YDRl/s7icCIh/9gEGfn7G - gwQQ9AM2p3JNjP2quclSjBvMv0uVj+yzL2bPGRz0hu90CDaIEU2FtBCse50/O75q - x0bQnPbuHKD3ajs0DfQYoAmFZGK078ZDl/VQxwIDAQABAoIBAEl17kXcNo/4GqDw - QE2hoslCdwhfnhQVn1AG09ESriBnRcylccF4308aaoVM4CXicqzUuJl9IEJimWav - B7GVRinfTtfyP71KiPCCSvv5sPBFDDYYGugVAS9UjTIYzLAMbLs7CDq5zglmnZkO - Z9QjAZnl/kRbsZFGO8wJ3s0Q1Cp/ygZcvFU331K2jHXW7B4YXiFOH/lBQrjdz0Gy - WBjX4zIdNWnwarvxu46IS/0z1P1YOHM8+B1Uv54MG94A6szBdd/Vp0cQRs78t/Cu - BQ1Rnuk16Pi+ieC5K04yUgeuNusYW0PWLtPX1nKNp9z46bmD1NHKAxaoDFXr7qP3 - pZCaDMkCgYEA8mmTYrhXJTRIrOxoUwM1e3OZ0uOxVXJJ8HF6X8t+UO6dFxXB/JC9 - ZBc+94cZQapaKFOeMmd/j3L2CQIjChk5yKV/G3Io+raxIoAAKPCkMF4NQQVvvNkS - CAGl61Qa78DoF5Habumz0AC1R9P877kNTC0aPSt4lhPWgfotbZNNMlMCgYEA38nM - s4a0pZseXPkuOtPYX/3Ms3E+d70XKSFuIMCHCg79YGsQ8h/9apYcPyeYkpQ0a4gs - I3IUqMaXC2OyqWA5LU1BZv51mXb6zcb2pokZfpiSWk+7sy5XjkE9EmQxp3xHfV3c - EO/DxHfWNvtMjESMbhu0yVzM2O/Aa53Tl9lqAT0CgYEA1dXBuHyqCtyTG08zO78B - 55Ny5rAJ1zkI9jvz2hr0o0nJcvqzcyruliNXXRxkcCNoglg4nXfk81JSrGGhLSBR - c6hhdoF+mqKboLZO7c5Q14WvpWK5TVoiaMOja/J2DHYbhecYS2yGPH7TargaUBDq - JP9IPRtitOhs+Z0Jg7ZDi5cCgYAMb7B6gY/kbBxh2k8hYchyfS41AqQQD2gMFxmB - pHFcs7yM8SY97l0s4S6sq8ykyKupFiYtyhcv0elu7pltJDXJOLPbv2RVpPEHInlu - g8vw5xWrAydRK9Adza5RKVRBFHz8kIy8PDbK4kX7RDfay6xqKgv/7LJNk/VDhb/O - fnyPmQKBgQDg/o8Ubf/gxA9Husnuld4DBu3wwFhkMlWqyO9QH3cKgojQ2JGSrfDz - xHhetmhionEyzg0JCaMSpzgIHY+8o/NAwc++OjNHEoYp3XWM9GTp81ROMz6b83jV - biVR9N0MhONdwF6vtzDCcJxNIUe2p4lTvLf/Xd9jaQDNXe35Gxsdyg== - -----END RSA PRIVATE KEY----- - `, - 'ssl/server.crt': tags.stripIndents` - -----BEGIN CERTIFICATE----- - MIID5jCCAs6gAwIBAgIJAJOebwfGCm61MA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV - BAYTAlVTMRAwDgYDVQQIEwdHZW9yZ2lhMRAwDgYDVQQHEwdBdGxhbnRhMRAwDgYD - VQQKEwdBbmd1bGFyMRAwDgYDVQQLEwdBbmd1bGFyMB4XDTE2MTAwNDAxMDAyMVoX - DTI2MTAwMjAxMDAyMVowVTELMAkGA1UEBhMCVVMxEDAOBgNVBAgTB0dlb3JnaWEx - EDAOBgNVBAcTB0F0bGFudGExEDAOBgNVBAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0Fu - Z3VsYXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDT6Q4d1+mw81SC - 4K1qLbsMn4O459XDiDDU/cGBiE0byqi6RpaB0MujCPn35xdeCf1mdDw929leEIRB - w/fCN3VwE+4ZDM7sF6SgoSDN8YT/OOush4tDu0djH110I+i1Bfg4m7gVkUnJLUCv - vMMOlD19LDqqaxdY3ojXx8gZJW9sNtUH2vCICwsZ7aNZp2NcCNKpU7LppP4IomCd - GfG501kY/UtELVgNGX+zuJwIiH/2AQZ+fsaDBBD0Azanck2M/aq5yVKMG8y/S5WP - 7LMvZs8ZHPSG73QINogRTYW0EKx7nT87vmrHRtCc9u4coPdqOzQN9BigCYVkYrTv - xkOX9VDHAgMBAAGjgbgwgbUwHQYDVR0OBBYEFG4VV6/aNLx/qFIS9MhAWuyeV5OX - MIGFBgNVHSMEfjB8gBRuFVev2jS8f6hSEvTIQFrsnleTl6FZpFcwVTELMAkGA1UE - BhMCVVMxEDAOBgNVBAgTB0dlb3JnaWExEDAOBgNVBAcTB0F0bGFudGExEDAOBgNV - BAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0FuZ3VsYXKCCQCTnm8HxgputTAMBgNVHRME - BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDO4jZT/oKVxaiWr+jV5TD+qwThl9zT - Uw/ZpFDkdbZdY/baCFaLCiJwkK9+puMOabLvm1VzcnHHWCoiUNbWpw8AOumLEnTv - ze/5OZXJ6XlA9kd9f3hDlN5zNB3S+Z2nKIrkPGfxQZ603QCbWaptip5dxgek6oDZ - YXVtnbOnPznRsG5jh07U49RO8CNebqZLzdRToLgObbqYlfRMcbUxCOHXjnB5wUlp - 377Iivm4ldnCTvFOjEiDh+FByWL5xic7PjyJPZFMidiYTmsGilP9XTFC83CRZwz7 - vW+RCSlU6x8Uejz98BPmASoqCuCTUeOo+2pFelFhX9NwR/Sb6b7ybdPv - -----END CERTIFICATE----- - `, - }); - - const overrides = { - ssl: true, - sslKey: '../ssl/server.key', - sslCert: '../ssl/server.crt', - }; - - const run = await architect.scheduleTarget(target, overrides); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('https://localhost:4200/'); - - const response = await fetch('https://localhost:4200/index.html', { - agent: new https.Agent({ rejectUnauthorized: false }), - }); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/dev-server/works_spec_large.ts b/packages/angular_devkit/build_angular/test/dev-server/works_spec_large.ts deleted file mode 100644 index 7b2dcafc7f90..000000000000 --- a/packages/angular_devkit/build_angular/test/dev-server/works_spec_large.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderRun } from '@angular-devkit/architect'; -import { logging } from '@angular-devkit/core'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import { DevServerBuilderOutput } from '../../src/dev-server'; -import { createArchitect, host } from '../utils'; - - -describe('Dev Server Builder', () => { - const target = { project: 'app', target: 'serve' }; - let architect: Architect; - let runs: BuilderRun[] = []; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - runs = []; - }); - afterEach(async () => { - await host.restore().toPromise(); - await Promise.all(runs.map(r => r.stop())); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(target); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(output.baseUrl).toBe('http://localhost:4200/'); - - const response = await fetch('http://localhost:4200/index.html'); - expect(await response.text()).toContain('HelloWorldApp'); - }, 30000); - - it('works with verbose', async () => { - const logger = new logging.Logger('verbose-serve'); - let logs = ''; - logger.subscribe(event => logs += event.message); - - const run = await architect.scheduleTarget(target, { verbose: true }, { logger }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - expect(logs).toContain('Built at'); - }, 30000); - - it(`doesn't serve files on the cwd directly`, async () => { - const run = await architect.scheduleTarget(target); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - - // When webpack-dev-server doesn't have `contentBase: false`, this will serve the repo README. - const response = await fetch('http://localhost:4200/README.md', { - headers: { - 'Accept': 'text/html', - }, - }); - - const res = await response.text(); - expect(res).not.toContain('This file is automatically generated during release.'); - expect(res).toContain('HelloWorldApp'); - }); - - it('works with port 0', async () => { - const logger = new logging.Logger(''); - const logs: string[] = []; - logger.subscribe(e => logs.push(e.message)); - - const run = await architect.scheduleTarget(target, { port: 0 }, { logger }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - - const groups = logs.join().match(/\:(\d+){4,6}/g); - if (!groups) { - throw new Error('Expected log to contain port number.'); - } - - // tests that both the ports in the logs are the same. - const [firstPort, secondPort] = groups; - expect(firstPort).toBe(secondPort); - - expect(output.baseUrl).toBe(`http://localhost${firstPort}/`); - const response = await fetch(`http://localhost${firstPort}/index.html`); - expect(await response.text()).toContain('HelloWorldApp'); - }); - - it('should not generate sourcemaps when running prod build', async () => { - // Production builds have sourcemaps turned off. - const run = await architect.scheduleTarget({ ...target, configuration: 'production' }); - runs.push(run); - const output = await run.result as DevServerBuilderOutput; - expect(output.success).toBe(true); - const hasSourceMaps = output.emittedFiles && output.emittedFiles.some(f => f.extension === '.map'); - expect(hasSourceMaps).toBe(false, `Expected emitted files not to contain '.map' files.`); - }); - -}); diff --git a/packages/angular_devkit/build_angular/test/extract-i18n/works_spec_large.ts b/packages/angular_devkit/build_angular/test/extract-i18n/works_spec_large.ts deleted file mode 100644 index a721e03e06f1..000000000000 --- a/packages/angular_devkit/build_angular/test/extract-i18n/works_spec_large.ts +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { TestLogger } from '@angular-devkit/architect/testing'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { createArchitect, extractI18nTargetSpec, host } from '../utils'; - - -describe('Extract i18n Target', () => { - const extractionFile = join(normalize('src'), 'messages.xlf'); - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - it('generates an extraction file', async () => { - host.appendToFile('src/app/app.component.html', '

i18n test

'); - - const run = await architect.scheduleTarget(extractI18nTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - const exists = host.scopedSync().exists(extractionFile); - expect(exists).toBe(true); - - if (exists) { - const content = virtualFs.fileBufferToString(host.scopedSync().read(extractionFile)); - expect(content).toContain('i18n test'); - } - }, 30000); - - it('does not show full build logs', async () => { - const logger = new TestLogger('i18n'); - host.appendToFile('src/app/app.component.html', '

i18n test

'); - - const run = await architect.scheduleTarget(extractI18nTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(logger.includes('Chunk Names')).toBe(false); - expect(logger.includes('[emitted]')).toBe(false); - }, 30000); - - it('shows errors', async () => { - const logger = new TestLogger('i18n-errors'); - host.appendToFile('src/app/app.component.html', - '

Hello world inner

'); - - const run = await architect.scheduleTarget(extractI18nTargetSpec, undefined, { logger }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); - - await run.stop(); - - const msg = 'Could not mark an element as translatable inside a translatable section'; - expect(logger.includes(msg)).toBe(true); - }, 30000); - - it('supports locale', async () => { - host.appendToFile('src/app/app.component.html', '

i18n test

'); - const overrides = { i18nLocale: 'fr' }; - - const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(host.scopedSync().exists((extractionFile))).toBe(true); - expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))) - .toContain('source-language="fr"'); - }, 30000); - - it('supports out file', async () => { - host.appendToFile('src/app/app.component.html', '

i18n test

'); - const outFile = 'messages.fr.xlf'; - const extractionFile = join(normalize('src'), outFile); - const overrides = { outFile }; - - const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(host.scopedSync().exists(extractionFile)).toBe(true); - expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))) - .toMatch(/i18n test/); - }, 30000); - - it('supports output path', async () => { - host.appendToFile('src/app/app.component.html', '

i18n test

'); - // Note: this folder will not be created automatically. It must exist beforehand. - const outputPath = 'app'; - const extractionFile = join(normalize('src'), outputPath, 'messages.xlf'); - const overrides = { outputPath }; - - const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(host.scopedSync().exists(extractionFile)).toBe(true); - expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))) - .toMatch(/i18n test/); - }, 30000); - - it('supports i18n format', async () => { - host.appendToFile('src/app/app.component.html', '

i18n test

'); - const extractionFile = join(normalize('src'), 'messages.xmb'); - const overrides = { format: 'xmb' }; - - const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(host.scopedSync().exists(extractionFile)).toBe(true); - expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))) - .toMatch(/i18n test/); - }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/karma/code-coverage_spec_large.ts b/packages/angular_devkit/build_angular/test/karma/code-coverage_spec_large.ts deleted file mode 100644 index 2364fd53f683..000000000000 --- a/packages/angular_devkit/build_angular/test/karma/code-coverage_spec_large.ts +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { normalize, virtualFs } from '@angular-devkit/core'; -import { createArchitect, host, karmaTargetSpec } from '../utils'; - -describe('Karma Builder code coverage', () => { - const coverageFilePath = normalize('coverage/lcov.info'); - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - it('supports code coverage option', async () => { - const run = await architect.scheduleTarget(karmaTargetSpec, { codeCoverage: true }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - const exists = host.scopedSync().exists(coverageFilePath); - expect(exists).toBe(true); - - if (exists) { - const content = virtualFs.fileBufferToString(host.scopedSync().read(coverageFilePath)); - expect(content).toContain('polyfills.ts'); - expect(content).toContain('test.ts'); - } - }, 120000); - - it('supports code coverage exclude option', async () => { - const overrides = { - codeCoverage: true, - codeCoverageExclude: [ - 'src/polyfills.ts', - '**/test.ts', - ], - }; - - const run = await architect.scheduleTarget(karmaTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - const exists = host.scopedSync().exists(coverageFilePath); - expect(exists).toBe(true); - - if (exists) { - const content = virtualFs.fileBufferToString(host.scopedSync().read(coverageFilePath)); - expect(content).not.toContain('polyfills.ts'); - expect(content).not.toContain('test.ts'); - } - }, 120000); - - it(`should collect coverage from paths in 'sourceRoot'`, async () => { - const files: { [path: string]: string } = { - './dist/my-lib/index.d.ts': ` - export declare const title = 'app'; - `, - './dist/my-lib/index.js': ` - export const title = 'app'; - `, - './src/app/app.component.ts': ` - import { Component } from '@angular/core'; - import { title } from 'my-lib'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - export class AppComponent { - title = title; - } - `, - }; - - host.writeMultipleFiles(files); - - host.replaceInFile('tsconfig.json', /"baseUrl": ".\/",/, ` - "baseUrl": "./", - "paths": { - "my-lib": [ - "./dist/my-lib" - ] - }, - `); - - const run = await architect.scheduleTarget(karmaTargetSpec, { codeCoverage: true }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - const exists = host.scopedSync().exists(coverageFilePath); - expect(exists).toBe(true); - - if (exists) { - const content = virtualFs.fileBufferToString(host.scopedSync().read(coverageFilePath)); - expect(content).not.toContain('my-lib'); - } - }, 120000); - - it(`should fail when coverage is below threhold and 'emitWarning' is false`, async () => { - host.replaceInFile('karma.conf.js', 'fixWebpackSourcePaths: true', - ` - fixWebpackSourcePaths: true, - thresholds: { - emitWarning: false, - global: { - statements: 200 - } - }`, - ); - - const run = await architect.scheduleTarget(karmaTargetSpec, { codeCoverage: true }); - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); - await run.stop(); - }, 120000); -}); diff --git a/packages/angular_devkit/build_angular/test/karma/rebuilds_spec_large.ts b/packages/angular_devkit/build_angular/test/karma/rebuilds_spec_large.ts deleted file mode 100644 index 36d75c037711..000000000000 --- a/packages/angular_devkit/build_angular/test/karma/rebuilds_spec_large.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { Subject, timer } from 'rxjs'; -import { - catchError, - debounceTime, - delay, - map, - switchMap, - takeUntil, - takeWhile, - tap, -} from 'rxjs/operators'; -import { createArchitect, host, karmaTargetSpec } from '../utils'; - -describe('Karma Builder watch mode', () => { - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - it('performs initial build', async () => { - const run = await architect.scheduleTarget(karmaTargetSpec, { watch: true }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - - it('recovers from compilation failures in watch mode', async () => { - let buildCount = 0; - let phase = 1; - - // The current linux-based CI environments may not fully settled in regards to filesystem - // changes from previous tests which reuse the same directory and fileset. - // The initial delay helps mitigate false positive rebuild triggers in such scenarios. - const { run } = await timer(1000).pipe( - switchMap(() => architect.scheduleTarget(karmaTargetSpec, { watch: true })), - switchMap(run => run.output.pipe(map(output => ({ run, output })))), - debounceTime(500), - tap(({ output }) => { - buildCount += 1; - switch (phase) { - case 1: - // Karma run should succeed. - // Add a compilation error. - expect(output.success).toBe(true); - // Add an syntax error to a non-main file. - host.appendToFile('src/app/app.component.spec.ts', `]]]`); - phase = 2; - break; - - case 2: - // Karma run should fail due to compilation error. Fix it. - expect(output.success).toBe(false); - host.replaceInFile('src/app/app.component.spec.ts', `]]]`, ''); - phase = 3; - break; - - case 3: - // Karma run should succeed again. - expect(output.success).toBe(true); - phase = 4; - break; - } - }), - takeWhile(() => phase < 4), - catchError((_, caught) => { - fail(`stuck at phase ${phase} [builds: ${buildCount}]`); - - return caught; - }), - ).toPromise(); - - await run.stop(); - }); - - it('does not rebuild when nothing changed', async () => { - let phase = 1; - - const stopSubject = new Subject(); - const stop$ = stopSubject.asObservable().pipe(delay(5000)); - - // The current linux-based CI environments may not fully settled in regards to filesystem - // changes from previous tests which reuse the same directory and fileset. - // The initial delay helps mitigate false positive rebuild triggers in such scenarios. - const { run } = await timer(1000).pipe( - switchMap(() => architect.scheduleTarget(karmaTargetSpec, { watch: true })), - switchMap(run => run.output.pipe(map(output => ({ run, output })))), - debounceTime(500), - tap(({ output }) => { - switch (phase) { - case 1: - // Karma run should succeed. - expect(output.success).toBe(true); - // Touch the file. - host.appendToFile('src/app/app.component.spec.ts', ``); - // Signal the stopper, which delays emission by 5s. - // If there's no rebuild within that time then the test is successful. - stopSubject.next(); - phase = 2; - break; - - case 2: - // Should never trigger this second build. - fail('Should not trigger second build.'); - break; - } - }), - takeUntil(stop$), - ).toPromise(); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/karma/selected_spec_large.ts b/packages/angular_devkit/build_angular/test/karma/selected_spec_large.ts deleted file mode 100644 index 62906e376266..000000000000 --- a/packages/angular_devkit/build_angular/test/karma/selected_spec_large.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { logging } from '@angular-devkit/core'; -import { createArchitect, host, karmaTargetSpec } from '../utils'; - -describe('Karma Builder', () => { - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - describe('with include option', () => { - it('should fail when include does not match any files', async () => { - const overrides = { - include: ['abc.spec.ts', 'def.spec.ts'], - }; - const run = await architect.scheduleTarget(karmaTargetSpec, overrides); - - await expectAsync(run.result).toBeRejectedWith( - `Specified patterns: "abc.spec.ts, def.spec.ts" did not match any spec files`, - ); - - await run.stop(); - }); - - it('should fail when main test file does not include require.context usage', async () => { - let lastErrorLogEntry: logging.LogEntry | undefined; - const logger = new logging.Logger('test'); - logger.subscribe(m => { - if (m.level === 'error') { - lastErrorLogEntry = m; - } - }); - - const mockedRequireContext = '{ keys: () => ({ map: (_a) => { } }) };'; - const regex = /require\.context\(.*/; - host.replaceInFile('src/test.ts', regex, mockedRequireContext); - - const overrides = { - include: ['**/*.spec.ts'], - }; - - const run = await architect.scheduleTarget(karmaTargetSpec, overrides, { - logger, - }); - - await expectAsync(run.result).toBeResolved(); - - expect(lastErrorLogEntry && lastErrorLogEntry.message).toContain( - 'const context = require.context', - ); - expect(lastErrorLogEntry && lastErrorLogEntry.message) - // tslint:disable-next-line:max-line-length - .toContain( - "The 'include' option requires that the 'main' file for tests include the line below:", - ); - - await run.stop(); - }); - - [ - { - test: 'relative path from workspace to spec', - input: ['src/app/app.component.spec.ts'], - }, - { - test: 'relative path from workspace to file', - input: ['src/app/app.component.ts'], - }, - { - test: 'relative path from project root to spec', - input: ['app/services/test.service.spec.ts'], - }, - { - test: 'relative path from project root to file', - input: ['app/services/test.service.ts'], - }, - { - test: 'relative path from workspace to directory', - input: ['src/app/services'], - }, - { - test: 'relative path from project root to directory', - input: ['app/services'], - }, - { - test: 'glob with spec suffix', - input: ['**/*.pipe.spec.ts', '**/*.pipe.spec.ts', '**/*test.service.spec.ts'], - }, - ].forEach((options, index) => { - it(`should work with ${options.test} (${index})`, async () => { - host.writeMultipleFiles({ - 'src/app/services/test.service.spec.ts': ` - describe('TestService', () => { - it('should succeed', () => { - expect(true).toBe(true); - }); - });`, - 'src/app/failing.service.spec.ts': ` - describe('FailingService', () => { - it('should be ignored', () => { - expect(true).toBe(false); - }); - });`, - 'src/app/property.pipe.spec.ts': ` - describe('PropertyPipe', () => { - it('should succeed', () => { - expect(true).toBe(true); - }); - });`, - }); - - const overrides = { - include: options.input, - }; - const logger = new logging.Logger('test'); - logger.subscribe(m => { - if (m.level === 'error') { - fail(m); - } - }); - const run = await architect.scheduleTarget(karmaTargetSpec, overrides, { - logger, - }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - }); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/karma/works_spec_large.ts b/packages/angular_devkit/build_angular/test/karma/works_spec_large.ts deleted file mode 100644 index 26683a0adf92..000000000000 --- a/packages/angular_devkit/build_angular/test/karma/works_spec_large.ts +++ /dev/null @@ -1,216 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { createArchitect, host, karmaTargetSpec } from '../utils'; - - -// tslint:disable-next-line:no-big-function -describe('Karma Builder', () => { - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - it('runs', async () => { - const run = await architect.scheduleTarget(karmaTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - - it('fails with broken compilation', async () => { - host.writeMultipleFiles({ - 'src/app/app.component.spec.ts': '

definitely not typescript

', - }); - - const run = await architect.scheduleTarget(karmaTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); - - await run.stop(); - }); - - it('supports ES2015 target', async () => { - host.replaceInFile('tsconfig.json', '"target": "es5"', '"target": "es2015"'); - - const run = await architect.scheduleTarget(karmaTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - - it('generates and uses global styles', async () => { - host.writeMultipleFiles({ - 'src/styles.css': 'p {display: none}', - 'src/app/app.component.ts': ` - import { Component } from '@angular/core'; - - @Component({ - selector: 'app-root', - template: '

Hello World

' - }) - export class AppComponent { - } - `, - 'src/app/app.component.spec.ts': ` - import { TestBed, async } from '@angular/core/testing'; - import { AppComponent } from './app.component'; - - describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ - ], - declarations: [ - AppComponent - ] - }).compileComponents(); - })); - - it('should not contain text that is hidden via css', async(() => { - const fixture = TestBed.createComponent(AppComponent); - expect(fixture.nativeElement.innerText).not.toContain('Hello World'); - })); - });`, - }); - - const run = await architect.scheduleTarget(karmaTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - - it('generates and uses assets', async () => { - const assets: { [path: string]: string } = { - './src/string-file-asset.txt': 'string-file-asset.txt', - './src/string-folder-asset/file.txt': 'string-folder-asset.txt', - './src/glob-asset.txt': 'glob-asset.txt', - './src/folder/folder-asset.txt': 'folder-asset.txt', - './src/output-asset.txt': 'output-asset.txt', - }; - host.writeMultipleFiles(assets); - host.writeMultipleFiles({ - 'src/app/app.module.ts': ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - import { HttpClientModule } from '@angular/common/http'; - import { AppComponent } from './app.component'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - HttpClientModule - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - `, - 'src/app/app.component.ts': ` - import { Component } from '@angular/core'; - import { HttpClient } from '@angular/common/http'; - - @Component({ - selector: 'app-root', - template: '

{{asset.content }}

' - }) - export class AppComponent { - public assets = [ - { path: './string-file-asset.txt', content: '' }, - { path: './string-folder-asset/file.txt', content: '' }, - { path: './glob-asset.txt', content: '' }, - { path: './folder/folder-asset.txt', content: '' }, - { path: './output-folder/output-asset.txt', content: '' }, - ]; - constructor(private http: HttpClient) { - this.assets.forEach(asset => http.get(asset.path, { responseType: 'text' }) - .subscribe(res => asset.content = res)); - } - }`, - 'src/app/app.component.spec.ts': ` - import { TestBed, async } from '@angular/core/testing'; - import { HttpClientModule } from '@angular/common/http'; - import { AppComponent } from './app.component'; - - describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ - HttpClientModule - ], - declarations: [ - AppComponent - ] - }).compileComponents(); - })); - - it('should create the app', async(() => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app).toBeTruthy(); - })); - });`, - }); - - const overrides = { - assets: [ - 'src/string-file-asset.txt', - 'src/string-folder-asset', - { glob: 'glob-asset.txt', input: 'src/', output: '/' }, - { glob: 'output-asset.txt', input: 'src/', output: '/output-folder' }, - { glob: '**/*', input: 'src/folder', output: '/folder' }, - ], - }; - - const run = await architect.scheduleTarget(karmaTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); - - it('allows file replacements', async () => { - host.writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 42;', - 'src/meaning.ts': `export var meaning = 10;`, - - 'src/test.ts': ` - import { meaning } from './meaning'; - - describe('Test file replacement', () => { - it('should replace file', () => { - expect(meaning).toBe(42); - }); - }); - `, - }); - - const overrides = { - fileReplacements: [{ - replace: '/src/meaning.ts', - with: '/src/meaning-too.ts', - }], - }; - - const run = await architect.scheduleTarget(karmaTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/protractor/works_spec_large.ts b/packages/angular_devkit/build_angular/test/protractor/works_spec_large.ts deleted file mode 100644 index 490a5985a545..000000000000 --- a/packages/angular_devkit/build_angular/test/protractor/works_spec_large.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { JsonObject, normalize } from '@angular-devkit/core'; -import { createArchitect, host, protractorTargetSpec } from '../utils'; - -describe('Protractor Builder', () => { - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - - afterEach(() => host.restore().toPromise()); - - it('executes tests with automatic dev server usage', async () => { - const run = await architect.scheduleTarget(protractorTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }, 30000); - - it('fails with no devServerTarget and no standalone server', async () => { - const overrides = { devServerTarget: undefined } as unknown as JsonObject; - const run = await architect.scheduleTarget(protractorTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); - - await run.stop(); - }, 30000); - - it('overrides protractor specs', async () => { - host.scopedSync().rename( - normalize('./e2e/app.e2e-spec.ts'), - normalize('./e2e/renamed-app.e2e.spec.ts'), - ); - - const overrides = { specs: ['./e2e/renamed-app.e2e.spec.ts'] }; - const run = await architect.scheduleTarget(protractorTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }, 60000); - - it('overrides protractor suites', async () => { - host.scopedSync().rename( - normalize('./e2e/app.e2e-spec.ts'), - normalize('./e2e/renamed-app.e2e-spec.ts'), - ); - - // Suites block needs to be added in the protractor.conf.js file to test suites - host.replaceInFile('protractor.conf.js', `allScriptsTimeout: 11000,`, ` - allScriptsTimeout: 11000, - suites: { - app: './e2e/app.e2e-spec.ts' - }, - `); - - const overrides = { suite: 'app' }; - const run = await architect.scheduleTarget(protractorTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }, 60000); - - it('supports automatic port assignment (port = 0)', async () => { - const overrides = { port: 0 }; - const run = await architect.scheduleTarget(protractorTargetSpec, overrides); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }, 30000); - - it('supports dev server builder with browser builder base HREF option', async () => { - host.replaceInFile( - 'angular.json', - '"main": "src/main.ts",', - '"main": "src/main.ts", "baseHref": "/base/",', - ); - // Need to reset architect to use the modified config - architect = (await createArchitect(host.root())).architect; - - const run = await architect.scheduleTarget(protractorTargetSpec); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - }, 30000); - -}); diff --git a/packages/angular_devkit/build_angular/test/server/base_spec_large.ts b/packages/angular_devkit/build_angular/test/server/base_spec_large.ts deleted file mode 100644 index 7593b880101c..000000000000 --- a/packages/angular_devkit/build_angular/test/server/base_spec_large.ts +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Architect } from '@angular-devkit/architect'; -import { getSystemPath, join, normalize, virtualFs } from '@angular-devkit/core'; -import { take, tap } from 'rxjs/operators'; -import { ServerBuilderOutput } from '../../src'; -import { BundleDependencies } from '../../src/server/schema'; -import { createArchitect, host, veEnabled } from '../utils'; - - -describe('Server Builder', () => { - const target = { project: 'app', target: 'server' }; - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - const outputPath = normalize('dist-server'); - - it('works (base)', async () => { - const run = await architect.scheduleTarget(target); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - const fileName = join(outputPath, 'main.js'); - const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - - if (veEnabled) { - expect(content).toMatch(/AppServerModuleNgFactory/); - } else { - expect(content).toMatch(/AppServerModule\.ɵmod/); - } - - await run.stop(); - }); - - it('should not emit polyfills', async () => { - const run = await architect.scheduleTarget(target); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - expect(host.fileMatchExists(getSystemPath(outputPath), /polyfills/)).not.toBeDefined(); - expect(host.fileMatchExists(getSystemPath(outputPath), /main/)).toBeDefined(); - - await run.stop(); - }); - - it('should not emit polyfills when ES5 support is needed', async () => { - // the below is needed because of different code paths - // for polyfills if differential loading is needed - host.writeMultipleFiles({ - 'browserslist': 'IE 10', - }); - - const run = await architect.scheduleTarget(target); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - expect(host.fileMatchExists(getSystemPath(outputPath), /polyfills/)).not.toBeDefined(); - expect(host.fileMatchExists(getSystemPath(outputPath), /main/)).toBeDefined(); - - await run.stop(); - }); - - it('supports sourcemaps', async () => { - const overrides = { sourceMap: true }; - const run = await architect.scheduleTarget(target, overrides); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - expect(host.scopedSync().exists(join(outputPath, 'main.js.map'))).toBeTruthy(); - await run.stop(); - }); - - it('supports scripts only sourcemaps', async () => { - host.writeMultipleFiles({ - 'src/app/app.component.css': `p { color: red; }`, - }); - - const run = await architect.scheduleTarget(target, { - bundleDependencies: BundleDependencies.None, - sourceMap: { - styles: false, - scripts: true, - }, - }); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - expect(host.scopedSync().exists(join(outputPath, 'main.js.map'))).toBe(true); - - const scriptContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - expect(scriptContent).toContain('sourceMappingURL=main.js.map'); - expect(scriptContent).not.toContain('sourceMappingURL=data:application/json'); - - await run.stop(); - }); - - it('supports component styles sourcemaps', async () => { - const overrides = { - bundleDependencies: BundleDependencies.None, - sourceMap: { - styles: true, - scripts: true, - }, - }; - - host.writeMultipleFiles({ - 'src/app/app.component.css': `p { color: red; }`, - }); - - const run = await architect.scheduleTarget(target, overrides); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - expect(host.scopedSync().exists(join(outputPath, 'main.js.map'))).toBe(true); - - const scriptContent = virtualFs.fileBufferToString( - host.scopedSync().read(join(outputPath, 'main.js')), - ); - expect(scriptContent).toContain('sourceMappingURL=main.js.map'); - expect(scriptContent).toContain('sourceMappingURL=data:application/json'); - - await run.stop(); - }); - - it('runs watch mode', async () => { - const overrides = { watch: true }; - - const run = await architect.scheduleTarget(target, overrides); - - await run.output.pipe( - tap((buildEvent) => { - expect(buildEvent.success).toBe(true); - - const fileName = join(outputPath, 'main.js'); - const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - if (veEnabled) { - expect(content).toMatch(/AppServerModuleNgFactory/); - } else { - expect(content).toMatch(/AppServerModule\.ɵmod/); - } - }), - take(1), - ).toPromise(); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/server/resources-output-path_spec_large.ts b/packages/angular_devkit/build_angular/test/server/resources-output-path_spec_large.ts deleted file mode 100644 index 8c10ef66d795..000000000000 --- a/packages/angular_devkit/build_angular/test/server/resources-output-path_spec_large.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -import { Architect } from '@angular-devkit/architect'; -import { join, normalize, virtualFs } from '@angular-devkit/core'; -import { ServerBuilderOutput } from '../../src'; -import { createArchitect, host } from '../utils'; - - -describe('Server Builder styles resources output path (No emit assets)', () => { - function writeFiles() { - host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); - host.copyFile('src/spectrum.png', './src/assets/component-img-absolute.png'); - host.writeMultipleFiles({ - 'src/app/app.component.css': ` - h3 { background: url('/assets/component-img-absolute.png'); } - h4 { background: url('../assets/component-img-relative.png'); } - `, - }); - } - - const target = { project: 'app', target: 'server' }; - let architect: Architect; - - const outputPath = normalize('dist-server'); - - beforeEach(async () => { - await host.initialize().toPromise(); - architect = (await createArchitect(host.root())).architect; - }); - afterEach(async () => host.restore().toPromise()); - - it(`supports resourcesOutputPath in resource urls`, async () => { - writeFiles(); - const overrides = { - resourcesOutputPath: 'out-assets', - }; - - const run = await architect.scheduleTarget(target, overrides); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - const fileName = join(outputPath, 'main.js'); - - const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - - expect(content).toContain(`url('/assets/component-img-absolute.png')`); - expect(content).toContain(`url('out-assets/component-img-relative.png')`); - - expect(host.scopedSync().exists(normalize(`${outputPath}/out-assets/component-img-relative.png`))) - .toBe(false); - }); - - it(`supports blank resourcesOutputPath`, async () => { - writeFiles(); - - const run = await architect.scheduleTarget(target); - const output = await run.result as ServerBuilderOutput; - expect(output.success).toBe(true); - - const fileName = join(outputPath, 'main.js'); - const content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); - - expect(content).toContain(`url('/assets/component-img-absolute.png')`); - expect(content).toContain(`url('component-img-relative.png')`); - - expect(host.scopedSync().exists(normalize(`${outputPath}/component-img-relative.png`))) - .toBe(false); - }); -}); diff --git a/packages/angular_devkit/build_angular/test/tslint/works_spec_large.ts b/packages/angular_devkit/build_angular/test/tslint/works_spec_large.ts deleted file mode 100644 index 897a121754a5..000000000000 --- a/packages/angular_devkit/build_angular/test/tslint/works_spec_large.ts +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, Target } from '@angular-devkit/architect'; -import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; -import { TestingArchitectHost } from '@angular-devkit/architect/testing'; -import { - logging, - normalize, - schema, - workspaces, -} from '@angular-devkit/core'; -import { NodeJsAsyncHost } from '@angular-devkit/core/node'; -import * as path from 'path'; - -const devkitRoot = (global as any)._DevKitRoot; // tslint:disable-line:no-any -const workspaceRoot = path.join(devkitRoot, 'tests/angular_devkit/build_angular/hello-world-app/'); - -const lintTarget: Target = { project: 'app', target: 'lint' }; - -// tslint:disable-next-line:no-big-function -describe('Tslint Target', () => { - // const filesWithErrors = { 'src/foo.ts': 'const foo = "";\n' }; - let testArchitectHost: TestingArchitectHost; - let architect: Architect; - - beforeEach(async () => { - const registry = new schema.CoreSchemaRegistry(); - registry.addPostTransform(schema.transforms.addUndefinedDefaults); - - const { workspace } = await workspaces.readWorkspace( - normalize(workspaceRoot), - workspaces.createWorkspaceHost(new NodeJsAsyncHost()), - ); - - testArchitectHost = new TestingArchitectHost( - workspaceRoot, - workspaceRoot, - new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot), - ); - architect = new Architect(testArchitectHost, registry); - }); - - it('works', async () => { - const run = await architect.scheduleTarget({ project: 'app', target: 'lint' }); - const output = await run.result; - expect(output.success).toBe(true); - await run.stop(); - }, 30000); - - it(`should show project name as status and in the logs`, async () => { - // Check logs. - const logger = new logging.Logger('lint-info'); - const allLogs: string[] = []; - logger.subscribe(entry => allLogs.push(entry.message)); - - const run = await architect.scheduleTarget(lintTarget, {}, { logger }); - - // Check status updates. - const allStatus: string[] = []; - run.progress.subscribe(progress => { - if (progress.status !== undefined) { - allStatus.push(progress.status); - } - }); - - const output = await run.result; - expect(output.success).toBe(true); - expect(allStatus).toContain(jasmine.stringMatching(/linting.*"app".*/i)); - expect(allLogs).toContain(jasmine.stringMatching(/linting.*"app".*/i)); - await run.stop(); - }); - - it(`should not show project name when formatter is non human readable`, async () => { - const overrides = { - format: 'checkstyle', - }; - - // Check logs. - const logger = new logging.Logger('lint-info'); - const allLogs: string[] = []; - logger.subscribe(entry => allLogs.push(entry.message)); - - const run = await architect.scheduleTarget(lintTarget, overrides, { logger }); - - // Check status updates. - const allStatus: string[] = []; - run.progress.subscribe(progress => { - if (progress.status !== undefined) { - allStatus.push(progress.status); - } - }); - - const output = await run.result; - expect(output.success).toBe(true); - expect(allLogs).toContain(jasmine.stringMatching(/file name=.*app.module.ts/i)); - expect(allStatus).toContain(jasmine.stringMatching(/linting.*"app".*/i)); - expect(allLogs).not.toContain(jasmine.stringMatching(/linting.*"app".*/i)); - await run.stop(); - }, 30000); - - // it('should report lint error once', (done) => { - // host.writeMultipleFiles({'src/app/app.component.ts': 'const foo = "";\n' }); - // const logger = new TestLogger('lint-error'); - // - // runTargetSpec(host, tslintTargetSpec, undefined, DefaultTimeout, logger).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(false)), - // tap(() => { - // // this is to make sure there are no duplicates - // expect(logger.includes(`" should be \'\nERROR`)).toBe(false); - // - // expect(logger.includes(`" should be '`)).toBe(true); - // expect(logger.includes(`Lint errors found in the listed files`)).toBe(true); - // }), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports exclude with glob', (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const overrides: Partial = { exclude: ['**/foo.ts'] }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports exclude with relative paths', (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const overrides: Partial = { exclude: ['src/foo.ts'] }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it(`supports exclude with paths starting with './'`, (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const overrides: Partial = { exclude: ['./src/foo.ts'] }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports fix', (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const overrides: Partial = { fix: true }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // tap(() => { - // const fileName = normalize('src/foo.ts'); - // const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName)); - // expect(content).toContain(`const foo = '';`); - // }), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports force', (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const logger = new TestLogger('lint-force'); - // const overrides: Partial = { force: true }; - // - // runTargetSpec(host, tslintTargetSpec, overrides, DefaultTimeout, logger).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // tap(() => { - // expect(logger.includes(`" should be '`)).toBe(true); - // expect(logger.includes(`Lint errors found in the listed files`)).toBe(true); - // }), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports format', (done) => { - // host.writeMultipleFiles(filesWithErrors); - // const logger = new TestLogger('lint-format'); - // const overrides: Partial = { format: 'stylish' }; - // - // runTargetSpec(host, tslintTargetSpec, overrides, DefaultTimeout, logger).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(false)), - // tap(() => { - // expect(logger.includes(`quotemark`)).toBe(true); - // }), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports finding configs', (done) => { - // host.writeMultipleFiles({ - // 'src/app/foo/foo.ts': `const foo = '';\n`, - // 'src/app/foo/tslint.json': ` - // { - // "rules": { - // "quotemark": [ - // true, - // "double" - // ] - // } - // } - // `, - // }); - // const overrides: Partial = { tslintConfig: undefined }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(false)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports overriding configs', (done) => { - // host.writeMultipleFiles({ - // 'src/app/foo/foo.ts': `const foo = '';\n`, - // 'src/app/foo/tslint.json': ` - // { - // "rules": { - // "quotemark": [ - // true, - // "double" - // ] - // } - // } - // `, - // }); - // const overrides: Partial = { tslintConfig: 'tslint.json' }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports using files with no project', (done) => { - // const overrides: Partial = { - // tsConfig: undefined, - // files: ['src/app/**/*.ts'], - // }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports using one project as a string', (done) => { - // const overrides: Partial = { - // tsConfig: 'src/tsconfig.app.json', - // }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports using one project as an array', (done) => { - // const overrides: Partial = { - // tsConfig: ['src/tsconfig.app.json'], - // }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('supports using two projects', (done) => { - // const overrides: Partial = { - // tsConfig: ['src/tsconfig.app.json', 'src/tsconfig.spec.json'], - // }; - // - // runTargetSpec(host, tslintTargetSpec, overrides).pipe( - // tap((buildEvent) => expect(buildEvent.success).toBe(true)), - // ).toPromise().then(done, done.fail); - // }, 30000); - // - // it('errors when type checking is used without a project', (done) => { - // const overrides: Partial = { - // tsConfig: undefined, - // typeCheck: true, - // }; - // - // runTargetSpec(host, tslintTargetSpec, overrides) - // .subscribe(undefined, () => done(), done.fail); - // }, 30000); -}); diff --git a/packages/angular_devkit/build_angular/test/utils.ts b/packages/angular_devkit/build_angular/test/utils.ts deleted file mode 100644 index 263d75d1ba1f..000000000000 --- a/packages/angular_devkit/build_angular/test/utils.ts +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect, BuilderOutput, ScheduleOptions, Target } from '@angular-devkit/architect'; -import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; -import { TestProjectHost, TestingArchitectHost } from '@angular-devkit/architect/testing'; -import { - Path, - getSystemPath, - join, - json, - normalize, - schema, - virtualFs, - workspaces, -} from '@angular-devkit/core'; -import { BrowserBuilderOutput } from '../src/browser'; - -export const veEnabled = process.argv.includes('--ve'); - -const devkitRoot = normalize((global as any)._DevKitRoot); // tslint:disable-line:no-any -export const workspaceRoot = join( - devkitRoot, - `tests/angular_devkit/build_angular/hello-world-app${veEnabled ? '-ve' : ''}/`, -); -export const host = new TestProjectHost(workspaceRoot); -export const outputPath: Path = normalize('dist'); - -export const browserTargetSpec = { project: 'app', target: 'build' }; -export const devServerTargetSpec = { project: 'app', target: 'serve' }; -export const extractI18nTargetSpec = { project: 'app', target: 'extract-i18n' }; -export const karmaTargetSpec = { project: 'app', target: 'test' }; -export const tslintTargetSpec = { project: 'app', target: 'lint' }; -export const protractorTargetSpec = { project: 'app-e2e', target: 'e2e' }; - -export async function createArchitect(workspaceRoot: Path) { - const registry = new schema.CoreSchemaRegistry(); - registry.addPostTransform(schema.transforms.addUndefinedDefaults); - const workspaceSysPath = getSystemPath(workspaceRoot); - - const { workspace } = await workspaces.readWorkspace( - workspaceSysPath, - workspaces.createWorkspaceHost(host), - ); - const architectHost = new TestingArchitectHost( - workspaceSysPath, - workspaceSysPath, - new WorkspaceNodeModulesArchitectHost(workspace, workspaceSysPath), - ); - const architect = new Architect(architectHost, registry); - - return { - workspace, - architectHost, - architect, - }; -} - -export interface BrowserBuildOutput { - output: BuilderOutput; - files: { [file: string]: Promise }; -} - -export async function browserBuild( - architect: Architect, - host: virtualFs.Host, - target: Target, - overrides?: json.JsonObject, - scheduleOptions?: ScheduleOptions, -): Promise { - const run = await architect.scheduleTarget(target, overrides, scheduleOptions); - const output = (await run.result) as BrowserBuilderOutput; - expect(output.success).toBe(true); - - expect(output.outputPaths[0]).not.toBeUndefined(); - const outputPath = normalize(output.outputPaths[0]); - - const fileNames = await host.list(outputPath).toPromise(); - const files = fileNames.reduce((acc: { [name: string]: Promise }, path) => { - let cache: Promise | null = null; - Object.defineProperty(acc, path, { - enumerable: true, - get() { - if (cache) { - return cache; - } - if (!fileNames.includes(path)) { - return Promise.reject('No file named ' + path); - } - - cache = host - .read(join(outputPath, path)) - .toPromise() - .then(content => virtualFs.fileBufferToString(content)); - - return cache; - }, - }); - - return acc; - }, {}); - - await run.stop(); - - return { - output, - files, - }; -} - -export const lazyModuleFiles: { [path: string]: string } = { - 'src/app/lazy/lazy-routing.module.ts': ` - import { NgModule } from '@angular/core'; - import { Routes, RouterModule } from '@angular/router'; - - const routes: Routes = []; - - @NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule] - }) - export class LazyRoutingModule { } - `, - 'src/app/lazy/lazy.module.ts': ` - import { NgModule } from '@angular/core'; - import { CommonModule } from '@angular/common'; - - import { LazyRoutingModule } from './lazy-routing.module'; - - @NgModule({ - imports: [ - CommonModule, - LazyRoutingModule - ], - declarations: [] - }) - export class LazyModule { } - `, -}; - -export const lazyModuleStringImport: { [path: string]: string } = { - 'src/app/app.module.ts': ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - import { RouterModule } from '@angular/router'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - RouterModule.forRoot([ - { path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule' } - ]) - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - `, -}; - -export const lazyModuleFnImport: { [path: string]: string } = { - 'src/app/app.module.ts': lazyModuleStringImport['src/app/app.module.ts'].replace( - `loadChildren: './lazy/lazy.module#LazyModule'`, - `loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)`, - ), -}; diff --git a/packages/angular_devkit/build_ng_packagr/README.md b/packages/angular_devkit/build_ng_packagr/README.md deleted file mode 100644 index acfeaea95427..000000000000 --- a/packages/angular_devkit/build_ng_packagr/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Angular Build Architect for ng-packagr - -WIP \ No newline at end of file diff --git a/packages/angular_devkit/build_ng_packagr/builders.json b/packages/angular_devkit/build_ng_packagr/builders.json deleted file mode 100644 index 3a699cdb2114..000000000000 --- a/packages/angular_devkit/build_ng_packagr/builders.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$schema": "../architect/src/builders-schema.json", - "builders": { - "build": { - "implementation": "./src/build", - "schema": "./src/build/schema.json", - "description": "Build a library with ng-packagr." - } - } -} diff --git a/packages/angular_devkit/build_ng_packagr/package.json b/packages/angular_devkit/build_ng_packagr/package.json deleted file mode 100644 index e7dd1fb90540..000000000000 --- a/packages/angular_devkit/build_ng_packagr/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "@angular-devkit/build-ng-packagr", - "version": "0.0.0", - "description": "Angular Build Architect for ng-packagr", - "experimental": true, - "main": "src/index.js", - "typings": "src/index.d.ts", - "builders": "builders.json", - "dependencies": { - "@angular-devkit/architect": "0.0.0", - "rxjs": "6.5.3" - }, - "peerDependencies": { - "ng-packagr": "^9.0.0-rc.0", - "tsickle": "~0.37.1" - }, - "devDependencies": { - "@angular/compiler": "9.0.0-rc.2", - "@angular/compiler-cli": "9.0.0-rc.2", - "@angular-devkit/core": "0.0.0", - "ng-packagr": "~9.0.0-rc.0", - "tslib": "^1.10.0" - }, - "peerDependenciesMeta": { - "tsickle": { - "optional": true - } - } -} \ No newline at end of file diff --git a/packages/angular_devkit/build_ng_packagr/src/build/index.ts b/packages/angular_devkit/build_ng_packagr/src/build/index.ts deleted file mode 100644 index 42c5555f5108..000000000000 --- a/packages/angular_devkit/build_ng_packagr/src/build/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; -import { resolve } from 'path'; -import { Observable, from } from 'rxjs'; -import { mapTo, switchMap } from 'rxjs/operators'; -import { Schema as NgPackagrBuilderOptions } from './schema'; - -async function initialize( - options: NgPackagrBuilderOptions, - root: string, -): Promise { - const packager = (await import('ng-packagr')).ngPackagr(); - - packager.forProject(resolve(root, options.project)); - - if (options.tsConfig) { - packager.withTsConfig(resolve(root, options.tsConfig)); - } - - return packager; -} - -export function execute( - options: NgPackagrBuilderOptions, - context: BuilderContext, -): Observable { - return from(initialize(options, context.workspaceRoot)).pipe( - switchMap(packager => options.watch ? packager.watch() : packager.build()), - mapTo({ success: true }), - ); -} - -export { NgPackagrBuilderOptions }; -export default createBuilder & NgPackagrBuilderOptions>(execute); diff --git a/packages/angular_devkit/build_ng_packagr/src/build/index_spec_large.ts b/packages/angular_devkit/build_ng_packagr/src/build/index_spec_large.ts deleted file mode 100644 index 7c8f6b6a21c6..000000000000 --- a/packages/angular_devkit/build_ng_packagr/src/build/index_spec_large.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; -import { TestProjectHost, TestingArchitectHost } from '@angular-devkit/architect/testing'; -import { - getSystemPath, - join, - normalize, - schema, - virtualFs, - workspaces, -} from '@angular-devkit/core'; // tslint:disable-line:no-implicit-dependencies -import { map, take, tap } from 'rxjs/operators'; - -const veEnabled = process.argv.includes('--ve'); - -const devkitRoot = (global as unknown as { _DevKitRoot: string})._DevKitRoot; -const workspaceRoot = join( - normalize(devkitRoot), - `tests/angular_devkit/build_ng_packagr/ng-packaged${veEnabled ? '-ve' : ''}/`, -); - -describe('NgPackagr Builder', () => { - const host = new TestProjectHost(workspaceRoot); - let architect: Architect; - - beforeEach(async () => { - await host.initialize().toPromise(); - - const registry = new schema.CoreSchemaRegistry(); - registry.addPostTransform(schema.transforms.addUndefinedDefaults); - - const workspaceSysPath = getSystemPath(host.root()); - const { workspace } = await workspaces.readWorkspace( - workspaceSysPath, - workspaces.createWorkspaceHost(host), - ); - const architectHost = new TestingArchitectHost( - workspaceSysPath, - workspaceSysPath, - new WorkspaceNodeModulesArchitectHost(workspace, workspaceSysPath), - ); - - architect = new Architect(architectHost, registry); - }); - - afterEach(() => host.restore().toPromise()); - - it('builds and packages a library', async () => { - const run = await architect.scheduleTarget({ project: 'lib', target: 'build' }); - - await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); - - await run.stop(); - - expect(host.scopedSync().exists(normalize('./dist/lib/fesm5/lib.js'))).toBe(true); - const content = virtualFs.fileBufferToString( - host.scopedSync().read(normalize('./dist/lib/fesm5/lib.js')), - ); - expect(content).toContain('lib works'); - - if (veEnabled) { - expect(content).not.toContain('ɵcmp'); - } else { - expect(content).toContain('ɵcmp'); - } - }); - - it('rebuilds on TS file changes', async () => { - const goldenValueFiles: { [path: string]: string } = { - 'projects/lib/src/lib/lib.component.ts': ` - import { Component } from '@angular/core'; - - @Component({ - selector: 'lib', - template: 'lib update works!' - }) - export class LibComponent { } - `, - }; - - const run = await architect.scheduleTarget( - { project: 'lib', target: 'build' }, - { watch: true }, - ); - - let buildNumber = 0; - - await run.output.pipe( - tap((buildEvent) => expect(buildEvent.success).toBe(true)), - map(() => { - const fileName = './dist/lib/fesm5/lib.js'; - const content = virtualFs.fileBufferToString( - host.scopedSync().read(normalize(fileName)), - ); - - return content; - }), - tap(content => { - buildNumber += 1; - switch (buildNumber) { - case 1: - expect(content).toMatch(/lib works/); - host.writeMultipleFiles(goldenValueFiles); - break; - - case 2: - expect(content).toMatch(/lib update works/); - break; - default: - break; - } - }), - take(2), - ).toPromise(); - - await run.stop(); - }); -}); diff --git a/packages/angular_devkit/build_ng_packagr/src/build/schema.json b/packages/angular_devkit/build_ng_packagr/src/build/schema.json deleted file mode 100644 index a72def315064..000000000000 --- a/packages/angular_devkit/build_ng_packagr/src/build/schema.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "title": "ng-packagr Target", - "description": "ng-packagr target options for Build Architect. Use to build library projects.", - "type": "object", - "properties": { - "project": { - "type": "string", - "description": "The file path for the ng-packagr configuration file, relative to the current workspace." - }, - "tsConfig": { - "type": "string", - "description": "The full path for the TypeScript configuration file, relative to the current workspace." - }, - "watch": { - "type": "boolean", - "description": "Run build when files change.", - "default": false - } - }, - "additionalProperties": false, - "required": [ - "project" - ] -} diff --git a/packages/angular_devkit/build_ng_packagr/src/index.ts b/packages/angular_devkit/build_ng_packagr/src/index.ts deleted file mode 100644 index 51ed774b37fc..000000000000 --- a/packages/angular_devkit/build_ng_packagr/src/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export * from './build'; diff --git a/packages/angular_devkit/build_optimizer/BUILD b/packages/angular_devkit/build_optimizer/BUILD deleted file mode 100644 index 4ca6e641289e..000000000000 --- a/packages/angular_devkit/build_optimizer/BUILD +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license - -licenses(["notice"]) # MIT - -load("@npm_bazel_jasmine//:index.bzl", "jasmine_node_test") -load("@npm_bazel_typescript//:index.bzl", "ts_library") -load("@build_bazel_rules_nodejs//:defs.bzl", "npm_package") - -package(default_visibility = ["//visibility:public"]) - -ts_library( - name = "build_optimizer", - srcs = glob( - include = ["src/**/*.ts"], - exclude = [ - # TODO(@filipesilva): shouldn't need to exclude the cli files but can't exclude them - # from jasmine_node_test. - "src/**/cli.ts", - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - "src/**/*_benchmark.ts", - ], - ), - deps = [ - "@npm//@types/node", - "@npm//@types/webpack", - "@npm//source-map", - "@npm//tslib", - "@npm//typescript", - ], -) - -ts_library( - name = "build_optimizer_test_lib", - testonly = True, - srcs = glob( - include = [ - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - ], - ), - # @external_begin - tsconfig = "//:tsconfig-test.json", - deps = [ - ":build_optimizer", - "//packages/angular_devkit/core", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//source-map", - ], - # @external_end -) - -jasmine_node_test( - name = "build_optimizer_test", - srcs = [":build_optimizer_test_lib"], - deps = [ - "@npm//jasmine", - "@npm//source-map", - ], -) - -npm_package( - name = "npm_package", - deps = [ - ":build_optimizer", - ], -) diff --git a/packages/angular_devkit/build_optimizer/README.md b/packages/angular_devkit/build_optimizer/README.md deleted file mode 100644 index 6b97c1b3588d..000000000000 --- a/packages/angular_devkit/build_optimizer/README.md +++ /dev/null @@ -1,215 +0,0 @@ -# Angular Build Optimizer - -Angular Build Optimizer contains Angular optimizations applicable to JavaScript code as a TypeScript transform pipeline. - - -## Available optimizations - -Transformations applied depend on file content: - -- [Class fold](#class-fold), [Scrub file](#scrub-file) and [Prefix functions](#prefix-functions): applied to Angular apps and libraries. -- [Import tslib](#import-tslib): applied when TypeScript helpers are found. - -Some of these optimizations add `/*@__PURE__*/` comments. -These are used by JS optimization tools to identify pure functions that can potentially be dropped. - - -### Class fold - -Static properties are folded into ES5 classes: - -```typescript -// input -var Clazz = (function () { function Clazz() { } return Clazz; }()); -Clazz.prop = 1; - -// output -var Clazz = (function () { function Clazz() { } Clazz.prop = 1; return Clazz; }()); -``` - - -### Scrub file - -Angular decorators, property decorators and constructor parameters are removed, while leaving non-Angular ones intact. - -```typescript -// input -import { Injectable, Input, Component } from '@angular/core'; -import { NotInjectable, NotComponent, NotInput } from 'another-lib'; -var Clazz = (function () { function Clazz() { } return Clazz; }()); -Clazz.decorators = [{ type: Injectable }, { type: NotInjectable }]; -Clazz.propDecorators = { 'ngIf': [{ type: Input }] }; -Clazz.ctorParameters = function () { return [{type: Injector}]; }; -var ComponentClazz = (function () { - function ComponentClazz() { } - __decorate([ - Input(), - __metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - __decorate([ - NotInput(), - __metadata("design:type", Object) - ], Clazz.prototype, "notSelected", void 0); - ComponentClazz = __decorate([ - NotComponent(), - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - ], ComponentClazz); - return ComponentClazz; -}()); - -// output -import { Injectable, Input, Component } from '@angular/core'; -import { NotInjectable, NotComponent } from 'another-lib'; -var Clazz = (function () { function Clazz() { } return Clazz; }()); -Clazz.decorators = [{ type: NotInjectable }]; -var ComponentClazz = (function () { - function ComponentClazz() { } - __decorate([ - NotInput(), - __metadata("design:type", Object) - ], Clazz.prototype, "notSelected", void 0); - ComponentClazz = __decorate([ - NotComponent() - ], ComponentClazz); - return ComponentClazz; -}()); -``` - - -### Prefix functions - -Adds `/*@__PURE__*/` comments to top level downleveled class declarations and instantiation. - -Warning: this transform assumes the file is a pure module. It should not be used with unpure modules. - -```typescript -// input -var Clazz = (function () { function Clazz() { } return Clazz; }()); -var newClazz = new Clazz(); -var newClazzTwo = Clazz(); - -// output -var Clazz = /*@__PURE__*/ (function () { function Clazz() { } return Clazz; }()); -var newClazz = /*@__PURE__*/ new Clazz(); -var newClazzTwo = /*@__PURE__*/ Clazz(); -``` - - -### Prefix Classes - -Adds `/*@__PURE__*/` to downleveled TypeScript classes. - -```typescript -// input -var ReplayEvent = (function () { - function ReplayEvent(time, value) { - this.time = time; - this.value = value; - } - return ReplayEvent; -}()); - -// output -var ReplayEvent = /*@__PURE__*/ (function () { - function ReplayEvent(time, value) { - this.time = time; - this.value = value; - } - return ReplayEvent; -}()); -``` - - -### Import tslib - -TypeScript helpers (`__extends/__decorate/__metadata/__param`) are replaced with `tslib` imports whenever found. - -```typescript -// input -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; - -// output -import { __extends } from "tslib"; -``` - -### Wrap enums - -Wrap downleveled TypeScript enums in a function, and adds `/*@__PURE__*/` comment. - -```typescript -// input -var ChangeDetectionStrategy; -(function (ChangeDetectionStrategy) { - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; -})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); - -// output -var ChangeDetectionStrategy = /*@__PURE__*/ (function () { - var ChangeDetectionStrategy = {}; - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; - return ChangeDetectionStrategy; -})(); -``` - - -## Library Usage - -```typescript -import { buildOptimizer } from '@angular-devkit/build-optimizer'; - -const transpiledContent = buildOptimizer({ content: input }).content; -``` - -Available options: -```typescript -export interface BuildOptimizerOptions { - content?: string; - inputFilePath?: string; - outputFilePath?: string; - emitSourceMap?: boolean; - strict?: boolean; - isSideEffectFree?: boolean; -} -``` - - -## Webpack loader usage: - -```typescript -import { BuildOptimizerWebpackPlugin } from '@angular-devkit/build-optimizer'; - -module.exports = { - plugins: [ - new BuildOptimizerWebpackPlugin(), - ] - module: { - rules: [ - { - test: /\.js$/, - loader: '@angular-devkit/build-optimizer/webpack-loader', - options: { - sourceMap: false - } - } - ] - } -} -``` - - -## CLI usage - -```bash -build-optimizer input.js -build-optimizer input.js output.js -``` diff --git a/packages/angular_devkit/build_optimizer/package.json b/packages/angular_devkit/build_optimizer/package.json deleted file mode 100644 index db2759e3426d..000000000000 --- a/packages/angular_devkit/build_optimizer/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@angular-devkit/build-optimizer", - "version": "0.0.0", - "description": "Angular Build Optimizer", - "experimental": true, - "main": "src/index.js", - "typings": "src/index.d.ts", - "bin": { - "build-optimizer": "./src/build-optimizer/cli.js" - }, - "dependencies": { - "loader-utils": "1.2.3", - "source-map": "0.7.3", - "tslib": "1.10.0", - "typescript": "3.6.4", - "webpack-sources": "1.4.3" - } -} diff --git a/packages/angular_devkit/build_optimizer/src/_golden-api.ts b/packages/angular_devkit/build_optimizer/src/_golden-api.ts deleted file mode 100644 index 06e63e7a2c84..000000000000 --- a/packages/angular_devkit/build_optimizer/src/_golden-api.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './index'; -export { default } from './build-optimizer/webpack-loader'; diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer.ts deleted file mode 100644 index eac95c7f23f0..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { readFileSync } from 'fs'; -import { - TransformJavascriptOptions, - TransformJavascriptOutput, - transformJavascript, -} from '../helpers/transform-javascript'; -import { getPrefixClassesTransformer, testPrefixClasses } from '../transforms/prefix-classes'; -import { getPrefixFunctionsTransformer } from '../transforms/prefix-functions'; -import { - getScrubFileTransformer, - getScrubFileTransformerForCore, - testScrubFile, -} from '../transforms/scrub-file'; -import { getWrapEnumsTransformer } from '../transforms/wrap-enums'; - - -// Angular packages are known to have no side effects. -const whitelistedAngularModules = [ - /[\\/]node_modules[\\/]@angular[\\/]animations[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]common[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]compiler[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]core[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]forms[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]http[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]platform-browser-dynamic[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]platform-browser[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]platform-webworker-dynamic[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]platform-webworker[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]router[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]upgrade[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]material[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]cdk[\\/]/, -]; - -// Factories created by AOT are known to have no side effects. -// In Angular 2/4 the file path for factories can be `.ts`, but in Angular 5 it is `.js`. -const ngFactories = [ - /\.ngfactory\.[jt]s/, - /\.ngstyle\.[jt]s/, -]; - -// Known locations for the source files of @angular/core. -const coreFilesRegex = [ - /[\\/]node_modules[\\/]@angular[\\/]core[\\/]esm5[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]core[\\/]fesm5[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]core[\\/]esm2015[\\/]/, - /[\\/]node_modules[\\/]@angular[\\/]core[\\/]fesm2015[\\/]/, -]; - -function isKnownCoreFile(filePath: string) { - return coreFilesRegex.some(re => re.test(filePath)); -} - -function isKnownSideEffectFree(filePath: string) { - return ngFactories.some((re) => re.test(filePath)) || - whitelistedAngularModules.some((re) => re.test(filePath)); -} - -export interface BuildOptimizerOptions { - content?: string; - originalFilePath?: string; - inputFilePath?: string; - outputFilePath?: string; - emitSourceMap?: boolean; - strict?: boolean; - isSideEffectFree?: boolean; - isAngularCoreFile?: boolean; -} - -export function buildOptimizer(options: BuildOptimizerOptions): TransformJavascriptOutput { - - const { inputFilePath, isAngularCoreFile } = options; - let { originalFilePath, content } = options; - - if (!originalFilePath && inputFilePath) { - originalFilePath = inputFilePath; - } - - if (!inputFilePath && content === undefined) { - throw new Error('Either filePath or content must be specified in options.'); - } - - if (content === undefined) { - content = readFileSync(inputFilePath as string, 'UTF-8'); - } - - if (!content) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - let selectedGetScrubFileTransformer = getScrubFileTransformer; - - if ( - isAngularCoreFile === true || - (isAngularCoreFile === undefined && originalFilePath && isKnownCoreFile(originalFilePath)) - ) { - selectedGetScrubFileTransformer = getScrubFileTransformerForCore; - } - - // Determine which transforms to apply. - const getTransforms = []; - - let typeCheck = false; - if (options.isSideEffectFree || originalFilePath && isKnownSideEffectFree(originalFilePath)) { - getTransforms.push( - // getPrefixFunctionsTransformer is rather dangerous, apply only to known pure es5 modules. - // It will mark both `require()` calls and `console.log(stuff)` as pure. - // We only apply it to whitelisted modules, since we know they are safe. - // getPrefixFunctionsTransformer needs to be before getFoldFileTransformer. - getPrefixFunctionsTransformer, - selectedGetScrubFileTransformer, - ); - typeCheck = true; - } else if (testScrubFile(content)) { - // Always test as these require the type checker - getTransforms.push( - selectedGetScrubFileTransformer, - ); - typeCheck = true; - } - - if (testPrefixClasses(content)) { - getTransforms.unshift(getPrefixClassesTransformer); - } - - getTransforms.push(getWrapEnumsTransformer); - - const transformJavascriptOpts: TransformJavascriptOptions = { - content: content, - inputFilePath: options.inputFilePath, - outputFilePath: options.outputFilePath, - emitSourceMap: options.emitSourceMap, - strict: options.strict, - getTransforms, - typeCheck, - }; - - return transformJavascript(transformJavascriptOpts); -} diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer_spec.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer_spec.ts deleted file mode 100644 index cb242499a1ae..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/build-optimizer_spec.ts +++ /dev/null @@ -1,356 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { RawSourceMap } from 'source-map'; -import { TransformJavascriptOutput } from '../helpers/transform-javascript'; -import { buildOptimizer } from './build-optimizer'; - - -describe('build-optimizer', () => { - const imports = 'import { Injectable, Input, Component } from \'@angular/core\';'; - const clazz = 'var Clazz = (function () { function Clazz() { } return Clazz; }());'; - const decorators = 'Clazz.decorators = [ { type: Injectable } ];'; - - describe('basic functionality', () => { - it('applies scrub-file and prefix-functions to side-effect free modules', () => { - const input = tags.stripIndent` - ${imports} - var ChangeDetectionStrategy; - (function (ChangeDetectionStrategy) { - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; - })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); - ${clazz} - ${decorators} - Clazz.propDecorators = { 'ngIf': [{ type: Input }] }; - Clazz.ctorParameters = function () { return [{type: Injectable}]; }; - var ComponentClazz = (function () { - function ComponentClazz() { } - __decorate([ - Input(), - __metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - ComponentClazz = __decorate([ - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }), - __metadata("design:paramtypes", [Injectable]) - ], ComponentClazz); - return ComponentClazz; - }()); - var RenderType_MdOption = ɵcrt({ encapsulation: 2, styles: styles_MdOption}); - `; - const output = tags.oneLine` - ${imports} - var ChangeDetectionStrategy = /*@__PURE__*/ (function (ChangeDetectionStrategy) { - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; - return ChangeDetectionStrategy; - })({}); - var Clazz = /*@__PURE__*/ (function () { function Clazz() { } return Clazz; }()); - var ComponentClazz = /*@__PURE__*/ (function () { - function ComponentClazz() { } - return ComponentClazz; - }()); - var RenderType_MdOption = /*@__PURE__*/ ɵcrt({ encapsulation: 2, styles: styles_MdOption }); - `; - - // Check Angular 4/5 and unix/windows paths. - const inputPaths = [ - '/node_modules/@angular/core/@angular/core.es5.js', - '/node_modules/@angular/core/esm5/core.js', - '\\node_modules\\@angular\\core\\@angular\\core.es5.js', - '\\node_modules\\@angular\\core\\esm5\\core.js', - '/project/file.ngfactory.js', - '/project/file.ngstyle.js', - ]; - - inputPaths.forEach((inputFilePath) => { - const boOutput = buildOptimizer({ content: input, inputFilePath }); - expect(tags.oneLine`${boOutput.content}`).toEqual(output); - expect(boOutput.emitSkipped).toEqual(false); - }); - }); - - it('supports flagging module as side-effect free', () => { - const output = tags.oneLine` - var RenderType_MdOption = /*@__PURE__*/ ɵcrt({ encapsulation: 2, styles: styles_MdOption }); - `; - const input = tags.stripIndent` - var RenderType_MdOption = ɵcrt({ encapsulation: 2, styles: styles_MdOption}); - `; - - const boOutput = buildOptimizer({ content: input, isSideEffectFree: true }); - expect(tags.oneLine`${boOutput.content}`).toEqual(output); - expect(boOutput.emitSkipped).toEqual(false); - }); - - it('should not add pure comments to tslib helpers', () => { - const input = tags.stripIndent` - class LanguageState { - } - - LanguageState.ctorParameters = () => [ - { type: TranslateService }, - { type: undefined, decorators: [{ type: Inject, args: [LANGUAGE_CONFIG,] }] } - ]; - - __decorate([ - Action(CheckLanguage), - __metadata("design:type", Function), - __metadata("design:paramtypes", [Object]), - __metadata("design:returntype", void 0) - ], LanguageState.prototype, "checkLanguage", null); - `; - - const output = tags.oneLine` - let LanguageState = /*@__PURE__*/ (() => { - class LanguageState { - } - - __decorate([ - Action(CheckLanguage), - __metadata("design:type", Function), - __metadata("design:paramtypes", [Object]), - __metadata("design:returntype", void 0) - ], LanguageState.prototype, "checkLanguage", null); - return LanguageState; - })(); - `; - - const boOutput = buildOptimizer({ content: input, isSideEffectFree: true }); - expect(tags.oneLine`${boOutput.content}`).toEqual(output); - expect(boOutput.emitSkipped).toEqual(false); - }); - - it('should not add pure comments to tslib helpers with $ and number suffix', () => { - const input = tags.stripIndent` - class LanguageState { - } - - LanguageState.ctorParameters = () => [ - { type: TranslateService }, - { type: undefined, decorators: [{ type: Inject, args: [LANGUAGE_CONFIG,] }] } - ]; - - __decorate$1([ - Action(CheckLanguage), - __metadata("design:type", Function), - __metadata("design:paramtypes", [Object]), - __metadata("design:returntype", void 0) - ], LanguageState.prototype, "checkLanguage", null); - `; - - const output = tags.oneLine` - let LanguageState = /*@__PURE__*/ (() => { - class LanguageState { - } - - __decorate$1([ - Action(CheckLanguage), - __metadata("design:type", Function), - __metadata("design:paramtypes", [Object]), - __metadata("design:returntype", void 0) - ], LanguageState.prototype, "checkLanguage", null); - return LanguageState; - })(); - `; - - const boOutput = buildOptimizer({ content: input, isSideEffectFree: true }); - expect(tags.oneLine`${boOutput.content}`).toEqual(output); - expect(boOutput.emitSkipped).toEqual(false); - }); - - it('should not wrap classes which had all static properties dropped in IIFE', () => { - const classDeclaration = tags.oneLine` - import { Injectable } from '@angular/core'; - - class Platform { - constructor(_doc) { - } - init() { - } - } - `; - const input = tags.oneLine` - ${classDeclaration} - - Platform.decorators = [ - { type: Injectable } - ]; - - /** @nocollapse */ - Platform.ctorParameters = () => [ - { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT] }] } - ]; - `; - - const boOutput = buildOptimizer({ content: input, isSideEffectFree: true }); - expect(tags.oneLine`${boOutput.content}`).toEqual(classDeclaration); - expect(boOutput.emitSkipped).toEqual(false); - }); - }); - - - describe('resilience', () => { - it('doesn\'t process files with invalid syntax by default', () => { - const input = tags.oneLine` - ))))invalid syntax - ${clazz} - Clazz.decorators = [ { type: Injectable } ]; - `; - - const boOutput = buildOptimizer({ content: input }); - expect(boOutput.content).toBeFalsy(); - expect(boOutput.emitSkipped).toEqual(true); - }); - - it('throws on files with invalid syntax in strict mode', () => { - const input = tags.oneLine` - ))))invalid syntax - ${clazz} - Clazz.decorators = [ { type: Injectable } ]; - `; - - expect(() => buildOptimizer({ content: input, strict: true })).toThrow(); - }); - - // TODO: re-enable this test when updating to TypeScript >2.9.1. - // The `prefix-classes` tests will also need to be adjusted. - // See https://github.com/angular/devkit/pull/998#issuecomment-393867606 for more info. - xit(`doesn't exceed call stack size when type checking very big classes`, () => { - // BigClass with a thousand methods. - // Clazz is included with ctorParameters to trigger transforms with type checking. - const input = ` - var BigClass = /** @class */ (function () { - function BigClass() { - } - ${Array.from(new Array(1000)).map((_v, i) => - `BigClass.prototype.method${i} = function () { return this.myVar; };`, - ).join('\n')} - return BigClass; - }()); - ${clazz} - Clazz.ctorParameters = function () { return []; }; - `; - - let boOutput: TransformJavascriptOutput; - expect(() => { - boOutput = buildOptimizer({ content: input }); - expect(boOutput.emitSkipped).toEqual(false); - }).not.toThrow(); - }); - }); - - describe('whitelisted modules', () => { - // This statement is considered pure by getPrefixFunctionsTransformer on whitelisted modules. - const input = 'console.log(42);'; - const output = '/*@__PURE__*/ console.log(42);'; - - it('should process whitelisted modules', () => { - const inputFilePath = '/node_modules/@angular/core/@angular/core.es5.js'; - const boOutput = buildOptimizer({ content: input, inputFilePath }); - expect(boOutput.content).toContain(output); - expect(boOutput.emitSkipped).toEqual(false); - }); - - it('should not process non-whitelisted modules', () => { - const inputFilePath = '/node_modules/other-package/core.es5.js'; - const boOutput = buildOptimizer({ content: input, inputFilePath }); - expect(boOutput.emitSkipped).toEqual(true); - }); - - it('should not process non-whitelisted umd modules', () => { - const inputFilePath = '/node_modules/other_lib/index.js'; - const boOutput = buildOptimizer({ content: input, inputFilePath }); - expect(boOutput.emitSkipped).toEqual(true); - }); - }); - - describe('sourcemaps', () => { - const transformableInput = tags.oneLine` - ${imports} - ${clazz} - ${decorators} - `; - - it('doesn\'t produce sourcemaps by default', () => { - expect(buildOptimizer({ content: transformableInput }).sourceMap).toBeFalsy(); - }); - - it('produces sourcemaps', () => { - expect(buildOptimizer( - { content: transformableInput, emitSourceMap: true }, - ).sourceMap).toBeTruthy(); - }); - - // TODO: re-enable this test, it was temporarily disabled as part of - // https://github.com/angular/devkit/pull/842 - xit('doesn\'t produce sourcemaps when emitting was skipped', () => { - const ignoredInput = tags.oneLine` - var Clazz = (function () { function Clazz() { } return Clazz; }()); - `; - const invalidInput = tags.oneLine` - ))))invalid syntax - ${clazz} - Clazz.decorators = [ { type: Injectable } ]; - `; - - const ignoredOutput = buildOptimizer({ content: ignoredInput, emitSourceMap: true }); - expect(ignoredOutput.emitSkipped).toBeTruthy(); - expect(ignoredOutput.sourceMap).toBeFalsy(); - - const invalidOutput = buildOptimizer({ content: invalidInput, emitSourceMap: true }); - expect(invalidOutput.emitSkipped).toBeTruthy(); - expect(invalidOutput.sourceMap).toBeFalsy(); - }); - - it('emits sources content', () => { - const sourceMap = buildOptimizer( - { content: transformableInput, emitSourceMap: true }, - ).sourceMap as RawSourceMap; - const sourceContent = sourceMap.sourcesContent as string[]; - expect(sourceContent[0]).toEqual(transformableInput); - }); - - it('uses empty strings if inputFilePath and outputFilePath is not provided', () => { - const { content, sourceMap } = buildOptimizer( - { content: transformableInput, emitSourceMap: true }); - - if (!sourceMap) { - throw new Error('sourceMap was not generated.'); - } - expect(sourceMap.file).toEqual(''); - expect(sourceMap.sources[0]).toEqual(''); - expect(content).not.toContain(`sourceMappingURL`); - }); - - it('uses inputFilePath and outputFilePath if provided', () => { - const inputFilePath = '/path/to/file.js'; - const outputFilePath = '/path/to/file.bo.js'; - const { content, sourceMap } = buildOptimizer({ - content: transformableInput, - emitSourceMap: true, - inputFilePath, - outputFilePath, - }); - - if (!sourceMap) { - throw new Error('sourceMap was not generated.'); - } - expect(sourceMap.file).toEqual(outputFilePath); - expect(sourceMap.sources[0]).toEqual(inputFilePath); - expect(content).toContain(`sourceMappingURL=${outputFilePath}.map`); - }); - }); - -}); diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/cli.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/cli.ts deleted file mode 100644 index f09f53defddc..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/cli.ts +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env node -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { writeFileSync } from 'fs'; -import { join } from 'path'; -import { buildOptimizer } from './build-optimizer'; - -// tslint:disable: no-console -if (process.argv.length < 3 || process.argv.length > 4) { - throw new Error(` - build-optimizer should be called with either one or two arguments: - - build-optimizer input.js - build-optimizer input.js output.js - `); -} - -const currentDir = process.cwd(); - -const inputFile = process.argv[2]; -const tsOrJsRegExp = /\.(j|t)s$/; - -if (!inputFile.match(tsOrJsRegExp)) { - throw new Error(`Input file must be .js or .ts.`); -} - -// Use provided output file, or add the .bo suffix before the extension. -const outputFile = process.argv[3] || inputFile.replace(tsOrJsRegExp, subStr => `.bo${subStr}`); - -const boOutput = buildOptimizer({ - inputFilePath: join(currentDir, inputFile), - outputFilePath: join(currentDir, outputFile), - emitSourceMap: true, -}); - -if (boOutput.emitSkipped) { - console.log('Nothing to emit.'); -} else { - writeFileSync(join(currentDir, outputFile), boOutput.content); - writeFileSync(join(currentDir, `${outputFile}.map`), JSON.stringify(boOutput.sourceMap)); - console.log('Emitted:'); - console.log(` ${outputFile}`); - console.log(` ${outputFile}.map`); -} diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/rollup-plugin.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/rollup-plugin.ts deleted file mode 100644 index cb661c66abbe..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/rollup-plugin.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -/** - * @fileoverview This adapts the buildOptimizer to run over each file as it is - * processed by Rollup. We must do this since buildOptimizer expects to see the - * ESModules in the input sources, and therefore cannot run on the rollup output - */ - -import * as path from 'path'; -import { RawSourceMap } from 'source-map'; -import { buildOptimizer } from './build-optimizer'; - -const DEBUG = false; - -export interface Options { - sideEffectFreeModules?: string[]; - angularCoreModules?: string[]; -} - -export default function optimizer(options: Options) { - // Normalize paths for comparison. - if (options.sideEffectFreeModules) { - options.sideEffectFreeModules = options.sideEffectFreeModules.map(p => p.replace(/\\/g, '/')); - } - - return { - name: 'build-optimizer', - transform: (content: string, id: string): { code: string; map: RawSourceMap } | null => { - const normalizedId = id.replace(/\\/g, '/'); - const isSideEffectFree = - options.sideEffectFreeModules && - options.sideEffectFreeModules.some(m => normalizedId.indexOf(m) >= 0); - const isAngularCoreFile = - options.angularCoreModules && - options.angularCoreModules.some(m => normalizedId.indexOf(m) >= 0); - const { content: code, sourceMap: map } = buildOptimizer({ - content, - inputFilePath: id, - emitSourceMap: true, - isSideEffectFree, - isAngularCoreFile, - }); - if (!code) { - if (DEBUG) { - // tslint:disable-next-line: no-console - console.error( - 'no transforms produced by buildOptimizer for ' + path.relative(process.cwd(), id), - ); - } - - return null; - } - if (!map) { - throw new Error('no sourcemap produced by buildOptimizer'); - } - - return { code, map }; - }, - }; -} diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-loader.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-loader.ts deleted file mode 100644 index 01d4acbb0f3d..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-loader.ts +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { RawSourceMap, SourceMapConsumer, SourceMapGenerator } from 'source-map'; -import * as webpack from 'webpack'; // tslint:disable-line:no-implicit-dependencies - -const loaderUtils = require('loader-utils'); - -import { buildOptimizer } from './build-optimizer'; - -interface BuildOptimizerLoaderOptions { - sourceMap: boolean; -} - -export const buildOptimizerLoaderPath = __filename; - -const alwaysProcess = (path: string) => - // Always process TS files. - path.endsWith('.ts') || - path.endsWith('.tsx') || - // Always process factory files. - path.endsWith('.ngfactory.js') || - path.endsWith('.ngstyle.js'); - -export default function buildOptimizerLoader( - this: webpack.loader.LoaderContext, - content: string, - previousSourceMap: RawSourceMap, -) { - this.cacheable(); - const callback = this.async(); - if (!callback) { - throw new Error('Async loader support is required.'); - } - - const skipBuildOptimizer = - this._module && this._module.factoryMeta && this._module.factoryMeta.skipBuildOptimizer; - - if (!alwaysProcess(this.resourcePath) && skipBuildOptimizer) { - // Skip loading processing this file with Build Optimizer if we determined in - // BuildOptimizerWebpackPlugin that we shouldn't. - - // Webpack typings for previousSourceMap are wrong, they are JSON objects and not strings. - // tslint:disable-next-line:no-any - this.callback(null, content, previousSourceMap as any); - - return; - } - - const options: BuildOptimizerLoaderOptions = loaderUtils.getOptions(this) || {}; - - // Make up names of the intermediate files so we can chain the sourcemaps. - const inputFilePath = this.resourcePath + '.pre-build-optimizer.js'; - const outputFilePath = this.resourcePath + '.post-build-optimizer.js'; - - const boOutput = buildOptimizer({ - content, - originalFilePath: this.resourcePath, - inputFilePath, - outputFilePath, - emitSourceMap: options.sourceMap, - isSideEffectFree: - this._module && this._module.factoryMeta && this._module.factoryMeta.sideEffectFree, - }); - - if (boOutput.emitSkipped || boOutput.content === null) { - // tslint:disable-next-line:no-any - this.callback(null, content, previousSourceMap as any); - - return; - } - - const intermediateSourceMap = boOutput.sourceMap; - let newContent = boOutput.content; - - let newSourceMap; - - if (options.sourceMap && intermediateSourceMap) { - // Webpack doesn't need sourceMappingURL since we pass them on explicitely. - newContent = newContent.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''); - - if (previousSourceMap) { - // If there's a previous sourcemap, we have to chain them. - // See https://github.com/mozilla/source-map/issues/216#issuecomment-150839869 for a simple - // source map chaining example. - // Use http://sokra.github.io/source-map-visualization/ to validate sourcemaps make sense. - - // Force the previous sourcemap to use the filename we made up for it. - // In order for source maps to be chained, the consumed source map `file` needs to be in the - // consumers source map `sources` array. - previousSourceMap.file = inputFilePath; - - // Chain the sourcemaps. - SourceMapConsumer.with(intermediateSourceMap, null, intermediate => { - return SourceMapConsumer.with(previousSourceMap, null, previous => { - const generator = SourceMapGenerator.fromSourceMap(intermediate); - generator.applySourceMap(previous); - - return generator.toJSON(); - }); - // tslint:disable-next-line: no-any - }).then(map => callback(null, newContent, map as any), error => callback(error)); - - return; - } else { - // Otherwise just return our generated sourcemap. - newSourceMap = intermediateSourceMap; - } - } - - // Webpack typings for previousSourceMap are wrong, they are JSON objects and not strings. - // tslint:disable-next-line:no-any - callback(null, newContent, newSourceMap as any); -} diff --git a/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-plugin.ts b/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-plugin.ts deleted file mode 100644 index 22437803d97f..000000000000 --- a/packages/angular_devkit/build_optimizer/src/build-optimizer/webpack-plugin.ts +++ /dev/null @@ -1,33 +0,0 @@ - -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Compiler } from 'webpack'; // tslint:disable-line:no-implicit-dependencies - -export class BuildOptimizerWebpackPlugin { - apply(compiler: Compiler) { - compiler.hooks.normalModuleFactory.tap('BuildOptimizerWebpackPlugin', nmf => { - nmf.hooks.module.tap('BuildOptimizerWebpackPlugin', (module, data) => { - const resolveData = data.resourceResolveData; - if (resolveData && resolveData.descriptionFileData) { - // Only TS packages should use Build Optimizer. - const typings = resolveData.descriptionFileData.typings; - // Notes: - // - a TS package might not have defined typings but still use .d.ts files next to their - // .js files. We don't cover that case because the Angular Package Format (APF) calls for - // using the Typings field and Build Optimizer is geared towards APF. Maybe we could - // provide configuration options to the plugin to cover that case if there's demand. - // - a JS-only package that also happens to provides typings will also be flagged by this - // check. Not sure there's a good way to skip those. - module.factoryMeta.skipBuildOptimizer = !typings; - } - - return module; - }); - }); - } -} diff --git a/packages/angular_devkit/build_optimizer/src/helpers/ast-utils.ts b/packages/angular_devkit/build_optimizer/src/helpers/ast-utils.ts deleted file mode 100644 index d035dda72612..000000000000 --- a/packages/angular_devkit/build_optimizer/src/helpers/ast-utils.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as tslib from 'tslib'; -import * as ts from 'typescript'; - -const pureFunctionComment = '@__PURE__'; - -// We include only exports that start with '__' because tslib helpers -// all start with a suffix of two underscores. -const tslibHelpers = new Set(Object.keys(tslib).filter(h => h.startsWith('__'))); - -// Find all nodes from the AST in the subtree of node of SyntaxKind kind. -export function collectDeepNodes(node: ts.Node, kind: ts.SyntaxKind): T[] { - const nodes: T[] = []; - const helper = (child: ts.Node) => { - if (child.kind === kind) { - nodes.push(child as T); - } - ts.forEachChild(child, helper); - }; - ts.forEachChild(node, helper); - - return nodes; -} - -export function addPureComment(node: T): T { - return ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - pureFunctionComment, - false, - ); -} - -export function hasPureComment(node: ts.Node): boolean { - if (!node) { - return false; - } - - const leadingComment = ts.getSyntheticLeadingComments(node); - - return !!leadingComment && leadingComment.some(comment => comment.text === pureFunctionComment); -} - -export function isHelperName(name: string): boolean { - return tslibHelpers.has(name); -} - -/** - * In FESM's when not using `importHelpers` there might be multiple in the same file. - @example - ``` - var __decorate$1 = ''; - var __decorate$2 = ''; - ``` - * @returns Helper name without the '$' and number suffix or `undefined` if it's not a helper. - */ -export function getCleanHelperName(name: string): string | undefined { - const parts = name.split('$'); - const cleanName = parts[0]; - - if (parts.length > 2 || (parts.length === 2 && isNaN(+parts[1]))) { - return undefined; - } - - return isHelperName(cleanName) ? cleanName : undefined; -} diff --git a/packages/angular_devkit/build_optimizer/src/helpers/transform-javascript.ts b/packages/angular_devkit/build_optimizer/src/helpers/transform-javascript.ts deleted file mode 100644 index efd568e70f21..000000000000 --- a/packages/angular_devkit/build_optimizer/src/helpers/transform-javascript.ts +++ /dev/null @@ -1,217 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { RawSourceMap } from 'source-map'; -import * as ts from 'typescript'; - - -export interface TransformJavascriptOptions { - content: string; - inputFilePath?: string; - outputFilePath?: string; - emitSourceMap?: boolean; - strict?: boolean; - typeCheck?: boolean; - getTransforms: Array<(program?: ts.Program) => ts.TransformerFactory>; -} - -export interface TransformJavascriptOutput { - content: string | null; - sourceMap: RawSourceMap | null; - emitSkipped: boolean; -} - -interface DiagnosticSourceFile extends ts.SourceFile { - readonly parseDiagnostics?: ReadonlyArray; -} - -function validateDiagnostics(diagnostics: ReadonlyArray, strict?: boolean): boolean { - // Print error diagnostics. - - const hasError = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error); - if (hasError) { - // Throw only if we're in strict mode, otherwise return original content. - if (strict) { - const errorMessages = ts.formatDiagnostics(diagnostics, { - getCurrentDirectory: () => ts.sys.getCurrentDirectory(), - getNewLine: () => ts.sys.newLine, - getCanonicalFileName: (f: string) => f, - }); - - throw new Error(` - TS failed with the following error messages: - - ${errorMessages} - `); - } else { - return false; - } - } - - return true; -} - -export function transformJavascript( - options: TransformJavascriptOptions, -): TransformJavascriptOutput { - - const { - content, - getTransforms, - emitSourceMap, - inputFilePath, - outputFilePath, - strict, - } = options; - - // Bail if there's no transform to do. - if (getTransforms.length === 0) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - const allowFastPath = options.typeCheck === false && !emitSourceMap; - const outputs = new Map(); - const tempFilename = 'bo-default-file.js'; - const tempSourceFile = ts.createSourceFile( - tempFilename, - content, - ts.ScriptTarget.Latest, - allowFastPath, - ); - const parseDiagnostics = (tempSourceFile as DiagnosticSourceFile).parseDiagnostics; - - const tsOptions: ts.CompilerOptions = { - // We target latest so that there is no downleveling. - target: ts.ScriptTarget.Latest, - isolatedModules: true, - suppressOutputPathCheck: true, - allowNonTsExtensions: true, - noLib: true, - noResolve: true, - sourceMap: emitSourceMap, - inlineSources: emitSourceMap, - inlineSourceMap: false, - }; - - if (allowFastPath && parseDiagnostics) { - if (!validateDiagnostics(parseDiagnostics, strict)) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - const transforms = getTransforms.map((getTf) => getTf(undefined)); - - const result = ts.transform(tempSourceFile, transforms, tsOptions); - if (result.transformed.length === 0 || result.transformed[0] === tempSourceFile) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - const printer = ts.createPrinter( - undefined, - { - onEmitNode: result.emitNodeWithNotification, - substituteNode: result.substituteNode, - }, - ); - - const output = printer.printFile(result.transformed[0]); - - result.dispose(); - - return { - content: output, - sourceMap: null, - emitSkipped: false, - }; - } - - const host: ts.CompilerHost = { - getSourceFile: (fileName) => { - if (fileName !== tempFilename) { - throw new Error(`File ${fileName} does not have a sourceFile.`); - } - - return tempSourceFile; - }, - getDefaultLibFileName: () => 'lib.d.ts', - getCurrentDirectory: () => '', - getDirectories: () => [], - getCanonicalFileName: (fileName) => fileName, - useCaseSensitiveFileNames: () => true, - getNewLine: () => '\n', - fileExists: (fileName) => fileName === tempFilename, - readFile: (_fileName) => '', - writeFile: (fileName, text) => outputs.set(fileName, text), - }; - - const program = ts.createProgram([tempFilename], tsOptions, host); - - const diagnostics = program.getSyntacticDiagnostics(tempSourceFile); - if (!validateDiagnostics(diagnostics, strict)) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - // We need the checker inside transforms. - const transforms = getTransforms.map((getTf) => getTf(program)); - - program.emit(undefined, undefined, undefined, undefined, { before: transforms, after: [] }); - - let transformedContent = outputs.get(tempFilename); - - if (!transformedContent) { - return { - content: null, - sourceMap: null, - emitSkipped: true, - }; - } - - let sourceMap: RawSourceMap | null = null; - const tsSourceMap = outputs.get(`${tempFilename}.map`); - - if (emitSourceMap && tsSourceMap) { - const urlRegExp = /^\/\/# sourceMappingURL=[^\r\n]*/gm; - sourceMap = JSON.parse(tsSourceMap) as RawSourceMap; - // Fix sourcemaps file references. - if (outputFilePath) { - sourceMap.file = outputFilePath; - transformedContent = transformedContent.replace(urlRegExp, - `//# sourceMappingURL=${sourceMap.file}.map\n`); - if (inputFilePath) { - sourceMap.sources = [inputFilePath]; - } else { - sourceMap.sources = ['']; - } - } else { - // TODO: figure out if we should inline sources here. - transformedContent = transformedContent.replace(urlRegExp, ''); - sourceMap.file = ''; - sourceMap.sources = ['']; - } - } - - return { - content: transformedContent, - sourceMap, - emitSkipped: false, - }; -} diff --git a/packages/angular_devkit/build_optimizer/src/index.ts b/packages/angular_devkit/build_optimizer/src/index.ts deleted file mode 100644 index 96b201de9f66..000000000000 --- a/packages/angular_devkit/build_optimizer/src/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export { - default as buildOptimizerLoader, - buildOptimizerLoaderPath, -} from './build-optimizer/webpack-loader'; -export { BuildOptimizerWebpackPlugin } from './build-optimizer/webpack-plugin'; -export { buildOptimizer } from './build-optimizer/build-optimizer'; - -export { transformJavascript } from './helpers/transform-javascript'; - -export { getFoldFileTransformer } from './transforms/class-fold'; -export { getImportTslibTransformer } from './transforms/import-tslib'; -export { getPrefixClassesTransformer } from './transforms/prefix-classes'; -export { getPrefixFunctionsTransformer } from './transforms/prefix-functions'; -export { - getScrubFileTransformer, - getScrubFileTransformerForCore, -} from './transforms/scrub-file'; -export { getWrapEnumsTransformer } from './transforms/wrap-enums'; diff --git a/packages/angular_devkit/build_optimizer/src/transforms/class-fold.ts b/packages/angular_devkit/build_optimizer/src/transforms/class-fold.ts deleted file mode 100644 index 634f195c92df..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/class-fold.ts +++ /dev/null @@ -1,232 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { addPureComment } from '../helpers/ast-utils'; - -interface ClassData { - name: string; - declaration: ts.VariableDeclaration | ts.ClassDeclaration; - function?: ts.FunctionExpression; - statements: StatementData[]; -} - -interface StatementData { - expressionStatement: ts.ExpressionStatement; - hostClass: ClassData; -} - -/** @deprecated Since version 8 */ -export function getFoldFileTransformer(program: ts.Program): ts.TransformerFactory { - const checker = program.getTypeChecker(); - - return (context: ts.TransformationContext): ts.Transformer => { - - const transformer: ts.Transformer = (sf: ts.SourceFile) => { - - const statementsToRemove: ts.ExpressionStatement[] = []; - const classesWithoutStatements = findClassDeclarations(sf); - let classes = findClassesWithStaticPropertyAssignments(sf, checker, classesWithoutStatements); - - const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult => { - if (classes.length === 0 && statementsToRemove.length === 0) { - // There are no more statements to fold. - return ts.visitEachChild(node, visitor, context); - } - - // Check if node is a statement to be dropped. - const stmtIdx = statementsToRemove.indexOf(node as ts.ExpressionStatement); - if (stmtIdx != -1) { - statementsToRemove.splice(stmtIdx, 1); - - return undefined; - } - - // Check if node is a ES5 class to add statements to. - let clazz = classes.find((cl) => cl.function === node); - if (clazz) { - const functionExpression = node as ts.FunctionExpression; - - // Create a new body with all the original statements, plus new ones, - // plus return statement. - const newBody = ts.createBlock([ - ...functionExpression.body.statements.slice(0, -1), - ...clazz.statements.map(st => st.expressionStatement), - ...functionExpression.body.statements.slice(-1), - ]); - - const newNode = ts.createFunctionExpression( - functionExpression.modifiers, - functionExpression.asteriskToken, - functionExpression.name, - functionExpression.typeParameters, - functionExpression.parameters, - functionExpression.type, - newBody, - ); - - // Update remaining classes and statements. - statementsToRemove.push(...clazz.statements.map(st => st.expressionStatement)); - classes = classes.filter(cl => cl != clazz); - - // Replace node with modified one. - return newNode; - } - - // Check if node is a ES2015 class to replace with a pure IIFE. - clazz = classes.find((cl) => !cl.function && cl.declaration === node); - if (clazz) { - const classStatement = clazz.declaration as ts.ClassDeclaration; - const innerReturn = ts.createReturn(ts.createIdentifier(clazz.name)); - - const pureIife = addPureComment( - ts.createImmediatelyInvokedFunctionExpression([ - classStatement, - ...clazz.statements.map(st => st.expressionStatement), - innerReturn, - ])); - - // Move the original class modifiers to the var statement. - const newNode = ts.createVariableStatement( - clazz.declaration.modifiers, - ts.createVariableDeclarationList([ - ts.createVariableDeclaration(clazz.name, undefined, pureIife), - ], ts.NodeFlags.Const), - ); - clazz.declaration.modifiers = undefined; - - // Update remaining classes and statements. - statementsToRemove.push(...clazz.statements.map(st => st.expressionStatement)); - classes = classes.filter(cl => cl != clazz); - - return newNode; - } - - // Otherwise return node as is. - return ts.visitEachChild(node, visitor, context); - }; - - return ts.visitNode(sf, visitor); - }; - - return transformer; - }; -} - -function findClassDeclarations(node: ts.Node): ClassData[] { - const classes: ClassData[] = []; - // Find all class declarations, build a ClassData for each. - ts.forEachChild(node, (child) => { - // Check if it is a named class declaration first. - // Technically it doesn't need a name in TS if it's the default export, but when downleveled - // it will be have a name (e.g. `default_1`). - if (ts.isClassDeclaration(child) && child.name) { - classes.push({ - name: child.name.text, - declaration: child, - statements: [], - }); - - return; - } - - if (child.kind !== ts.SyntaxKind.VariableStatement) { - return; - } - const varStmt = child as ts.VariableStatement; - if (varStmt.declarationList.declarations.length > 1) { - return; - } - const varDecl = varStmt.declarationList.declarations[0]; - if (varDecl.name.kind !== ts.SyntaxKind.Identifier) { - return; - } - const name = (varDecl.name as ts.Identifier).text; - const expr = varDecl.initializer; - if (!expr || expr.kind !== ts.SyntaxKind.ParenthesizedExpression) { - return; - } - if ((expr as ts.ParenthesizedExpression).expression.kind !== ts.SyntaxKind.CallExpression) { - return; - } - const callExpr = (expr as ts.ParenthesizedExpression).expression as ts.CallExpression; - if (callExpr.expression.kind !== ts.SyntaxKind.FunctionExpression) { - return; - } - const fn = callExpr.expression as ts.FunctionExpression; - if (fn.body.statements.length < 2) { - return; - } - if (fn.body.statements[0].kind !== ts.SyntaxKind.FunctionDeclaration) { - return; - } - const innerFn = fn.body.statements[0] as ts.FunctionDeclaration; - if (fn.body.statements[fn.body.statements.length - 1].kind !== ts.SyntaxKind.ReturnStatement) { - return; - } - if (!innerFn.name || innerFn.name.kind !== ts.SyntaxKind.Identifier) { - return; - } - if ((innerFn.name as ts.Identifier).text !== name) { - return; - } - classes.push({ - name, - declaration: varDecl, - function: fn, - statements: [], - }); - }); - - return classes; -} - -function findClassesWithStaticPropertyAssignments( - node: ts.Node, - checker: ts.TypeChecker, - classes: ClassData[], -) { - // Find each assignment outside of the declaration. - ts.forEachChild(node, (child) => { - if (child.kind !== ts.SyntaxKind.ExpressionStatement) { - return; - } - const expressionStatement = child as ts.ExpressionStatement; - if (expressionStatement.expression.kind !== ts.SyntaxKind.BinaryExpression) { - return; - } - const binEx = expressionStatement.expression as ts.BinaryExpression; - if (binEx.left.kind !== ts.SyntaxKind.PropertyAccessExpression) { - return; - } - const propAccess = binEx.left as ts.PropertyAccessExpression; - if (propAccess.expression.kind !== ts.SyntaxKind.Identifier) { - return; - } - - const symbol = checker.getSymbolAtLocation(propAccess.expression); - if (!symbol) { - return; - } - - const decls = symbol.declarations; - if (decls == undefined || decls.length === 0) { - return; - } - - const hostClass = classes.find((clazz => decls.includes(clazz.declaration))); - if (!hostClass) { - return; - } - const statement: StatementData = { expressionStatement, hostClass }; - - hostClass.statements.push(statement); - }); - - // Only return classes that have static property assignments. - return classes.filter(cl => cl.statements.length != 0); -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/class-fold_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/class-fold_spec.ts deleted file mode 100644 index 1b50bbe38691..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/class-fold_spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { getFoldFileTransformer } from './class-fold'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getFoldFileTransformer], typeCheck: true }).content; - -describe('class-fold', () => { - describe('es5', () => { - it('folds static properties into class', () => { - const staticProperty = 'Clazz.prop = 1;'; - const input = tags.stripIndent` - var Clazz = (function () { function Clazz() { } return Clazz; }()); - ${staticProperty} - `; - const output = tags.stripIndent` - var Clazz = (function () { function Clazz() { } - ${staticProperty} return Clazz; }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('folds multiple static properties into class', () => { - const staticProperty = 'Clazz.prop = 1;'; - const anotherStaticProperty = 'Clazz.anotherProp = 2;'; - const input = tags.stripIndent` - var Clazz = (function () { function Clazz() { } return Clazz; }()); - ${staticProperty} - ${anotherStaticProperty} - `; - const output = tags.stripIndent` - var Clazz = (function () { function Clazz() { } - ${staticProperty} ${anotherStaticProperty} return Clazz; }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('es2015', () => { - it('folds static properties in IIFE', () => { - const input = tags.stripIndent` - export class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - `; - const output = tags.stripIndent` - export const TemplateRef = /*@__PURE__*/ function () { - class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - return TemplateRef; - }(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('folds multiple static properties into class', () => { - const input = tags.stripIndent` - export class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - TemplateRef.somethingElse = true; - `; - const output = tags.stripIndent` - export const TemplateRef = /*@__PURE__*/ function () { - class TemplateRef { - } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - TemplateRef.somethingElse = true; - return TemplateRef; - }(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it(`doesn't wrap classes without static properties in IIFE`, () => { - const input = tags.stripIndent` - export class TemplateRef { } - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`); - }); - }); -}); diff --git a/packages/angular_devkit/build_optimizer/src/transforms/import-tslib.ts b/packages/angular_devkit/build_optimizer/src/transforms/import-tslib.ts deleted file mode 100644 index 46905f26a6ec..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/import-tslib.ts +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { getCleanHelperName } from '../helpers/ast-utils'; - -/** - * @deprecated From 0.900.0 - */ -export function getImportTslibTransformer(): ts.TransformerFactory { - return (context: ts.TransformationContext): ts.Transformer => { - - const transformer: ts.Transformer = (sf: ts.SourceFile) => { - - const tslibImports: (ts.VariableStatement | ts.ImportDeclaration)[] = []; - - // Check if module has CJS exports. If so, use 'require()' instead of 'import'. - const useRequire = /exports.\S+\s*=/.test(sf.getText()); - - const visitor: ts.Visitor = (node: ts.Node): ts.Node | undefined => { - - // Check if node is a TS helper declaration and replace with import if yes - if (ts.isVariableStatement(node)) { - const declarations = node.declarationList.declarations; - - if (declarations.length === 1 && ts.isIdentifier(declarations[0].name)) { - const name = declarations[0].name.text; - const helperName = getCleanHelperName(name); - - if (helperName) { - // TODO: maybe add a few more checks, like checking the first part of the assignment. - const alias = name === helperName ? undefined : name; - const tslibImport = createTslibImport(helperName, alias, useRequire); - tslibImports.push(tslibImport); - - return undefined; - } - } - } - - return ts.visitEachChild(node, visitor, context); - }; - - const sfUpdated = ts.visitEachChild(sf, visitor, context); - - // Add tslib imports before any other statement - return tslibImports.length > 0 - ? ts.updateSourceFileNode(sfUpdated, [ - ...tslibImports, - ...sfUpdated.statements, - ]) - : sfUpdated; - }; - - return transformer; - }; -} - -function createTslibImport( - name: string, - aliases?: string, - useRequire = false, -): ts.VariableStatement | ts.ImportDeclaration { - if (useRequire) { - // Use `var __helper = /*@__PURE__*/ require("tslib").__helper`. - const requireCall = ts.createCall(ts.createIdentifier('require'), undefined, - [ts.createLiteral('tslib')]); - const pureRequireCall = ts.addSyntheticLeadingComment( - requireCall, ts.SyntaxKind.MultiLineCommentTrivia, '@__PURE__', false); - const helperAccess = ts.createPropertyAccess(pureRequireCall, name); - const variableDeclaration = ts.createVariableDeclaration(aliases || name, undefined, helperAccess); - const variableStatement = ts.createVariableStatement(undefined, [variableDeclaration]); - - return variableStatement; - } else { - // Use `import { __helper } from "tslib"`. - const namedImports = ts.createNamedImports([ - ts.createImportSpecifier(aliases ? ts.createIdentifier(name) : undefined, ts.createIdentifier(aliases || name)), - ]); - const importClause = ts.createImportClause(undefined, namedImports); - const newNode = ts.createImportDeclaration(undefined, undefined, importClause, - ts.createLiteral('tslib')); - - return newNode; - } -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/import-tslib_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/import-tslib_spec.ts deleted file mode 100644 index 0cc7d167bc6a..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/import-tslib_spec.ts +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { getImportTslibTransformer } from './import-tslib'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getImportTslibTransformer] }).content; - -describe('import-tslib', () => { - it('replaces __extends', () => { - const input = tags.stripIndent` - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - `; - const output = tags.stripIndent` - import { __extends } from "tslib"; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces wrapped __extends', () => { - const input = tags.stripIndent` - export default function appGlobal() { - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - } - `; - const output = tags.stripIndent` - import { __extends } from "tslib"; - export default function appGlobal() { } - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces __decorate', () => { - // tslint:disable:max-line-length - const input = tags.stripIndent` - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - `; - const output = tags.stripIndent` - import { __decorate } from "tslib"; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces multiple __decorate', () => { - // tslint:disable:max-line-length - const input = tags.stripIndent` - var __decorate$1 = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var __decorate$2 = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - `; - const output = tags.stripIndent` - import { __decorate as __decorate$1 } from "tslib"; - import { __decorate as __decorate$2 } from "tslib"; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces multiple __decorate in CJS modules', () => { - // tslint:disable:max-line-length - const input = tags.stripIndent` - var __decorate$1 = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var __decorate$2 = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - exports.meaning = 42; - `; - const output = tags.stripIndent` - var __decorate$1 = /*@__PURE__*/ require("tslib").__decorate; - var __decorate$2 = /*@__PURE__*/ require("tslib").__decorate; - - exports.meaning = 42; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces __metadata', () => { - const input = tags.stripIndent` - var __metadata = (this && this.__metadata) || function (k, v) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); - }; - `; - const output = tags.stripIndent` - import { __metadata } from "tslib"; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces __param', () => { - const input = tags.stripIndent` - var __param = (this && this.__param) || function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - `; - - const output = tags.stripIndent` - import { __param } from "tslib"; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('replaces uses "require" instead of "import" on CJS modules', () => { - const input = tags.stripIndent` - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - exports.meaning = 42; - `; - const output = tags.stripIndent` - var __extends = /*@__PURE__*/ require("tslib").__extends; - exports.meaning = 42; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - -}); diff --git a/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes.ts b/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes.ts deleted file mode 100644 index 8637c66baa71..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes.ts +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { addPureComment } from '../helpers/ast-utils'; - -/** - * @deprecated From 0.9.0 - */ -export function testPrefixClasses(content: string) { - const exportVarSetter = /(?:export )?(?:var|const)\s+(?:\S+)\s*=\s*/; - const multiLineComment = /\s*(?:\/\*[\s\S]*?\*\/)?\s*/; - const newLine = /\s*\r?\n\s*/; - - const regexes = [ - [ - /^/, - exportVarSetter, multiLineComment, - /\(/, multiLineComment, - /\s*function \(\) {/, newLine, - multiLineComment, - /function (?:\S+)\([^\)]*\) \{/, newLine, - ], - [ - /^/, - exportVarSetter, multiLineComment, - /\(/, multiLineComment, - /\s*function \(_super\) {/, newLine, - /\S*\.?__extends\(\S+, _super\);/, - ], - ].map(arr => new RegExp(arr.map(x => x.source).join(''), 'm')); - - return regexes.some((regex) => regex.test(content)); -} - -const superParameterName = '_super'; -const extendsHelperName = '__extends'; - -export function getPrefixClassesTransformer(): ts.TransformerFactory { - return (context: ts.TransformationContext): ts.Transformer => { - const transformer: ts.Transformer = (sf: ts.SourceFile) => { - const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult => { - - // Add pure comment to downleveled classes. - if (ts.isVariableStatement(node) && isDownleveledClass(node)) { - const varDecl = node.declarationList.declarations[0]; - const varInitializer = varDecl.initializer as ts.Expression; - - // Update node with the pure comment before the variable declaration initializer. - const newNode = ts.updateVariableStatement( - node, - node.modifiers, - ts.updateVariableDeclarationList( - node.declarationList, - [ - ts.updateVariableDeclaration( - varDecl, - varDecl.name, - varDecl.type, - addPureComment(varInitializer), - ), - ], - ), - ); - - // Replace node with modified one. - return ts.visitEachChild(newNode, visitor, context); - } - - // Otherwise return node as is. - return ts.visitEachChild(node, visitor, context); - }; - - return ts.visitEachChild(sf, visitor, context); - }; - - return transformer; - }; -} - -// Determine if a node matched the structure of a downleveled TS class. -function isDownleveledClass(node: ts.Node): boolean { - - if (!ts.isVariableStatement(node)) { - return false; - } - - if (node.declarationList.declarations.length !== 1) { - return false; - } - - const variableDeclaration = node.declarationList.declarations[0]; - - if (!ts.isIdentifier(variableDeclaration.name) - || !variableDeclaration.initializer) { - return false; - } - - let potentialClass = variableDeclaration.initializer; - - // TS 2.3 has an unwrapped class IIFE - // TS 2.4 uses a function expression wrapper - // TS 2.5 uses an arrow function wrapper - if (ts.isParenthesizedExpression(potentialClass)) { - potentialClass = potentialClass.expression; - } - - if (!ts.isCallExpression(potentialClass) || potentialClass.arguments.length > 1) { - return false; - } - - let wrapperBody: ts.Block; - if (ts.isFunctionExpression(potentialClass.expression)) { - wrapperBody = potentialClass.expression.body; - } else if (ts.isArrowFunction(potentialClass.expression) - && ts.isBlock(potentialClass.expression.body)) { - wrapperBody = potentialClass.expression.body; - } else { - return false; - } - - if (wrapperBody.statements.length === 0) { - return false; - } - - const functionExpression = potentialClass.expression; - const functionStatements = wrapperBody.statements; - - // need a minimum of two for a function declaration and return statement - if (functionStatements.length < 2) { - return false; - } - - const firstStatement = functionStatements[0]; - - // find return statement - may not be last statement - let returnStatement: ts.ReturnStatement | undefined; - for (let i = functionStatements.length - 1; i > 0; i--) { - if (ts.isReturnStatement(functionStatements[i])) { - returnStatement = functionStatements[i] as ts.ReturnStatement; - break; - } - } - - if (returnStatement == undefined - || returnStatement.expression == undefined - || !ts.isIdentifier(returnStatement.expression)) { - return false; - } - - if (functionExpression.parameters.length === 0) { - // potential non-extended class or wrapped es2015 class - return (ts.isFunctionDeclaration(firstStatement) || ts.isClassDeclaration(firstStatement)) - && firstStatement.name !== undefined - && returnStatement.expression.text === firstStatement.name.text; - } else if (functionExpression.parameters.length !== 1) { - return false; - } - - // Potential extended class - - const functionParameter = functionExpression.parameters[0]; - - if (!ts.isIdentifier(functionParameter.name) - || functionParameter.name.text !== superParameterName) { - return false; - } - - if (functionStatements.length < 3 || !ts.isExpressionStatement(firstStatement)) { - return false; - } - - if (!ts.isCallExpression(firstStatement.expression)) { - return false; - } - - const extendCallExpression = firstStatement.expression; - - let functionName; - if (ts.isIdentifier(extendCallExpression.expression)) { - functionName = extendCallExpression.expression.text; - } else if (ts.isPropertyAccessExpression(extendCallExpression.expression)) { - functionName = extendCallExpression.expression.name.text; - } - - if (!functionName || !functionName.endsWith(extendsHelperName)) { - return false; - } - - if (extendCallExpression.arguments.length === 0) { - return false; - } - - const lastArgument = extendCallExpression.arguments[extendCallExpression.arguments.length - 1]; - - if (!ts.isIdentifier(lastArgument) || lastArgument.text !== functionParameter.name.text) { - return false; - } - - const secondStatement = functionStatements[1]; - - return ts.isFunctionDeclaration(secondStatement) - && secondStatement.name !== undefined - && returnStatement.expression.text === secondStatement.name.text; -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes_spec.ts deleted file mode 100644 index 21149b28bf00..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/prefix-classes_spec.ts +++ /dev/null @@ -1,361 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { getPrefixClassesTransformer, testPrefixClasses } from './prefix-classes'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getPrefixClassesTransformer] }).content; - -describe('prefix-classes', () => { - it('prefix TS 2.0 - 2.4 downlevel class', () => { - const input = tags.stripIndent` - var BasicTestCase = (function () { - function BasicTestCase() { - } - return BasicTestCase; - }()); - `; - const output = tags.stripIndent` - var BasicTestCase = /*@__PURE__*/ (function () { - function BasicTestCase() { - } - return BasicTestCase; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - // NOTE: TS 2.1+ uses a standalone export after the variable statement - it('prefix TS 2.0 exported downlevel class with ES2015 modules', () => { - const input = tags.stripIndent` - export var OuterSubscriber = (function (_super) { - __extends(OuterSubscriber, _super); - function OuterSubscriber() { - _super.apply(this, arguments); - } - return OuterSubscriber; - }()); - `; - const output = tags.stripIndent` - export var OuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(OuterSubscriber, _super); - function OuterSubscriber() { - _super.apply(this, arguments); - } - return OuterSubscriber; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.0 downlevel class with extends', () => { - const input = tags.stripIndent` - var ExtendedClass = (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - _super.apply(this, arguments); - } - return ExtendedClass; - }(StaticTestCase)); - `; - const output = tags.stripIndent` - var ExtendedClass = /*@__PURE__*/ (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - _super.apply(this, arguments); - } - return ExtendedClass; - }(StaticTestCase)); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.1 - 2.3 downlevel class with static variable', () => { - const input = tags.stripIndent` - var StaticTestCase = (function () { - function StaticTestCase() { - } - return StaticTestCase; - }()); - StaticTestCase.StaticTest = true; - `; - const output = tags.stripIndent` - var StaticTestCase = /*@__PURE__*/ (function () { - function StaticTestCase() { - } - return StaticTestCase; - }()); - StaticTestCase.StaticTest = true; - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.1 - 2.4 downlevel class with extends', () => { - const input = tags.stripIndent` - var ExtendedClass = (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - `; - const output = tags.stripIndent` - var ExtendedClass = /*@__PURE__*/ (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.0 & 2.4 downlevel class with static variable', () => { - const input = tags.stripIndent` - var StaticTestCase = (function () { - function StaticTestCase() { - } - StaticTestCase.StaticTest = true; - return StaticTestCase; - }()); - `; - const output = tags.stripIndent` - var StaticTestCase = /*@__PURE__*/ (function () { - function StaticTestCase() { - } - StaticTestCase.StaticTest = true; - return StaticTestCase; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.5 - 2.6 downlevel class', () => { - const input = tags.stripIndent` - var BasicTestCase = /** @class */ (function () { - function BasicTestCase() { - } - return BasicTestCase; - }()); - `; - const output = tags.stripIndent` - var BasicTestCase = /** @class */ /*@__PURE__*/ (function () { - function BasicTestCase() { - } - return BasicTestCase; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.5 - 2.6 renamed downlevel class', () => { - const input = tags.stripIndent` - var ComponentFactoryResolver$1 = /** @class */ (function () { - function ComponentFactoryResolver$$1() { - } - return ComponentFactoryResolver$$1; - }()); - `; - const output = tags.stripIndent` - var ComponentFactoryResolver$1 = /** @class */ /*@__PURE__*/ (function () { - function ComponentFactoryResolver$$1() { - } - return ComponentFactoryResolver$$1; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.5 - 2.6 renamed downlevel class with extends', () => { - const input = tags.stripIndent` - var NgModuleFactory$1 = /** @class */ (function (_super) { - __extends(NgModuleFactory$$1, _super); - function NgModuleFactory$$1(moduleType) { - var _this = _super.call(this) || this; - _this.moduleType = moduleType; - return _this; - } - NgModuleFactory$$1.prototype.create = function (parentInjector) { - return new NgModuleRef$1(this.moduleType, parentInjector); - }; - return NgModuleFactory$$1; - }(NgModuleFactory)); - `; - const output = tags.stripIndent` - var NgModuleFactory$1 = /** @class */ /*@__PURE__*/ (function (_super) { - __extends(NgModuleFactory$$1, _super); - function NgModuleFactory$$1(moduleType) { - var _this = _super.call(this) || this; - _this.moduleType = moduleType; - return _this; - } - NgModuleFactory$$1.prototype.create = function (parentInjector) { - return new NgModuleRef$1(this.moduleType, parentInjector); - }; - return NgModuleFactory$$1; - }(NgModuleFactory)); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.5 - 2.6 downlevel class with static variable', () => { - const input = tags.stripIndent` - var StaticTestCase = /** @class */ (function () { - function StaticTestCase() { - } - StaticTestCase.StaticTest = true; - return StaticTestCase; - }()); - `; - const output = tags.stripIndent` - var StaticTestCase = /** @class */ /*@__PURE__*/ (function () { - function StaticTestCase() { - } - StaticTestCase.StaticTest = true; - return StaticTestCase; - }()); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('prefix TS 2.5 - 2.6 downlevel class with extends', () => { - const input = tags.stripIndent` - var ExtendedClass = /** @class */ (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - `; - const output = tags.stripIndent` - var ExtendedClass = /** @class */ /*@__PURE__*/ (function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('works with tslib namespace import', () => { - const input = tags.stripIndent` - var BufferSubscriber = /** @class */ (function (_super) { - tslib_1.__extends(BufferSubscriber, _super); - function BufferSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - return BufferSubscriber; - }(OuterSubscriber)); - `; - const output = tags.stripIndent` - var BufferSubscriber = /** @class */ /*@__PURE__*/ (function (_super) { - tslib_1.__extends(BufferSubscriber, _super); - function BufferSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - return BufferSubscriber; - }(OuterSubscriber)); - `; - - expect(testPrefixClasses(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('fixes the RxJS use case (issue #214)', () => { - const input = ` - var ExtendedClass = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - - /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ - var zip_ZipSubscriber = /*@__PURE__*/ (/*@__PURE__*/ function (_super) { - zip___extends(ZipSubscriber, _super); - function ZipSubscriber(destination, project, values) { - if (values === void 0) { - values = Object.create(null); - } - _super.call(this, destination); - this.iterators = []; - this.active = 0; - this.project = (typeof project === 'function') ? project : null; - this.values = values; - } - return ZipSubscriber; - }(Subscriber)); - `; - const output = ` - var ExtendedClass = /*@__PURE__*/ /*@__PURE__*/ ( /*@__PURE__*/function (_super) { - __extends(ExtendedClass, _super); - function ExtendedClass() { - return _super !== null && _super.apply(this, arguments) || this; - } - return ExtendedClass; - }(StaticTestCase)); - - /** - * We need this JSDoc comment for affecting ESDoc. - * @ignore - * @extends {Ignored} - */ - var zip_ZipSubscriber = /*@__PURE__*/ /*@__PURE__*/ ( /*@__PURE__*/function (_super) { - zip___extends(ZipSubscriber, _super); - function ZipSubscriber(destination, project, values) { - if (values === void 0) { - values = Object.create(null); - } - _super.call(this, destination); - this.iterators = []; - this.active = 0; - this.project = (typeof project === 'function') ? project : null; - this.values = values; - } - return ZipSubscriber; - }(Subscriber)); - `; - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); -}); diff --git a/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions.ts b/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions.ts deleted file mode 100644 index d058047284f9..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { addPureComment, getCleanHelperName, hasPureComment } from '../helpers/ast-utils'; - -export function getPrefixFunctionsTransformer(): ts.TransformerFactory { - return (context: ts.TransformationContext): ts.Transformer => { - const transformer: ts.Transformer = (sf: ts.SourceFile) => { - - const topLevelFunctions = findTopLevelFunctions(sf); - - const visitor: ts.Visitor = (node: ts.Node): ts.Node => { - // Add pure function comment to top level functions. - if (topLevelFunctions.has(node)) { - const newNode = addPureComment(node); - - // Replace node with modified one. - return ts.visitEachChild(newNode, visitor, context); - } - - // Otherwise return node as is. - return ts.visitEachChild(node, visitor, context); - }; - - return ts.visitNode(sf, visitor); - }; - - return transformer; - }; -} - -export function findTopLevelFunctions(parentNode: ts.Node): Set { - const topLevelFunctions = new Set(); - - function cb(node: ts.Node) { - // Stop recursing into this branch if it's a definition construct. - // These are function expression, function declaration, class, or arrow function (lambda). - // The body of these constructs will not execute when loading the module, so we don't - // need to mark function calls inside them as pure. - // Class static initializers in ES2015 are an exception we don't cover. They would need similar - // processing as enums to prevent property setting from causing the class to be retained. - if (ts.isFunctionLike(node) - || ts.isClassLike(node) - || ts.isArrowFunction(node) - || ts.isMethodDeclaration(node) - ) { - return; - } - - let noPureComment = !hasPureComment(node); - let innerNode = node; - while (innerNode && ts.isParenthesizedExpression(innerNode)) { - innerNode = innerNode.expression; - noPureComment = noPureComment && !hasPureComment(innerNode); - } - - if (!innerNode) { - return; - } - - if ((ts.isFunctionExpression(innerNode) || ts.isArrowFunction(innerNode)) - && ts.isParenthesizedExpression(node)) { - // pure functions can be wrapped in parentizes - // we should not add pure comments to this sort of syntax. - // example var foo = (() => x) - return; - } - - if (noPureComment) { - if (ts.isNewExpression(innerNode)) { - topLevelFunctions.add(node); - } else if (ts.isCallExpression(innerNode)) { - let expression: ts.Expression = innerNode.expression; - - if (ts.isIdentifier(expression) && getCleanHelperName(expression.text)) { - return; - } - - while (expression && ts.isParenthesizedExpression(expression)) { - expression = expression.expression; - } - - if (expression) { - if (ts.isFunctionExpression(expression)) { - // Skip IIFE's with arguments - // This could be improved to check if there are any references to variables - if (innerNode.arguments.length === 0) { - topLevelFunctions.add(node); - } - } else { - topLevelFunctions.add(node); - } - } - } - } - - ts.forEachChild(innerNode, cb); - } - - ts.forEachChild(parentNode, cb); - - return topLevelFunctions; -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions_spec.ts deleted file mode 100644 index ec7bb8fd0fdd..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/prefix-functions_spec.ts +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { getPrefixFunctionsTransformer } from './prefix-functions'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getPrefixFunctionsTransformer] }).content; - -describe('prefix-functions', () => { - const clazz = 'var Clazz = (function () { function Clazz() { } return Clazz; }());'; - - describe('pure functions', () => { - it('adds comment to new calls', () => { - const input = tags.stripIndent` - var newClazz = new Clazz(); - `; - const output = tags.stripIndent` - var newClazz = /*@__PURE__*/ new Clazz(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('adds comment to function calls', () => { - const input = tags.stripIndent` - var newClazz = Clazz(); - `; - const output = tags.stripIndent` - var newClazz = /*@__PURE__*/ Clazz(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('adds comment outside of IIFEs', () => { - const input = tags.stripIndent` - ${clazz} - var ClazzTwo = (function () { function Clazz() { } return Clazz; })(); - `; - const output = tags.stripIndent` - var Clazz = /*@__PURE__*/ (function () { function Clazz() { } return Clazz; }()); - var ClazzTwo = /*@__PURE__*/ (function () { function Clazz() { } return Clazz; })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment when inside function declarations or expressions', () => { - const input = tags.stripIndent` - function funcDecl() { - var newClazz = Clazz(); - var newClazzTwo = new Clazz(); - } - - var funcExpr = function () { - var newClazz = Clazz(); - var newClazzTwo = new Clazz(); - }; - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment to downlevel namespaces', () => { - const input = tags.stripIndent` - function MyFunction() { } - - (function (MyFunction) { - function subFunction() { } - MyFunction.subFunction = subFunction; - })(MyFunction || (MyFunctionn = {})); - - export { MyFunction }; - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment when inside class', () => { - const input = tags.stripIndent` - class Foo { - constructor(e) { - super(e); - } - method() { - var newClazz = new Clazz(); - } - } - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment when inside arrow function', () => { - const input = tags.stripIndent` - export const subscribeToArray = (array) => (subscriber) => { - for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - if (!subscriber.closed) { - subscriber.complete(); - } - }; - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment when inside object literal method', () => { - const input = tags.stripIndent` - const literal = { - method() { - var newClazz = new Clazz(); - } - }; - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - it('doesn\'t add comment to downlevel arrow function', () => { - const input = tags.stripIndent` - var populate = (function (props, rawData, entity) { - props.forEach(function (prop) { }); - }); - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment inside arrow function', () => { - const input = tags.stripIndent` - const populate = ((props, rawData, entity) => { - props.forEach(x => x); - }); - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t add comment when inside class expression', () => { - const input = tags.stripIndent` - let Foo = class Foo { - constructor() { - this.isExpandedChange = new EventEmitter(); - } - - set isExpanded(value) { - this.isExpandedChange.emit(value); - } - }; - `; - const output = tags.stripIndent` - ${input} - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it(`doesn't add pure comments to tslib helpers`, () => { - const input = tags.stripIndent` - class LanguageState { - - } - - LanguageState.ctorParameters = () => [ - { type: TranslateService }, - { type: undefined, decorators: [{ type: Inject, args: [LANGUAGE_CONFIG,] }] } - ]; - - __decorate([ - Action(CheckLanguage), - __metadata("design:type", Function), - __metadata("design:paramtypes", [Object]), - __metadata("design:returntype", void 0) - ], LanguageState.prototype, "checkLanguage", null); - `; - - const output = input; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); -}); diff --git a/packages/angular_devkit/build_optimizer/src/transforms/scrub-file.ts b/packages/angular_devkit/build_optimizer/src/transforms/scrub-file.ts deleted file mode 100644 index 9bf57689d111..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/scrub-file.ts +++ /dev/null @@ -1,601 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { collectDeepNodes } from '../helpers/ast-utils'; - -/** - * @deprecated From 0.9.0 - */ -export function testScrubFile(content: string) { - const markers = [ - 'decorators', - '__decorate', - 'propDecorators', - 'ctorParameters', - 'ɵsetClassMetadata', - 'ɵɵsetNgModuleScope', - ]; - - return markers.some((marker) => content.indexOf(marker) !== -1); -} - -export function getScrubFileTransformer(program: ts.Program): ts.TransformerFactory { - return scrubFileTransformer(program.getTypeChecker(), false); -} - -export function getScrubFileTransformerForCore( - program: ts.Program, -): ts.TransformerFactory { - return scrubFileTransformer(program.getTypeChecker(), true); -} - -function scrubFileTransformer(checker: ts.TypeChecker, isAngularCoreFile: boolean) { - return (context: ts.TransformationContext): ts.Transformer => { - - const transformer: ts.Transformer = (sf: ts.SourceFile) => { - - const ngMetadata = findAngularMetadata(sf, isAngularCoreFile); - const tslibImports = findTslibImports(sf); - - const nodes: ts.Node[] = []; - ts.forEachChild(sf, checkNodeForDecorators); - - function checkNodeForDecorators(node: ts.Node): void { - if (node.kind !== ts.SyntaxKind.ExpressionStatement) { - // TS 2.4 nests decorators inside downleveled class IIFEs, so we - // must recurse into them to find the relevant expression statements. - return ts.forEachChild(node, checkNodeForDecorators); - } - const exprStmt = node as ts.ExpressionStatement; - // Do checks that don't need the typechecker first and bail early. - if (isIvyPrivateCallExpression(exprStmt) - || isCtorParamsAssignmentExpression(exprStmt)) { - nodes.push(node); - } else if (isDecoratorAssignmentExpression(exprStmt)) { - nodes.push(...pickDecorationNodesToRemove(exprStmt, ngMetadata, checker)); - } else if (isDecorateAssignmentExpression(exprStmt, tslibImports, checker) - || isAngularDecoratorExpression(exprStmt, ngMetadata, tslibImports, checker)) { - nodes.push(...pickDecorateNodesToRemove(exprStmt, tslibImports, ngMetadata, checker)); - } else if (isPropDecoratorAssignmentExpression(exprStmt)) { - nodes.push(...pickPropDecorationNodesToRemove(exprStmt, ngMetadata, checker)); - } - } - - const visitor: ts.Visitor = (node: ts.Node): ts.VisitResult => { - // Check if node is a statement to be dropped. - if (nodes.find((n) => n === node)) { - return undefined; - } - - // Otherwise return node as is. - return ts.visitEachChild(node, visitor, context); - }; - - return ts.visitNode(sf, visitor); - }; - - return transformer; - }; -} - -export function expect(node: ts.Node, kind: ts.SyntaxKind): T { - if (node.kind !== kind) { - throw new Error('Invalid node type.'); - } - - return node as T; -} - -function findAngularMetadata(node: ts.Node, isAngularCoreFile: boolean): ts.Node[] { - let specs: ts.Node[] = []; - // Find all specifiers from imports of `@angular/core`. - ts.forEachChild(node, (child) => { - if (child.kind === ts.SyntaxKind.ImportDeclaration) { - const importDecl = child as ts.ImportDeclaration; - if (isAngularCoreImport(importDecl, isAngularCoreFile)) { - specs.push(...collectDeepNodes(importDecl, ts.SyntaxKind.ImportSpecifier)); - } - } - }); - - // If the current module is a Angular core file, we also consider all declarations in it to - // potentially be Angular metadata. - if (isAngularCoreFile) { - const localDecl = findAllDeclarations(node); - specs = specs.concat(localDecl); - } - - return specs; -} - -function findAllDeclarations(node: ts.Node): ts.VariableDeclaration[] { - const nodes: ts.VariableDeclaration[] = []; - ts.forEachChild(node, (child) => { - if (child.kind === ts.SyntaxKind.VariableStatement) { - const vStmt = child as ts.VariableStatement; - vStmt.declarationList.declarations.forEach((decl) => { - if (decl.name.kind !== ts.SyntaxKind.Identifier) { - return; - } - nodes.push(decl); - }); - } - }); - - return nodes; -} - -function isAngularCoreImport(node: ts.ImportDeclaration, isAngularCoreFile: boolean): boolean { - if (!(node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier))) { - return false; - } - const importText = node.moduleSpecifier.text; - - // Imports to `@angular/core` are always core imports. - if (importText === '@angular/core') { - return true; - } - - // Relative imports from a Angular core file are also core imports. - if (isAngularCoreFile && (importText.startsWith('./') || importText.startsWith('../'))) { - return true; - } - - return false; -} - -// Check if assignment is `Clazz.decorators = [...];`. -function isDecoratorAssignmentExpression(exprStmt: ts.ExpressionStatement): boolean { - if (!isAssignmentExpressionTo(exprStmt, 'decorators')) { - return false; - } - const expr = exprStmt.expression as ts.BinaryExpression; - if (expr.right.kind !== ts.SyntaxKind.ArrayLiteralExpression) { - return false; - } - - return true; -} - -// Check if assignment is `Clazz = __decorate([...], Clazz)`. -function isDecorateAssignmentExpression( - exprStmt: ts.ExpressionStatement, - tslibImports: ts.NamespaceImport[], - checker: ts.TypeChecker, -): boolean { - - if (exprStmt.expression.kind !== ts.SyntaxKind.BinaryExpression) { - return false; - } - const expr = exprStmt.expression as ts.BinaryExpression; - if (expr.left.kind !== ts.SyntaxKind.Identifier) { - return false; - } - const classIdent = expr.left as ts.Identifier; - let callExpr: ts.CallExpression; - - if (expr.right.kind === ts.SyntaxKind.CallExpression) { - callExpr = expr.right as ts.CallExpression; - } else if (expr.right.kind === ts.SyntaxKind.BinaryExpression) { - // `Clazz = Clazz_1 = __decorate([...], Clazz)` can be found when there are static property - // accesses. - const innerExpr = expr.right as ts.BinaryExpression; - if (innerExpr.left.kind !== ts.SyntaxKind.Identifier - || innerExpr.right.kind !== ts.SyntaxKind.CallExpression) { - return false; - } - callExpr = innerExpr.right as ts.CallExpression; - } else { - return false; - } - - if (!isTslibHelper(callExpr, '__decorate', tslibImports, checker)) { - return false; - } - - if (callExpr.arguments.length !== 2) { - return false; - } - if (callExpr.arguments[1].kind !== ts.SyntaxKind.Identifier) { - return false; - } - const classArg = callExpr.arguments[1] as ts.Identifier; - if (classIdent.text !== classArg.text) { - return false; - } - if (callExpr.arguments[0].kind !== ts.SyntaxKind.ArrayLiteralExpression) { - return false; - } - - return true; -} - -// Check if expression is `__decorate([smt, __metadata("design:type", Object)], ...)`. -function isAngularDecoratorExpression( - exprStmt: ts.ExpressionStatement, - ngMetadata: ts.Node[], - tslibImports: ts.NamespaceImport[], - checker: ts.TypeChecker, -): boolean { - - if (exprStmt.expression.kind !== ts.SyntaxKind.CallExpression) { - return false; - } - const callExpr = exprStmt.expression as ts.CallExpression; - if (!isTslibHelper(callExpr, '__decorate', tslibImports, checker)) { - return false; - } - if (callExpr.arguments.length !== 4) { - return false; - } - if (callExpr.arguments[0].kind !== ts.SyntaxKind.ArrayLiteralExpression) { - return false; - } - const decorateArray = callExpr.arguments[0] as ts.ArrayLiteralExpression; - // Check first array entry for Angular decorators. - if (decorateArray.elements.length === 0 || !ts.isCallExpression(decorateArray.elements[0])) { - return false; - } - - return decorateArray.elements.some(decoratorCall => { - if (!ts.isCallExpression(decoratorCall) || !ts.isIdentifier(decoratorCall.expression)) { - return false; - } - - const decoratorId = decoratorCall.expression; - - return identifierIsMetadata(decoratorId, ngMetadata, checker); - }); -} - -// Check if assignment is `Clazz.propDecorators = [...];`. -function isPropDecoratorAssignmentExpression(exprStmt: ts.ExpressionStatement): boolean { - if (!isAssignmentExpressionTo(exprStmt, 'propDecorators')) { - return false; - } - const expr = exprStmt.expression as ts.BinaryExpression; - if (expr.right.kind !== ts.SyntaxKind.ObjectLiteralExpression) { - return false; - } - - return true; -} - -// Check if assignment is `Clazz.ctorParameters = [...];`. -function isCtorParamsAssignmentExpression(exprStmt: ts.ExpressionStatement): boolean { - if (!isAssignmentExpressionTo(exprStmt, 'ctorParameters')) { - return false; - } - const expr = exprStmt.expression as ts.BinaryExpression; - if (expr.right.kind !== ts.SyntaxKind.FunctionExpression - && expr.right.kind !== ts.SyntaxKind.ArrowFunction - ) { - return false; - } - - return true; -} - -function isAssignmentExpressionTo(exprStmt: ts.ExpressionStatement, name: string) { - if (exprStmt.expression.kind !== ts.SyntaxKind.BinaryExpression) { - return false; - } - const expr = exprStmt.expression as ts.BinaryExpression; - if (expr.left.kind !== ts.SyntaxKind.PropertyAccessExpression) { - return false; - } - const propAccess = expr.left as ts.PropertyAccessExpression; - if (propAccess.name.text !== name) { - return false; - } - if (propAccess.expression.kind !== ts.SyntaxKind.Identifier) { - return false; - } - if (expr.operatorToken.kind !== ts.SyntaxKind.FirstAssignment) { - return false; - } - - return true; -} - -function isIvyPrivateCallExpression(exprStmt: ts.ExpressionStatement) { - const callExpr = exprStmt.expression; - if (!ts.isCallExpression(callExpr)) { - return false; - } - const propAccExpr = callExpr.expression; - if (!ts.isPropertyAccessExpression(propAccExpr)) { - return false; - } - - if (propAccExpr.name.text != 'ɵsetClassMetadata' - && propAccExpr.name.text != 'ɵɵsetNgModuleScope') { - return false; - } - - return true; -} - -// Remove Angular decorators from`Clazz.decorators = [...];`, or expression itself if all are -// removed. -function pickDecorationNodesToRemove( - exprStmt: ts.ExpressionStatement, - ngMetadata: ts.Node[], - checker: ts.TypeChecker, -): ts.Node[] { - - const expr = expect(exprStmt.expression, ts.SyntaxKind.BinaryExpression); - const literal = expect(expr.right, - ts.SyntaxKind.ArrayLiteralExpression); - if (!literal.elements.every((elem) => elem.kind === ts.SyntaxKind.ObjectLiteralExpression)) { - return []; - } - const elements = literal.elements as ts.NodeArray; - const ngDecorators = elements.filter((elem) => isAngularDecorator(elem, ngMetadata, checker)); - - return (elements.length > ngDecorators.length) ? ngDecorators : [exprStmt]; -} - -// Remove Angular decorators from `Clazz = __decorate([...], Clazz)`, or expression itself if all -// are removed. -function pickDecorateNodesToRemove( - exprStmt: ts.ExpressionStatement, - tslibImports: ts.NamespaceImport[], - ngMetadata: ts.Node[], - checker: ts.TypeChecker, -): ts.Node[] { - let callExpr: ts.CallExpression | undefined; - if (ts.isCallExpression(exprStmt.expression)) { - callExpr = exprStmt.expression; - } else if (ts.isBinaryExpression(exprStmt.expression)) { - const expr = exprStmt.expression; - if (ts.isCallExpression(expr.right)) { - callExpr = expr.right; - } else if (ts.isBinaryExpression(expr.right) && ts.isCallExpression(expr.right.right)) { - callExpr = expr.right.right; - } - } - - if (!callExpr) { - return []; - } - - const arrLiteral = expect(callExpr.arguments[0], - ts.SyntaxKind.ArrayLiteralExpression); - - if (!arrLiteral.elements.every((elem) => elem.kind === ts.SyntaxKind.CallExpression)) { - return []; - } - const elements = arrLiteral.elements as ts.NodeArray; - const ngDecoratorCalls = elements.filter((el) => { - if (el.expression.kind !== ts.SyntaxKind.Identifier) { - return false; - } - const id = el.expression as ts.Identifier; - - return identifierIsMetadata(id, ngMetadata, checker); - }); - - - // Remove __metadata calls of type 'design:paramtypes'. - const metadataCalls = elements.filter((el) => { - if (!isTslibHelper(el, '__metadata', tslibImports, checker)) { - return false; - } - if (el.arguments.length < 2) { - return false; - } - if (el.arguments[0].kind !== ts.SyntaxKind.StringLiteral) { - return false; - } - - return true; - }); - // Remove all __param calls. - const paramCalls = elements.filter((el) => { - if (!isTslibHelper(el, '__param', tslibImports, checker)) { - return false; - } - if (el.arguments.length != 2) { - return false; - } - if (el.arguments[0].kind !== ts.SyntaxKind.NumericLiteral) { - return false; - } - - return true; - }); - - ngDecoratorCalls.push(...metadataCalls, ...paramCalls); - - // If all decorators are metadata decorators then return the whole `Class = __decorate([...])'` - // statement so that it is removed in entirety - return (elements.length === ngDecoratorCalls.length) ? [exprStmt] : ngDecoratorCalls; -} - -// Remove Angular decorators from`Clazz.propDecorators = [...];`, or expression itself if all -// are removed. -function pickPropDecorationNodesToRemove( - exprStmt: ts.ExpressionStatement, - ngMetadata: ts.Node[], - checker: ts.TypeChecker, -): ts.Node[] { - - const expr = expect(exprStmt.expression, ts.SyntaxKind.BinaryExpression); - const literal = expect(expr.right, - ts.SyntaxKind.ObjectLiteralExpression); - if (!literal.properties.every((elem) => elem.kind === ts.SyntaxKind.PropertyAssignment && - (elem as ts.PropertyAssignment).initializer.kind === ts.SyntaxKind.ArrayLiteralExpression)) { - return []; - } - const assignments = literal.properties as ts.NodeArray; - // Consider each assignment individually. Either the whole assignment will be removed or - // a particular decorator within will. - const toRemove = assignments - .map((assign) => { - const decorators = - expect(assign.initializer, - ts.SyntaxKind.ArrayLiteralExpression).elements; - if (!decorators.every((el) => el.kind === ts.SyntaxKind.ObjectLiteralExpression)) { - return []; - } - const decsToRemove = decorators.filter((expression) => { - const lit = expect(expression, - ts.SyntaxKind.ObjectLiteralExpression); - - return isAngularDecorator(lit, ngMetadata, checker); - }); - if (decsToRemove.length === decorators.length) { - return [assign]; - } - - return decsToRemove; - }) - .reduce((accum, toRm) => accum.concat(toRm), [] as ts.Node[]); - // If every node to be removed is a property assignment (full property's decorators) and - // all properties are accounted for, remove the whole assignment. Otherwise, remove the - // nodes which were marked as safe. - if (toRemove.length === assignments.length && - toRemove.every((node) => node.kind === ts.SyntaxKind.PropertyAssignment)) { - return [exprStmt]; - } - - return toRemove; -} - -function isAngularDecorator( - literal: ts.ObjectLiteralExpression, - ngMetadata: ts.Node[], - checker: ts.TypeChecker, -): boolean { - - const types = literal.properties.filter(isTypeProperty); - if (types.length !== 1) { - return false; - } - const assign = expect(types[0], ts.SyntaxKind.PropertyAssignment); - if (assign.initializer.kind !== ts.SyntaxKind.Identifier) { - return false; - } - const id = assign.initializer as ts.Identifier; - const res = identifierIsMetadata(id, ngMetadata, checker); - - return res; -} - -function isTypeProperty(prop: ts.ObjectLiteralElement): boolean { - if (prop.kind !== ts.SyntaxKind.PropertyAssignment) { - return false; - } - const assignment = prop as ts.PropertyAssignment; - if (assignment.name.kind !== ts.SyntaxKind.Identifier) { - return false; - } - const name = assignment.name as ts.Identifier; - - return name.text === 'type'; -} - -// Check if an identifier is part of the known Angular Metadata. -function identifierIsMetadata( - id: ts.Identifier, - metadata: ts.Node[], - checker: ts.TypeChecker, -): boolean { - const symbol = checker.getSymbolAtLocation(id); - if (!symbol || !symbol.declarations || !symbol.declarations.length) { - return false; - } - - return symbol - .declarations - .some((spec) => metadata.indexOf(spec) !== -1); -} - -// Check if an import is a tslib helper import (`import * as tslib from "tslib";`) -function isTslibImport(node: ts.ImportDeclaration): boolean { - return !!(node.moduleSpecifier && - node.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral && - (node.moduleSpecifier as ts.StringLiteral).text === 'tslib' && - node.importClause && - node.importClause.namedBindings && - node.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport); -} - -// Find all namespace imports for `tslib`. -function findTslibImports(node: ts.Node): ts.NamespaceImport[] { - const imports: ts.NamespaceImport[] = []; - ts.forEachChild(node, (child) => { - if (child.kind === ts.SyntaxKind.ImportDeclaration) { - const importDecl = child as ts.ImportDeclaration; - if (isTslibImport(importDecl)) { - const importClause = importDecl.importClause as ts.ImportClause; - const namespaceImport = importClause.namedBindings as ts.NamespaceImport; - imports.push(namespaceImport); - } - } - }); - - return imports; -} - -// Check if an identifier is part of the known tslib identifiers. -function identifierIsTslib( - id: ts.Identifier, - tslibImports: ts.NamespaceImport[], - checker: ts.TypeChecker, -): boolean { - const symbol = checker.getSymbolAtLocation(id); - if (!symbol || !symbol.declarations || !symbol.declarations.length) { - return false; - } - - return symbol - .declarations - .some((spec) => tslibImports.indexOf(spec as ts.NamespaceImport) !== -1); -} - -// Check if a function call is a tslib helper. -function isTslibHelper( - callExpr: ts.CallExpression, - helper: string, - tslibImports: ts.NamespaceImport[], - checker: ts.TypeChecker, -) { - - let callExprIdent = callExpr.expression as ts.Identifier; - - if (callExpr.expression.kind !== ts.SyntaxKind.Identifier) { - if (callExpr.expression.kind === ts.SyntaxKind.PropertyAccessExpression) { - const propAccess = callExpr.expression as ts.PropertyAccessExpression; - const left = propAccess.expression; - callExprIdent = propAccess.name; - - if (left.kind !== ts.SyntaxKind.Identifier) { - return false; - } - - const id = left as ts.Identifier; - - if (!identifierIsTslib(id, tslibImports, checker)) { - return false; - } - - } else { - return false; - } - } - - // node.text on a name that starts with two underscores will return three instead. - // Unless it's an expression like tslib.__decorate, in which case it's only 2. - if (callExprIdent.text !== `_${helper}` && callExprIdent.text !== helper) { - return false; - } - - return true; -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/scrub-file_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/scrub-file_spec.ts deleted file mode 100644 index 1ef06dc0c2f8..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/scrub-file_spec.ts +++ /dev/null @@ -1,754 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { - getScrubFileTransformer, - getScrubFileTransformerForCore, - testScrubFile, -} from './scrub-file'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getScrubFileTransformer], typeCheck: true }).content; -const transformCore = (content: string) => transformJavascript( - { content, getTransforms: [getScrubFileTransformerForCore], typeCheck: true }).content; - -describe('scrub-file', () => { - const clazz = 'var Clazz = (function () { function Clazz() { } return Clazz; }());'; - - describe('decorators', () => { - it('removes top-level Angular decorators', () => { - const output = tags.stripIndent` - import { Injectable } from '@angular/core'; - ${clazz} - `; - const input = tags.stripIndent` - ${output} - Clazz.decorators = [ { type: Injectable } ]; - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes nested Angular decorators', () => { - const output = tags.stripIndent` - import { Injectable } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Injectable } from '@angular/core'; - var Clazz = (function () { - function Clazz() {} - Clazz.decorators = [ { type: Injectable } ]; - return Clazz; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t remove non Angular decorators', () => { - const input = tags.stripIndent` - import { Injectable } from 'another-lib'; - ${clazz} - Clazz.decorators = [{ type: Injectable }]; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`); - }); - - it('leaves non-Angular decorators in mixed arrays', () => { - const input = tags.stripIndent` - import { Injectable } from '@angular/core'; - import { NotInjectable } from 'another-lib'; - ${clazz} - Clazz.decorators = [{ type: Injectable }, { type: NotInjectable }]; - `; - const output = tags.stripIndent` - import { Injectable } from '@angular/core'; - import { NotInjectable } from 'another-lib'; - ${clazz} - Clazz.decorators = [{ type: NotInjectable }]; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('__decorate', () => { - it('removes Angular decorators calls in __decorate', () => { - const output = tags.stripIndent` - import { Component, Injectable } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Component, Injectable } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - Clazz = __decorate([ - Injectable(), - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - ], Clazz); - return Clazz; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes constructor parameter metadata in __decorate', () => { - const output = tags.stripIndent` - import { Component, ElementRef } from '@angular/core'; - import { LibService } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Component, ElementRef } from '@angular/core'; - import { LibService } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - Clazz = __decorate([ - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }), - __metadata("design:paramtypes", [ElementRef, LibService]) - ], Clazz); - return Clazz; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes constructor parameter metadata when static properties are present', () => { - const output = tags.stripIndent` - import { Injectable } from '@angular/core'; - import { Logger } from 'another-lib'; - var GaService = (function () { - function GaService(logger) { - this.logger = logger; - } - GaService_1 = GaService; - GaService.prototype.initializeGa = function () { - console.log(GaService_1.initializeDelay); - }; - GaService.initializeDelay = 1000; - return GaService; - var GaService_1; - }()); - `; - const input = tags.stripIndent` - import { Injectable } from '@angular/core'; - import { Logger } from 'another-lib'; - var GaService = (function () { - function GaService(logger) { - this.logger = logger; - } - GaService_1 = GaService; - GaService.prototype.initializeGa = function () { - console.log(GaService_1.initializeDelay); - }; - GaService.initializeDelay = 1000; - GaService = GaService_1 = __decorate([ - Injectable(), - __metadata("design:paramtypes", [Logger]) - ], GaService); - return GaService; - var GaService_1; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes only Angular decorators calls in __decorate', () => { - const output = tags.stripIndent` - import { Component } from '@angular/core'; - import { NotComponent } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - Clazz = __decorate([ - NotComponent() - ], Clazz); - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Component } from '@angular/core'; - import { NotComponent } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - Clazz = __decorate([ - NotComponent(), - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - ], Clazz); - return Clazz; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('recognizes tslib as well', () => { - const input = tags.stripIndent` - import * as tslib from "tslib"; - import * as tslib_2 from "tslib"; - import { Component } from '@angular/core'; - import { NotComponent } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - Clazz = tslib.__decorate([ - NotComponent(), - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - ], Clazz); - return Clazz; - }()); - - var Clazz2 = (function () { - function Clazz2() { } - Clazz2 = tslib_2.__decorate([ - NotComponent(), - Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] - }) - ], Clazz2); - return Clazz2; - }()); - `; - const output = tags.stripIndent` - import * as tslib from "tslib"; - import * as tslib_2 from "tslib"; - import { Component } from '@angular/core'; - import { NotComponent } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - Clazz = tslib.__decorate([ - NotComponent() - ], Clazz); - return Clazz; - }()); - - var Clazz2 = (function () { - function Clazz2() { } - Clazz2 = tslib_2.__decorate([ - NotComponent() - ], Clazz2); - return Clazz2; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('recognizes decorator imports in Angular core', () => { - const input = tags.stripIndent` - import * as tslib_1 from "tslib"; - import { Injectable } from './di'; - var Console = /** @class */ (function () { - function Console() { - } - Console.prototype.log = function (message) { - console.log(message); - }; - Console.prototype.warn = function (message) { - console.warn(message); - }; - Console = tslib_1.__decorate([ - Injectable() - ], Console); - return Console; - }()); - export { Console }; - `; - const output = tags.stripIndent` - import * as tslib_1 from "tslib"; - import { Injectable } from './di'; - var Console = /** @class */ (function () { - function Console() { - } - Console.prototype.log = function (message) { - console.log(message); - }; - Console.prototype.warn = function (message) { - console.warn(message); - }; - return Console; - }()); - export { Console }; - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transformCore(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes Angular decorators calls in __decorate when no __metadata is present', () => { - const input = tags.stripIndent` - import { __decorate } from 'tslib'; - import { Component, ElementRef, ContentChild} from '@angular/core'; - - var FooBarComponent = /** @class */ (function () { - function FooBarComponent(elementRef) { - this.elementRef = elementRef; - this.inlineButtons = []; - this.menuButtons = []; - } - FooBarComponent.ctorParameters = function () { return [ - { type: ElementRef } - ]; }; - __decorate([ - ContentChild('heading', { read: ElementRef, static: true }) - ], FooBarComponent.prototype, "buttons", void 0); - FooBarComponent = __decorate([ - Component({ - selector: 'custom-foo-bar', - template: '', - styles: [] - }) - ], FooBarComponent); - return FooBarComponent; - }()); - `; - - const output = tags.stripIndent` - import { __decorate } from 'tslib'; - import { Component, ElementRef, ContentChild } from '@angular/core'; - - var FooBarComponent = /** @class */ (function () { - function FooBarComponent(elementRef) { - this.elementRef = elementRef; - this.inlineButtons = []; - this.menuButtons = []; - } - - return FooBarComponent; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transformCore(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes only Angular decorators calls in __decorate when no __metadata is present', () => { - const input = tags.stripIndent` - import { __decorate } from 'tslib'; - import { Component, ElementRef, ContentChild} from '@angular/core'; - import { NotComponent } from 'another-lib'; - - var FooBarComponent = /** @class */ (function () { - function FooBarComponent(elementRef) { - this.elementRef = elementRef; - this.inlineButtons = []; - this.menuButtons = []; - } - FooBarComponent.ctorParameters = function () { return [ - { type: ElementRef } - ]; }; - __decorate([ - NotComponent(), - ContentChild('heading', { read: ElementRef, static: true }) - ], FooBarComponent.prototype, "buttons", void 0); - FooBarComponent = __decorate([ - NotComponent(), - Component({ - selector: 'custom-foo-bar', - template: '', - styles: [] - }) - ], FooBarComponent); - return FooBarComponent; - }()); - `; - - const output = tags.stripIndent` - import { __decorate } from 'tslib'; - import { Component, ElementRef, ContentChild } from '@angular/core'; - import { NotComponent } from 'another-lib'; - - var FooBarComponent = /** @class */ (function () { - function FooBarComponent(elementRef) { - this.elementRef = elementRef; - this.inlineButtons = []; - this.menuButtons = []; - } - __decorate([ - NotComponent() - ], FooBarComponent.prototype, "buttons", void 0); - - FooBarComponent = __decorate([ NotComponent() ], FooBarComponent); return FooBarComponent; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transformCore(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('__metadata', () => { - it('removes Angular decorators metadata', () => { - const output = tags.stripIndent` - import { Input, Output, EventEmitter, HostListener } from '@angular/core'; - var Clazz = (function () { - function Clazz() { - this.change = new EventEmitter(); - } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Input, Output, EventEmitter, HostListener } from '@angular/core'; - import { NotInput } from 'another-lib'; - var Clazz = (function () { - function Clazz() { - this.change = new EventEmitter(); - } - __decorate([ - Input(), - __metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - __decorate([ - Output(), - __metadata("design:type", Object) - ], Clazz.prototype, "change", void 0); - __decorate([ - HostListener('document:keydown.escape'), - __metadata("design:type", Function), - __metadata("design:paramtypes", []), - __metadata("design:returntype", void 0) - ], Clazz.prototype, "onKeyDown", null); - return Clazz; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes only Angular decorator metadata', () => { - const output = tags.stripIndent` - import { Input } from '@angular/core'; - import { NotInput } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - __decorate([ - NotInput(), - __metadata("design:type", Object) - ], Clazz.prototype, "other", void 0); - Clazz.prototype.myMethod = function () { return 'bar'; }; - __decorate([ - myDecorator(), - __metadata("design:type", Function), - __metadata("design:paramtypes", []), - __metadata("design:returntype", void 0) - ], MyClass.prototype, "myMethod", null); - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Input } from '@angular/core'; - import { NotInput } from 'another-lib'; - var Clazz = (function () { - function Clazz() { } - __decorate([ - Input(), - __metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - __decorate([ - NotInput(), - __metadata("design:type", Object) - ], Clazz.prototype, "other", void 0); - Clazz.prototype.myMethod = function () { return 'bar'; }; - __decorate([ - myDecorator(), - __metadata("design:type", Function), - __metadata("design:paramtypes", []), - __metadata("design:returntype", void 0) - ], MyClass.prototype, "myMethod", null); - return Clazz; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('recognizes tslib as well', () => { - const input = tags.stripIndent` - import * as tslib from "tslib"; - import * as tslib_2 from "tslib"; - import { Input } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - tslib.__decorate([ - Input(), - tslib.__metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - return Clazz; - }()); - - var Clazz2 = (function () { - function Clazz2() { } - tslib_2.__decorate([ - Input(), - tslib_2.__metadata("design:type", Object) - ], Clazz.prototype, "selected", void 0); - return Clazz2; - }()); - `; - const output = tags.stripIndent` - import * as tslib from "tslib"; - import * as tslib_2 from "tslib"; - import { Input } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - - var Clazz2 = (function () { - function Clazz2() { } - return Clazz2; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('__param', () => { - it('removes all constructor parameters and their type metadata', () => { - const output = tags.stripIndent` - var MyClass = /** @class */ (function () { - function MyClass(myParam) { - this.myProp = 'foo'; - } - MyClass = __decorate([ - myDecorator() - ], MyClass); - return MyClass; - }()); - `; - const input = tags.stripIndent` - var MyClass = /** @class */ (function () { - function MyClass(myParam) { - this.myProp = 'foo'; - } - MyClass = __decorate([ - myDecorator(), - __param(0, myDecorator()), - __metadata("design:paramtypes", [Number]) - ], MyClass); - return MyClass; - }()); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('propDecorators', () => { - it('removes top-level Angular propDecorators', () => { - const output = tags.stripIndent` - import { Input } from '@angular/core'; - ${clazz} - `; - const input = tags.stripIndent` - ${output} - Clazz.propDecorators = { 'ngIf': [{ type: Input }] } - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes nested Angular propDecorators', () => { - const output = tags.stripIndent` - import { Input } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Input } from '@angular/core'; - var Clazz = (function () { - function Clazz() {} - Clazz.propDecorators = { 'ngIf': [{ type: Input }] }; - return Clazz; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('doesn\'t remove non Angular propDecorators', () => { - const input = tags.stripIndent` - import { Input } from 'another-lib'; - ${clazz} - Clazz.propDecorators = { 'ngIf': [{ type: Input }] }; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`); - }); - - it('leaves non-Angular propDecorators in mixed arrays', () => { - const output = tags.stripIndent` - import { Input } from '@angular/core'; - import { NotInput } from 'another-lib'; - ${clazz} - Clazz.propDecorators = { - 'notNgIf': [{ type: NotInput }] - }; - `; - const input = tags.stripIndent` - import { Input } from '@angular/core'; - import { NotInput } from 'another-lib'; - ${clazz} - Clazz.propDecorators = { - 'ngIf': [{ type: Input }], - 'notNgIf': [{ type: NotInput }] - }; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('ctorParameters', () => { - it('removes empty constructor parameters', () => { - const output = tags.stripIndent` - ${clazz} - `; - const input = tags.stripIndent` - ${output} - Clazz.ctorParameters = function () { return []; }; - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes non-empty top-level style constructor parameters', () => { - const output = tags.stripIndent` - ${clazz} - `; - const input = tags.stripIndent` - ${clazz} - Clazz.ctorParameters = function () { return [{type: Injector}]; }; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - - it('removes top-level Angular constructor parameters in es2015', () => { - const output = tags.stripIndent` - class Clazz extends BaseClazz { constructor(e) { super(e); } } - `; - const input = tags.stripIndent` - ${output} - Clazz.ctorParameters = () => [ { type: Injectable } ]; - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes nested constructor parameters', () => { - const output = tags.stripIndent` - import { Injector } from '@angular/core'; - var Clazz = (function () { - function Clazz() { } - return Clazz; - }()); - `; - const input = tags.stripIndent` - import { Injector } from '@angular/core'; - var Clazz = (function () { - function Clazz() {} - Clazz.ctorParameters = function () { return [{type: Injector}]; }; - return Clazz; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('Ivy', () => { - it('removes ɵsetClassMetadata call', () => { - const output = tags.stripIndent` - import { Component } from '@angular/core'; - ${clazz} - `; - const input = tags.stripIndent` - ${output} - /*@__PURE__*/ i0.ɵsetClassMetadata(Clazz, [{ - type: Component, - args: [{ - selector: 'app-lazy', - template: 'very lazy', - styles: [] - }] - }], null, null); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('removes ɵɵsetNgModuleScope call', () => { - const output = tags.stripIndent` - import { CommonModule } from '@angular/common'; - import * as i0 from "@angular/core"; - ${clazz} - `; - const input = tags.stripIndent` - ${output} - /*@__PURE__*/ i0.ɵɵsetNgModuleScope(Clazz, { declarations: [], imports: [CommonModule] }); - `; - - expect(testScrubFile(input)).toBeTruthy(); - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); -}); diff --git a/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums.ts b/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums.ts deleted file mode 100644 index d1f315431649..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums.ts +++ /dev/null @@ -1,523 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as ts from 'typescript'; -import { addPureComment } from '../helpers/ast-utils'; - -function isBlockLike(node: ts.Node): node is ts.BlockLike { - return node.kind === ts.SyntaxKind.Block - || node.kind === ts.SyntaxKind.ModuleBlock - || node.kind === ts.SyntaxKind.CaseClause - || node.kind === ts.SyntaxKind.DefaultClause - || node.kind === ts.SyntaxKind.SourceFile; -} - -export function getWrapEnumsTransformer(): ts.TransformerFactory { - return (context: ts.TransformationContext): ts.Transformer => { - const transformer: ts.Transformer = sf => { - const result = visitBlockStatements(sf.statements, context); - - return ts.updateSourceFileNode(sf, ts.setTextRange(result, sf.statements)); - }; - - return transformer; - }; -} - -function visitBlockStatements( - statements: ts.NodeArray, - context: ts.TransformationContext, -): ts.NodeArray { - - // copy of statements to modify; lazy initialized - let updatedStatements: Array | undefined; - - const visitor: ts.Visitor = (node) => { - if (isBlockLike(node)) { - let result = visitBlockStatements(node.statements, context); - if (result === node.statements) { - return node; - } - result = ts.setTextRange(result, node.statements); - switch (node.kind) { - case ts.SyntaxKind.Block: - return ts.updateBlock(node, result); - case ts.SyntaxKind.ModuleBlock: - return ts.updateModuleBlock(node, result); - case ts.SyntaxKind.CaseClause: - return ts.updateCaseClause(node, node.expression, result); - case ts.SyntaxKind.DefaultClause: - return ts.updateDefaultClause(node, result); - default: - return node; - } - } else { - return node; - } - }; - - // 'oIndex' is the original statement index; 'uIndex' is the updated statement index - for (let oIndex = 0, uIndex = 0; oIndex < statements.length - 1; oIndex++, uIndex++) { - const currentStatement = statements[oIndex]; - let newStatement: ts.Statement[] | undefined; - let oldStatementsLength = 0; - - // these can't contain an enum declaration - if (currentStatement.kind === ts.SyntaxKind.ImportDeclaration) { - continue; - } - - // enum declarations must: - // * not be last statement - // * be a variable statement - // * have only one declaration - // * have an identifer as a declaration name - - // ClassExpression declarations must: - // * not be last statement - // * be a variable statement - // * have only one declaration - // * have an ClassExpression or BinaryExpression and a right - // of kind ClassExpression as a initializer - if (ts.isVariableStatement(currentStatement) - && currentStatement.declarationList.declarations.length === 1) { - - const variableDeclaration = currentStatement.declarationList.declarations[0]; - const initializer = variableDeclaration.initializer; - if (ts.isIdentifier(variableDeclaration.name)) { - const name = variableDeclaration.name.text; - - if (!initializer) { - const iife = findTs2_3EnumIife(name, statements[oIndex + 1]); - if (iife) { - // update IIFE and replace variable statement and old IIFE - oldStatementsLength = 2; - newStatement = updateEnumIife( - currentStatement, - iife[0], - iife[1], - ); - // skip IIFE statement - oIndex++; - } - } else if (ts.isObjectLiteralExpression(initializer)) { - // tsickle es2015 enums first statement is an export declaration - const isPotentialEnumExport = ts.isExportDeclaration(statements[oIndex + 1]); - if (isPotentialEnumExport) { - // skip the export - oIndex++; - } - - const enumStatements = findStatements(name, statements, oIndex, 1); - if (!enumStatements) { - continue; - } - - // create wrapper and replace variable statement and enum member statements - oldStatementsLength = enumStatements.length + (isPotentialEnumExport ? 2 : 1); - newStatement = createWrappedEnum( - name, - currentStatement, - enumStatements, - initializer, - isPotentialEnumExport, - ); - // skip enum member declarations - oIndex += enumStatements.length; - } else if ( - ts.isClassExpression(initializer) - || ( - ts.isBinaryExpression(initializer) - && ts.isClassExpression(initializer.right) - ) - ) { - const classStatements = findStatements(name, statements, oIndex); - if (!classStatements) { - continue; - } - - oldStatementsLength = classStatements.length; - newStatement = createWrappedClass( - variableDeclaration, - classStatements, - ); - - oIndex += classStatements.length - 1; - } - } - } else if (ts.isClassDeclaration(currentStatement)) { - const name = (currentStatement.name as ts.Identifier).text; - const classStatements = findStatements(name, statements, oIndex); - if (!classStatements) { - continue; - } - - oldStatementsLength = classStatements.length; - newStatement = createWrappedClass( - currentStatement, - classStatements, - ); - - oIndex += classStatements.length - 1; - } - - if (newStatement && newStatement.length > 0) { - if (!updatedStatements) { - updatedStatements = [...statements]; - } - - updatedStatements.splice(uIndex, oldStatementsLength, ...newStatement); - // When having more than a single new statement - // we need to update the update Index - uIndex += (newStatement ? newStatement.length - 1 : 0); - } - - const result = ts.visitNode(currentStatement, visitor); - if (result !== currentStatement) { - if (!updatedStatements) { - updatedStatements = statements.slice(); - } - updatedStatements[uIndex] = result; - } - } - - // if changes, return updated statements - // otherwise, return original array instance - return updatedStatements ? ts.createNodeArray(updatedStatements) : statements; -} - -// TS 2.3 enums have statements that are inside a IIFE. -function findTs2_3EnumIife( - name: string, - statement: ts.Statement, -): [ts.CallExpression, ts.Expression | undefined] | null { - if (!ts.isExpressionStatement(statement)) { - return null; - } - - const expression = statement.expression; - if (!expression || !ts.isCallExpression(expression) || expression.arguments.length !== 1) { - return null; - } - - const callExpression = expression; - let exportExpression: ts.Expression | undefined; - - if (!ts.isParenthesizedExpression(callExpression.expression)) { - return null; - } - - const functionExpression = callExpression.expression.expression; - if (!ts.isFunctionExpression(functionExpression)) { - return null; - } - - // The name of the parameter can be different than the name of the enum if it was renamed - // due to scope hoisting. - const parameter = functionExpression.parameters[0]; - if (!ts.isIdentifier(parameter.name)) { - return null; - } - const parameterName = parameter.name.text; - - let argument = callExpression.arguments[0]; - if ( - !ts.isBinaryExpression(argument) - || !ts.isIdentifier(argument.left) - || argument.left.text !== name - ) { - return null; - } - - let potentialExport = false; - if (argument.operatorToken.kind === ts.SyntaxKind.FirstAssignment) { - if (ts.isBinaryExpression(argument.right) && argument.right.operatorToken.kind !== ts.SyntaxKind.BarBarToken) { - return null; - } - - potentialExport = true; - argument = argument.right; - } - - if (!ts.isBinaryExpression(argument)) { - return null; - } - - if (argument.operatorToken.kind !== ts.SyntaxKind.BarBarToken) { - return null; - } - - if (potentialExport && !ts.isIdentifier(argument.left)) { - exportExpression = argument.left; - } - - // Go through all the statements and check that all match the name - for (const statement of functionExpression.body.statements) { - if ( - !ts.isExpressionStatement(statement) - || !ts.isBinaryExpression(statement.expression) - || !ts.isElementAccessExpression(statement.expression.left) - ) { - return null; - } - - const leftExpression = statement.expression.left.expression; - if (!ts.isIdentifier(leftExpression) || leftExpression.text !== parameterName) { - return null; - } - } - - return [callExpression, exportExpression]; -} - -function updateHostNode( - hostNode: ts.VariableStatement, - expression: ts.Expression, -): ts.Statement { - // Update existing host node with the pure comment before the variable declaration initializer. - const variableDeclaration = hostNode.declarationList.declarations[0]; - const outerVarStmt = ts.updateVariableStatement( - hostNode, - hostNode.modifiers, - ts.updateVariableDeclarationList( - hostNode.declarationList, - [ - ts.updateVariableDeclaration( - variableDeclaration, - variableDeclaration.name, - variableDeclaration.type, - expression, - ), - ], - ), - ); - - return outerVarStmt; -} - -/** - * Find enums, class expression or declaration statements. - * - * The classExpressions block to wrap in an iife must - * - end with an ExpressionStatement - * - it's expression must be a BinaryExpression - * - have the same name - * - * ``` - let Foo = class Foo {}; - Foo = __decorate([]); - ``` - */ -function findStatements( - name: string, - statements: ts.NodeArray, - statementIndex: number, - offset = 0, -): ts.Statement[] | undefined { - let count = 1; - - for (let index = statementIndex + 1; index < statements.length; ++index) { - const statement = statements[index]; - if (!ts.isExpressionStatement(statement)) { - break; - } - - const expression = statement.expression; - - if (ts.isCallExpression(expression)) { - // Ex: - // setClassMetadata(FooClass, [{}], void 0); - // __decorate([propDecorator()], FooClass.prototype, "propertyName", void 0); - // __decorate([propDecorator()], FooClass, "propertyName", void 0); - // __decorate$1([propDecorator()], FooClass, "propertyName", void 0); - const args = expression.arguments; - - if (args.length > 2) { - const isReferenced = args.some(arg => { - const potentialIdentifier = ts.isPropertyAccessExpression(arg) ? arg.expression : arg; - - return ts.isIdentifier(potentialIdentifier) && potentialIdentifier.text === name; - }); - - if (isReferenced) { - count++; - continue; - } - } - } else if (ts.isBinaryExpression(expression)) { - const node = ts.isBinaryExpression(expression.left) - ? expression.left.left - : expression.left; - - const leftExpression = ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - // Static Properties // Ex: Foo.bar = 'value'; - // ENUM Property // Ex: ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = "Default"; - ? node.expression - // Ex: FooClass = __decorate([Component()], FooClass); - : node; - - if (ts.isIdentifier(leftExpression) && leftExpression.text === name) { - count++; - continue; - } - } - - break; - } - - if (count > 1) { - return statements.slice(statementIndex + offset, statementIndex + count); - } - - return undefined; -} - -function updateEnumIife( - hostNode: ts.VariableStatement, - iife: ts.CallExpression, - exportAssignment?: ts.Expression, -): ts.Statement[] { - if (!ts.isParenthesizedExpression(iife.expression) - || !ts.isFunctionExpression(iife.expression.expression)) { - throw new Error('Invalid IIFE Structure'); - } - - // Ignore export assignment if variable is directly exported - if (hostNode.modifiers - && hostNode.modifiers.findIndex(m => m.kind == ts.SyntaxKind.ExportKeyword) != -1) { - exportAssignment = undefined; - } - - const expression = iife.expression.expression; - const updatedFunction = ts.updateFunctionExpression( - expression, - expression.modifiers, - expression.asteriskToken, - expression.name, - expression.typeParameters, - expression.parameters, - expression.type, - ts.updateBlock( - expression.body, - [ - ...expression.body.statements, - ts.createReturn(expression.parameters[0].name as ts.Identifier), - ], - ), - ); - - let arg: ts.Expression = ts.createObjectLiteral(); - if (exportAssignment) { - arg = ts.createBinary(exportAssignment, ts.SyntaxKind.BarBarToken, arg); - } - const updatedIife = ts.updateCall( - iife, - ts.updateParen( - iife.expression, - updatedFunction, - ), - iife.typeArguments, - [arg], - ); - - let value: ts.Expression = addPureComment(updatedIife); - if (exportAssignment) { - value = ts.createBinary( - exportAssignment, - ts.SyntaxKind.FirstAssignment, - updatedIife); - } - - return [updateHostNode(hostNode, value)]; -} - -function createWrappedEnum( - name: string, - hostNode: ts.VariableStatement, - statements: Array, - literalInitializer: ts.ObjectLiteralExpression = ts.createObjectLiteral(), - addExportModifier = false, -): ts.Statement[] { - const node = addExportModifier - ? ts.updateVariableStatement( - hostNode, - [ts.createToken(ts.SyntaxKind.ExportKeyword)], - hostNode.declarationList, - ) - : hostNode; - - const innerVarStmt = ts.createVariableStatement( - undefined, - ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, undefined, literalInitializer), - ]), - ); - - const innerReturn = ts.createReturn(ts.createIdentifier(name)); - - const iife = ts.createImmediatelyInvokedFunctionExpression([ - innerVarStmt, - ...statements, - innerReturn, - ]); - - return [updateHostNode(node, addPureComment(ts.createParen(iife)))]; -} - -function createWrappedClass( - hostNode: ts.ClassDeclaration | ts.VariableDeclaration, - statements: ts.Statement[], -): ts.Statement[] { - const name = (hostNode.name as ts.Identifier).text; - - const updatedStatements = [...statements]; - - if (ts.isClassDeclaration(hostNode)) { - updatedStatements[0] = ts.createClassDeclaration( - hostNode.decorators, - undefined, - hostNode.name, - hostNode.typeParameters, - hostNode.heritageClauses, - hostNode.members, - ); - } - - const pureIife = addPureComment( - ts.createImmediatelyInvokedArrowFunction([ - ...updatedStatements, - ts.createReturn(ts.createIdentifier(name)), - ]), - ); - - const modifiers = hostNode.modifiers; - const isDefault = !!modifiers - && modifiers.some(x => x.kind === ts.SyntaxKind.DefaultKeyword); - - const newStatement: ts.Statement[] = []; - newStatement.push( - ts.createVariableStatement( - isDefault ? undefined : modifiers, - ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, undefined, pureIife), - ], - ts.NodeFlags.Let, - ), - )); - - if (isDefault) { - newStatement.push( - ts.createExportAssignment( - undefined, - undefined, - false, - ts.createIdentifier(name), - )); - } - - return newStatement; -} diff --git a/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums_spec.ts b/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums_spec.ts deleted file mode 100644 index 98c57053a8ac..000000000000 --- a/packages/angular_devkit/build_optimizer/src/transforms/wrap-enums_spec.ts +++ /dev/null @@ -1,768 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable-next-line:no-implicit-dependencies -import { tags } from '@angular-devkit/core'; -import { transformJavascript } from '../helpers/transform-javascript'; -import { getWrapEnumsTransformer } from './wrap-enums'; - - -const transform = (content: string) => transformJavascript( - { content, getTransforms: [getWrapEnumsTransformer] }).content; - -// tslint:disable:no-big-function -describe('wrap enums and classes transformer', () => { - describe('wraps class declarations', () => { - it('should wrap default exported classes', () => { - const defaultClass = tags.stripIndent` - export default class CustomComponentEffects { - constructor(_actions) { - this._actions = _actions; - this.doThis = this._actions; - } - } - CustomComponentEffects.decorators = [{ type: Injectable }]; - `; - - const namedClass = tags.stripIndent` - class CustomComponent { - constructor(_actions) { - this._actions = _actions; - this.doThis = this._actions; - } - } - CustomComponent.decorators = [{ type: Injectable }]; - `; - - const output = tags.stripIndent` - let CustomComponentEffects = /*@__PURE__*/ (() => { - ${defaultClass.replace('export default ', '')} - - return CustomComponentEffects; - })(); - export default CustomComponentEffects; - - let CustomComponent = /*@__PURE__*/ (() => { - ${namedClass} - - return CustomComponent; - })(); - `; - - const input = defaultClass + namedClass; - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should wrap tsickle emitted classes which followed by metadata', () => { - const input = tags.stripIndent` - class CustomComponentEffects { - constructor(_actions) { - this._actions = _actions; - this.doThis = this._actions; - } - } - CustomComponentEffects.decorators = [{ type: Injectable }]; - CustomComponentEffects.ctorParameters = () => [{ type: Actions }]; - tslib_1.__decorate([ - Effect(), - tslib_1.__metadata("design:type", Object) - ], CustomComponentEffects.prototype, "doThis", void 0); - tslib_1.__decorate([ - Effect({ dispatch: false }), - tslib_1.__metadata("design:type", Object) - ], CustomComponentEffects.prototype, "doThat", void 0); - `; - - const output = tags.stripIndent` - let CustomComponentEffects = /*@__PURE__*/ (() => { - ${input} - - return CustomComponentEffects; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should not wrap enum like which are inside of methods', () => { - const input = tags.stripIndent` - class LayoutDirective { - constructor(elRef) { } - - applyStyleToElement(element, style, value) { - let styles = {}; - if (typeof style === 'string') { - styles[style] = value; - style = styles; - } - styles = this.layoutConfig.disableVendorPrefixes ? style : applyCssPrefixes(style); - this._applyMultiValueStyleToElement(styles, element); - } - } - LayoutDirective.ctorParameters = () => [ - { type: ElementRef } - ]; - `; - - const output = tags.stripIndent` - let LayoutDirective = /*@__PURE__*/ (() => { - ${input} - - return LayoutDirective; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should ClassDeclarations that are referenced with in CallExpressions', () => { - const input = tags.stripIndent` - class ApplicationModule { - constructor(appRef) { } - } - ApplicationModule.ɵmod = ɵɵdefineNgModule({ type: ApplicationModule }); - /*@__PURE__*/ setClassMetadata(ApplicationModule, [{ - type: NgModule, - args: [{ providers: APPLICATION_MODULE_PROVIDERS }] - }], function () { return [{ type: ApplicationRef }]; }, { constructor: [] }); - ApplicationModule.ctorParameters = () => [ - { type: ApplicationRef } - ]; - `; - - const output = tags.stripIndent` - let ApplicationModule = /*@__PURE__*/ (() => { - ${input} - - return ApplicationModule; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('with nested static properties in IIFE', () => { - const input = tags.stripIndent` - class CommonModule { } - CommonModule.ɵmod = defineNgModule({ - type: CommonModule - }), CommonModule.ngInjectorDef = defineInjector({ - factory: function (t) { - return new (t || CommonModule)(); - }, - providers: [{ - provide: NgLocalization, - useClass: NgLocaleLocalization - }] - }); - `; - - const output = tags.stripIndent` - let CommonModule = /*@__PURE__*/ (() => { - ${input} - - return CommonModule; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('with property decorators in IIFE', () => { - const input = tags.stripIndent` - export class Foo { - method() { - } - } - Foo.bar = 'barValue'; - __decorate([ - methodDecorator - ], Foo.prototype, "method", null); - `; - - const output = tags.stripIndent` - export let Foo = /*@__PURE__*/ (() => { - ${input.replace('export ', '')} - - return Foo; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('folds static properties in IIFE', () => { - const input = tags.stripIndent` - export class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - `; - const output = tags.stripIndent` - export let TemplateRef = /*@__PURE__*/ (() => { - class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - return TemplateRef; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('folds multiple static properties into class', () => { - const input = tags.stripIndent` - export class TemplateRef { } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - TemplateRef.somethingElse = true; - `; - const output = tags.stripIndent` - export let TemplateRef = /*@__PURE__*/ (() => { - class TemplateRef { - } - TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef); - TemplateRef.somethingElse = true; - return TemplateRef; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it(`doesn't wrap classes without static properties in IIFE`, () => { - const input = tags.stripIndent` - export class TemplateRef { } - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`); - }); - }); - - describe('wrap class expressions', () => { - it('should wrap default exported classes', () => { - const defaultClass = tags.stripIndent` - let Foo = class Foo { - }; - Foo.bar = 'bar'; - Foo = __decorate([ - component() - ], Foo); - export default Foo; - `; - - const namedClass = tags.stripIndent` - let AggregateColumnDirective = class AggregateColumnDirective { - constructor(viewContainerRef) { } - }; - AggregateColumnDirective = __decorate([ - Directive({}), - __metadata("design:paramtypes", [ViewContainerRef]) - ], AggregateColumnDirective); - `; - - const output = tags.stripIndent` - let Foo = /*@__PURE__*/ (() => { - ${defaultClass.replace('export default Foo;', '')} - - return Foo; - })(); - export default Foo; - - let AggregateColumnDirective = /*@__PURE__*/ (() => { - ${namedClass} - - return AggregateColumnDirective; - })(); - `; - - const input = defaultClass + namedClass; - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('without property decorators in IIFE', () => { - const input = tags.stripIndent` - let AggregateColumnDirective = class AggregateColumnDirective { - constructor(viewContainerRef) { } - }; - AggregateColumnDirective = __decorate([ - Directive({}), - __metadata("design:paramtypes", [ViewContainerRef]) - ], AggregateColumnDirective); - `; - - const output = tags.stripIndent` - let AggregateColumnDirective = /*@__PURE__*/ (() => { - ${input} - - return AggregateColumnDirective; - })(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('with forwardRef in IIFE', () => { - const classContent = tags.stripIndent` - let FooDirective = FooDirective_1 = class FooDirective { - constructor(parent) { } - }; - FooDirective = FooDirective_1 = __decorate([ - Directive({ - selector: '[libUnshakeable2]', - }), - __param(0, SkipSelf()), __param(0, Inject(forwardRef(() => FooDirective_1))), - __metadata("design:paramtypes", [FooDirective]) - ], FooDirective); - `; - - const input = tags.stripIndent` - var FooDirective_1; - ${classContent} - export { FooDirective }; - `; - - const output = tags.stripIndent` - var FooDirective_1; - let FooDirective = /*@__PURE__*/ (() => { - ${classContent} - - return FooDirective; - })(); - export { FooDirective }; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('with property decorators in IIFE', () => { - const input = tags.stripIndent` - let ChipList = class ChipList extends Component { - constructor(options, element) { - super(options, element); - } - }; - __decorate$4([Property([])], ChipList.prototype, "chips", void 0); - ChipList = __decorate$4([NotifyPropertyChanges], ChipList); - `; - - const output = tags.stripIndent` - let ChipList = /*@__PURE__*/ (() => { - ${input} - return ChipList; - })();`; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should not wrap without decorators', () => { - const input = tags.stripIndent` - let ChipList = class ChipList extends Component { - constructor(options, element) { - super(options, element); - } - }; - fooBar(); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`); - }); - - it('should wrap ClassExpression with property decorators and static property in IIFE', () => { - const input = tags.stripIndent` - let ChipList = class ChipList extends Component { - constructor(options, element) { - super(options, element); - } - }; - ChipList.prop = 1; - __decorate$4([Property([])], ChipList.prototype, "chips", void 0); - ChipList = __decorate$4([NotifyPropertyChanges], ChipList);`; - - const output = tags.stripIndent` - let ChipList = /*@__PURE__*/ (() => { - ${input} - return ChipList; - })();`; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should wrap multiple ClassExpression in IIFE', () => { - const firstClass = ` - let AggregateColumnDirective = class AggregateColumnDirective { - constructor(viewContainerRef) { } - }; - AggregateColumnDirective = __decorate([ - Directive({}), - __metadata("design:paramtypes", [ViewContainerRef]) - ], AggregateColumnDirective); - `; - - const secondClass = ` - let ChipList = class ChipList extends Component { - constructor(options, element) { - super(options, element); - } - }; - __decorate$4([Property([])], ChipList.prototype, "chips", void 0); - ChipList = __decorate$4([NotifyPropertyChanges], ChipList); - `; - - const input = tags.stripIndent` - const minutesMilliSeconds = 60000; - - ${firstClass} - - const CSS = 'e-css'; - const PRIMARY = 'e-primary'; - - ${secondClass} - - const chipList = new ChipList({}, {}); - `; - - const output = tags.stripIndent` - const minutesMilliSeconds = 60000; - - let AggregateColumnDirective = /*@__PURE__*/ (() => { - ${firstClass} - - return AggregateColumnDirective; - })(); - - const CSS = 'e-css'; - const PRIMARY = 'e-primary'; - - let ChipList = /*@__PURE__*/ (() => { - ${secondClass} - - return ChipList; - })(); - - const chipList = new ChipList({}, {}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); - - describe('wrap enums', () => { - it('wraps ts 2.2 enums in IIFE', () => { - const input = tags.stripIndent` - export var ChangeDetectionStrategy = {}; - ChangeDetectionStrategy.OnPush = 0; - ChangeDetectionStrategy.Default = 1; - ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = "Default"; - `; - const output = tags.stripIndent` - export var ChangeDetectionStrategy = /*@__PURE__*/ (function () { - var ChangeDetectionStrategy = {}; - ChangeDetectionStrategy.OnPush = 0; - ChangeDetectionStrategy.Default = 1; - ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = "Default"; - return ChangeDetectionStrategy; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('should not wrap enum like object literal declarations', () => { - const input = tags.stripIndent` - const RendererStyleFlags3 = { - Important: 1, - DashCase: 2, - }; - if (typeof RendererStyleFlags3 === 'object') { - RendererStyleFlags3[RendererStyleFlags3.Important] = 'DashCase'; - } - RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important'; - `; - const output = input; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps ES2015 tsickle enums in IIFE', () => { - const input = tags.stripIndent` - const ChangeDetectionStrategy = { - OnPush: 0, - Default: 1, - }; - export { ChangeDetectionStrategy }; - ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = 'OnPush'; - ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = 'Default'; - `; - - const output = tags.stripIndent` - export const ChangeDetectionStrategy = /*@__PURE__*/ (function () { - var ChangeDetectionStrategy = { OnPush: 0, Default: 1, }; - - ChangeDetectionStrategy[ChangeDetectionStrategy.OnPush] = 'OnPush'; - ChangeDetectionStrategy[ChangeDetectionStrategy.Default] = 'Default'; - return ChangeDetectionStrategy; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps only ES2015 tsickle enums in IIFE', () => { - const input = tags.stripIndent` - const RendererStyleFlags3 = { - Important: 1, - DashCase: 2, - }; - export { RendererStyleFlags3 }; - RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important'; - RendererStyleFlags3[RendererStyleFlags3.DashCase] = 'DashCase'; - - export const domRendererFactory3 = { - createRenderer: (hostElement, rendererType) => { return document; } - }; - - export const unusedValueExportToPlacateAjd = 1; - `; - const output = tags.stripIndent` - export const RendererStyleFlags3 = /*@__PURE__*/ (function () { - var RendererStyleFlags3 = { Important: 1, DashCase: 2, }; - RendererStyleFlags3[RendererStyleFlags3.Important] = 'Important'; - RendererStyleFlags3[RendererStyleFlags3.DashCase] = 'DashCase'; - return RendererStyleFlags3; - }()); - - export const domRendererFactory3 = { - createRenderer: (hostElement, rendererType) => { return document; } - }; - - export const unusedValueExportToPlacateAjd = 1; - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps ts >2.3 enums in IIFE', () => { - const input = tags.stripIndent` - export var ChangeDetectionStrategy; - (function (ChangeDetectionStrategy) { - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; - })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); - `; - const output = tags.stripIndent` - export var ChangeDetectionStrategy = /*@__PURE__*/ (function (ChangeDetectionStrategy) { - ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; - ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; - return ChangeDetectionStrategy; - })({}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps ts >2.3 enums in IIFE, even if they have funny numbers', () => { - const input = tags.stripIndent` - export var AnimatorControlState; - (function (AnimatorControlState) { - AnimatorControlState[AnimatorControlState["INITIALIZED"] = 1] = "INITIALIZED"; - AnimatorControlState[AnimatorControlState["STARTED"] = 2] = "STARTED"; - AnimatorControlState[AnimatorControlState["FINISHED"] = 3] = "FINISHED"; - AnimatorControlState[AnimatorControlState["DESTROYED"] = 4] = "DESTROYED"; - })(AnimatorControlState || (AnimatorControlState = {})); - `; - const output = tags.stripIndent` - export var AnimatorControlState = /*@__PURE__*/ (function (AnimatorControlState) { - AnimatorControlState[AnimatorControlState["INITIALIZED"] = 1] = "INITIALIZED"; - AnimatorControlState[AnimatorControlState["STARTED"] = 2] = "STARTED"; - AnimatorControlState[AnimatorControlState["FINISHED"] = 3] = "FINISHED"; - AnimatorControlState[AnimatorControlState["DESTROYED"] = 4] = "DESTROYED"; - return AnimatorControlState; - })({}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps ts >2.3 enums in IIFE, even if they were renamed due to scope hoisting', () => { - const input = tags.stripIndent` - var TokenType$1; - (function (TokenType) { - TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START"; - TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END"; - TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID"; - TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE"; - TokenType[TokenType["TEXT"] = 4] = "TEXT"; - TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT"; - TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT"; - TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START"; - TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END"; - TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START"; - TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END"; - TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME"; - TokenType[TokenType["ATTR_VALUE"] = 12] = "ATTR_VALUE"; - TokenType[TokenType["DOC_TYPE"] = 13] = "DOC_TYPE"; - TokenType[TokenType["EXPANSION_FORM_START"] = 14] = "EXPANSION_FORM_START"; - TokenType[TokenType["EXPANSION_CASE_VALUE"] = 15] = "EXPANSION_CASE_VALUE"; - TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 16] = "EXPANSION_CASE_EXP_START"; - TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 17] = "EXPANSION_CASE_EXP_END"; - TokenType[TokenType["EXPANSION_FORM_END"] = 18] = "EXPANSION_FORM_END"; - TokenType[TokenType["EOF"] = 19] = "EOF"; - })(TokenType$1 || (TokenType$1 = {})); - `; - const output = tags.stripIndent` - var TokenType$1 = /*@__PURE__*/ (function (TokenType) { - TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START"; - TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END"; - TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID"; - TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE"; - TokenType[TokenType["TEXT"] = 4] = "TEXT"; - TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT"; - TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT"; - TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START"; - TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END"; - TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START"; - TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END"; - TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME"; - TokenType[TokenType["ATTR_VALUE"] = 12] = "ATTR_VALUE"; - TokenType[TokenType["DOC_TYPE"] = 13] = "DOC_TYPE"; - TokenType[TokenType["EXPANSION_FORM_START"] = 14] = "EXPANSION_FORM_START"; - TokenType[TokenType["EXPANSION_CASE_VALUE"] = 15] = "EXPANSION_CASE_VALUE"; - TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 16] = "EXPANSION_CASE_EXP_START"; - TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 17] = "EXPANSION_CASE_EXP_END"; - TokenType[TokenType["EXPANSION_FORM_END"] = 18] = "EXPANSION_FORM_END"; - TokenType[TokenType["EOF"] = 19] = "EOF"; - return TokenType; - })({}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps TS string enums in IIFE', () => { - const input = tags.stripIndent` - export var NotificationKind; - (function (NotificationKind) { - NotificationKind["NEXT"] = "N"; - NotificationKind["ERROR"] = "E"; - NotificationKind["COMPLETE"] = "C"; - })(NotificationKind || (NotificationKind = {})); - `; - const output = tags.stripIndent` - export var NotificationKind = /*@__PURE__*/ (function (NotificationKind) { - NotificationKind["NEXT"] = "N"; - NotificationKind["ERROR"] = "E"; - NotificationKind["COMPLETE"] = "C"; - return NotificationKind; - })({}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps tsickle enums in IIFE', () => { - const input = tags.stripIndent` - /** @enum {number} */ - var FormatWidth = { - Short: 0, - Medium: 1, - Long: 2, - Full: 3, - }; - FormatWidth[FormatWidth.Short] = "Short"; - FormatWidth[FormatWidth.Medium] = "Medium"; - FormatWidth[FormatWidth.Long] = "Long"; - FormatWidth[FormatWidth.Full] = "Full"; - `; - const output = tags.stripIndent` - /** @enum {number} */ var FormatWidth = /*@__PURE__*/ (function () { - var FormatWidth = { - Short: 0, - Medium: 1, - Long: 2, - Full: 3, - }; - FormatWidth[FormatWidth.Short] = "Short"; - FormatWidth[FormatWidth.Medium] = "Medium"; - FormatWidth[FormatWidth.Long] = "Long"; - FormatWidth[FormatWidth.Full] = "Full"; - return FormatWidth; - }()); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps enums with multi-line comments in IIFE', () => { - const input = tags.stripIndent` - /** - * Supported http methods. - * @deprecated use @angular/common/http instead - */ - var RequestMethod; - /** - * Supported http methods. - * @deprecated use @angular/common/http instead - */ - (function (RequestMethod) { - RequestMethod[RequestMethod["Get"] = 0] = "Get"; - RequestMethod[RequestMethod["Post"] = 1] = "Post"; - RequestMethod[RequestMethod["Put"] = 2] = "Put"; - RequestMethod[RequestMethod["Delete"] = 3] = "Delete"; - RequestMethod[RequestMethod["Options"] = 4] = "Options"; - RequestMethod[RequestMethod["Head"] = 5] = "Head"; - RequestMethod[RequestMethod["Patch"] = 6] = "Patch"; - })(RequestMethod || (RequestMethod = {})); - `; - // We need to interpolate this space because our editorconfig automatically strips - // trailing whitespace. - const space = ' '; - const output = tags.stripIndent` - /** - * Supported http methods. - * @deprecated use @angular/common/http instead - */ - var RequestMethod =${space} - /** - * Supported http methods. - * @deprecated use @angular/common/http instead - */ - /*@__PURE__*/ (function (RequestMethod) { - RequestMethod[RequestMethod["Get"] = 0] = "Get"; - RequestMethod[RequestMethod["Post"] = 1] = "Post"; - RequestMethod[RequestMethod["Put"] = 2] = "Put"; - RequestMethod[RequestMethod["Delete"] = 3] = "Delete"; - RequestMethod[RequestMethod["Options"] = 4] = "Options"; - RequestMethod[RequestMethod["Head"] = 5] = "Head"; - RequestMethod[RequestMethod["Patch"] = 6] = "Patch"; - return RequestMethod; - })({}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - - it('wraps exported enums in IIFE', () => { - const input = tags.stripIndent` - var ExportEnum; - (function (ExportEnum) { - ExportEnum[ExportEnum["A"] = 0] = "A"; - ExportEnum[ExportEnum["B"] = 1] = "B"; - ExportEnum[ExportEnum["C"] = 2] = "C"; - })(ExportEnum = exports.ExportEnum || (exports.ExportEnum = {})); - `; - const output = tags.stripIndent` - var ExportEnum = exports.ExportEnum = /*@__PURE__*/ (function (ExportEnum) { - ExportEnum[ExportEnum["A"] = 0] = "A"; - ExportEnum[ExportEnum["B"] = 1] = "B"; - ExportEnum[ExportEnum["C"] = 2] = "C"; - return ExportEnum; - })(exports.ExportEnum || {}); - `; - - expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${output}`); - }); - }); -}); diff --git a/packages/angular_devkit/build_optimizer/webpack-loader/package.json b/packages/angular_devkit/build_optimizer/webpack-loader/package.json deleted file mode 100644 index a18ef898c128..000000000000 --- a/packages/angular_devkit/build_optimizer/webpack-loader/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "main": "../src/build-optimizer/webpack-loader.js" -} diff --git a/packages/angular_devkit/build_webpack/BUILD.bazel b/packages/angular_devkit/build_webpack/BUILD.bazel new file mode 100644 index 000000000000..10b435d66e06 --- /dev/null +++ b/packages/angular_devkit/build_webpack/BUILD.bazel @@ -0,0 +1,127 @@ +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license + +load("@devinfra//bazel/api-golden:index.bzl", "api_golden_test_npm_package") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defaults.bzl", "jasmine_test", "npm_package", "ts_project") +load("//tools:ts_json_schema.bzl", "ts_json_schema") + +licenses(["notice"]) + +package(default_visibility = ["//visibility:public"]) + +npm_link_all_packages() + +ts_json_schema( + name = "webpack_schema", + src = "src/builders/webpack/schema.json", +) + +ts_json_schema( + name = "webpack_dev_server_schema", + src = "src/builders/webpack-dev-server/schema.json", +) + +RUNTIME_ASSETS = [ + "builders.json", + "package.json", + "src/builders/webpack-dev-server/schema.json", + "src/builders/webpack/schema.json", +] + +ts_project( + name = "build_webpack", + srcs = glob( + include = ["src/**/*.ts"], + exclude = [ + "src/test-utils.ts", + "**/*_spec.ts", + ], + ) + [ + "index.ts", + "//packages/angular_devkit/build_webpack:src/builders/webpack-dev-server/schema.ts", + "//packages/angular_devkit/build_webpack:src/builders/webpack/schema.ts", + ], + data = RUNTIME_ASSETS, + deps = [ + ":node_modules/@angular-devkit/architect", + ":node_modules/rxjs", + ":node_modules/webpack", + ":node_modules/webpack-dev-server", + "//:node_modules/@types/node", + ], +) + +ts_project( + name = "build_webpack_test_lib", + testonly = True, + srcs = glob( + include = [ + "src/**/*_spec.ts", + ], + ), + data = glob( + include = [ + "test/**/*", + ], + ), + deps = [ + ":build_webpack", + ":node_modules/@angular-devkit/architect", + ":node_modules/@angular-devkit/core", + ":node_modules/@ngtools/webpack", + "//:node_modules/@types/jasmine", + "//:node_modules/@types/node", + ], +) + +jasmine_test( + name = "build_webpack_test", + data = [ + "build_webpack_test_lib", + "//:node_modules/@angular/common", + "//:node_modules/@angular/compiler", + "//:node_modules/@angular/compiler-cli", + "//:node_modules/@angular/core", + "//:node_modules/@angular/platform-browser", + "//:node_modules/tslib", + "//:node_modules/typescript", + "//:node_modules/zone.js", + ], + env = { + # Force IPv4 to resolve RBE resolution issues + "NODE_OPTIONS": "--dns-result-order=ipv4first", + }, +) + +genrule( + name = "license", + srcs = ["//:LICENSE"], + outs = ["LICENSE"], + cmd = "cp $(execpath //:LICENSE) $@", +) + +npm_package( + name = "pkg", + pkg_deps = [ + "//packages/angular_devkit/architect:package.json", + ], + tags = ["release-package"], + deps = RUNTIME_ASSETS + [ + ":README.md", + ":build_webpack", + ":license", + ], +) + +api_golden_test_npm_package( + name = "build_webpack_api", + data = [ + ":npm_package", + "//goldens:public-api", + ], + golden_dir = "goldens/public-api/angular_devkit/build_webpack", + npm_package = "packages/angular_devkit/build_webpack/npm_package", +) diff --git a/packages/angular_devkit/build_webpack/README.md b/packages/angular_devkit/build_webpack/README.md index 49e19302d939..2663efe82dae 100644 --- a/packages/angular_devkit/build_webpack/README.md +++ b/packages/angular_devkit/build_webpack/README.md @@ -7,6 +7,7 @@ To use it on your Angular CLI app, follow these steps: - run `npm install @angular-devkit/build-webpack`. - create a webpack configuration. - add the following targets inside `angular.json`. + ``` "projects": { "app": { @@ -27,6 +28,7 @@ To use it on your Angular CLI app, follow these steps: } } ``` + - run `ng run app:build-webpack` to build, and `ng run app:serve-webpack` to serve. -All options, including `watch` and `stats`, are looked up inside the webpack configuration. \ No newline at end of file +All options, including `watch` and `stats`, are looked up inside the webpack configuration. diff --git a/packages/angular_devkit/build_webpack/builders.json b/packages/angular_devkit/build_webpack/builders.json index 0241e0e02a76..7c53a7eacdab 100644 --- a/packages/angular_devkit/build_webpack/builders.json +++ b/packages/angular_devkit/build_webpack/builders.json @@ -2,23 +2,23 @@ "$schema": "../architect/src/builders-schema.json", "builders": { "build": { - "implementation": "./src/webpack", - "schema": "./src/webpack/schema.json", + "implementation": "./src/builders/webpack", + "schema": "./src/builders/webpack/schema.json", "description": "Build a webpack app." }, "webpack": { - "implementation": "./src/webpack", - "schema": "./src/webpack/schema.json", + "implementation": "./src/builders/webpack", + "schema": "./src/builders/webpack/schema.json", "description": "Build a webpack app." }, "dev-server": { - "implementation": "./src/webpack-dev-server", - "schema": "./src/webpack-dev-server/schema.json", + "implementation": "./src/builders/webpack-dev-server", + "schema": "./src/builders/webpack-dev-server/schema.json", "description": "Serve a webpack app." }, "webpack-dev-server": { - "implementation": "./src/webpack-dev-server", - "schema": "./src/webpack-dev-server/schema.json", + "implementation": "./src/builders/webpack-dev-server", + "schema": "./src/builders/webpack-dev-server/schema.json", "description": "Serve a webpack app." } } diff --git a/packages/angular_devkit/build_webpack/index.ts b/packages/angular_devkit/build_webpack/index.ts new file mode 100644 index 000000000000..e6da94cc7ded --- /dev/null +++ b/packages/angular_devkit/build_webpack/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './src/index'; diff --git a/packages/angular_devkit/build_webpack/package.json b/packages/angular_devkit/build_webpack/package.json index fe99af1167a8..6d6dcaf4cda1 100644 --- a/packages/angular_devkit/build_webpack/package.json +++ b/packages/angular_devkit/build_webpack/package.json @@ -1,22 +1,32 @@ { "name": "@angular-devkit/build-webpack", - "version": "0.0.0", + "version": "0.0.0-EXPERIMENTAL-PLACEHOLDER", "description": "Webpack Builder for Architect", "experimental": true, "main": "src/index.js", "typings": "src/index.d.ts", "builders": "builders.json", - "dependencies": { - "@angular-devkit/architect": "0.0.0", - "@angular-devkit/core": "0.0.0", - "rxjs": "6.5.3" + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json", + "./*": "./*.js", + "./*.js": "./*.js" }, - "peerDependencies": { - "webpack": "^4.6.0", - "webpack-dev-server": "^3.1.4" + "dependencies": { + "@angular-devkit/architect": "workspace:0.0.0-EXPERIMENTAL-PLACEHOLDER", + "rxjs": "7.8.2" }, "devDependencies": { - "webpack": "4.41.2", - "webpack-dev-server": "^3.1.4" + "@angular-devkit/core": "workspace:0.0.0-PLACEHOLDER", + "@ngtools/webpack": "workspace:0.0.0-PLACEHOLDER", + "webpack": "5.112.2", + "webpack-dev-server": "6.1.0" + }, + "peerDependencies": { + "webpack": "^5.30.0", + "webpack-dev-server": "^5.0.2 || ^6.0.0" } } diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index.ts b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index.ts new file mode 100644 index 000000000000..c370efc1ec37 --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index.ts @@ -0,0 +1,145 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Builder, BuilderContext, createBuilder } from '@angular-devkit/architect'; +import assert from 'node:assert'; +import { resolve as pathResolve } from 'node:path'; +import { Observable, from, isObservable, of, switchMap } from 'rxjs'; +import type webpack from 'webpack'; +import type WebpackDevServer from 'webpack-dev-server'; +import type { Configuration } from 'webpack-dev-server'; +import { getEmittedFiles, getWebpackConfig } from '../../utils'; +import { BuildResult, WebpackFactory, WebpackLoggingCallback } from '../webpack'; +import { Schema as WebpackDevServerBuilderSchema } from './schema'; + +export type WebpackDevServerFactory = typeof WebpackDevServer; + +export type DevServerBuildOutput = BuildResult & { + port: number; + family: string; + address: string; +}; + +/** + * @deprecated Part of Angular's Webpack support deprecation. Use `@angular/build` APIs instead. + * Deprecated since v22. + */ +export function runWebpackDevServer( + config: webpack.Configuration, + context: BuilderContext, + options: { + shouldProvideStats?: boolean; + devServerConfig?: Configuration; + logging?: WebpackLoggingCallback; + webpackFactory?: WebpackFactory; + webpackDevServerFactory?: WebpackDevServerFactory; + } = {}, +): Observable { + const createWebpack = (c: webpack.Configuration) => { + if (options.webpackFactory) { + const result = options.webpackFactory(c); + if (isObservable(result)) { + return result; + } else { + return of(result); + } + } else { + return from(import('webpack').then((mod) => mod.default(c))); + } + }; + + const { + logging: log = (stats, config) => { + if (config.stats !== false) { + const statsOptions = config.stats === true ? undefined : config.stats; + context.logger.info(stats.toString(statsOptions)); + } + }, + shouldProvideStats = true, + } = options; + + return createWebpack({ ...config, watch: false }).pipe( + switchMap(async (webpackCompiler) => { + return [ + webpackCompiler, + options.webpackDevServerFactory ?? (await import('webpack-dev-server')).default, + ] as unknown as [webpack.Compiler | null, WebpackDevServerFactory]; + }), + switchMap( + ([webpackCompiler, webpackDevServerFactory]) => + new Observable((obs) => { + assert(webpackCompiler, 'Webpack compiler factory did not return a compiler instance.'); + + const devServerConfig = options.devServerConfig || config.devServer || {}; + devServerConfig.host ??= 'localhost'; + + let result: Partial; + const statsOptions = typeof config.stats === 'boolean' ? undefined : config.stats; + + webpackCompiler.hooks.done.tap('build-webpack', (stats) => { + // Log stats. + log(stats, config); + obs.next({ + ...result, + webpackStats: shouldProvideStats ? stats.toJson(statsOptions) : undefined, + emittedFiles: getEmittedFiles(stats.compilation), + success: !stats.hasErrors(), + outputPath: stats.compilation.outputOptions.path, + } as unknown as DevServerBuildOutput); + }); + + const devServer = new webpackDevServerFactory(devServerConfig, webpackCompiler); + devServer.startCallback((err) => { + if (err) { + obs.error(err); + + return; + } + + const address = devServer.server?.address(); + if (!address) { + obs.error(new Error(`Dev-server address info is not defined.`)); + + return; + } + + result = { + success: true, + port: typeof address === 'string' ? 0 : address.port, + family: typeof address === 'string' ? '' : address.family, + address: typeof address === 'string' ? address : address.address, + }; + }); + + // Teardown logic. Close the server when unsubscribed from. + return () => { + devServer.stopCallback(() => {}); + webpackCompiler.close(() => {}); + }; + }), + ), + ); +} + +const builder: Builder = createBuilder< + WebpackDevServerBuilderSchema, + DevServerBuildOutput +>((options, context) => { + context.logger.warn( + 'The "@angular-devkit/build-webpack:webpack-dev-server" builder is deprecated as part of Angular\'s Webpack support deprecation. ' + + 'Use "@angular/build" instead.', + ); + + const configPath = pathResolve(context.workspaceRoot, options.webpackConfig); + + return from(getWebpackConfig(configPath)).pipe( + switchMap((config) => runWebpackDevServer(config, context)), + ); +}); + +export default builder; diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index_spec.ts b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index_spec.ts new file mode 100644 index 000000000000..9e4f688d0c4e --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/index_spec.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; +import { TestingArchitectHost } from '@angular-devkit/architect/testing'; +import { schema, workspaces } from '@angular-devkit/core'; +import { NodeJsSyncHost } from '@angular-devkit/core/node'; +import * as path from 'node:path'; +import { DevServerBuildOutput } from './index'; + +describe('Dev Server Builder', () => { + let testArchitectHost: TestingArchitectHost; + let architect: Architect; + let vfHost: NodeJsSyncHost; + + const webpackTargetSpec = { project: 'app', target: 'serve' }; + + async function createArchitect(workspaceRoot: string) { + vfHost = new NodeJsSyncHost(); + + const registry = new schema.CoreSchemaRegistry(); + registry.addPostTransform(schema.transforms.addUndefinedDefaults); + + const { workspace } = await workspaces.readWorkspace( + workspaceRoot, + workspaces.createWorkspaceHost(vfHost), + ); + + testArchitectHost = new TestingArchitectHost( + workspaceRoot, + workspaceRoot, + new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot), + ); + architect = new Architect(testArchitectHost, registry); + } + + beforeEach(async () => { + const ngJsonPath = path.join(__dirname, '../../../test/basic-app/angular.json'); + const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); + await createArchitect(workspaceRoot); + }); + + it('works with CJS config', async () => { + const run = await architect.scheduleTarget(webpackTargetSpec, { + webpackConfig: 'webpack.config.cjs', + }); + const output = await run.result; + expect(output.success).toBe(true); + + const response = await fetch(`http://localhost:${output.port}/bundle.js`); + expect(await response.text()).toContain(`console.log('hello world')`); + + await run.stop(); + }, 30000); + + it('works with ESM config', async () => { + const run = await architect.scheduleTarget(webpackTargetSpec, { + webpackConfig: 'webpack.config.mjs', + }); + const output = await run.result; + expect(output.success).toBe(true); + + const response = await fetch(`http://localhost:${output.port}/bundle.js`); + expect(await response.text()).toContain(`console.log('hello world')`); + + await run.stop(); + }, 30000); + + it('works and returns emitted files', async () => { + const run = await architect.scheduleTarget(webpackTargetSpec); + const output = await run.result; + + expect(output.success).toBe(true); + expect(output.emittedFiles).toContain({ + id: 'main', + name: 'main', + initial: true, + file: 'bundle.js', + extension: '.js', + }); + await run.stop(); + }, 30000); +}); diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/schema.json b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/schema.json new file mode 100644 index 000000000000..6a1e18fd92e5 --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack-dev-server/schema.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "Webpack Dev-Server Builder", + "description": "Webpack Dev-Server Builder schema for Architect.", + "type": "object", + "properties": { + "webpackConfig": { + "type": "string", + "description": "The path to the Webpack configuration file." + } + }, + "additionalProperties": false, + "required": ["webpackConfig"] +} diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack/index.ts b/packages/angular_devkit/build_webpack/src/builders/webpack/index.ts new file mode 100644 index 000000000000..2a97a075e78f --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack/index.ts @@ -0,0 +1,145 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Builder, BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; +import assert from 'node:assert'; +import { resolve as pathResolve } from 'node:path'; +import { Observable, from, isObservable, of, switchMap } from 'rxjs'; +import type webpack from 'webpack'; +import { EmittedFiles, getEmittedFiles, getWebpackConfig } from '../../utils'; +import { Schema as RealWebpackBuilderSchema } from './schema'; + +export type WebpackBuilderSchema = RealWebpackBuilderSchema; + +export interface WebpackLoggingCallback { + (stats: webpack.Stats, config: webpack.Configuration): void; +} +export interface WebpackFactory { + (config: webpack.Configuration): Observable | webpack.Compiler | null; +} + +export type BuildResult = BuilderOutput & { + emittedFiles?: EmittedFiles[]; + webpackStats?: webpack.StatsCompilation; + outputPath: string; +}; + +/** + * @deprecated Part of Angular's Webpack support deprecation. Use `@angular/build` APIs instead. + * Deprecated since v22. + */ +export function runWebpack( + config: webpack.Configuration, + context: BuilderContext, + options: { + logging?: WebpackLoggingCallback; + webpackFactory?: WebpackFactory; + shouldProvideStats?: boolean; + } = {}, +): Observable { + const { + logging: log = (stats, config) => { + if (config.stats !== false) { + const statsOptions = config.stats === true ? undefined : config.stats; + context.logger.info(stats.toString(statsOptions)); + } + }, + shouldProvideStats = true, + } = options; + + const createWebpack = (c: webpack.Configuration) => { + if (options.webpackFactory) { + const result = options.webpackFactory(c); + if (isObservable(result)) { + return result; + } else { + return of(result); + } + } else { + return from(import('webpack').then((mod) => mod.default(c))); + } + }; + + return createWebpack({ ...config, watch: false }).pipe( + switchMap( + (webpackCompiler) => + new Observable((obs) => { + assert(webpackCompiler, 'Webpack compiler factory did not return a compiler instance.'); + + const callback = (err?: Error | null, stats?: webpack.Stats) => { + if (err) { + return obs.error(err); + } + + if (!stats) { + return; + } + + // Log stats. + log(stats, config); + + const statsOptions = typeof config.stats === 'boolean' ? undefined : config.stats; + const result = { + success: !stats.hasErrors(), + webpackStats: shouldProvideStats ? stats.toJson(statsOptions) : undefined, + emittedFiles: getEmittedFiles(stats.compilation), + outputPath: stats.compilation.outputOptions.path, + } as unknown as BuildResult; + + if (config.watch) { + obs.next(result); + } else { + webpackCompiler.close(() => { + obs.next(result); + obs.complete(); + }); + } + }; + + try { + if (config.watch) { + const watchOptions = config.watchOptions || {}; + const watching = webpackCompiler.watch(watchOptions, callback); + + // Teardown logic. Close the watcher when unsubscribed from. + return () => { + watching?.close(() => {}); + webpackCompiler.close(() => {}); + }; + } else { + webpackCompiler.run(callback); + } + } catch (err) { + if (err) { + context.logger.error( + `\nAn error occurred during the build:\n${err instanceof Error ? err.stack : err}`, + ); + } + throw err; + } + }), + ), + ); +} + +const builder: Builder = createBuilder( + (options, context) => { + context.logger.warn( + 'The "@angular-devkit/build-webpack:webpack" builder is deprecated as part of Angular\'s Webpack support deprecation. ' + + 'Use "@angular/build" instead.', + ); + + const configPath = pathResolve(context.workspaceRoot, options.webpackConfig); + + return from(getWebpackConfig(configPath)).pipe( + switchMap((config) => runWebpack(config, context)), + ); + }, +); + +export default builder; diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack/index_spec.ts b/packages/angular_devkit/build_webpack/src/builders/webpack/index_spec.ts new file mode 100644 index 000000000000..3632f6858e77 --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack/index_spec.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { Architect } from '@angular-devkit/architect'; +import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; +import { TestingArchitectHost } from '@angular-devkit/architect/testing'; +import { join, normalize, schema, workspaces } from '@angular-devkit/core'; +import { NodeJsSyncHost } from '@angular-devkit/core/node'; +import * as path from 'node:path'; + +describe('Webpack Builder basic test', () => { + let testArchitectHost: TestingArchitectHost; + let architect: Architect; + let vfHost: NodeJsSyncHost; + + async function createArchitect(workspaceRoot: string) { + vfHost = new NodeJsSyncHost(); + + const registry = new schema.CoreSchemaRegistry(); + registry.addPostTransform(schema.transforms.addUndefinedDefaults); + + const { workspace } = await workspaces.readWorkspace( + workspaceRoot, + workspaces.createWorkspaceHost(vfHost), + ); + + testArchitectHost = new TestingArchitectHost( + workspaceRoot, + workspaceRoot, + new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot), + ); + architect = new Architect(testArchitectHost, registry); + } + + describe('basic app', () => { + const ngJsonPath = path.join(__dirname, '../../../test/basic-app/angular.json'); + const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); + const outputPath = join(normalize(workspaceRoot), 'dist'); + + beforeEach(async () => { + await createArchitect(workspaceRoot); + }); + + it('works with CJS config', async () => { + const run = await architect.scheduleTarget( + { project: 'app', target: 'build' }, + { webpackConfig: 'webpack.config.cjs' }, + ); + const output = await run.result; + + expect(output.success).toBe(true); + expect(await vfHost.exists(join(outputPath, 'bundle.js')).toPromise()).toBe(true); + await run.stop(); + }); + + it('works with ESM config', async () => { + const run = await architect.scheduleTarget( + { project: 'app', target: 'build' }, + { webpackConfig: 'webpack.config.mjs' }, + ); + const output = await run.result; + + expect(output.success).toBe(true); + expect(await vfHost.exists(join(outputPath, 'bundle.js')).toPromise()).toBe(true); + await run.stop(); + }); + + it('works and returns emitted files', async () => { + const run = await architect.scheduleTarget({ project: 'app', target: 'build' }); + const output = await run.result; + + expect(output.success).toBe(true); + expect(output.emittedFiles).toContain({ + id: 'main', + name: 'main', + initial: true, + file: 'bundle.js', + extension: '.js', + }); + + await run.stop(); + }); + }); + + describe('Angular app', () => { + jasmine.DEFAULT_TIMEOUT_INTERVAL = 150000; + const ngJsonPath = path.join(__dirname, '../../../test/angular-app/angular.json'); + const workspaceRoot = path.dirname(require.resolve(ngJsonPath)); + const outputPath = join(normalize(workspaceRoot), 'dist'); + + beforeEach(async () => { + await createArchitect(workspaceRoot); + }); + + it('works', async () => { + const run = await architect.scheduleTarget({ project: 'app', target: 'build-webpack' }); + const output = await run.result; + + expect(output.success).toBe(true); + expect(await vfHost.exists(join(outputPath, 'main.js')).toPromise()).toBe(true); + expect(await vfHost.exists(join(outputPath, 'polyfills.js')).toPromise()).toBe(true); + await run.stop(); + }); + + it('works and returns emitted files', async () => { + const run = await architect.scheduleTarget({ project: 'app', target: 'build-webpack' }); + const output = await run.result; + + expect(output.success).toBe(true); + expect(output.emittedFiles).toContain( + { id: 'main', name: 'main', initial: true, file: 'main.js', extension: '.js' }, + { + id: 'polyfills', + name: 'polyfills', + initial: true, + file: 'polyfills.js', + extension: '.js', + }, + ); + + await run.stop(); + }); + }); +}); diff --git a/packages/angular_devkit/build_webpack/src/builders/webpack/schema.json b/packages/angular_devkit/build_webpack/src/builders/webpack/schema.json new file mode 100644 index 000000000000..fc27c6082b9c --- /dev/null +++ b/packages/angular_devkit/build_webpack/src/builders/webpack/schema.json @@ -0,0 +1,14 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "Webpack Builder.", + "description": "Webpack Builder schema for Architect.", + "type": "object", + "properties": { + "webpackConfig": { + "type": "string", + "description": "The path to the Webpack configuration file." + } + }, + "additionalProperties": false, + "required": ["webpackConfig"] +} diff --git a/packages/angular_devkit/build_webpack/src/index.ts b/packages/angular_devkit/build_webpack/src/index.ts index 457e3b2882dc..e56c11d1cf24 100644 --- a/packages/angular_devkit/build_webpack/src/index.ts +++ b/packages/angular_devkit/build_webpack/src/index.ts @@ -1,14 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -export * from './webpack'; -export * from './webpack-dev-server'; - -export * from './plugins/architect'; - -export { EmittedFiles } from './utils'; +export * from './builders/webpack'; +export * from './builders/webpack-dev-server'; +export type { EmittedFiles } from './utils'; diff --git a/packages/angular_devkit/build_webpack/src/plugins/architect.ts b/packages/angular_devkit/build_webpack/src/plugins/architect.ts deleted file mode 100644 index 4ba52d3fe436..000000000000 --- a/packages/angular_devkit/build_webpack/src/plugins/architect.ts +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext } from '@angular-devkit/architect'; -import { strings } from '@angular-devkit/core'; -import * as path from 'path'; -import * as webpack from 'webpack'; - -/** - * This list was taken from a list of events we want to listen to, from the list of hooks in - * webpack's typings. - */ -const hookSafelist: (keyof webpack.compilation.CompilationHooks)[] = [ - 'seal', - 'optimizeDependenciesBasic', - 'optimizeDependencies', - 'optimizeDependenciesAdvanced', - 'afterOptimizeDependencies', - 'optimize', - 'optimizeModulesBasic', - 'optimizeModules', - 'optimizeModulesAdvanced', - 'afterOptimizeModules', - 'optimizeChunksBasic', - 'optimizeChunks', - 'optimizeChunksAdvanced', - 'afterOptimizeChunks', - 'optimizeTree', - 'afterOptimizeTree', - 'optimizeChunkModulesBasic', - 'optimizeChunkModules', - 'optimizeChunkModulesAdvanced', - 'afterOptimizeChunkModules', - 'reviveModules', - 'optimizeModuleOrder', - 'advancedOptimizeModuleOrder', - 'beforeModuleIds', - 'moduleIds', - 'optimizeModuleIds', - 'afterOptimizeModuleIds', - 'reviveChunks', - 'optimizeChunkOrder', - 'beforeChunkIds', - 'optimizeChunkIds', - 'afterOptimizeChunkIds', - 'recordModules', - 'recordChunks', - 'beforeHash', - 'afterHash', - 'recordHash', - 'record', - 'beforeModuleAssets', - 'shouldGenerateChunkAssets', - 'beforeChunkAssets', - 'additionalChunkAssets', - 'additionalAssets', - 'optimizeChunkAssets', - 'afterOptimizeChunkAssets', - 'optimizeAssets', - 'afterOptimizeAssets', - 'afterSeal', - 'optimizeExtractedChunksBasic', - 'optimizeExtractedChunks', - 'optimizeExtractedChunksAdvanced', - 'afterOptimizeExtractedChunks', -]; - -/** - * A webpack plugin that reports status and progress to Architect. - */ -export class ArchitectPlugin { - constructor(protected context: BuilderContext) {} - - apply(compiler: webpack.Compiler) { - const context = this.context; - let modulesCount = 0; - let modulesDone = 0; - let hooksDone = 0; - let numberOfHooks = 0; - let reset = false; // Will be true when a full compilation is done. - - function done() { - modulesDone = modulesCount; - hooksDone = Math.max(hooksDone, numberOfHooks); - update('Done.'); - reset = true; - } - function update(status: string) { - context.reportProgress( - modulesDone + hooksDone, - modulesCount + Math.max(hooksDone, numberOfHooks), - status, - ); - } - function updateModule(module: webpack.Module) { - // This is safe since we still verify it. - const m = module as unknown as { identifier?: () => string }; - const moduleId = '' + (typeof m.identifier == 'function' ? m.identifier() : ''); - const id = moduleId.split(/!|\s+|\bmulti\b/).slice(-1)[0].trim(); - const p = path.relative(context.workspaceRoot, id); - - update(`Building ${p}`); - } - - function buildModule(module: webpack.Module) { - modulesCount++; - updateModule(module); - } - function failedModule(module: webpack.Module) { - modulesDone++; - updateModule(module); - } - function succeedModule(module: webpack.Module) { - modulesDone++; - updateModule(module); - } - - // On the start of a new compilation, maybe reset the counters (and update the total), then - // listen to all hooks we're interested in. - compiler.hooks.compilation.tap('ArchitectPlugin', compilation => { - const hooks = hookSafelist; - if (reset) { - reset = false; - modulesCount = modulesDone = hooksDone = numberOfHooks = 0; - } - // Need to add hooks for each compilation. - numberOfHooks += hooks.length; - - // Pre-emptively tell the user. - context.reportRunning(); - update('Preparing...'); - - compilation.hooks.buildModule.tap('ArchitectPlugin', buildModule); - compilation.hooks.failedModule.tap('ArchitectPlugin', failedModule); - compilation.hooks.succeedModule.tap('ArchitectPlugin', succeedModule); - - for (const name of hooks) { - // Transforms `camelCase` into `Camel case`. decamelize() transforms it into `camel_case` - // and then we replace the `_` with spaces. - const title = strings.capitalize(strings.decamelize(name).replace(/_/g, ' ')); - - compilation.hooks[name].intercept({ - call: () => { - hooksDone++; - update(title); - }, - }); - } - }); - - compiler.hooks.done.tap('ArchitectPlugin', done); - } -} diff --git a/packages/angular_devkit/build_webpack/src/test-utils.ts b/packages/angular_devkit/build_webpack/src/test-utils.ts deleted file mode 100644 index 5941213dd574..000000000000 --- a/packages/angular_devkit/build_webpack/src/test-utils.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { TestProjectHost } from '@angular-devkit/architect/testing'; -import { join, normalize } from '@angular-devkit/core'; - - -const devkitRoot = normalize((global as any)._DevKitRoot); // tslint:disable-line:no-any -const basicWorkspaceRoot = join(devkitRoot, 'tests/angular_devkit/build_webpack/basic-app/'); -export const basicHost = new TestProjectHost(basicWorkspaceRoot); -const angularWorkspaceRoot = join(devkitRoot, 'tests/angular_devkit/build_webpack/angular-app/'); -export const angularHost = new TestProjectHost(angularWorkspaceRoot); diff --git a/packages/angular_devkit/build_webpack/src/utils.ts b/packages/angular_devkit/build_webpack/src/utils.ts index 4cf61464e1fa..98a9aa04fe83 100644 --- a/packages/angular_devkit/build_webpack/src/utils.ts +++ b/packages/angular_devkit/build_webpack/src/utils.ts @@ -1,13 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as path from 'path'; -import * as webpack from 'webpack'; +import { existsSync } from 'node:fs'; +import * as path from 'node:path'; +import { URL, pathToFileURL } from 'node:url'; +import { Compilation, Configuration } from 'webpack'; export interface EmittedFiles { id?: string; @@ -18,15 +20,21 @@ export interface EmittedFiles { extension: string; } -export function getEmittedFiles(compilation: webpack.compilation.Compilation): EmittedFiles[] { +export function getEmittedFiles(compilation: Compilation): EmittedFiles[] { const files: EmittedFiles[] = []; + const chunkFileNames = new Set(); // adds all chunks to the list of emitted files such as lazy loaded modules - for (const chunk of compilation.chunks as webpack.compilation.Chunk[]) { - for (const file of chunk.files as string[]) { + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + if (chunkFileNames.has(file)) { + continue; + } + + chunkFileNames.add(file); files.push({ - id: chunk.id.toString(), - name: chunk.name, + id: chunk.id?.toString(), + name: chunk.name ?? undefined, file, extension: path.extname(file), initial: chunk.isOnlyInitial(), @@ -34,12 +42,25 @@ export function getEmittedFiles(compilation: webpack.compilation.Compilation): E } } - // other all files + // add all other files for (const file of Object.keys(compilation.assets)) { + // Chunk files have already been added to the files list above + if (chunkFileNames.has(file)) { + continue; + } + files.push({ file, extension: path.extname(file), initial: false, asset: true }); } - // dedupe - return files.filter(({ file, name }, index) => - files.findIndex(f => f.file === file && (!name || name === f.name)) === index); + return files; +} + +export async function getWebpackConfig(configPath: string): Promise { + if (!existsSync(configPath)) { + throw new Error(`Webpack configuration file ${configPath} does not exist.`); + } + + const config = await import(configPath); + + return 'default' in config ? config.default : config; } diff --git a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts b/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts deleted file mode 100644 index d4e09abb64e1..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext, createBuilder } from '@angular-devkit/architect'; -import { getSystemPath, json, normalize, resolve } from '@angular-devkit/core'; -import * as net from 'net'; -import { Observable, from, isObservable, of } from 'rxjs'; -import { switchMap } from 'rxjs/operators'; -import * as webpack from 'webpack'; -import * as WebpackDevServer from 'webpack-dev-server'; -import { getEmittedFiles } from '../utils'; -import { BuildResult, WebpackFactory, WebpackLoggingCallback } from '../webpack'; -import { Schema as WebpackDevServerBuilderSchema } from './schema'; - -export type DevServerBuildOutput = BuildResult & { - port: number; - family: string; - address: string; -}; - -export function runWebpackDevServer( - config: webpack.Configuration, - context: BuilderContext, - options: { - devServerConfig?: WebpackDevServer.Configuration, - logging?: WebpackLoggingCallback, - webpackFactory?: WebpackFactory, - } = {}, -): Observable { - const createWebpack = (c: webpack.Configuration) => { - if (options.webpackFactory) { - const result = options.webpackFactory(c); - if (isObservable(result)) { - return result; - } else { - return of(result); - } - } else { - return of(webpack(c)); - } - }; - const log: WebpackLoggingCallback = options.logging - || ((stats, config) => context.logger.info(stats.toString(config.stats))); - - const devServerConfig = options.devServerConfig || config.devServer || {}; - if (devServerConfig.stats) { - config.stats = devServerConfig.stats; - } - // Disable stats reporting by the devserver, we have our own logger. - devServerConfig.stats = false; - - return createWebpack(config).pipe( - switchMap(webpackCompiler => new Observable(obs => { - const server = new WebpackDevServer(webpackCompiler, devServerConfig); - let result: DevServerBuildOutput; - - webpackCompiler.hooks.done.tap('build-webpack', (stats) => { - // Log stats. - log(stats, config); - - obs.next({ - ...result, - emittedFiles: getEmittedFiles(stats.compilation), - success: !stats.hasErrors(), - } as unknown as DevServerBuildOutput); - }); - - server.listen( - devServerConfig.port === undefined ? 8080 : devServerConfig.port, - devServerConfig.host === undefined ? 'localhost' : devServerConfig.host, - function (this: net.Server, err) { - if (err) { - obs.error(err); - } else { - const address = this.address(); - result = { - success: true, - port: typeof address === 'string' ? 0 : address.port, - family: typeof address === 'string' ? '' : address.family, - address: typeof address === 'string' ? address : address.address, - }; - } - }, - ); - - // Teardown logic. Close the server when unsubscribed from. - return () => server.close(); - })), - ); -} - - -export default createBuilder< - json.JsonObject & WebpackDevServerBuilderSchema, DevServerBuildOutput ->((options, context) => { - const configPath = resolve(normalize(context.workspaceRoot), normalize(options.webpackConfig)); - - return from(import(getSystemPath(configPath))).pipe( - switchMap((config: webpack.Configuration) => runWebpackDevServer(config, context)), - ); -}); diff --git a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index_spec_large.ts b/packages/angular_devkit/build_webpack/src/webpack-dev-server/index_spec_large.ts deleted file mode 100644 index a2e2f431c0ab..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index_spec_large.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; -import { TestingArchitectHost } from '@angular-devkit/architect/testing'; -import { schema, workspaces } from '@angular-devkit/core'; -import { NodeJsSyncHost } from '@angular-devkit/core/node'; -import fetch from 'node-fetch'; // tslint:disable-line:no-implicit-dependencies -import * as path from 'path'; -import { DevServerBuildOutput } from './index'; - -const devkitRoot = (global as any)._DevKitRoot; // tslint:disable-line:no-any - - -describe('Dev Server Builder', () => { - let testArchitectHost: TestingArchitectHost; - let architect: Architect; - let vfHost: NodeJsSyncHost; - - const webpackTargetSpec = { project: 'app', target: 'serve' }; - - async function createArchitect(workspaceRoot: string) { - vfHost = new NodeJsSyncHost(); - - const registry = new schema.CoreSchemaRegistry(); - registry.addPostTransform(schema.transforms.addUndefinedDefaults); - - const { workspace } = await workspaces.readWorkspace( - workspaceRoot, - workspaces.createWorkspaceHost(vfHost), - ); - - testArchitectHost = new TestingArchitectHost(workspaceRoot, workspaceRoot, - new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot)); - architect = new Architect(testArchitectHost, registry); - } - - beforeEach(async () => { - await createArchitect(path.join(devkitRoot, 'tests/angular_devkit/build_webpack/basic-app/')); - }); - - it('works', async () => { - const run = await architect.scheduleTarget(webpackTargetSpec); - const output = await run.result as DevServerBuildOutput; - expect(output.success).toBe(true); - - const response = await fetch(`http://${output.address}:${output.port}/bundle.js`); - expect(await response.text()).toContain(`console.log('hello world')`); - - await run.stop(); - }, 30000); - - it('works and returns emitted files', async () => { - const run = await architect.scheduleTarget(webpackTargetSpec); - const output = await run.result as DevServerBuildOutput; - - expect(output.success).toBe(true); - expect(output.emittedFiles).toContain({ - id: 'main', - name: 'main', - initial: true, - file: 'bundle.js', - extension: '.js', - }); - await run.stop(); - }, 30000); -}); diff --git a/packages/angular_devkit/build_webpack/src/webpack-dev-server/schema.json b/packages/angular_devkit/build_webpack/src/webpack-dev-server/schema.json deleted file mode 100644 index 697106775979..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack-dev-server/schema.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": "http://json-schema.org/schema", - "title": "Webpack Dev-Server Builder", - "description": "Webpack Dev-Server Builder schema for Architect.", - "type": "object", - "properties": { - "webpackConfig": { - "type": "string", - "description": "The path to the Webpack configuration file." - } - }, - "additionalProperties": false, - "required": [ - "webpackConfig" - ] -} diff --git a/packages/angular_devkit/build_webpack/src/webpack/index.ts b/packages/angular_devkit/build_webpack/src/webpack/index.ts deleted file mode 100644 index 727962fa5c43..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack/index.ts +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; -import { getSystemPath, json, normalize, resolve } from '@angular-devkit/core'; -import { Observable, from, isObservable, of } from 'rxjs'; -import { switchMap } from 'rxjs/operators'; -import * as webpack from 'webpack'; -import { EmittedFiles, getEmittedFiles } from '../utils'; -import { Schema as RealWebpackBuilderSchema } from './schema'; - -export type WebpackBuilderSchema = json.JsonObject & RealWebpackBuilderSchema; - -export interface WebpackLoggingCallback { - (stats: webpack.Stats, config: webpack.Configuration): void; -} -export interface WebpackFactory { - (config: webpack.Configuration): Observable | webpack.Compiler; -} - -export type BuildResult = BuilderOutput & { - emittedFiles?: EmittedFiles[]; - webpackStats?: webpack.Stats.ToJsonOutput; -}; - -export function runWebpack( - config: webpack.Configuration, - context: BuilderContext, - options: { - logging?: WebpackLoggingCallback, - webpackFactory?: WebpackFactory, - } = {}, -): Observable { - const createWebpack = (c: webpack.Configuration) => { - if (options.webpackFactory) { - const result = options.webpackFactory(c); - if (isObservable(result)) { - return result; - } else { - return of(result); - } - } else { - return of(webpack(c)); - } - }; - const log: WebpackLoggingCallback = options.logging - || ((stats, config) => context.logger.info(stats.toString(config.stats))); - - return createWebpack(config).pipe( - switchMap(webpackCompiler => new Observable(obs => { - const callback: webpack.Compiler.Handler = (err, stats) => { - if (err) { - return obs.error(err); - } - - // Log stats. - log(stats, config); - - obs.next({ - success: !stats.hasErrors(), - webpackStats: stats.toJson(), - emittedFiles: getEmittedFiles(stats.compilation), - } as unknown as BuildResult); - - if (!config.watch) { - obs.complete(); - } - }; - - try { - if (config.watch) { - const watchOptions = config.watchOptions || {}; - const watching = webpackCompiler.watch(watchOptions, callback); - - // Teardown logic. Close the watcher when unsubscribed from. - return () => watching.close(() => { }); - } else { - webpackCompiler.run(callback); - } - } catch (err) { - if (err) { - context.logger.error(`\nAn error occurred during the build:\n${err && err.stack || err}`); - } - throw err; - } - }), - )); -} - - -export default createBuilder((options, context) => { - const configPath = resolve(normalize(context.workspaceRoot), normalize(options.webpackConfig)); - - return from(import(getSystemPath(configPath))).pipe( - switchMap((config: webpack.Configuration) => runWebpack(config, context)), - ); -}); diff --git a/packages/angular_devkit/build_webpack/src/webpack/index_spec_large.ts b/packages/angular_devkit/build_webpack/src/webpack/index_spec_large.ts deleted file mode 100644 index d81a7b8c5c04..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack/index_spec_large.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Architect } from '@angular-devkit/architect'; -import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node'; -import { TestingArchitectHost } from '@angular-devkit/architect/testing'; -import { join, normalize, schema, workspaces } from '@angular-devkit/core'; -import { NodeJsSyncHost } from '@angular-devkit/core/node'; -import * as path from 'path'; -import { BuildResult } from './index'; - -const devkitRoot = (global as any)._DevKitRoot; // tslint:disable-line:no-any - - -describe('Webpack Builder basic test', () => { - let testArchitectHost: TestingArchitectHost; - let architect: Architect; - let vfHost: NodeJsSyncHost; - - async function createArchitect(workspaceRoot: string) { - vfHost = new NodeJsSyncHost(); - - const registry = new schema.CoreSchemaRegistry(); - registry.addPostTransform(schema.transforms.addUndefinedDefaults); - - const { workspace } = await workspaces.readWorkspace( - workspaceRoot, - workspaces.createWorkspaceHost(vfHost), - ); - - testArchitectHost = new TestingArchitectHost(workspaceRoot, workspaceRoot, - new WorkspaceNodeModulesArchitectHost(workspace, workspaceRoot)); - architect = new Architect(testArchitectHost, registry); - } - - describe('basic app', () => { - const workspaceRoot = path.join(devkitRoot, 'tests/angular_devkit/build_webpack/basic-app/'); - const outputPath = join(normalize(workspaceRoot), 'dist'); - - beforeEach(async () => { - await createArchitect(workspaceRoot); - }); - - it('works', async () => { - const run = await architect.scheduleTarget({ project: 'app', target: 'build' }); - const output = await run.result; - - expect(output.success).toBe(true); - expect(await vfHost.exists(join(outputPath, 'bundle.js')).toPromise()).toBe(true); - await run.stop(); - }); - - it('works and returns emitted files', async () => { - const run = await architect.scheduleTarget({ project: 'app', target: 'build' }); - const output = await run.result as BuildResult; - - expect(output.success).toBe(true); - expect(output.emittedFiles).toContain({ - id: 'main', - name: 'main', - initial: true, - file: 'bundle.js', - extension: '.js', - }); - - await run.stop(); - }); - }); - - describe('Angular app', () => { - const workspaceRoot = path.join(devkitRoot, 'tests/angular_devkit/build_webpack/angular-app/'); - const outputPath = join(normalize(workspaceRoot), 'dist/'); - - beforeEach(async () => { - await createArchitect(workspaceRoot); - }); - - it('works', async () => { - const run = await architect.scheduleTarget({ project: 'app', target: 'build-webpack' }); - const output = await run.result; - - expect(output.success).toBe(true); - expect(await vfHost.exists(join(outputPath, 'main.js')).toPromise()).toBe(true); - expect(await vfHost.exists(join(outputPath, 'polyfills.js')).toPromise()).toBe(true); - await run.stop(); - }); - - it('works and returns emitted files', async () => { - const run = await architect.scheduleTarget({ project: 'app', target: 'build-webpack' }); - const output = await run.result as BuildResult; - - expect(output.success).toBe(true); - expect(output.emittedFiles).toContain( - { id: 'main', name: 'main', initial: true, file: 'main.js', extension: '.js' }, - { id: 'polyfills', name: 'polyfills', initial: true, file: 'polyfills.js', extension: '.js' }, - ); - - await run.stop(); - }); - }); -}); diff --git a/packages/angular_devkit/build_webpack/src/webpack/schema.json b/packages/angular_devkit/build_webpack/src/webpack/schema.json deleted file mode 100644 index 6c4ba8cc3783..000000000000 --- a/packages/angular_devkit/build_webpack/src/webpack/schema.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": "http://json-schema.org/schema", - "title": "Webpack Builder.", - "description": "Webpack Builder schema for Architect.", - "type": "object", - "properties": { - "webpackConfig": { - "type": "string", - "description": "The path to the Webpack configuration file." - } - }, - "additionalProperties": false, - "required": [ - "webpackConfig" - ] -} diff --git a/packages/angular_devkit/build_webpack/test/angular-app/angular.json b/packages/angular_devkit/build_webpack/test/angular-app/angular.json new file mode 100644 index 000000000000..3bb325a1d073 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/angular.json @@ -0,0 +1,33 @@ +{ + "$schema": "../../../../packages/angular_devkit/core/src/workspace/workspace-schema.json", + "version": 1, + "newProjectRoot": "./projects", + "cli": { + "cache": { + "enabled": false + } + }, + "schematics": {}, + "projects": { + "app": { + "root": "src", + "sourceRoot": "src", + "projectType": "application", + "schematics": {}, + "targets": { + "build-webpack": { + "builder": "../../:webpack", + "options": { + "webpackConfig": "webpack.config.js" + } + }, + "serve-webpack": { + "builder": "../../:webpack-dev-server", + "options": { + "webpackConfig": "webpack.config.js" + } + } + } + } + } +} diff --git a/tests/angular_devkit/build_angular/hello-world-app/src/app/app.component.css b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.css similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app/src/app/app.component.css rename to packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.css diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.html b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.html new file mode 100644 index 000000000000..bfa311626596 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.html @@ -0,0 +1,27 @@ + +
+

Welcome to {{ title }}!

+ Angular Logo +
+

Here are some links to help you start:

+
+ +

i18n test

diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.spec.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.spec.ts new file mode 100644 index 000000000000..c57b4250561f --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.spec.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { TestBed } from '@angular/core/testing'; +import { AppComponent } from './app.component'; +describe('AppComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + declarations: [AppComponent], + }); + }); + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); + }); + it(`should have as title 'app'`, () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('app'); + }); + it('should render title in a h1 tag', () => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); + }); +}); diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.ts new file mode 100644 index 000000000000..93a041e8aec7 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.component.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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'; + +@Component({ + selector: 'app-root', + standalone: false, + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'], +}) +export class AppComponent { + title = 'app'; +} diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.module.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.module.ts new file mode 100644 index 000000000000..3c42f0048330 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/app/app.module.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; + +import { AppComponent } from './app.component'; + +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule], + providers: [], + bootstrap: [AppComponent], +}) +export class AppModule {} diff --git a/tests/angular_devkit/build_angular/hello-world-app/src/assets/.gitkeep b/packages/angular_devkit/build_webpack/test/angular-app/src/assets/.gitkeep similarity index 100% rename from tests/angular_devkit/build_angular/hello-world-app/src/assets/.gitkeep rename to packages/angular_devkit/build_webpack/test/angular-app/src/assets/.gitkeep diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts new file mode 100644 index 000000000000..9fff4140458d --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/main.ts @@ -0,0 +1,14 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { platformBrowser } from '@angular/platform-browser'; +import { AppModule } from './app/app.module'; + +platformBrowser() + .bootstrapModule(AppModule) + .catch((err) => console.log(err)); diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/polyfills.ts b/packages/angular_devkit/build_webpack/test/angular-app/src/polyfills.ts new file mode 100644 index 000000000000..a8b1b2c83975 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/polyfills.ts @@ -0,0 +1,42 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.dev/reference/versions#browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** + * Required to support Web Animations `@angular/platform-browser/animations`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation + **/ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js'; // Included with Angular CLI. + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/packages/angular_devkit/build_webpack/test/angular-app/src/tsconfig.app.json b/packages/angular_devkit/build_webpack/test/angular-app/src/tsconfig.app.json new file mode 100644 index 000000000000..4191001bb4d4 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/src/tsconfig.app.json @@ -0,0 +1,9 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "module": "es2022", + "types": [] + }, + "exclude": ["test.ts", "**/*.spec.ts"] +} diff --git a/packages/angular_devkit/build_webpack/test/angular-app/tsconfig.json b/packages/angular_devkit/build_webpack/test/angular-app/tsconfig.json new file mode 100644 index 000000000000..beb80b8f4d01 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "bundler", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es2022", + "lib": ["es2022", "dom"] + }, + "angularCompilerOptions": { + "enableIvy": true, + "disableTypeScriptVersionCheck": true + } +} diff --git a/packages/angular_devkit/build_webpack/test/angular-app/webpack.config.js b/packages/angular_devkit/build_webpack/test/angular-app/webpack.config.js new file mode 100644 index 000000000000..ed885f54ad43 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/angular-app/webpack.config.js @@ -0,0 +1,39 @@ +const ngToolsWebpack = require('@ngtools/webpack'); +const path = require('path'); + +const workspaceRoot = path.resolve(__dirname, './'); +const projectRoot = path.resolve(__dirname, './'); + +module.exports = { + mode: 'development', + resolve: { + extensions: ['.ts', '.js'], + }, + entry: { + main: path.resolve(projectRoot, './src/main.ts'), + polyfills: path.resolve(projectRoot, './src/polyfills.ts'), + }, + output: { + path: path.resolve(workspaceRoot, './dist'), + filename: `[name].js`, + }, + plugins: [ + new ngToolsWebpack.AngularWebpackPlugin({ + tsconfig: path.resolve(projectRoot, './src/tsconfig.app.json'), + }), + ], + module: { + rules: [ + // rxjs 6 requires directory imports which are not support in ES modules. + // Disabling `fullySpecified` allows Webpack to ignore this but this is + // not ideal because it currently disables ESM behavior import for all JS files. + { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, + { test: /\.css$/, type: 'asset/source' }, + { test: /\.html$/, type: 'asset/source' }, + { test: /\.ts$/, loader: '@ngtools/webpack' }, + ], + }, + devServer: { + historyApiFallback: true, + }, +}; diff --git a/packages/angular_devkit/build_webpack/test/basic-app/.gitignore b/packages/angular_devkit/build_webpack/test/basic-app/.gitignore new file mode 100644 index 000000000000..e0406551d1ea --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/.gitignore @@ -0,0 +1,43 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc + +# dependencies +/node_modules + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# misc +/.angular/cache +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +testem.log +/typings + +# e2e +/e2e/*.js +/e2e/*.map + +# System Files +.DS_Store +Thumbs.db diff --git a/packages/angular_devkit/build_webpack/test/basic-app/angular.json b/packages/angular_devkit/build_webpack/test/basic-app/angular.json new file mode 100644 index 000000000000..5620c21f7ff8 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/angular.json @@ -0,0 +1,29 @@ +{ + "$schema": "../../../core/src/workspace/workspace-schema.json", + "version": 1, + "newProjectRoot": "./projects", + "cli": {}, + "schematics": {}, + "projects": { + "app": { + "root": "src", + "sourceRoot": "src", + "projectType": "application", + "schematics": {}, + "targets": { + "build": { + "builder": "../../:webpack", + "options": { + "webpackConfig": "webpack.config.cjs" + } + }, + "serve": { + "builder": "../../:webpack-dev-server", + "options": { + "webpackConfig": "webpack.config.cjs" + } + } + } + } + } +} diff --git a/packages/angular_devkit/build_webpack/test/basic-app/src/main.js b/packages/angular_devkit/build_webpack/test/basic-app/src/main.js new file mode 100644 index 000000000000..6be02374db11 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/src/main.js @@ -0,0 +1 @@ +console.log('hello world'); diff --git a/packages/angular_devkit/build_webpack/test/basic-app/tsconfig.json b/packages/angular_devkit/build_webpack/test/basic-app/tsconfig.json new file mode 100644 index 000000000000..d93948c96ff0 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "moduleResolution": "bundler", + "experimentalDecorators": true, + "target": "es2022", + "module": "esnext", + "lib": ["es2022", "dom"] + }, + "angularCompilerOptions": { + "disableTypeScriptVersionCheck": true + } +} diff --git a/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.cjs b/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.cjs new file mode 100644 index 000000000000..b1f988ab2071 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.cjs @@ -0,0 +1,18 @@ +const path = require('path'); + +module.exports = { + mode: 'development', + entry: path.resolve(__dirname, './src/main.js'), + module: { + rules: [ + // rxjs 6 requires directory imports which are not support in ES modules. + // Disabling `fullySpecified` allows Webpack to ignore this but this is + // not ideal because it currently disables ESM behavior import for all JS files. + { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, + ], + }, + output: { + path: path.resolve(__dirname, './dist'), + filename: 'bundle.js', + }, +}; diff --git a/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.mjs b/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.mjs new file mode 100644 index 000000000000..289fff7bdb69 --- /dev/null +++ b/packages/angular_devkit/build_webpack/test/basic-app/webpack.config.mjs @@ -0,0 +1,19 @@ +import { resolve } from 'path'; +import { fileURLToPath } from 'url'; + +export default { + mode: 'development', + entry: resolve(fileURLToPath(import.meta.url), '../src/main.js'), + module: { + rules: [ + // rxjs 6 requires directory imports which are not support in ES modules. + // Disabling `fullySpecified` allows Webpack to ignore this but this is + // not ideal because it currently disables ESM behavior import for all JS files. + { test: /\.[m]?js$/, resolve: { fullySpecified: false } }, + ], + }, + output: { + path: resolve(fileURLToPath(import.meta.url), '../dist'), + filename: 'bundle.js', + }, +}; diff --git a/packages/angular_devkit/core/BUILD b/packages/angular_devkit/core/BUILD deleted file mode 100644 index 6644f6462e23..000000000000 --- a/packages/angular_devkit/core/BUILD +++ /dev/null @@ -1,184 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -package(default_visibility = ["//visibility:public"]) - -load("@npm_bazel_jasmine//:index.bzl", "jasmine_node_test") -load("@npm_bazel_typescript//:index.bzl", "ts_library") - -# @external_begin -load("@build_bazel_rules_nodejs//:defs.bzl", "npm_package") -# @external_end - -licenses(["notice"]) # MIT License - -# @angular-devkit/core - -ts_library( - name = "core", - srcs = glob( - include = ["src/**/*.ts"], - exclude = [ - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - "src/**/*_benchmark.ts", - ], - ), - data = glob(["**/*.json"]) + [ - "//packages/angular_devkit/core/third_party/github.com/chalk/supports-color", - ], - module_name = "@angular-devkit/core", - module_root = "src/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - "@npm//@types/fast-json-stable-stringify", - "@npm//@types/node", - "@npm//ajv", - "@npm//magic-string", - "@npm//rxjs", - "@npm//source-map", - # @node_module: typescript:es2015.core - # @node_module: typescript:es2015.proxy - # @node_module: typescript:es2015.reflect - # @node_module: typescript:es2015.symbol.wellknown - # @node_module: typescript:es2016.array.include - ], -) - -ts_library( - name = "core_test_lib", - testonly = True, - srcs = glob( - include = [ - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - ], - ), - data = [ - "src/experimental/workspace/test/test-workspace.json", - "src/experimental/workspace/workspace-schema.json", - ], - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - # @external_begin - tsconfig = "//:tsconfig-test.json", - # @external_end - deps = [ - ":core", - ":node", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -jasmine_node_test( - name = "core_test", - srcs = [":core_test_lib"], - # TODO: Audit tests to determine if tests can be run in RBE environments - local = True, - deps = [ - # @node_module: ajv - # @node_module: fast_json_stable_stringify - # @node_module: magic_string - # @node_module: source_map - ], -) - -# @angular-devkit/core/node - -ts_library( - name = "node", - srcs = glob( - include = ["node/**/*.ts"], - exclude = [ - "node/testing/**/*.ts", - "node/**/*_spec.ts", - "node/**/*_spec_large.ts", - "node/**/*_benchmark.ts", - ], - ), - module_name = "@angular-devkit/core/node", - module_root = "node/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - ":core", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -ts_library( - name = "node_test_lib", - testonly = True, - srcs = glob( - include = [ - "node/**/*_spec.ts", - "node/**/*_spec_large.ts", - ], - ), - # @external_begin - tsconfig = "//:tsconfig-test.json", - # @external_end - deps = [ - ":core", - ":node", - "//tests/angular_devkit/core/node/jobs:jobs_test_lib", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -jasmine_node_test( - name = "node_test", - srcs = [":node_test_lib"], - # TODO: Audit tests to determine if tests can be run in RBE environments - local = True, - deps = [ - "@npm//chokidar", - "@npm//temp", - # @node_module: ajv - # @node_module: fast_json_stable_stringify - # @node_module: magic_string - ], -) - -# @angular-devkit/core/node/testing - -ts_library( - name = "node_testing", - srcs = glob( - include = ["node/testing/**/*.ts"], - exclude = [ - "node/testing/**/*_spec.ts", - "node/testing/**/*_spec_large.ts", - "node/testing/**/*_benchmark.ts", - ], - ), - module_name = "@angular-devkit/core/node/testing", - module_root = "node/testing/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - ":core", - ":node", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -# @external_begin -npm_package( - name = "npm_package", - deps = [ - ":core", - ":node", - ":node_testing", - ], -) -# @external_end diff --git a/packages/angular_devkit/core/BUILD.bazel b/packages/angular_devkit/core/BUILD.bazel new file mode 100644 index 000000000000..d57bd782596b --- /dev/null +++ b/packages/angular_devkit/core/BUILD.bazel @@ -0,0 +1,97 @@ +load("@devinfra//bazel/api-golden:index.bzl", "api_golden_test_npm_package") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defaults.bzl", "jasmine_test", "npm_package", "ts_project") + +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +npm_link_all_packages() + +RUNTIME_ASSETS = glob( + include = ["**/*.json"], + # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces + exclude = [ + "node_modules/**", + "src/workspace/json/test/**", + ], +) + +ts_project( + name = "core", + srcs = glob( + include = ["src/**/*.ts"], + exclude = [ + "src/**/*_spec.ts", + ], + ) + ["index.ts"], + data = RUNTIME_ASSETS, + deps = [ + ":node_modules/ajv", + ":node_modules/ajv-formats", + ":node_modules/jsonc-parser", + ":node_modules/picomatch", + ":node_modules/rxjs", + ":node_modules/source-map", + "//:node_modules/@types/jasmine", + "//:node_modules/@types/node", + "//:node_modules/@types/picomatch", + ], +) + +# @external_begin + +ts_project( + name = "core_test_lib", + testonly = True, + srcs = glob(["src/**/*_spec.ts"]), + data = glob(["src/workspace/json/test/**/*.json"]), + deps = [ + ":core", + ":node_modules/rxjs", + "//:node_modules/@types/node", + "//packages/angular_devkit/core/node", + ], +) + +jasmine_test( + name = "test", + data = [":core_test_lib"], +) + +genrule( + name = "license", + srcs = ["//:LICENSE"], + outs = ["LICENSE"], + cmd = "cp $(execpath //:LICENSE) $@", +) + +npm_package( + name = "pkg", + tags = ["release-package"], + deps = RUNTIME_ASSETS + [ + ":README.md", + ":core", + ":license", + "//packages/angular_devkit/core/node", + "//packages/angular_devkit/core/node/testing", + ], +) + +api_golden_test_npm_package( + name = "core_api", + data = [ + ":npm_package", + "//goldens:public-api", + ], + golden_dir = "goldens/public-api/angular_devkit/core", + npm_package = "packages/angular_devkit/core/npm_package", + types = { + "//:node_modules/@types/node": "node", + }, +) +# @external_end diff --git a/packages/angular_devkit/core/README.md b/packages/angular_devkit/core/README.md index bc4b5b0991a5..18ebc31ca477 100644 --- a/packages/angular_devkit/core/README.md +++ b/packages/angular_devkit/core/README.md @@ -1,4 +1,5 @@ # Core + > Shared utilities for Angular DevKit. # Exception @@ -8,6 +9,7 @@ ## Schema ### SchemaValidatorResult + ``` export interface SchemaValidatorResult { success: boolean; @@ -62,33 +64,33 @@ export class CoreSchemaRegistry implements SchemaRegistry { The `workspaces` namespace provides an API for interacting with the workspace file formats. It provides an abstraction of the underlying storage format of the workspace and provides -support for both reading and writing. Currently, the only supported format is the JSON-based -format used by the Angular CLI. For this format, the API provides internal change tracking of values which -enables fine-grained updates to the underlying storage of the workspace. This allows for the +support for both reading and writing. Currently, the only supported format is the JSON-based +format used by the Angular CLI. For this format, the API provides internal change tracking of values which +enables fine-grained updates to the underlying storage of the workspace. This allows for the retention of existing formatting and comments. -A workspace is defined via the following object model. Definition collection objects are specialized +A workspace is defined via the following object model. Definition collection objects are specialized Javascript `Map` objects with an additional `add` method to simplify addition and provide more localized error checking of the newly added values. ```ts export interface WorkspaceDefinition { - readonly extensions: Record; - readonly projects: ProjectDefinitionCollection; + readonly extensions: Record; + readonly projects: ProjectDefinitionCollection; } export interface ProjectDefinition { - readonly extensions: Record; - readonly targets: TargetDefinitionCollection; - root: string; - prefix?: string; - sourceRoot?: string; + readonly extensions: Record; + readonly targets: TargetDefinitionCollection; + root: string; + prefix?: string; + sourceRoot?: string; } export interface TargetDefinition { - options?: Record; - configurations?: Record | undefined>; - builder: string; + options?: Record; + configurations?: Record | undefined>; + builder: string; } ``` @@ -106,7 +108,7 @@ export function readWorkspace( path: string, host: WorkspaceHost, format?: WorkspaceFormat, -): Promise<{ workspace: WorkspaceDefinition; }>; +): Promise<{ workspace: WorkspaceDefinition }>; ``` ```ts @@ -118,16 +120,16 @@ export function writeWorkspace( ): Promise; ``` -A `WorkspaceHost` abstracts the underlying data access methods from the functions. It provides -methods to read, write, and analyze paths. A utility function is provided to create +A `WorkspaceHost` abstracts the underlying data access methods from the functions. It provides +methods to read, write, and analyze paths. A utility function is provided to create an instance of a `WorkspaceHost` from the Angular DevKit's virtual filesystem host abstraction. ```ts export interface WorkspaceHost { - readFile(path: string): Promise; - writeFile(path: string, data: string): Promise; - isDirectory(path: string): Promise; - isFile(path: string): Promise; + readFile(path: string): Promise; + writeFile(path: string, data: string): Promise; + isDirectory(path: string): Promise; + isFile(path: string): Promise; } export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost; @@ -143,23 +145,23 @@ import { NodeJsSyncHost } from '@angular-devkit/core/node'; import { workspaces } from '@angular-devkit/core'; async function demonstrate() { - const host = workspaces.createWorkspaceHost(new NodeJsSyncHost()); - const workspace = await workspaces.readWorkspace('path/to/workspace/directory/', host); + const host = workspaces.createWorkspaceHost(new NodeJsSyncHost()); + const { workspace } = await workspaces.readWorkspace('path/to/workspace/directory/', host); - const project = workspace.projects.get('my-app'); - if (!project) { - throw new Error('my-app does not exist'); - } + const project = workspace.projects.get('my-app'); + if (!project) { + throw new Error('my-app does not exist'); + } - const buildTarget = project.targets.get('build'); - if (!buildTarget) { - throw new Error('build target does not exist'); - } + const buildTarget = project.targets.get('build'); + if (!buildTarget) { + throw new Error('build target does not exist'); + } - buildTarget.options.optimization = true; + buildTarget.options.optimization = true; - await workspaces.writeWorkspace(workspace, host); + await workspaces.writeWorkspace(workspace, host); } demonstrate(); -``` \ No newline at end of file +``` diff --git a/packages/angular_devkit/core/index.ts b/packages/angular_devkit/core/index.ts new file mode 100644 index 000000000000..e6da94cc7ded --- /dev/null +++ b/packages/angular_devkit/core/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './src/index'; diff --git a/packages/angular_devkit/core/node/BUILD.bazel b/packages/angular_devkit/core/node/BUILD.bazel new file mode 100644 index 000000000000..9c6f34c3a51f --- /dev/null +++ b/packages/angular_devkit/core/node/BUILD.bazel @@ -0,0 +1,52 @@ +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license + +load("//tools:defaults.bzl", "jasmine_test", "ts_project") + +licenses(["notice"]) + +package(default_visibility = ["//visibility:public"]) + +ts_project( + name = "node", + srcs = glob( + include = ["**/*.ts"], + exclude = [ + "testing/**/*.ts", + "**/*_spec.ts", + ], + ), + deps = [ + "//:node_modules/@types/node", + "//packages/angular_devkit/core", + "//packages/angular_devkit/core:node_modules/chokidar", + "//packages/angular_devkit/core:node_modules/rxjs", + ], +) + +ts_project( + name = "node_test_lib", + testonly = True, + srcs = glob( + include = [ + "**/*_spec.ts", + ], + exclude = [ + "testing/**/*.ts", + ], + ), + deps = [ + ":node", + "//:node_modules/@types/jasmine", + "//:node_modules/@types/node", + "//packages/angular_devkit/core", + "//packages/angular_devkit/core:node_modules/rxjs", + ], +) + +jasmine_test( + name = "test", + data = [":node_test_lib"], +) diff --git a/packages/angular_devkit/core/node/_golden-api.ts b/packages/angular_devkit/core/node/_golden-api.ts deleted file mode 100644 index 47ee07c9b864..000000000000 --- a/packages/angular_devkit/core/node/_golden-api.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// Start experimental namespace -// Start jobs namespace -export * from './experimental/jobs/job-registry'; -// End jobs namespace -// End experimental namespace - -export * from './fs'; -export * from './cli-logger'; -export * from './host'; -export { ModuleNotFoundException, ResolveOptions, resolve } from './resolve'; diff --git a/packages/angular_devkit/core/node/cli-logger.ts b/packages/angular_devkit/core/node/cli-logger.ts index 2a9eb1562f47..a5cbada271ec 100644 --- a/packages/angular_devkit/core/node/cli-logger.ts +++ b/packages/angular_devkit/core/node/cli-logger.ts @@ -1,12 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { filter } from 'rxjs/operators'; -import { logging, terminal } from '../src'; + +import { filter } from 'rxjs'; +import { logging } from '../src'; export interface ProcessOutput { write(buffer: string | Buffer): boolean; @@ -14,6 +15,8 @@ export interface ProcessOutput { /** * A Logger that sends information to STDOUT and STDERR. + * + * @deprecated Use a custom logger implementation instead. */ export function createConsoleLogger( verbose = false, @@ -23,53 +26,46 @@ export function createConsoleLogger( ): logging.Logger { const logger = new logging.IndentLogger('cling'); - logger - .pipe(filter(entry => (entry.level != 'debug' || verbose))) - .subscribe(entry => { - let color = colors && colors[entry.level]; - let output = stdout; - switch (entry.level) { - case 'info': - break; - case 'warn': - color = color || (s => terminal.bold(terminal.yellow(s))); - output = stderr; - break; - case 'fatal': - case 'error': - color = color || (s => terminal.bold(terminal.red(s))); - output = stderr; - break; - } + logger.pipe(filter((entry) => entry.level !== 'debug' || verbose)).subscribe((entry) => { + const color = colors && colors[entry.level]; + let output = stdout; + + switch (entry.level) { + case 'warn': + case 'fatal': + case 'error': + output = stderr; + break; + } - // If we do console.log(message) or process.stdout.write(message + '\n'), the process might - // stop before the whole message is written and the stream is flushed. This happens when - // streams are asynchronous. - // - // NodeJS IO streams are different depending on platform and usage. In POSIX environment, - // for example, they're asynchronous when writing to a pipe, but synchronous when writing - // to a TTY. In windows, it's the other way around. You can verify which is which with - // stream.isTTY and platform, but this is not good enough. - // In the async case, one should wait for the callback before sending more data or - // continuing the process. In our case it would be rather hard to do (but not impossible). - // - // Instead we take the easy way out and simply chunk the message and call the write - // function while the buffer drain itself asynchronously. With a smaller chunk size than - // the buffer, we are mostly certain that it works. In this case, the chunk has been picked - // as half a page size (4096/2 = 2048), minus some bytes for the color formatting. - // On POSIX it seems the buffer is 2 pages (8192), but just to be sure (could be different - // by platform). - // - // For more details, see https://nodejs.org/api/process.html#process_a_note_on_process_i_o - const chunkSize = 2000; // Small chunk. - let message = entry.message; - while (message) { - const chunk = message.slice(0, chunkSize); - message = message.slice(chunkSize); - output.write(color ? color(chunk) : chunk); - } - output.write('\n'); - }); + // If we do console.log(message) or process.stdout.write(message + '\n'), the process might + // stop before the whole message is written and the stream is flushed. This happens when + // streams are asynchronous. + // + // NodeJS IO streams are different depending on platform and usage. In POSIX environment, + // for example, they're asynchronous when writing to a pipe, but synchronous when writing + // to a TTY. In windows, it's the other way around. You can verify which is which with + // stream.isTTY and platform, but this is not good enough. + // In the async case, one should wait for the callback before sending more data or + // continuing the process. In our case it would be rather hard to do (but not impossible). + // + // Instead we take the easy way out and simply chunk the message and call the write + // function while the buffer drain itself asynchronously. With a smaller chunk size than + // the buffer, we are mostly certain that it works. In this case, the chunk has been picked + // as half a page size (4096/2 = 2048), minus some bytes for the color formatting. + // On POSIX it seems the buffer is 2 pages (8192), but just to be sure (could be different + // by platform). + // + // For more details, see https://nodejs.org/api/process.html#process_a_note_on_process_i_o + const chunkSize = 2000; // Small chunk. + let message = entry.message; + while (message) { + const chunk = message.slice(0, chunkSize); + message = message.slice(chunkSize); + output.write(color ? color(chunk) : chunk); + } + output.write('\n'); + }); return logger; } diff --git a/packages/angular_devkit/core/node/experimental/index.ts b/packages/angular_devkit/core/node/experimental/index.ts deleted file mode 100644 index 012ac72a4ae5..000000000000 --- a/packages/angular_devkit/core/node/experimental/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as jobs from './jobs'; - -export { - jobs, -}; diff --git a/packages/angular_devkit/core/node/experimental/jobs/index.ts b/packages/angular_devkit/core/node/experimental/jobs/index.ts deleted file mode 100644 index d931a0289414..000000000000 --- a/packages/angular_devkit/core/node/experimental/jobs/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './job-registry'; diff --git a/packages/angular_devkit/core/node/experimental/jobs/job-registry.ts b/packages/angular_devkit/core/node/experimental/jobs/job-registry.ts deleted file mode 100644 index d1f5d6e15adb..000000000000 --- a/packages/angular_devkit/core/node/experimental/jobs/job-registry.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Observable, of } from 'rxjs'; -import { JsonValue, experimental as core_experimental, schema } from '../../../src'; - -export class NodeModuleJobRegistry implements core_experimental.jobs.Registry { - - protected _resolve(name: string): string | null { - try { - return require.resolve(name); - } catch (e) { - if (e.code === 'MODULE_NOT_FOUND') { - return null; - } - throw e; - } - } - - /** - * Get a job description for a named job. - * - * @param name The name of the job. - * @returns A description, or null if the job is not registered. - */ - get( - name: core_experimental.jobs.JobName, - ): Observable | null> { - const [moduleName, exportName] = name.split(/#/, 2); - - const resolvedPath = this._resolve(moduleName); - if (!resolvedPath) { - return of(null); - } - - const pkg = require(resolvedPath); - const handler = pkg[exportName || 'default']; - if (!handler) { - return of(null); - } - - // TODO: this should be unknown - // tslint:disable-next-line:no-any - function _getValue(...fields: any[]) { - return fields.find(x => schema.isJsonSchema(x)) || true; - } - - const argument = _getValue(pkg.argument, handler.argument); - const input = _getValue(pkg.input, handler.input); - const output = _getValue(pkg.output, handler.output); - const channels = _getValue(pkg.channels, handler.channels); - - return of(Object.assign(handler.bind(undefined), { - jobDescription: { - argument, - input, - output, - channels, - }, - })); - } -} diff --git a/packages/angular_devkit/core/node/experimental/jobs/job-registry_spec.ts b/packages/angular_devkit/core/node/experimental/jobs/job-registry_spec.ts deleted file mode 100644 index 2a46aa873995..000000000000 --- a/packages/angular_devkit/core/node/experimental/jobs/job-registry_spec.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as path from 'path'; -import { experimental as core_experimental } from '../../../src'; -import { NodeModuleJobRegistry } from './job-registry'; - -const root = path.join( - path.dirname(require.resolve(__filename)), - '../../../../../../tests/angular_devkit/core/node/jobs', -); - - -describe('NodeModuleJobScheduler', () => { - it('works', async () => { - const registry = new NodeModuleJobRegistry(); - const scheduler = new core_experimental.jobs.SimpleScheduler(registry); - - const job = scheduler.schedule(path.join(root, 'add'), [1, 2, 3]); - expect(await job.output.toPromise()).toBe(6); - }); -}); diff --git a/packages/angular_devkit/core/node/fs.ts b/packages/angular_devkit/core/node/fs.ts deleted file mode 100644 index f6df37c3cb63..000000000000 --- a/packages/angular_devkit/core/node/fs.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { statSync } from 'fs'; - -export function isFile(filePath: string): boolean { - let stat; - try { - stat = statSync(filePath); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) { - return false; - } - throw e; - } - - return stat.isFile() || stat.isFIFO(); -} - - -export function isDirectory(filePath: string): boolean { - let stat; - try { - stat = statSync(filePath); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) { - return false; - } - throw e; - } - - return stat.isDirectory(); -} diff --git a/packages/angular_devkit/core/node/host.ts b/packages/angular_devkit/core/node/host.ts index 27e716fc2a41..107ce003c7f0 100644 --- a/packages/angular_devkit/core/node/host.ts +++ b/packages/angular_devkit/core/node/host.ts @@ -1,193 +1,114 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as fs from 'fs'; -import { Observable, concat, from as observableFrom, of, throwError } from 'rxjs'; -import { - concatMap, - ignoreElements, - map, - mergeMap, - publish, - refCount, -} from 'rxjs/operators'; + import { - Path, - PathFragment, - dirname, - fragment, - getSystemPath, - join, - normalize, - virtualFs, -} from '../src'; - - -interface ChokidarWatcher { - new (options: {}): ChokidarWatcher; - - add(path: string): ChokidarWatcher; - on(type: 'change', cb: (path: string) => void): ChokidarWatcher; - on(type: 'add', cb: (path: string) => void): ChokidarWatcher; - on(type: 'unlink', cb: (path: string) => void): ChokidarWatcher; - - close(): void; + PathLike, + Stats, + constants, + existsSync, + promises as fsPromises, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname as pathDirname } from 'node:path'; +import { Observable, map, mergeMap, from as observableFrom, publish, refCount } from 'rxjs'; +import { Path, PathFragment, dirname, fragment, getSystemPath, normalize, virtualFs } from '../src'; + +async function exists(path: PathLike): Promise { + try { + await fsPromises.access(path, constants.F_OK); + + return true; + } catch { + return false; + } } // This will only be initialized if the watch() method is called. // Otherwise chokidar appears only in type positions, and shouldn't be referenced // in the JavaScript output. -let FSWatcher: ChokidarWatcher; +let FSWatcher: typeof import('chokidar').FSWatcher; function loadFSWatcher() { if (!FSWatcher) { try { - // tslint:disable-next-line:no-implicit-dependencies FSWatcher = require('chokidar').FSWatcher; } catch (e) { - if (e.code !== 'MODULE_NOT_FOUND') { - throw new Error('As of angular-devkit version 8.0, the "chokidar" package ' + - 'must be installed in order to use watch() features.'); + if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') { + throw new Error( + 'As of angular-devkit version 8.0, the "chokidar" package ' + + 'must be installed in order to use watch() features.', + { + cause: e, + }, + ); } throw e; } } } -type FsFunction0 = (cb: (err?: Error, result?: R) => void) => void; -type FsFunction1 = (p1: T1, cb: (err?: Error, result?: R) => void) => void; -type FsFunction2 - = (p1: T1, p2: T2, cb: (err?: Error, result?: R) => void) => void; - - -function _callFs(fn: FsFunction0): Observable; -function _callFs(fn: FsFunction1, p1: T1): Observable; -function _callFs(fn: FsFunction2, p1: T1, p2: T2): Observable; - -function _callFs(fn: Function, ...args: {}[]): Observable { - return new Observable(obs => { - fn(...args, (err?: Error, result?: ResultT) => { - if (err) { - obs.error(err); - } else { - obs.next(result); - obs.complete(); - } - }); - }); -} - - /** * An implementation of the Virtual FS using Node as the background. There are two versions; one * synchronous and one asynchronous. */ -export class NodeJsAsyncHost implements virtualFs.Host { +export class NodeJsAsyncHost implements virtualFs.Host { get capabilities(): virtualFs.HostCapabilities { return { synchronous: false }; } write(path: Path, content: virtualFs.FileBuffer): Observable { - return new Observable(obs => { - // Create folders if necessary. - const _createDir = (path: Path) => { - if (fs.existsSync(getSystemPath(path))) { - return; - } - if (dirname(path) === path) { - throw new Error(); - } - _createDir(dirname(path)); - fs.mkdirSync(getSystemPath(path)); - }; - _createDir(dirname(path)); - - _callFs( - fs.writeFile, - getSystemPath(path), - new Uint8Array(content), - ).subscribe(obs); - }); + return observableFrom(fsPromises.mkdir(getSystemPath(dirname(path)), { recursive: true })).pipe( + mergeMap(() => fsPromises.writeFile(getSystemPath(path), new Uint8Array(content))), + ); } read(path: Path): Observable { - return _callFs(fs.readFile, getSystemPath(path)).pipe( - map(buffer => new Uint8Array(buffer).buffer as virtualFs.FileBuffer), + return observableFrom(fsPromises.readFile(getSystemPath(path))).pipe( + map((buffer) => new Uint8Array(buffer).buffer), ); } delete(path: Path): Observable { - return this.isDirectory(path).pipe( - mergeMap(isDirectory => { - if (isDirectory) { - const allFiles: Path[] = []; - const allDirs: Path[] = []; - const _recurseList = (path: Path) => { - for (const fragment of fs.readdirSync(getSystemPath(path))) { - if (fs.statSync(getSystemPath(join(path, fragment))).isDirectory()) { - _recurseList(join(path, fragment)); - allDirs.push(join(path, fragment)); - } else { - allFiles.push(join(path, fragment)); - } - } - }; - _recurseList(path); - - return concat( - observableFrom(allFiles).pipe( - mergeMap(p => _callFs(fs.unlink, getSystemPath(p))), - ignoreElements(), - ), - observableFrom(allDirs).pipe( - concatMap(p => _callFs(fs.rmdir, getSystemPath(p))), - ), - ); - } else { - return _callFs(fs.unlink, getSystemPath(path)); - } - }), - map(() => undefined), + return observableFrom( + fsPromises.rm(getSystemPath(path), { force: true, recursive: true, maxRetries: 3 }), ); } rename(from: Path, to: Path): Observable { - return _callFs(fs.rename, getSystemPath(from), getSystemPath(to)); + return observableFrom(fsPromises.rename(getSystemPath(from), getSystemPath(to))); } list(path: Path): Observable { - return _callFs(fs.readdir, getSystemPath(path)).pipe( - map((names: string[]) => names.map(name => fragment(name))), + return observableFrom(fsPromises.readdir(getSystemPath(path))).pipe( + map((names) => names.map((name) => fragment(name))), ); } exists(path: Path): Observable { - // Exists is a special case because it cannot error. - return new Observable(obs => { - fs.exists(path, exists => { - obs.next(exists); - obs.complete(); - }); - }); + return observableFrom(exists(getSystemPath(path))); } isDirectory(path: Path): Observable { - return _callFs(fs.stat, getSystemPath(path)).pipe( - map(stat => stat.isDirectory()), - ); + return this.stat(path).pipe(map((stat) => stat.isDirectory())); } + isFile(path: Path): Observable { - return _callFs(fs.stat, getSystemPath(path)).pipe( - map(stat => stat.isFile()), - ); + return this.stat(path).pipe(map((stat) => stat.isFile())); } // Some hosts may not support stat. - stat(path: Path): Observable> | null { - return _callFs(fs.stat, getSystemPath(path)); + stat(path: Path): Observable> { + return observableFrom(fsPromises.stat(getSystemPath(path))); } // Some hosts may not support watching. @@ -195,26 +116,27 @@ export class NodeJsAsyncHost implements virtualFs.Host { path: Path, _options?: virtualFs.HostWatchOptions, ): Observable | null { - return new Observable(obs => { + return new Observable((obs) => { loadFSWatcher(); - const watcher = new FSWatcher({ persistent: true }).add(getSystemPath(path)); + const watcher = new FSWatcher({ persistent: true }); + watcher.add(getSystemPath(path)); watcher - .on('change', path => { + .on('change', (path) => { obs.next({ path: normalize(path), time: new Date(), type: virtualFs.HostWatchEventType.Changed, }); }) - .on('add', path => { + .on('add', (path) => { obs.next({ path: normalize(path), time: new Date(), type: virtualFs.HostWatchEventType.Created, }); }) - .on('unlink', path => { + .on('unlink', (path) => { obs.next({ path: normalize(path), time: new Date(), @@ -222,156 +144,85 @@ export class NodeJsAsyncHost implements virtualFs.Host { }); }); - return () => watcher.close(); - }).pipe( - publish(), - refCount(), - ); + return () => { + void watcher.close(); + }; + }).pipe(publish(), refCount()); } } - /** * An implementation of the Virtual FS using Node as the backend, synchronously. */ -export class NodeJsSyncHost implements virtualFs.Host { +export class NodeJsSyncHost implements virtualFs.Host { get capabilities(): virtualFs.HostCapabilities { return { synchronous: true }; } write(path: Path, content: virtualFs.FileBuffer): Observable { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - // Create folders if necessary. - const _createDir = (path: Path) => { - if (fs.existsSync(getSystemPath(path))) { - return; - } - _createDir(dirname(path)); - fs.mkdirSync(getSystemPath(path)); - }; - _createDir(dirname(path)); - fs.writeFileSync(getSystemPath(path), new Uint8Array(content)); - - obs.next(); - obs.complete(); - } catch (err) { - obs.error(err); - } + return new Observable((obs) => { + mkdirSync(getSystemPath(dirname(path)), { recursive: true }); + writeFileSync(getSystemPath(path), new Uint8Array(content)); + obs.next(); + obs.complete(); }); } read(path: Path): Observable { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - const buffer = fs.readFileSync(getSystemPath(path)); - - obs.next(new Uint8Array(buffer).buffer as virtualFs.FileBuffer); - obs.complete(); - } catch (err) { - obs.error(err); - } + return new Observable((obs) => { + const buffer = readFileSync(getSystemPath(path)); + + obs.next(new Uint8Array(buffer).buffer); + obs.complete(); }); } delete(path: Path): Observable { - return this.isDirectory(path).pipe( - concatMap(isDir => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - if (isDir) { - const dirPaths = fs.readdirSync(getSystemPath(path)); - const rmDirComplete = new Observable((obs) => { - try { - fs.rmdirSync(getSystemPath(path)); - obs.complete(); - } catch (e) { - obs.error(e); - } - }); + return new Observable((obs) => { + rmSync(getSystemPath(path), { force: true, recursive: true, maxRetries: 3 }); - return concat( - ...dirPaths.map(name => this.delete(join(path, name))), - rmDirComplete, - ); - } else { - try { - fs.unlinkSync(getSystemPath(path)); - } catch (err) { - return throwError(err); - } - - return of(undefined); - } - }), - ); + obs.complete(); + }); } rename(from: Path, to: Path): Observable { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - fs.renameSync(getSystemPath(from), getSystemPath(to)); - obs.next(); - obs.complete(); - } catch (err) { - obs.error(err); - } + return new Observable((obs) => { + const toSystemPath = getSystemPath(to); + mkdirSync(pathDirname(toSystemPath), { recursive: true }); + renameSync(getSystemPath(from), toSystemPath); + obs.next(); + obs.complete(); }); } list(path: Path): Observable { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - const names = fs.readdirSync(getSystemPath(path)); - obs.next(names.map(name => fragment(name))); - obs.complete(); - } catch (err) { - obs.error(err); - } + return new Observable((obs) => { + const names = readdirSync(getSystemPath(path)); + obs.next(names.map((name) => fragment(name))); + obs.complete(); }); } exists(path: Path): Observable { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - obs.next(fs.existsSync(getSystemPath(path))); - obs.complete(); - } catch (err) { - obs.error(err); - } + return new Observable((obs) => { + obs.next(existsSync(getSystemPath(path))); + obs.complete(); }); } isDirectory(path: Path): Observable { - // tslint:disable-next-line:no-non-null-assertion - return this.stat(path) !.pipe(map(stat => stat.isDirectory())); + return this.stat(path).pipe(map((stat) => stat.isDirectory())); } + isFile(path: Path): Observable { - // tslint:disable-next-line:no-non-null-assertion - return this.stat(path) !.pipe(map(stat => stat.isFile())); + return this.stat(path).pipe(map((stat) => stat.isFile())); } // Some hosts may not support stat. - stat(path: Path): Observable> { - return new Observable(obs => { - // TODO: remove this try+catch when issue https://github.com/ReactiveX/rxjs/issues/3740 is - // fixed. - try { - obs.next(fs.statSync(getSystemPath(path))); - obs.complete(); - } catch (err) { - obs.error(err); - } + stat(path: Path): Observable> { + return new Observable((obs) => { + obs.next(statSync(getSystemPath(path))); + obs.complete(); }); } @@ -380,27 +231,27 @@ export class NodeJsSyncHost implements virtualFs.Host { path: Path, _options?: virtualFs.HostWatchOptions, ): Observable | null { - return new Observable(obs => { - const opts = { persistent: false }; + return new Observable((obs) => { loadFSWatcher(); - const watcher = new FSWatcher(opts).add(getSystemPath(path)); + const watcher = new FSWatcher({ persistent: false }); + watcher.add(getSystemPath(path)); watcher - .on('change', path => { + .on('change', (path) => { obs.next({ path: normalize(path), time: new Date(), type: virtualFs.HostWatchEventType.Changed, }); }) - .on('add', path => { + .on('add', (path) => { obs.next({ path: normalize(path), time: new Date(), type: virtualFs.HostWatchEventType.Created, }); }) - .on('unlink', path => { + .on('unlink', (path) => { obs.next({ path: normalize(path), time: new Date(), @@ -408,10 +259,9 @@ export class NodeJsSyncHost implements virtualFs.Host { }); }); - return () => watcher.close(); - }).pipe( - publish(), - refCount(), - ); + return () => { + void watcher.close(); + }; + }).pipe(publish(), refCount()); } } diff --git a/packages/angular_devkit/core/node/host_spec.ts b/packages/angular_devkit/core/node/host_spec.ts index 1b55218d64f9..fba147359f98 100644 --- a/packages/angular_devkit/core/node/host_spec.ts +++ b/packages/angular_devkit/core/node/host_spec.ts @@ -1,20 +1,17 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any -// tslint:disable:no-non-null-assertion -// tslint:disable:no-implicit-dependencies -import { normalize, virtualFs } from '@angular-devkit/core'; -import { NodeJsAsyncHost, NodeJsSyncHost } from '@angular-devkit/core/node'; -import * as fs from 'fs'; -import { Observable, Subscription } from 'rxjs'; - -const temp = require('temp'); +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { normalize, virtualFs } from '../src'; +import { NodeJsAsyncHost, NodeJsSyncHost } from './host'; // TODO: replace this with an "it()" macro that's reusable globally. let linuxOnlyIt: typeof it = it; @@ -22,90 +19,113 @@ if (process.platform.startsWith('win') || process.platform.startsWith('darwin')) linuxOnlyIt = xit; } - describe('NodeJsAsyncHost', () => { let root: string; let host: virtualFs.Host; beforeEach(() => { - root = temp.mkdirSync('core-node-spec-'); + root = fs.mkdtempSync(join(fs.realpathSync(tmpdir()), 'core-node-spec-')); host = new virtualFs.ScopedHost(new NodeJsAsyncHost(), normalize(root)); }); - afterEach(done => host.delete(normalize('/')).toPromise().then(done, done.fail)); - - linuxOnlyIt('can watch', done => { - let obs: Observable; - let subscription: Subscription; - const content = virtualFs.stringToFileBuffer('hello world'); - const content2 = virtualFs.stringToFileBuffer('hello world 2'); - const allEvents: virtualFs.HostWatchEvent[] = []; - - Promise.resolve() - .then(() => fs.mkdirSync(root + '/sub1')) - .then(() => fs.writeFileSync(root + '/sub1/file1', 'hello world')) - .then(() => { - obs = host.watch(normalize('/sub1'), { recursive: true }) !; - expect(obs).not.toBeNull(); - subscription = obs.subscribe(event => { allEvents.push(event); }); - }) - .then(() => new Promise(resolve => setTimeout(resolve, 100))) + + afterEach(async () => host.delete(normalize('/')).toPromise()); + + it('should get correct result for exists', async () => { + const filePath = normalize('not-found'); + expect(await host.exists(filePath).toPromise()).toBeFalse(); + await host.write(filePath, new TextEncoder().encode('content').buffer).toPromise(); + expect(await host.exists(filePath).toPromise()).toBeTrue(); + }); + + linuxOnlyIt( + 'can watch', + async () => { + const content = new TextEncoder().encode('hello world').buffer; + const content2 = new TextEncoder().encode('hello world 2').buffer; + const allEvents: virtualFs.HostWatchEvent[] = []; + + fs.mkdirSync(root + '/sub1'); + fs.writeFileSync(root + '/sub1/file1', 'hello world'); + + const obs = host.watch(normalize('/sub1'), { recursive: true }); + expect(obs).toBeDefined(); + const subscription = obs!.subscribe((event) => { + allEvents.push(event); + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + // Discard the events registered so far. - .then(() => allEvents.splice(0)) - .then(() => host.write(normalize('/sub1/sub2/file3'), content).toPromise()) - .then(() => host.write(normalize('/sub1/file2'), content2).toPromise()) - .then(() => host.delete(normalize('/sub1/file1')).toPromise()) - .then(() => new Promise(resolve => setTimeout(resolve, 2000))) - .then(() => { - expect(allEvents.length).toBe(3); - subscription.unsubscribe(); - }) - .then(done, done.fail); - }, 30000); -}); + allEvents.splice(0); + await host.write(normalize('/sub1/sub2/file3'), content).toPromise(); + await host.write(normalize('/sub1/file2'), content2).toPromise(); + await host.delete(normalize('/sub1/file1')).toPromise(); + await new Promise((resolve) => setTimeout(resolve, 2000)); + expect(allEvents.length).toBe(3); + subscription.unsubscribe(); + }, + 30000, + ); +}); describe('NodeJsSyncHost', () => { let root: string; let host: virtualFs.SyncDelegateHost; beforeEach(() => { - root = temp.mkdirSync('core-node-spec-'); + root = fs.mkdtempSync(join(fs.realpathSync(tmpdir()), 'core-node-spec-')); host = new virtualFs.SyncDelegateHost( - new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(root))); + new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(root)), + ); }); afterEach(() => { host.delete(normalize('/')); }); - linuxOnlyIt('can watch', done => { - let obs: Observable; - let subscription: Subscription; - const content = virtualFs.stringToFileBuffer('hello world'); - const content2 = virtualFs.stringToFileBuffer('hello world 2'); - const allEvents: virtualFs.HostWatchEvent[] = []; - - Promise.resolve() - .then(() => fs.mkdirSync(root + '/sub1')) - .then(() => fs.writeFileSync(root + '/sub1/file1', 'hello world')) - .then(() => { - obs = host.watch(normalize('/sub1'), { recursive: true })!; - expect(obs).not.toBeNull(); - subscription = obs.subscribe(event => { allEvents.push(event); }); - }) - .then(() => new Promise(resolve => setTimeout(resolve, 100))) + linuxOnlyIt( + 'can watch', + async () => { + const content = new TextEncoder().encode('hello world').buffer; + const content2 = new TextEncoder().encode('hello world 2').buffer; + const allEvents: virtualFs.HostWatchEvent[] = []; + + fs.mkdirSync(root + '/sub1'); + fs.writeFileSync(root + '/sub1/file1', 'hello world'); + + const obs = host.watch(normalize('/sub1'), { recursive: true }); + expect(obs).toBeDefined(); + const subscription = obs!.subscribe((event) => { + allEvents.push(event); + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + // Discard the events registered so far. - .then(() => allEvents.splice(0)) - .then(() => { - host.write(normalize('/sub1/sub2/file3'), content); - host.write(normalize('/sub1/file2'), content2); - host.delete(normalize('/sub1/file1')); - }) - .then(() => new Promise(resolve => setTimeout(resolve, 2000))) - .then(() => { - expect(allEvents.length).toBe(3); - subscription.unsubscribe(); - }) - .then(done, done.fail); - }, 30000); + allEvents.splice(0); + + host.write(normalize('/sub1/sub2/file3'), content); + host.write(normalize('/sub1/file2'), content2); + host.delete(normalize('/sub1/file1')); + await new Promise((resolve) => setTimeout(resolve, 2000)); + + expect(allEvents.length).toBe(3); + subscription.unsubscribe(); + }, + 30000, + ); + + linuxOnlyIt( + 'rename to a non-existing dir', + () => { + fs.mkdirSync(root + '/rename'); + fs.writeFileSync(root + '/rename/a.txt', 'hello world'); + host.rename(normalize('/rename/a.txt'), normalize('/rename/b/c/d/a.txt')); + if (fs.existsSync(root + '/rename/b/c/d/a.txt')) { + const resContent = host.read(normalize('/rename/b/c/d/a.txt')); + const content = new TextDecoder().decode(resContent); + expect(content).toEqual('hello world'); + } + }, + 30000, + ); }); diff --git a/packages/angular_devkit/core/node/index.ts b/packages/angular_devkit/core/node/index.ts index fa96ae914e54..ab21d04c9e30 100644 --- a/packages/angular_devkit/core/node/index.ts +++ b/packages/angular_devkit/core/node/index.ts @@ -1,17 +1,10 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as experimental from './experimental/jobs/job-registry'; -import * as fs from './fs'; + export * from './cli-logger'; export * from './host'; -export { ModuleNotFoundException, ResolveOptions, resolve } from './resolve'; - -export { - experimental, - fs, -}; diff --git a/packages/angular_devkit/core/node/resolve.ts b/packages/angular_devkit/core/node/resolve.ts deleted file mode 100644 index 47c0578940ec..000000000000 --- a/packages/angular_devkit/core/node/resolve.ts +++ /dev/null @@ -1,316 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as fs from 'fs'; -import * as path from 'path'; -import { BaseException } from '../src'; -import { isFile } from './fs'; - -/** - * Exception thrown when a module could not be resolved. - * @deprecated since version 8. Use `MODULE_NOT_FOUND` Node error code instead. - */ -export class ModuleNotFoundException extends BaseException { - public readonly code: string; - - constructor(public readonly moduleName: string, public readonly basePath: string) { - super(`Could not find module ${JSON.stringify(moduleName)} from ${JSON.stringify(basePath)}.`); - this.code = 'MODULE_NOT_FOUND'; - } -} - -/** - * Returns a list of all the callers from the resolve() call. - * @returns {string[]} - * @private - */ -function _caller(): string[] { - // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - const error = Error as {} as { prepareStackTrace: (x: {}, stack: {}) => {} }; - const origPrepareStackTrace = error.prepareStackTrace; - error.prepareStackTrace = (_, stack) => stack; - const stack = (new Error()).stack as {} | undefined as { getFileName(): string }[] | undefined; - error.prepareStackTrace = origPrepareStackTrace; - - return stack ? stack.map(x => x.getFileName()).filter(x => !!x) : []; -} - - -/** - * Get the global directory for node_modules. This is based on NPM code itself, and may be subject - * to change, but is relatively stable. - * @returns {string} The path to node_modules itself. - * @private - */ -function _getGlobalNodeModules() { - let globalPrefix; - - if (process.env.PREFIX) { - globalPrefix = process.env.PREFIX; - } else if (process.platform === 'win32') { - // c:\node\node.exe --> prefix=c:\node\ - globalPrefix = path.dirname(process.execPath); - } else { - // /usr/local/bin/node --> prefix=/usr/local - globalPrefix = path.dirname(path.dirname(process.execPath)); - - // destdir only is respected on Unix - const destdir = process.env.DESTDIR; - if (destdir) { - globalPrefix = path.join(destdir, globalPrefix); - } - } - - return (process.platform !== 'win32') - ? path.resolve(globalPrefix || '', 'lib', 'node_modules') - : path.resolve(globalPrefix || '', 'node_modules'); -} - - -/** @deprecated since version 8. Use `require.resolve` instead. */ -export interface ResolveOptions { - /** - * The basedir to use from which to resolve. - */ - basedir: string; - - /** - * The list of extensions to resolve. By default uses Object.keys(require.extensions). - */ - extensions?: string[]; - - /** - * An additional list of paths to look into. - */ - paths?: string[]; - - /** - * Whether or not to preserve symbolic links. If false, the actual paths pointed by - * the symbolic links will be used. This defaults to true. - */ - preserveSymlinks?: boolean; - - /** - * Whether to fallback to a global lookup if the basedir one failed. - */ - checkGlobal?: boolean; - - /** - * Whether to fallback to using the local caller's directory if the basedir failed. - */ - checkLocal?: boolean; - - /** - * Whether to only resolve and return the first package.json file found. By default, - * resolves the main field or the index of the package. - */ - resolvePackageJson?: boolean; -} - - -let _resolveHook: ((x: string, options: ResolveOptions) => string | null) | null = null; -/** @deprecated since version 8. Use `require.resolve` instead. */ -export function setResolveHook( - hook: ((x: string, options: ResolveOptions) => string | null) | null, -) { - _resolveHook = hook; -} - - -/** - * Resolve a package using a logic similar to npm require.resolve, but with more options. - * @param packageName The package name to resolve. - * @param options A list of options. See documentation of those options. - * @returns {string} Path to the index to include, or if `resolvePackageJson` option was - * passed, a path to that file. - * @throws {ModuleNotFoundException} If no module with that name was found anywhere. - * @deprecated since version 8. Use `require.resolve` instead. - */ -export function resolve(packageName: string, options: ResolveOptions): string { - if (_resolveHook) { - const maybe = _resolveHook(packageName, options); - if (maybe) { - return maybe; - } - } - - const readFileSync = fs.readFileSync; - - const extensions: string[] = options.extensions || Object.keys(require.extensions); - const basePath = options.basedir; - - options.paths = options.paths || []; - - if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\/\\])/.test(packageName)) { - let res = path.resolve(basePath, packageName); - if (packageName === '..' || packageName.slice(-1) === '/') { - res += '/'; - } - - const m = loadAsFileSync(res) || loadAsDirectorySync(res); - if (m) { - return m; - } - } else { - const n = loadNodeModulesSync(packageName, basePath); - if (n) { - return n; - } - } - - // Fallback to checking the local (callee) node modules. - if (options.checkLocal) { - const callers = _caller(); - for (const caller of callers) { - const localDir = path.dirname(caller); - if (localDir !== options.basedir) { - try { - return resolve(packageName, { - ...options, - checkLocal: false, - checkGlobal: false, - basedir: localDir, - }); - } catch (e) { - // Just swap the basePath with the original call one. - if (!(e instanceof ModuleNotFoundException)) { - throw e; - } - } - } - } - } - - // Fallback to checking the global node modules. - if (options.checkGlobal) { - const globalDir = path.dirname(_getGlobalNodeModules()); - if (globalDir !== options.basedir) { - try { - return resolve(packageName, { - ...options, - checkLocal: false, - checkGlobal: false, - basedir: globalDir, - }); - } catch (e) { - // Just swap the basePath with the original call one. - if (!(e instanceof ModuleNotFoundException)) { - throw e; - } - } - } - } - - throw new ModuleNotFoundException(packageName, basePath); - - function loadAsFileSync(x: string): string | null { - if (isFile(x)) { - return x; - } - - return extensions.map(ex => x + ex).find(f => isFile(f)) || null; - } - - function loadAsDirectorySync(x: string): string | null { - const pkgfile = path.join(x, 'package.json'); - if (isFile(pkgfile)) { - if (options.resolvePackageJson) { - return pkgfile; - } - - try { - const body = readFileSync(pkgfile, 'UTF8'); - const pkg = JSON.parse(body); - - if (pkg['main']) { - if (pkg['main'] === '.' || pkg['main'] === './') { - pkg['main'] = 'index'; - } - - const m = loadAsFileSync(path.resolve(x, pkg['main'])); - if (m) { - return m; - } - const n = loadAsDirectorySync(path.resolve(x, pkg['main'])); - if (n) { - return n; - } - } - } catch {} - } - - return loadAsFileSync(path.join(x, '/index')); - } - - function loadNodeModulesSync(x: string, start: string): string | null { - const dirs = nodeModulesPaths(start, options); - for (const dir of dirs) { - const m = loadAsFileSync(path.join(dir, x)); - if (m) { - return m; - } - const n = loadAsDirectorySync(path.join(dir, x)); - if (n) { - return n; - } - } - - return null; - } - - function nodeModulesPaths(start: string, opts: ResolveOptions) { - const modules = ['node_modules']; - if (process.env.BAZEL_TARGET) { - // When running test under Bazel, node_modules have to be resolved - // differently. node_modules are installed in the `npm` workspace. - // For more info, see `yarn_install` rule in WORKSPACE file. - modules.push(path.join('npm', 'node_modules')); - } - - // ensure that `start` is an absolute path at this point, - // resolving against the process' current working directory - let absoluteStart = path.resolve(start); - - if (opts && opts.preserveSymlinks === false) { - try { - absoluteStart = fs.realpathSync(absoluteStart); - } catch (err) { - if (err.code !== 'ENOENT') { - throw err; - } - } - } - - let prefix = '/'; - if (/^([A-Za-z]:)/.test(absoluteStart)) { - prefix = ''; - } else if (/^\\\\/.test(absoluteStart)) { - prefix = '\\\\'; - } - - const paths = [absoluteStart]; - let parsed = path.parse(absoluteStart); - while (parsed.dir !== paths[paths.length - 1]) { - paths.push(parsed.dir); - parsed = path.parse(parsed.dir); - } - - const dirs = paths.reduce((dirs: string[], aPath: string) => { - return dirs.concat(modules.map(function (moduleDir) { - return path.join(prefix, aPath, moduleDir); - })); - }, []); - - if (process.env.NG_TEMP_MODULES_DIR) { - // When running from a temporary installations, node_modules have to be resolved - // differently and they should be prefered over others. - dirs.unshift(process.env.NG_TEMP_MODULES_DIR); - } - - return opts && opts.paths ? dirs.concat(opts.paths) : dirs; - } -} diff --git a/packages/angular_devkit/core/node/resolve_spec.ts b/packages/angular_devkit/core/node/resolve_spec.ts deleted file mode 100644 index 03bed1baa803..000000000000 --- a/packages/angular_devkit/core/node/resolve_spec.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-any -// tslint:disable-next-line:no-implicit-dependencies -import { resolve } from '@angular-devkit/core/node'; - -describe('resolve', () => { - - it('works', () => { - const tslintRe = /[\\/]node_modules[\\/]tslint[\\/]lib[\\/]index.js$/; - expect(resolve('tslint', { basedir: __dirname })).toMatch(tslintRe); - - expect(() => resolve('npm', { basedir: '/' })).toThrow(); - - expect(() => resolve('npm', { basedir: '/', checkGlobal: true })).not.toThrow(); - }); - -}); diff --git a/packages/angular_devkit/core/node/testing/BUILD.bazel b/packages/angular_devkit/core/node/testing/BUILD.bazel new file mode 100644 index 000000000000..fb7ffe1059d5 --- /dev/null +++ b/packages/angular_devkit/core/node/testing/BUILD.bazel @@ -0,0 +1,26 @@ +load("//tools:defaults.bzl", "ts_project") + +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license +licenses(["notice"]) + +package(default_visibility = ["//visibility:public"]) + +ts_project( + name = "testing", + srcs = glob( + include = ["**/*.ts"], + exclude = [ + "**/*_spec.ts", + ], + ), + deps = [ + "//:node_modules/@types/jasmine", + "//:node_modules/@types/node", + "//packages/angular_devkit/core", + "//packages/angular_devkit/core:node_modules/rxjs", + "//packages/angular_devkit/core/node", + ], +) diff --git a/packages/angular_devkit/core/node/testing/index.ts b/packages/angular_devkit/core/node/testing/index.ts index ec9d6fd9e257..cecc0c08e3c6 100644 --- a/packages/angular_devkit/core/node/testing/index.ts +++ b/packages/angular_devkit/core/node/testing/index.ts @@ -1,25 +1,29 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as fs from 'fs'; -import * as os from 'os'; -import * as path from 'path'; -import { Path, PathFragment, getSystemPath, join, normalize, virtualFs } from '../../src'; + +import * as crypto from 'node:crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { Path, getSystemPath, join, normalize, virtualFs } from '../../src'; import { NodeJsSyncHost } from '../host'; /** * A Sync Scoped Host that creates a temporary directory and scope to it. */ export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost { - protected _sync: virtualFs.SyncDelegateHost; - protected _root: Path; + protected _sync?: virtualFs.SyncDelegateHost; + protected override _root: Path; constructor() { - const root = normalize(path.join(os.tmpdir(), `devkit-host-${+Date.now()}-${process.pid}`)); + const root = normalize( + path.join(os.tmpdir(), `devkit-host-${crypto.randomUUID()}-${process.pid}`), + ); fs.mkdirSync(getSystemPath(root)); super(new NodeJsSyncHost(), root); @@ -29,9 +33,10 @@ export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost { get files(): Path[] { const sync = this.sync; function _visit(p: Path): Path[] { - return sync.list(p) - .map((fragment: PathFragment) => join(p, fragment)) - .reduce((files: Path[], path: PathFragment) => { + return sync + .list(p) + .map((fragment) => join(p, fragment)) + .reduce((files, path) => { if (sync.isDirectory(path)) { return files.concat(_visit(path)); } else { @@ -43,7 +48,9 @@ export class TempScopedNodeJsSyncHost extends virtualFs.ScopedHost { return _visit(normalize('/')); } - get root() { return this._root; } + get root() { + return this._root; + } get sync() { if (!this._sync) { this._sync = new virtualFs.SyncDelegateHost(this); diff --git a/packages/angular_devkit/core/package.json b/packages/angular_devkit/core/package.json index c564a8b8cecf..2d93dde02305 100644 --- a/packages/angular_devkit/core/package.json +++ b/packages/angular_devkit/core/package.json @@ -1,20 +1,46 @@ { "name": "@angular-devkit/core", - "version": "0.0.0", + "version": "0.0.0-PLACEHOLDER", "description": "Angular DevKit - Core Utility Library", "main": "src/index.js", "typings": "src/index.d.ts", "keywords": [ "core" ], + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./node": { + "types": "./node/index.d.ts", + "default": "./node/index.js" + }, + "./node/testing": { + "types": "./node/testing/index.d.ts", + "default": "./node/testing/index.js" + }, + "./package.json": "./package.json", + "./*": "./*.js", + "./*.js": "./*.js" + }, "dependencies": { - "ajv": "6.10.2", - "fast-json-stable-stringify": "2.0.0", - "magic-string": "0.25.4", - "rxjs": "6.5.3", - "source-map": "0.7.3" + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "jsonc-parser": "3.3.1", + "picomatch": "4.0.7", + "rxjs": "7.8.2", + "source-map": "0.8.0" }, "devDependencies": { - "seedrandom": "^2.4.4" + "chokidar": "6.0.0" + }, + "peerDependencies": { + "chokidar": "^6.0.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } } } diff --git a/packages/angular_devkit/core/src/_golden-api.ts b/packages/angular_devkit/core/src/_golden-api.ts deleted file mode 100644 index 3956a152e0e6..000000000000 --- a/packages/angular_devkit/core/src/_golden-api.ts +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export * from './exception/exception'; - - // Start experimental namespace -export * from './experimental/workspace/index'; -// End experimental namespace - -// Start json namespace -export * from './json/interface'; -export * from './json/parser'; -export * from './json/schema/interface'; -export * from './json/schema/pointer'; -export * from './json/schema/registry'; -export * from './json/schema/visitor'; -export * from './json/schema/utility'; -export * from './json/schema/transforms'; -// End json namespace - -// Start logging namespace -export * from './logger/indent'; -export * from './logger/level'; -export * from './logger/logger'; -export * from './logger/null-logger'; -export * from './logger/transform-logger'; -// End logging namespace - -// Start terminal namespace -export * from './terminal/text'; -export * from './terminal/colors'; -// End terminal namespace - -// Start utils namespace -export * from './utils/literals'; -export * from './utils/strings'; -export * from './utils/array'; -export * from './utils/object'; -export * from './utils/template'; -export * from './utils/partially-ordered-set'; -export * from './utils/priority-queue'; -export * from './utils/lang'; -// End utils namespace - -// Start virtualFs namespace -export * from './virtual-fs/path'; -export * from './virtual-fs/host/index'; -// End virtualFs namespace - -// Start workspace namespace -export * from './workspace/index'; -// End workspace namespace - -// Start analytics namespace -export * from './analytics/index'; -// End analytics namespace diff --git a/packages/angular_devkit/core/src/analytics/api.ts b/packages/angular_devkit/core/src/analytics/api.ts deleted file mode 100644 index f538d1ba088a..000000000000 --- a/packages/angular_devkit/core/src/analytics/api.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export interface CustomDimensionsAndMetricsOptions { - dimensions?: (boolean | number | string)[]; - metrics?: (boolean | number | string)[]; -} - -export interface EventOptions extends CustomDimensionsAndMetricsOptions { - label?: string; - value?: string; -} - -export interface ScreenviewOptions extends CustomDimensionsAndMetricsOptions { - appVersion?: string; - appId?: string; - appInstallerId?: string; -} - -export interface PageviewOptions extends CustomDimensionsAndMetricsOptions { - hostname?: string; - title?: string; -} - -export interface TimingOptions extends CustomDimensionsAndMetricsOptions { - label?: string; -} - -/** - * Interface for managing analytics. This is highly platform dependent, and mostly matches - * Google Analytics. The reason the interface is here is to remove the dependency to an - * implementation from most other places. - * - * The methods exported from this interface more or less match those needed by us in the - * universal analytics package, see https://unpkg.com/@types/universal-analytics@0.4.2/index.d.ts - * for typings. We mostly named arguments to make it easier to follow, but didn't change or - * add any semantics to those methods. They're mapping GA and u-a one for one. - * - * The Angular CLI (or any other kind of backend) should forward it to some compatible backend. - */ -export interface Analytics { - event(category: string, action: string, options?: EventOptions): void; - screenview(screenName: string, appName: string, options?: ScreenviewOptions): void; - pageview(path: string, options?: PageviewOptions): void; - timing(category: string, variable: string, time: string | number, options?: TimingOptions): void; - - flush(): Promise; -} diff --git a/packages/angular_devkit/core/src/analytics/forwarder.ts b/packages/angular_devkit/core/src/analytics/forwarder.ts deleted file mode 100644 index 8c1ba6de6a92..000000000000 --- a/packages/angular_devkit/core/src/analytics/forwarder.ts +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { JsonObject } from '../json'; -import { Analytics, EventOptions, PageviewOptions, ScreenviewOptions, TimingOptions } from './api'; - - -export enum AnalyticsReportKind { - Event = 'event', - Screenview = 'screenview', - Pageview = 'pageview', - Timing = 'timing', -} - -export interface AnalyticsReportBase extends JsonObject { - kind: AnalyticsReportKind; -} - -export interface AnalyticsReportEvent extends AnalyticsReportBase { - kind: AnalyticsReportKind.Event; - options: JsonObject & EventOptions; - category: string; - action: string; -} -export interface AnalyticsReportScreenview extends AnalyticsReportBase { - kind: AnalyticsReportKind.Screenview; - options: JsonObject & ScreenviewOptions; - screenName: string; - appName: string; -} -export interface AnalyticsReportPageview extends AnalyticsReportBase { - kind: AnalyticsReportKind.Pageview; - options: JsonObject & PageviewOptions; - path: string; -} -export interface AnalyticsReportTiming extends AnalyticsReportBase { - kind: AnalyticsReportKind.Timing; - options: JsonObject & TimingOptions; - category: string; - variable: string; - time: string | number; -} - -export type AnalyticsReport = - AnalyticsReportEvent - | AnalyticsReportScreenview - | AnalyticsReportPageview - | AnalyticsReportTiming - ; - -/** - * A function that can forward analytics along some stream. AnalyticsReport is already a - * JsonObject descendant, but we force it here so the user knows it's safe to serialize. - */ -export type AnalyticsForwarderFn = (report: JsonObject & AnalyticsReport) => void; - -/** - * A class that follows the Analytics interface and forwards analytic reports (JavaScript objects). - * AnalyticsReporter is the counterpart which takes analytic reports and report them to another - * Analytics interface. - */ -export class ForwardingAnalytics implements Analytics { - constructor(protected _fn: AnalyticsForwarderFn) {} - - event(category: string, action: string, options?: EventOptions) { - this._fn({ - kind: AnalyticsReportKind.Event, - category, - action, - options: { ...options } as JsonObject, - }); - } - screenview(screenName: string, appName: string, options?: ScreenviewOptions) { - this._fn({ - kind: AnalyticsReportKind.Screenview, - screenName, - appName, - options: { ...options } as JsonObject, - }); - } - pageview(path: string, options?: PageviewOptions) { - this._fn({ - kind: AnalyticsReportKind.Pageview, - path, - options: { ...options } as JsonObject, - }); - } - timing(category: string, variable: string, time: string | number, options?: TimingOptions): void { - this._fn({ - kind: AnalyticsReportKind.Timing, - category, - variable, - time, - options: { ...options } as JsonObject, - }); - } - - // We do not support flushing. - flush() { - return Promise.resolve(); - } -} - - -export class AnalyticsReporter { - constructor(protected _analytics: Analytics) {} - - report(report: AnalyticsReport) { - switch (report.kind) { - case AnalyticsReportKind.Event: - this._analytics.event(report.category, report.action, report.options); - break; - case AnalyticsReportKind.Screenview: - this._analytics.screenview(report.screenName, report.appName, report.options); - break; - case AnalyticsReportKind.Pageview: - this._analytics.pageview(report.path, report.options); - break; - case AnalyticsReportKind.Timing: - this._analytics.timing(report.category, report.variable, report.time, report.options); - break; - - default: - throw new Error('Unexpected analytics report: ' + JSON.stringify(report)); - } - } -} diff --git a/packages/angular_devkit/core/src/analytics/index.ts b/packages/angular_devkit/core/src/analytics/index.ts deleted file mode 100644 index 4a209fd85beb..000000000000 --- a/packages/angular_devkit/core/src/analytics/index.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './api'; -export * from './forwarder'; -export * from './logging'; -export * from './multi'; -export * from './noop'; - -/** - * MAKE SURE TO KEEP THIS IN SYNC WITH THE TABLE AND CONTENT IN `/docs/design/analytics.md`. - * WE LIST THOSE DIMENSIONS (AND MORE). - * - * These cannot be in their respective schema.json file because we either change the type - * (e.g. --buildEventLog is string, but we want to know the usage of it, not its value), or - * some validation needs to be done (we cannot record ng add --collection if it's not whitelisted). - */ -export enum NgCliAnalyticsDimensions { - CpuCount = 1, - CpuSpeed = 2, - RamInGigabytes = 3, - NodeVersion = 4, - NgAddCollection = 6, - NgBuildBuildEventLog = 7, - NgIvyEnabled = 8, - BuildErrors = 20, -} - -export enum NgCliAnalyticsMetrics { - NgComponentCount = 1, - UNUSED_2 = 2, - UNUSED_3 = 3, - UNUSED_4 = 4, - BuildTime = 5, - NgOnInitCount = 6, - InitialChunkSize = 7, - TotalChunkCount = 8, - TotalChunkSize = 9, - LazyChunkCount = 10, - LazyChunkSize = 11, - AssetCount = 12, - AssetSize = 13, - PolyfillSize = 14, - CssSize = 15, -} - -// This table is used when generating the analytics.md file. It should match the enum above -// or the validate-user-analytics script will fail. -export const NgCliAnalyticsDimensionsFlagInfo: { [name: string]: [string, string] } = { - CpuCount: ['CPU Count', 'number'], - CpuSpeed: ['CPU Speed', 'number'], - RamInGigabytes: ['RAM (In GB)', 'number'], - NodeVersion: ['Node Version', 'number'], - NgAddCollection: ['--collection', 'string'], - NgBuildBuildEventLog: ['--buildEventLog', 'boolean'], - NgIvyEnabled: ['Ivy Enabled', 'boolean'], - BuildErrors: ['Build Errors (comma separated)', 'string'], -}; - -// This table is used when generating the analytics.md file. It should match the enum above -// or the validate-user-analytics script will fail. -export const NgCliAnalyticsMetricsFlagInfo: { [name: string]: [string, string] } = { - NgComponentCount: ['NgComponentCount', 'number'], - UNUSED_2: ['UNUSED_2', 'none'], - UNUSED_3: ['UNUSED_3', 'none'], - UNUSED_4: ['UNUSED_4', 'none'], - BuildTime: ['Build Time', 'number'], - NgOnInitCount: ['NgOnInit Count', 'number'], - InitialChunkSize: ['Initial Chunk Size', 'number'], - TotalChunkCount: ['Total Chunk Count', 'number'], - TotalChunkSize: ['Total Chunk Size', 'number'], - LazyChunkCount: ['Lazy Chunk Count', 'number'], - LazyChunkSize: ['Lazy Chunk Size', 'number'], - AssetCount: ['Asset Count', 'number'], - AssetSize: ['Asset Size', 'number'], - PolyfillSize: [' Polyfill Size', 'number'], - CssSize: [' Css Size', 'number'], -}; diff --git a/packages/angular_devkit/core/src/analytics/logging.ts b/packages/angular_devkit/core/src/analytics/logging.ts deleted file mode 100644 index e19785727ffe..000000000000 --- a/packages/angular_devkit/core/src/analytics/logging.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Logger } from '../logger'; -import { Analytics, EventOptions, PageviewOptions, ScreenviewOptions, TimingOptions } from './api'; - -/** - * Analytics implementation that logs analytics events to a logger. This should be used for - * debugging mainly. - */ -export class LoggingAnalytics implements Analytics { - constructor(protected _logger: Logger) {} - - event(category: string, action: string, options?: EventOptions): void { - this._logger.info('event ' + JSON.stringify({ category, action, ...options })); - } - screenview(screenName: string, appName: string, options?: ScreenviewOptions): void { - this._logger.info('screenview ' + JSON.stringify({ screenName, appName, ...options })); - } - pageview(path: string, options?: PageviewOptions): void { - this._logger.info('pageview ' + JSON.stringify({ path, ...options })); - } - timing(category: string, variable: string, time: string | number, options?: TimingOptions): void { - this._logger.info('timing ' + JSON.stringify({ category, variable, time, ...options })); - } - - flush(): Promise { - return Promise.resolve(); - } -} diff --git a/packages/angular_devkit/core/src/analytics/multi.ts b/packages/angular_devkit/core/src/analytics/multi.ts deleted file mode 100644 index 141f0db38e0b..000000000000 --- a/packages/angular_devkit/core/src/analytics/multi.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { Analytics, EventOptions, PageviewOptions, ScreenviewOptions, TimingOptions } from './api'; - -/** - * Analytics implementation that reports to multiple analytics backend. - */ -export class MultiAnalytics implements Analytics { - constructor(protected _backends: Analytics[] = []) {} - - push(...backend: Analytics[]) { - this._backends.push(...backend); - } - - event(category: string, action: string, options?: EventOptions): void { - this._backends.forEach(be => be.event(category, action, options)); - } - screenview(screenName: string, appName: string, options?: ScreenviewOptions): void { - this._backends.forEach(be => be.screenview(screenName, appName, options)); - } - pageview(path: string, options?: PageviewOptions): void { - this._backends.forEach(be => be.pageview(path, options)); - } - timing(category: string, variable: string, time: string | number, options?: TimingOptions): void { - this._backends.forEach(be => be.timing(category, variable, time, options)); - } - - - flush(): Promise { - return Promise.all(this._backends.map(x => x.flush())).then(() => {}); - } -} diff --git a/packages/angular_devkit/core/src/analytics/noop.ts b/packages/angular_devkit/core/src/analytics/noop.ts deleted file mode 100644 index a4592a75c174..000000000000 --- a/packages/angular_devkit/core/src/analytics/noop.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Analytics } from './api'; - -/** - * Analytics implementation that does nothing. - */ -export class NoopAnalytics implements Analytics { - event() {} - screenview() {} - pageview() {} - timing() {} - flush(): Promise { return Promise.resolve(); } -} diff --git a/packages/angular_devkit/core/src/exception.ts b/packages/angular_devkit/core/src/exception.ts new file mode 100644 index 000000000000..7c439528dc6f --- /dev/null +++ b/packages/angular_devkit/core/src/exception.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 class BaseException extends Error { + constructor(message = '') { + super(message); + } +} + +export class UnknownException extends BaseException { + constructor(message: string) { + super(message); + } +} + +// Exceptions +export class FileDoesNotExistException extends BaseException { + constructor(path: string) { + super(`Path "${path}" does not exist.`); + } +} +export class FileAlreadyExistException extends BaseException { + constructor(path: string) { + super(`Path "${path}" already exist.`); + } +} +export class PathIsDirectoryException extends BaseException { + constructor(path: string) { + super(`Path "${path}" is a directory.`); + } +} +export class PathIsFileException extends BaseException { + constructor(path: string) { + super(`Path "${path}" is a file.`); + } +} +export class DependencyNotFoundException extends BaseException { + constructor() { + super('One of the dependencies is not part of the set.'); + } +} +export class CircularDependencyFoundException extends BaseException { + constructor() { + super('Circular dependencies found.'); + } +} diff --git a/packages/angular_devkit/core/src/exception/exception.ts b/packages/angular_devkit/core/src/exception/exception.ts deleted file mode 100644 index 31dc67badb1a..000000000000 --- a/packages/angular_devkit/core/src/exception/exception.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export class BaseException extends Error { - constructor(message = '') { - super(message); - } -} - - -export class UnknownException extends BaseException { - constructor(message: string) { super(message); } -} - - -// Exceptions -export class FileDoesNotExistException extends BaseException { - constructor(path: string) { super(`Path "${path}" does not exist.`); } -} -export class FileAlreadyExistException extends BaseException { - constructor(path: string) { super(`Path "${path}" already exist.`); } -} -export class PathIsDirectoryException extends BaseException { - constructor(path: string) { super(`Path "${path}" is a directory.`); } -} -export class PathIsFileException extends BaseException { - constructor(path: string) { super(`Path "${path}" is a file.`); } -} -export class ContentHasMutatedException extends BaseException { - constructor(path: string) { - super(`Content at path "${path}" has changed between the start and the end of an update.`); - } -} -export class InvalidUpdateRecordException extends BaseException { - constructor() { super(`Invalid record instance.`); } -} -export class MergeConflictException extends BaseException { - constructor(path: string) { - super(`A merge conflicted on path "${path}".`); - } -} - -export class UnimplementedException extends BaseException { - constructor() { super('This function is unimplemented.'); } -} - -export class UnsupportedPlatformException extends BaseException { - constructor() { super('This platform is not supported by this code path.'); } -} diff --git a/packages/angular_devkit/core/src/exception/index.ts b/packages/angular_devkit/core/src/exception/index.ts deleted file mode 100644 index b335f36dcb1d..000000000000 --- a/packages/angular_devkit/core/src/exception/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export * from './exception'; diff --git a/packages/angular_devkit/core/src/experimental.ts b/packages/angular_devkit/core/src/experimental.ts deleted file mode 100644 index e577f4e59acc..000000000000 --- a/packages/angular_devkit/core/src/experimental.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as jobs from './experimental/jobs/index'; -import * as workspace from './experimental/workspace/index'; - -export { - jobs, - workspace, -}; diff --git a/packages/angular_devkit/core/src/experimental/jobs/README.md b/packages/angular_devkit/core/src/experimental/jobs/README.md deleted file mode 100644 index e1640a5382b9..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/README.md +++ /dev/null @@ -1,489 +0,0 @@ -# Description - -Jobs is the Angular DevKit subsystem for scheduling and running generic functions with clearly -typed inputs and outputs. A `Job` instance is a function associated with metadata. You can -schedule a job, synchronize it with other jobs, and use it to schedule other jobs. - -The whole API is serializable, allowing you to use a Node Stream or message channel to -communicate between the job and the job scheduler. - -Jobs are lazy, cold, and guaranteed to execute exactly once when scheduled. Subscribing to a job -returns messages from the point where the job is at. - -## Argument, Input, Output and Channels -A job receives a single argument when scheduled and can also listen to an input channel. It can -emit multiple outputs, and can also provide multiple output channels that emit asynchronous JSON -messages, which can be typed. - -The I/O model is like that of an executable, where the argument corresponds to arguments on the -command line, the input channel to STDIN, the output channel to STDOUT, and the channels -would be additional output streams. - -## LifeCycle -A `Job` goes through multiple LifeCycle messages before its completion; -1. `JobState.Queued`. The job was queued and is waiting. This is the default state from the - scheduler. -1. `JobState.Ready`. The job's dependencies (see - ["Synchronizing and Dependencies"](#Dependencies)) are done running, the argument is - validated, and the job is ready to execute. -1. `JobState.Started`. The argument has been validated, the job has been called and is running. - This is handled by the job itself (or `createJobHandler()`). -1. `JobState.Ended`. The job has ended and is done running. This is handled by the job itself (or - `createJobHandler()`). -1. `JobState.Errored`. A unrecoverable error happened. - -Each state (except `Queued`) corresponds to a `JobOutboundMessage` on the `outboundBus` observable -that triggers the state change. The `Scheduler` emits the `Ready` and `Errored` messages; the job -implementation should not emit them, and if it does they are filtered out. You can listen for -these messages or use the corresponding state member. - -The job implementation should emit the `Start` and `End` messages when it is starting the job logic -itself. Only the first `Start` and `End` messages will be forwarded. Any more will be filtered out. - -The `Queued` state is set as the job is scheduled, so there is no need to listen for the message. - -## `Job` Object -The `Job` object that is returned when you schedule a job provides access to the job's status and -utilities for tracking and modifying the job. - -1. `id`. A unique symbol that can be used as a Map key. -1. `description`. The description of the job from the scheduler. See `JobDescription` object. -1. `argument`. The argument value that was used to start the job. -1. `input`. An `Observer` that can be used to send validated inputs to the job itself. -1. `output`. An `Observable` that filters out messages to get only the returned output - of a job. -1. `promise`. A promise that waits for the last output of a job. Returns the last value outputted - (or no value if there's no last value). -1. `state`. The current state of the job (see `LifeCycle`). -1. `channels`. A map of side channels the user can listen to as `Observable`. -1. `ping()`. A function that can be used to ping the job, receiving a `Promise` for when the ping - is answered. -1. `stop()`. Sends a `stop` input to the job, which suggests to stop the job. The job itself can - choose to ignore this message. -1. `inboundBus`. The raw input `Observer`. This can be used to send messages to - the `context.inboundBus` observable in the job. These are `JobInboundMessage` messages. See - ["Communicating With Jobs"](#Communicating). -1. `outboundBus`. The raw output `Observable`. This can be used to listen to messages - from the job. See ["Communicating With Jobs"](#Communicating). - -## `JobHandlerContext` Object -The `JobHandlerContext<>` is passed to the job handler code in addition to its argument. The -context contains the following members: - -1. `description`. The description of the job. Its name and schemas. -1. `scheduler`. A `Scheduler<>` instance that can be used to create additional jobs. -1. `dependencies`. A generic list of other job instances that were run as dependencies when - scheduling this job. Their `id` is not guaranteed to match the `id` of the `Job<>` instance - itself (those `Job<>`s might just be proxies). The state of those `Job<>` is guaranteed to be - `JobState.Ended`, as `JobState.Errored` would have prevented this handler from running. -1. `inboundBus`. The raw input observable, complement of the `inboundBus` observer from the `Job<>`. - -# Examples - -An example of a job that adds all input together and return the output value. We use a -simple synchronous job registry and a simple job scheduler. - -```typescript -import { jobs } from '@angular-devkit/core'; - -const add = jobs.createJobHandle( - input => input.reduce((total, curr) => total + curr, 0), -); - -// Register the job in a SimpleJobRegistry. Different registries have different API. -const registry = new jobs.SimpleJobRegistry(); -const scheduler = new jobs.SimpleScheduler(registry); -registry.register(add, { - name: 'add', - input: { type: 'array', items: { type: 'number' } }, - output: { type: 'number' }, -}); - -scheduler.schedule('add', [1, 2, 3, 4]).promise - .then(output => console.log('1 + 2 + 3 + 4 is ' + output)); -``` - -# Creating Jobs - -A job is at its core a function with a description object attached to it. The description object -stores the JSON schemas used to validate the types of the argument passed in, the input and -output values. By default, a job accepts and can output any JSON object. - -```typescript -import { Observable } from 'rxjs'; -import { jobs } from '@angular-devkit/core'; - -const argument = { - type: 'array', items: { type: 'number' }, -}; -const output = { - type: 'number', -}; - -export function add(argument: number[]): Observable> { - return new Observable(o => { - o.next({ kind: jobs.JobOutboundMessageKind.Start }); - o.next({ - kind: jobs.JobOutboundMessageKind.Output, - output: argument.reduce((total, curr) => total + curr, 0), - }); - o.next({ kind: jobs.JobOutboundMessageKind.End }); - o.complete(); - }); -} - -// Add a property to `add` to make it officially a JobHandler. The Job system does not recognize -// any function as a JobHandler. -add.jobDescription = { - argument: argument, - output: output, -}; - -// Call the job with an array as argument, and log its output. -declare const scheduler: jobs.Scheduler; -scheduler.schedule('add', [1, 2, 3, 4]) - .output.subscribe(x => console.log(x)); // Will output 10. -``` - -This is a lot of boilerplate, so we made some helpers to improve readability and manage argument, -input and output automatically: - -```typescript -// Add is a JobHandler function, like the above. -export const add = jobs.createJobHandler( - argument => argument.reduce((total, curr) => total + curr, 0), -); - -// Schedule like above. -``` - -You can also return a Promise or an Observable, as jobs are asynchronous. This helper will set -start and end messages appropriately. It will also manage channels automatically (see below). - -A more complex job can be declared like this: - -```typescript -import { Observable } from 'rxjs'; -import { jobs } from '@angular-devkit/core'; - -// Show progress with each count in a separate output channel. Output "more" in a channel. -export const count = jobs.createJobHandler( - // Receive a context that contains additional methods to create channels. - (argument: number, { createChannel }) => new Observable(o => { - const side = createChannel('side', { type: 'string', const: 'more' }); - const progress = createChannel('progress', { type: 'number' }); - let i = 0; - function doCount() { - o.next(i++); - progress.next(i / argument); - side.next('more'); - - if (i < argument) { - setTimeout(doCount, 100); - } else { - o.complete(); - } - } - setTimeout(doCount, 100); - }), - { - argument: { type: 'number' }, - output: { type: 'number' }, - }, -); - -// Get a hold of a scheduler that refers to the job above. -declare const scheduler: jobs.Scheduler; - -const job = scheduler.schedule('count', 0); -job.getChannel('side').subscribe(x => console.log(x)); -// You can type a channel too. Messages will be filtered out. -job.getChannel('progress', { type: 'number' }).subscribe(x => console.log(x)); -``` - -## Communicating With Jobs -Jobs can be started and updated in a separate process or thread, and as such communication with a -job should avoid using global objects (which might not be shared). The jobs API and schedulers -provide 2 communication streams (one for input and the other for output), named `inboundBus` and -`outboundBus`. - -### Raw Input Stream -The `schedule()` function returns a `Job<>` interface that contains a `inboundBus` member of type -`Observer`. All messages sent _to_ the job goes through this stream. The `kind` -member of the `JobInboundMessage` interface dictates what kind of message it is sending: - -1. `JobInboundMessageKind.Ping`. A simple message that should be answered with - `JobOutboundMessageKind.Pong` when the job is responsive. The `id` field of the message should - be used when returning `Pong`. -1. `JobInboundMessageKind.Stop`. The job should be stopped. This is used when - cancelling/unsubscribing from the `output` (or by calling `stop()`). Any inputs or outputs - after this message will be ignored. -1. `JobInboundMessageKind.Input` is used when sending inputs to a job. These correspond to the - `next` methods of an `Observer` and are reported to the job through its `context.input` - Observable. There is no way to communicate an error to the job. - -Using the `createJobHandler()` helper, all those messages are automatically handled by the -boilerplate code. If you need direct access to raw inputs, you should subscribe to the -`context.inboundBus` Observable. - -### Raw Output Stream -The `Job<>` interface also contains a `outboundBus` member (of type -`Observable>` where `O` is the typed output of the job) which is the output -complement of `inboundBus`. All messages sent _from_ the job goes through this stream. The `kind` -member of the `JobOutboundMessage` interface dictates what kind of message it is sending: - -1. `JobOutboundMessageKind.Create`. The `Job<>` was created, its dependencies are done, and the - library is validating Argument and calling the internal job code. -1. `JobOutboundMessageKind.Start`. The job code itself should send that message when started. - `createJobHandler()` will do it automatically. -1. `JobOutboundMessageKind.End`. The job has ended. This is done by the job itself and should always - be sent when completed. The scheduler will listen to this message to set the state and unblock - dependent jobs. `createJobHandler()` automatically send this message. -1. `JobOutboundMessageKind.Pong`. The job should answer a `JobInboundMessageKind.Ping` message with - this. Automatically done by `createJobHandler()`. -1. `JobOutboundMessageKind.Output`. An `Output` has been generated by the job. -1. `JobOutboundMessageKind.ChannelMessage`, `JobOutboundMessageKind.ChannelError` and - `JobOutboundMessageKind.ChannelComplete` are used for output channels. These correspond to the - `next`, `error` and `complete` methods of an `Observer` and are available to the callee through - the `job.channels` map of Observable. - -Those messages can be accessed directly through the `job.outboundBus` member. The job itself should -return an `Observable>`. The `createJobHandler()` helper handles most of use -cases of this and makes it easier for jobs to handle this. - -## Job Dispatchers -Dispatchers are a helper that redirect to different jobs given conditions. To create a job -dispatcher, use the `createDispatcher()` function: - -```typescript -import { jobs } from '@angular-devkit/core'; - -// A dispatcher that installs node modules given a user's preference. -const dispatcher = jobs.createDispatcher({ - name: 'node-install', - argument: { properties: { moduleName: { type: 'string' } } }, - output: { type: 'boolean' }, -}); - -const npmInstall = jobs.createJobHandler(/* ... */, { name: 'npm-install' }); -const yarnInstall = jobs.createJobHandler(/* ... */, { name: 'yarn-install' }); -const pnpmInstall = jobs.createJobHandler(/* ... */, { name: 'pnpm-install' }); - -declare const registry: jobs.SimpleJobRegistry; -registry.register(dispatcher); -registry.register(npmInstall); -registry.register(yarnInstall); -registry.register(pnpmInstall); - -// Default to npm. -dispatcher.setDefaultDelegate(npmInstall.name); -// If the user is asking for yarn over npm, uses it. -dispatcher.addConditionalDelegate(() => userWantsYarn, yarnInstall.name); -``` - -## Execution Strategy -Jobs are always run in parallel and will always start, but many helper functions are provided -when creating a job to help you control the execution strategy; - -1. `serialize()`. Multiple runs of this job will be queued with each others. -1. `memoize(replayMessages = false)` will create a job, or reuse the same job when inputs are -matching. If the inputs don't match, a new job will be started and its outputs will be stored. - -These strategies can be used when creating the job: - -```typescript -// Same input and output as above. - -export const add = jobs.strategy.memoize()( - jobs.createJobHandler( - argument => argument.reduce((total, curr) => total + curr, 0), - ), -); -``` - -Strategies can be reused to synchronize between jobs. For example, given jobs `jobA` and `jobB`, -you can reuse the strategy to serialize both jobs together; - -```typescript -const strategy = jobs.strategy.serialize(); -const jobA = strategy(jobs.createJobHandler(...)); -const jobB = strategy(jobs.createJobHandler(...)); -``` - -Even further, we can have package A and package B run in serialization, and B and C also be -serialized. Running A and C will run in parallel, while running B will wait for both A and C -to finish. - -```typescript -const strategy1 = jobs.strategy.serialize(); -const strategy2 = jobs.strategy.serialize(); -const jobA = strategy1(jobs.createJobHandler(...)); -const jobB = strategy1(strategy2(jobs.createJobHandler(...))); -const jobC = strategy2(jobs.createJobHandler(...)); -``` - -# Scheduling Jobs -Jobs can be scheduled using a `Scheduler` interface, which contains a `schedule()` method: - -```typescript -interface Scheduler { - /** - * Schedule a job to be run, using its name. - * @param name The name of job to be run. - * @param argument The argument to send to the job when starting it. - * @param options Scheduling options. - * @returns The Job being run. - */ - schedule( - name: JobName, - argument: I, - options?: ScheduleJobOptions, - ): Job; -} -``` - -The scheduler also has a `getDescription()` method to get a `JobDescription` object for a certain -name; that description contains schemas for the argument, input, output, and other channels: - -```typescript -interface Scheduler { - /** - * Get a job description for a named job. - * - * @param name The name of the job. - * @returns A description, or null if the job cannot be scheduled. - */ - getDescription(name: JobName): JobDescription | null; - - /** - * Returns true if the job name has been registered. - * @param name The name of the job. - * @returns True if the job exists, false otherwise. - */ - has(name: JobName): boolean; -} -``` - -Finally, the scheduler interface has a `pause()` method to stop scheduling. This will queue all -jobs and wait for the unpause function to be called before unblocking all the jobs scheduled. -This does not affect already running jobs. - -```typescript -interface Scheduler { - /** - * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be - * used to resume execution. If multiple `pause()` were called, all their resume functions must - * be called before the Scheduler actually starts new jobs. Additional calls to the same resume - * function will have no effect. - * - * Jobs already running are NOT paused. This is pausing the scheduler only. - * - * @returns A function that can be run to resume the scheduler. If multiple `pause()` calls - * were made, all their return function must be called (in any order) before the - * scheduler can resume. - */ - pause(): () => void; -} -``` - -## Synchronizing and Dependencies -When scheduling jobs, it is often necessary to run jobs after certain other jobs are finished. -This is done through the `dependencies` options in the `schedule()` method. - -These jobs will also be passed to the job being scheduled, through its context. This can be -useful if, for example, the output of those jobs are of a known type, or have known side channels. - -An example of this would be a compiler that needs to know the output directory of other compilers -before it, in a tool chain. - -### Dependencies -When scheduling jobs, the user can add a `dependencies` field to the scheduling options. The -scheduler will wait for those dependencies to finish before running the job, and pass those jobs -in the context of the job. - -### Accessing Dependencies -Jobs are called with a `JobHandlerContext` as a second argument, which contains a -`dependencies: Job[]` member which contains all dependencies that were used when -scheduling the job. Those aren't fully typed as they are determined by the user, and not the job -itself. They also can contain jobs that are not finished, and the job should use the `state` -member of the job itself before trying to access its content. - -### Scheduler Sub Jobs -The `JobHandlerContext` also contains a `scheduler` member which can be used to schedule jobs -using the same scheduler that was used for the job. This allows jobs to call other jobs -and wait for them to end. - -## Available Schedulers -The Core Angular DevKit library provides 2 implementations for the `Scheduler` interface: - -## SimpleJobRegistry -Available in the jobs namespace. A registry that accept job registration, and can also schedule -jobs. - -```typescript -import { jobs } from '@angular-devkit/core'; - -const add = jobs.createJobHandler( - argument => argument.reduce((total, curr) => total + curr, 0), -); - -// Register the job in a SimpleJobRegistry. Different registries have different API. -const registry = new jobs.SimpleJobRegistry(); -const scheduler = new SimpleJobScheduler(registry); - -registry.register(add, { - name: 'add', - argument: { type: 'array', items: { type: 'number' } }, - output: { type: 'number' }, -}); - -scheduler.schedule('add', [1, 2, 3, 4]); -``` - -## NodeModuleJobRegistry -Available through `@angular-devkit/core/node`. - -A scheduler that loads jobs using their node package names. These jobs need to use the -`createJobHandler()` helper and report their argument/input/output schemas that way. - -```typescript -declare const registry: NodeModuleJobRegistry; -const scheduler = new SimpleJobScheduler(registry); - -scheduler.schedule('some-node-package#someExport', 'input'); -``` - -# Gotchas - -1. Deadlocking Dependencies - It is impossible to add dependencies to an already running job, but it is entirely possible to - get locked between jobs. Be aware of your own dependencies. - -1. Using `job.promise` - `job.promise` waits for the job to ends. Don't rely on it unless you know the job is not - watching and running for a long time. If you aren't sure, use - `job.output.pipe(first()).toPromise()` instead which will return the first next output, - regardless of whether the job watches and rerun or not. - - -# FAQ - -1. Laziness - A job is lazy until executed, but its messages will be replayed when resubscribed. - -1. Serialize Strategy vs Dependencies - Strategies are functions that transform the execution of a job, and can be used when - declaring the job, or registering it. Dependencies, on the other hand, are listed when - scheduling a job to order jobs during scheduling. - - A job has no control over the way it's scheduled, and its dependencies. It can, however, - declare that it shouldn't run at the same time as itself. Alternatively, a user could - schedule a job twice and imply that the second run should wait for the first to finish. In - practice, this would be equivalent to having the job be serialized, but the important detail - is in _whom_ is defining the rules; using the `serialize()` strategy, the job implementation - is, while when using dependencies, the user is. - - The user does not need to know how to job needs to synchronize with itself, and the job does - not need to know how it synchronizes with other jobs that it doesn't know about. That's part - of the strength of this system as every job can be developed in a vacuum, only caring about - its contracts (argument, input and output) and its own synchronization. diff --git a/packages/angular_devkit/core/src/experimental/jobs/api.ts b/packages/angular_devkit/core/src/experimental/jobs/api.ts deleted file mode 100644 index 5d109bf0904b..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/api.ts +++ /dev/null @@ -1,462 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Observable, Observer } from 'rxjs'; -import { JsonObject, JsonValue, schema } from '../../json/index'; -import { DeepReadonly } from '../../utils/index'; - -/** - * A job name is just a string (needs to be serializable). - */ -export type JobName = string; - - -/** - * The job handler function, which is a method that's executed for the job. - */ -export interface JobHandler< - ArgT extends JsonValue, - InputT extends JsonValue, - OutputT extends JsonValue, -> { - ( - argument: ArgT, - context: JobHandlerContext, - ): Observable>; - - jobDescription: Partial; -} - - -/** - * The context in which the job is run. - */ -export interface JobHandlerContext< - MinimumArgumentValueT extends JsonValue = JsonValue, - MinimumInputValueT extends JsonValue = JsonValue, - MinimumOutputValueT extends JsonValue = JsonValue, -> { - readonly description: JobDescription; - readonly scheduler: Scheduler; - - // In this context, JsonValue is comparable to `any`. - readonly dependencies: Job[]; - - readonly inboundBus: Observable>; -} - - -/** - * Metadata associated with a job. - */ -export interface JobDescription extends JsonObject { - readonly name: JobName; - - readonly argument: DeepReadonly; - readonly input: DeepReadonly; - readonly output: DeepReadonly; -} - -/** - * Messages that can be sent TO a job. The job needs to listen to those. - */ -export enum JobInboundMessageKind { - Ping = 'ip', - Stop = 'is', - - // Channel specific messages. - Input = 'in', - // Input channel does not allow completion / error. Erroring this will just close the Subject - // but not notify the job. -} - -/** Base interface for the all job inbound messages. */ -export interface JobInboundMessageBase extends JsonObject { - /** - * The kind of message this is. - */ - readonly kind: JobInboundMessageKind; -} - -/** - * A ping to the job. The job should reply with a pong as soon as possible. - */ -export interface JobInboundMessagePing extends JobInboundMessageBase { - readonly kind: JobInboundMessageKind.Ping; - - /** - * An ID that should be returned in the corresponding Pong. - */ - readonly id: number; -} - -/** - * Stop the job. This is handled by the job itself and jobs might not handle it. It will also - * unsubscribe from the Observable<>. - * This is equivalent to SIGTERM. - */ -export interface JobInboundMessageStop extends JobInboundMessageBase { - readonly kind: JobInboundMessageKind.Stop; -} - -/** - * A Job wants to send a message to a channel. This can be marshaled, and the Job object - * has helpers to transform this into an observable. The context also can create RxJS subjects that - * marshall messages through a channel. - */ -export interface JobInboundMessageInput extends JobInboundMessageBase { - readonly kind: JobInboundMessageKind.Input; - - /** - * The input being sent to the job. - */ - readonly value: InputT; -} - -export type JobInboundMessage = - JobInboundMessagePing - | JobInboundMessageStop - | JobInboundMessageInput - ; - -/** - * Kind of messages that can be outputted from a job. - */ -export enum JobOutboundMessageKind { - // Lifecycle specific messages. - OnReady = 'c', - Start = 's', - End = 'e', - Pong = 'p', - - // Feedback messages. - Output = 'o', - - // Channel specific messages. - ChannelCreate = 'cn', - ChannelMessage = 'cm', - ChannelError = 'ce', - ChannelComplete = 'cc', -} - -/** Base interface for the all job messages. */ -export interface JobOutboundMessageBase { - /** - * The job description. - */ - readonly description: JobDescription; - - /** - * The kind of message this is. - */ - readonly kind: JobOutboundMessageKind; -} - -/** - * The job has been created and will validate its input. - */ -export interface JobOutboundMessageOnReady extends JobOutboundMessageBase { - readonly kind: JobOutboundMessageKind.OnReady; -} - -/** - * The job started. This is done by the job itself. - */ -export interface JobOutboundMessageStart extends JobOutboundMessageBase { - readonly kind: JobOutboundMessageKind.Start; -} - -/** - * An output value is available. - */ -export interface JobOutboundMessageOutput< - OutputT extends JsonValue, -> extends JobOutboundMessageBase { - readonly kind: JobOutboundMessageKind.Output; - - /** - * The message being outputted from the job. - */ - readonly value: OutputT; -} - - -/** - * Base interface for all job message related to channels. - */ -export interface JobOutboundMessageChannelBase extends JobOutboundMessageBase { - /** - * The name of the channel. - */ - readonly name: string; -} - -/** - * A job wants to send a message to a channel. This can be marshaled, and the Job object - * has helpers to transform this into an observable. The context also can create RxJS subjects that - * marshall messages through a channel. - */ -export interface JobOutboundMessageChannelMessage extends JobOutboundMessageChannelBase { - readonly kind: JobOutboundMessageKind.ChannelMessage; - - /** - * The message being sent to the channel. - */ - readonly message: JsonValue; -} - -/** - * A job wants to send an error to one of its channel. This is the equivalent of throwing through - * an Observable. The side channel will not receive any more messages after this, and will not - * complete. - */ -export interface JobOutboundMessageChannelError extends JobOutboundMessageChannelBase { - readonly kind: JobOutboundMessageKind.ChannelError; - - /** - * The error message being sent to the channel. - */ - readonly error: JsonValue; -} - -/** - * A job wants to create a new channel. - */ -export interface JobOutboundMessageChannelCreate extends JobOutboundMessageChannelBase { - readonly kind: JobOutboundMessageKind.ChannelCreate; -} - -/** - * A job wants to close the channel, as completed. This is done automatically when the job ends, - * or can be done from the job to close it. A closed channel might be reopened, but the user - * need to recall getChannel(). - */ -export interface JobOutboundMessageChannelComplete extends JobOutboundMessageChannelBase { - readonly kind: JobOutboundMessageKind.ChannelComplete; -} - -/** - * OnEnd of the job run. - */ -export interface JobOutboundMessageEnd extends JobOutboundMessageBase { - readonly kind: JobOutboundMessageKind.End; -} - -/** - * A pong response from a ping input. The id is the same as the one passed in. - */ -export interface JobOutboundMessagePong extends JobOutboundMessageBase { - readonly kind: JobOutboundMessageKind.Pong; - - /** - * The ID that was passed in the `Ping` messages. - */ - readonly id: number; -} - -/** - * Generic message type. - */ -export type JobOutboundMessage = - JobOutboundMessageOnReady - | JobOutboundMessageStart - | JobOutboundMessageOutput - | JobOutboundMessageChannelCreate - | JobOutboundMessageChannelMessage - | JobOutboundMessageChannelError - | JobOutboundMessageChannelComplete - | JobOutboundMessageEnd - | JobOutboundMessagePong - ; - - -/** - * The state of a job. These are changed as the job reports a new state through its messages. - */ -export enum JobState { - /** - * The job was queued and is waiting to start. - */ - Queued = 'queued', - /** - * The job description was found, its dependencies (see "Synchronizing and Dependencies") - * are done running, and the job's argument is validated and the job's code will be executed. - */ - Ready = 'ready', - /** - * The job has been started. The job implementation is expected to send this as soon as its - * work is starting. - */ - Started = 'started', - /** - * The job has ended and is done running. - */ - Ended = 'ended', - /** - * An error occured and the job stopped because of internal state. - */ - Errored = 'errored', -} - - -/** - * A Job instance, returned from scheduling a job. A Job instance is _not_ serializable. - */ -export interface Job< - ArgumentT extends JsonValue = JsonValue, - InputT extends JsonValue = JsonValue, - OutputT extends JsonValue = JsonValue, -> { - /** - * Description of the job. Resolving the job's description can be done asynchronously, so this - * is an observable that will resolve when it's ready. - */ - readonly description: Observable; - - /** - * Argument sent when scheduling the job. This is a copy of the argument. - */ - readonly argument: ArgumentT; - - /** - * The input to the job. This goes through the input channel as messages. - */ - readonly input: Observer; - - /** - * Outputs of this job. - */ - readonly output: Observable; - - /** - * The current state of the job. - */ - readonly state: JobState; - - /** - * Get a channel that validates against the schema. Messages will be filtered by the schema. - * @param name The name of the channel. - * @param schema A schema to use to validate messages. - */ - getChannel(name: string, schema?: schema.JsonSchema): Observable; - - /** - * Pings the job and wait for the resulting Pong before completing. - */ - ping(): Observable; - - /** - * Stops the job from running. This is different than unsubscribing from the output as in it - * sends the JobInboundMessageKind.Stop raw input to the job. - */ - stop(): void; - - /** - * The JobInboundMessage messages TO the job. - */ - readonly inboundBus: Observer>; - - /** - * The JobOutboundMessage FROM the job. - */ - readonly outboundBus: Observable>; -} - -/** - * Options for scheduling jobs. - */ -export interface ScheduleJobOptions { - /** - * Jobs that need to finish before scheduling this job. These dependencies will be passed - * to the job itself in its context. - */ - dependencies?: Job | Job[]; -} - -export interface Registry< - MinimumArgumentValueT extends JsonValue = JsonValue, - MinimumInputValueT extends JsonValue = JsonValue, - MinimumOutputValueT extends JsonValue = JsonValue, -> { - /** - * Get a job handler. - * @param name The name of the job to get a handler from. - */ - get< - A extends MinimumArgumentValueT, - I extends MinimumInputValueT, - O extends MinimumOutputValueT, - >(name: JobName): Observable | null>; -} - -/** - * An interface that can schedule jobs. - */ -export interface Scheduler< - MinimumArgumentValueT extends JsonValue = JsonValue, - MinimumInputValueT extends JsonValue = JsonValue, - MinimumOutputValueT extends JsonValue = JsonValue, -> { - /** - * Get a job description for a named job. - * - * @param name The name of the job. - * @returns A description, or null if no description is available for this job. - */ - getDescription(name: JobName): Observable; - - /** - * Returns true if the job name has been registered. - * @param name The name of the job. - * @returns True if the job exists, false otherwise. - */ - has(name: JobName): Observable; - - /** - * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be - * used to resume execution. If multiple `pause()` were called, all their resume functions must - * be called before the Scheduler actually starts new jobs. Additional calls to the same resume - * function will have no effect. - * - * Jobs already running are NOT paused. This is pausing the scheduler only. - * - * @returns A function that can be run to resume the scheduler. If multiple `pause()` calls - * were made, all their return function must be called (in any order) before the - * scheduler can resume. - */ - pause(): () => void; - - /** - * Schedule a job to be run, using its name. - * @param name The name of job to be run. - * @param argument The argument to send to the job when starting it. - * @param options Scheduling options. - * @returns The job being run. - */ - schedule< - A extends MinimumArgumentValueT, - I extends MinimumInputValueT, - O extends MinimumOutputValueT, - >( - name: JobName, - argument: A, - options?: ScheduleJobOptions, - ): Job; -} - - -export function isJobHandler< - A extends JsonValue, - I extends JsonValue, - O extends JsonValue, -// TODO: this should be unknown -// tslint:disable-next-line:no-any ->(value: any): value is JobHandler { - return typeof value == 'function' - && typeof value.jobDescription == 'object' - && value.jobDescription !== null; -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/create-job-handler.ts b/packages/angular_devkit/core/src/experimental/jobs/create-job-handler.ts deleted file mode 100644 index 08f381dc081f..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/create-job-handler.ts +++ /dev/null @@ -1,205 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - * - */ -import { Observable, Observer, Subject, Subscription, from, isObservable, of } from 'rxjs'; -import { switchMap, tap } from 'rxjs/operators'; -import { BaseException } from '../../exception/index'; -import { JsonValue } from '../../json/index'; -import { LoggerApi } from '../../logger'; -import { isPromise } from '../../utils/index'; -import { - JobDescription, - JobHandler, - JobHandlerContext, - JobInboundMessageKind, - JobOutboundMessage, - JobOutboundMessageKind, -} from './api'; - - -export class ChannelAlreadyExistException extends BaseException { - constructor(name: string) { - super(`Channel ${JSON.stringify(name)} already exist.`); - } -} - -/** - * Interface for the JobHandler context that is used when using `createJobHandler()`. It extends - * the basic `JobHandlerContext` with additional functionality. - */ -export interface SimpleJobHandlerContext< - A extends JsonValue, - I extends JsonValue, - O extends JsonValue, -> extends JobHandlerContext { - createChannel: (name: string) => Observer; - input: Observable; -} - - -/** - * A simple version of the JobHandler. This simplifies a lot of the interaction with the job - * scheduler and registry. For example, instead of returning a JobOutboundMessage observable, you - * can directly return an output. - */ -export type SimpleJobHandlerFn = ( - input: A, - context: SimpleJobHandlerContext, -) => O | Promise | Observable; - - -/** - * Make a simple job handler that sets start and end from a function that's synchronous. - * - * @param fn The function to create a handler for. - * @param options An optional set of properties to set on the handler. Some fields might be - * required by registry or schedulers. - */ -export function createJobHandler( - fn: SimpleJobHandlerFn, - options: Partial = {}, -): JobHandler { - const handler = (argument: A, context: JobHandlerContext) => { - const description = context.description; - const inboundBus = context.inboundBus; - const inputChannel = new Subject(); - let subscription: Subscription; - - return new Observable>(subject => { - function complete() { - if (subscription) { - subscription.unsubscribe(); - } - subject.next({ kind: JobOutboundMessageKind.End, description }); - subject.complete(); - inputChannel.complete(); - } - - // Handle input. - const inboundSub = inboundBus.subscribe(message => { - switch (message.kind) { - case JobInboundMessageKind.Ping: - subject.next({ kind: JobOutboundMessageKind.Pong, description, id: message.id }); - break; - - case JobInboundMessageKind.Stop: - // There's no way to cancel a promise or a synchronous function, but we do cancel - // observables where possible. - complete(); - break; - - case JobInboundMessageKind.Input: - inputChannel.next(message.value); - break; - } - }); - - // Execute the function with the additional context. - const channels = new Map>(); - - const newContext: SimpleJobHandlerContext = { - ...context, - input: inputChannel.asObservable(), - createChannel(name: string) { - if (channels.has(name)) { - throw new ChannelAlreadyExistException(name); - } - const channelSubject = new Subject(); - const channelSub = channelSubject.subscribe( - message => { - subject.next({ - kind: JobOutboundMessageKind.ChannelMessage, description, name, message, - }); - }, - error => { - subject.next({ kind: JobOutboundMessageKind.ChannelError, description, name, error }); - // This can be reopened. - channels.delete(name); - }, - () => { - subject.next({ kind: JobOutboundMessageKind.ChannelComplete, description, name }); - // This can be reopened. - channels.delete(name); - }, - ); - - channels.set(name, channelSubject); - if (subscription) { - subscription.add(channelSub); - } - - return channelSubject; - }, - }; - - subject.next({ kind: JobOutboundMessageKind.Start, description }); - let result = fn(argument, newContext); - // If the result is a promise, simply wait for it to complete before reporting the result. - if (isPromise(result)) { - result = from(result); - } else if (!isObservable(result)) { - result = of(result as O); - } - - subscription = (result as Observable).subscribe( - (value: O) => subject.next({ kind: JobOutboundMessageKind.Output, description, value }), - error => subject.error(error), - () => complete(), - ); - subscription.add(inboundSub); - - return subscription; - }); - }; - - return Object.assign(handler, { jobDescription: options }); -} - - -/** - * Lazily create a job using a function. - * @param loader A factory function that returns a promise/observable of a JobHandler. - * @param options Same options as createJob. - */ -export function createJobFactory( - loader: () => Promise>, - options: Partial = {}, -): JobHandler { - const handler = (argument: A, context: JobHandlerContext) => { - return from(loader()) - .pipe(switchMap(fn => fn(argument, context))); - }; - - return Object.assign(handler, { jobDescription: options }); -} - - -/** - * Creates a job that logs out input/output messages of another Job. The messages are still - * propagated to the other job. - */ -export function createLoggerJob( - job: JobHandler, - logger: LoggerApi, -): JobHandler { - const handler = (argument: A, context: JobHandlerContext) => { - context.inboundBus.pipe( - tap(message => logger.info(`Input: ${JSON.stringify(message)}`)), - ).subscribe(); - - return job(argument, context).pipe( - tap( - message => logger.info(`Message: ${JSON.stringify(message)}`), - error => logger.warn(`Error: ${JSON.stringify(error)}`), - () => logger.info(`Completed`), - ), - ); - }; - - return Object.assign(handler, job); -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/dispatcher.ts b/packages/angular_devkit/core/src/experimental/jobs/dispatcher.ts deleted file mode 100644 index fc3841042d82..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/dispatcher.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - * - */ -import { JsonValue } from '../../json/index'; -import { Readwrite } from '../../utils/index'; -import { - Job, - JobDescription, - JobHandler, - JobHandlerContext, - JobName, - isJobHandler, -} from './api'; -import { JobDoesNotExistException } from './exception'; - -/** - * A JobDispatcher can be used to dispatch between multiple jobs. - */ -export interface JobDispatcher< - A extends JsonValue, - I extends JsonValue, - O extends JsonValue, -> extends JobHandler { - /** - * Set the default job if all conditionals failed. - * @param name The default name if all conditions are false. - */ - setDefaultJob(name: JobName | null | JobHandler): void; - - /** - * Add a conditional job that will be selected if the input fits a predicate. - * @param predicate - * @param name - */ - addConditionalJob(predicate: (args: A) => boolean, name: string): void; -} - - -/** - * OnReady a dispatcher that can dispatch to a sub job, depending on conditions. - * @param options - */ -export function createDispatcher< - A extends JsonValue, - I extends JsonValue, - O extends JsonValue, ->( - options: Partial> = {}, -): JobDispatcher { - let defaultDelegate: JobName | null = null; - const conditionalDelegateList: [(args: A) => boolean, JobName][] = []; - - const job: JobHandler = Object.assign((argument: A, context: JobHandlerContext) => { - const maybeDelegate = conditionalDelegateList.find(([predicate]) => predicate(argument)); - let delegate: Job | null = null; - - if (maybeDelegate) { - delegate = context.scheduler.schedule(maybeDelegate[1], argument); - } else if (defaultDelegate) { - delegate = context.scheduler.schedule(defaultDelegate, argument); - } else { - throw new JobDoesNotExistException(''); - } - - context.inboundBus.subscribe(delegate.inboundBus); - - return delegate.outboundBus; - }, { - jobDescription: options, - }); - - return Object.assign(job, { - setDefaultJob(name: JobName | null | JobHandler) { - if (isJobHandler(name)) { - name = name.jobDescription.name === undefined ? null : name.jobDescription.name; - } - - defaultDelegate = name; - }, - addConditionalJob(predicate: (args: A) => boolean, name: JobName) { - conditionalDelegateList.push([predicate, name]); - }, - }); -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/dispatcher_spec.ts b/packages/angular_devkit/core/src/experimental/jobs/dispatcher_spec.ts deleted file mode 100644 index d7cabe13a3da..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/dispatcher_spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { createJobHandler } from './create-job-handler'; -import { createDispatcher } from './dispatcher'; -import { SimpleJobRegistry } from './simple-registry'; -import { SimpleScheduler } from './simple-scheduler'; - -describe('createDispatcher', () => { - it('works', async () => { - const registry = new SimpleJobRegistry(); - const scheduler = new SimpleScheduler(registry); - - const dispatcher = createDispatcher({ - name: 'add', - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - }); - const add0 = createJobHandler((input: number[]) => input.reduce((a, c) => a + c, 0), { - name: 'add0', - }); - const add100 = createJobHandler((input: number[]) => input.reduce((a, c) => a + c, 100), { - name: 'add100', - }); - - registry.register(dispatcher); - registry.register(add0); - registry.register(add100); - - dispatcher.setDefaultJob(add0); - const sum = scheduler.schedule('add', [1, 2, 3, 4]); - expect(await sum.output.toPromise()).toBe(10); - }); -}); diff --git a/packages/angular_devkit/core/src/experimental/jobs/exception.ts b/packages/angular_devkit/core/src/experimental/jobs/exception.ts deleted file mode 100644 index 0fcb761a978f..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/exception.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BaseException } from '../../exception/index'; -import { JobName } from './api'; - -export class JobNameAlreadyRegisteredException extends BaseException { - constructor(name: JobName) { - super(`Job named ${JSON.stringify(name)} already exists.`); - } -} - -export class JobDoesNotExistException extends BaseException { - constructor(name: JobName) { - super(`Job name ${JSON.stringify(name)} does not exist.`); - } -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/fallback-registry.ts b/packages/angular_devkit/core/src/experimental/jobs/fallback-registry.ts deleted file mode 100644 index efa12b769abf..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/fallback-registry.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { Observable, from, of } from 'rxjs'; -import { concatMap, first } from 'rxjs/operators'; -import { JsonValue, schema } from '../../json'; -import { JobDescription, JobHandler, JobName, Registry, isJobHandler } from './api'; -import { JobNameAlreadyRegisteredException } from './exception'; - - -/** - * A simple job registry that keep a map of JobName => JobHandler internally. - */ -export class FallbackRegistry< - MinimumArgumentValueT extends JsonValue = JsonValue, - MinimumInputValueT extends JsonValue = JsonValue, - MinimumOutputValueT extends JsonValue = JsonValue, -> implements Registry { - constructor(protected _fallbacks: Registry< - MinimumArgumentValueT, - MinimumInputValueT, - MinimumOutputValueT - >[] = []) {} - - addFallback(registry: Registry) { - this._fallbacks.push(registry); - } - - get< - A extends MinimumArgumentValueT = MinimumArgumentValueT, - I extends MinimumInputValueT = MinimumInputValueT, - O extends MinimumOutputValueT = MinimumOutputValueT, - >(name: JobName): Observable | null> { - return from(this._fallbacks).pipe( - concatMap(fb => fb.get(name)), - first(x => x !== null, null), - ); - } -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/index.ts b/packages/angular_devkit/core/src/experimental/jobs/index.ts deleted file mode 100644 index 70210cb22e9f..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './api'; -export * from './create-job-handler'; -export * from './exception'; -export * from './dispatcher'; -export * from './fallback-registry'; -export * from './simple-registry'; -export * from './simple-scheduler'; -export * from './strategy'; diff --git a/packages/angular_devkit/core/src/experimental/jobs/simple-registry_spec.ts b/packages/angular_devkit/core/src/experimental/jobs/simple-registry_spec.ts deleted file mode 100644 index 770a14682357..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/simple-registry_spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function no-non-null-assertion -import { EMPTY, Observable, of, timer } from 'rxjs'; -import { map, take, toArray } from 'rxjs/operators'; -import { JobHandlerContext, JobOutboundMessage, JobOutboundMessageKind, JobState } from './api'; -import { createJobHandler } from './create-job-handler'; -import { SimpleJobRegistry } from './simple-registry'; -import { SimpleScheduler } from './simple-scheduler'; - -describe('SimpleJobRegistry', () => { - let registry: SimpleJobRegistry; - - beforeEach(() => { - registry = new SimpleJobRegistry(); - }); - - it('works for a simple case', async () => { - registry.register( - 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - }, - ); - - expect(await registry.get('add').toPromise()).not.toBeNull(); - expect(await registry.get('add2').toPromise()).toBeNull(); - }); -}); diff --git a/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler.ts b/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler.ts deleted file mode 100644 index 9c79628b8544..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler.ts +++ /dev/null @@ -1,546 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { - EMPTY, - MonoTypeOperatorFunction, - Observable, - Observer, - Subject, - Subscription, - concat, - from, - merge, - of, -} from 'rxjs'; -import { - concatMap, - filter, - first, - ignoreElements, - map, - shareReplay, - switchMap, - tap, -} from 'rxjs/operators'; -import { JsonValue, schema } from '../../json'; -import { - Job, - JobDescription, - JobHandler, - JobInboundMessage, - JobInboundMessageKind, - JobName, - JobOutboundMessage, - JobOutboundMessageKind, - JobOutboundMessageOutput, - JobState, - Registry, - ScheduleJobOptions, - Scheduler, -} from './api'; -import { JobDoesNotExistException } from './exception'; - - -export class JobArgumentSchemaValidationError extends schema.SchemaValidationException { - constructor(errors?: schema.SchemaValidatorError[]) { - super(errors, 'Job Argument failed to validate. Errors: '); - } -} -export class JobInboundMessageSchemaValidationError extends schema.SchemaValidationException { - constructor(errors?: schema.SchemaValidatorError[]) { - super(errors, 'Job Inbound Message failed to validate. Errors: '); - } -} -export class JobOutputSchemaValidationError extends schema.SchemaValidationException { - constructor(errors?: schema.SchemaValidatorError[]) { - super(errors, 'Job Output failed to validate. Errors: '); - } -} - - -interface JobHandlerWithExtra extends JobHandler { - jobDescription: JobDescription; - - argumentV: Observable; - outputV: Observable; - inputV: Observable; -} - - -function _jobShare(): MonoTypeOperatorFunction { - // This is the same code as a `shareReplay()` operator, but uses a dumber Subject rather than a - // ReplaySubject. - return (source: Observable): Observable => { - let refCount = 0; - let subject: Subject; - let hasError = false; - let isComplete = false; - let subscription: Subscription; - - return new Observable(subscriber => { - let innerSub: Subscription; - refCount++; - if (!subject) { - subject = new Subject(); - - innerSub = subject.subscribe(subscriber); - subscription = source.subscribe({ - next(value) { subject.next(value); }, - error(err) { - hasError = true; - subject.error(err); - }, - complete() { - isComplete = true; - subject.complete(); - }, - }); - } else { - innerSub = subject.subscribe(subscriber); - } - - return () => { - refCount--; - innerSub.unsubscribe(); - if (subscription && refCount === 0 && (isComplete || hasError)) { - subscription.unsubscribe(); - } - }; - }); - }; -} - - -/** - * Simple scheduler. Should be the base of all registries and schedulers. - */ -export class SimpleScheduler< - MinimumArgumentT extends JsonValue = JsonValue, - MinimumInputT extends JsonValue = JsonValue, - MinimumOutputT extends JsonValue = JsonValue, -> implements Scheduler { - private _internalJobDescriptionMap = new Map(); - private _queue: (() => void)[] = []; - private _pauseCounter = 0; - - constructor( - protected _jobRegistry: Registry, - protected _schemaRegistry: schema.SchemaRegistry = new schema.CoreSchemaRegistry(), - ) {} - - private _getInternalDescription(name: JobName): Observable { - const maybeHandler = this._internalJobDescriptionMap.get(name); - if (maybeHandler !== undefined) { - return of(maybeHandler); - } - - const handler = this._jobRegistry.get(name); - - return handler.pipe( - switchMap(handler => { - if (handler === null) { - return of(null); - } - - const description: JobDescription = { - // Make a copy of it to be sure it's proper JSON. - ...JSON.parse(JSON.stringify(handler.jobDescription)), - name: handler.jobDescription.name || name, - argument: handler.jobDescription.argument || true, - input: handler.jobDescription.input || true, - output: handler.jobDescription.output || true, - channels: handler.jobDescription.channels || {}, - }; - - const handlerWithExtra = Object.assign(handler.bind(undefined), { - jobDescription: description, - argumentV: this._schemaRegistry.compile(description.argument).pipe(shareReplay(1)), - inputV: this._schemaRegistry.compile(description.input).pipe(shareReplay(1)), - outputV: this._schemaRegistry.compile(description.output).pipe(shareReplay(1)), - }); - this._internalJobDescriptionMap.set(name, handlerWithExtra); - - return of(handlerWithExtra); - }), - ); - } - - /** - * Get a job description for a named job. - * - * @param name The name of the job. - * @returns A description, or null if the job is not registered. - */ - getDescription(name: JobName) { - return concat( - this._getInternalDescription(name).pipe(map(x => x && x.jobDescription)), - of(null), - ).pipe( - first(), - ); - } - - /** - * Returns true if the job name has been registered. - * @param name The name of the job. - * @returns True if the job exists, false otherwise. - */ - has(name: JobName) { - return this.getDescription(name).pipe( - map(x => x !== null), - ); - } - - /** - * Pause the scheduler, temporary queueing _new_ jobs. Returns a resume function that should be - * used to resume execution. If multiple `pause()` were called, all their resume functions must - * be called before the Scheduler actually starts new jobs. Additional calls to the same resume - * function will have no effect. - * - * Jobs already running are NOT paused. This is pausing the scheduler only. - */ - pause() { - let called = false; - this._pauseCounter++; - - return () => { - if (!called) { - called = true; - if (--this._pauseCounter == 0) { - // Resume the queue. - const q = this._queue; - this._queue = []; - q.forEach(fn => fn()); - } - } - }; - } - - /** - * Schedule a job to be run, using its name. - * @param name The name of job to be run. - * @param argument The argument to send to the job when starting it. - * @param options Scheduling options. - * @returns The Job being run. - */ - schedule( - name: JobName, - argument: A, - options?: ScheduleJobOptions, - ): Job { - if (this._pauseCounter > 0) { - const waitable = new Subject(); - this._queue.push(() => waitable.complete()); - - return this._scheduleJob(name, argument, options || {}, waitable); - } - - return this._scheduleJob(name, argument, options || {}, EMPTY); - } - - /** - * Filter messages. - * @private - */ - private _filterJobOutboundMessages( - message: JobOutboundMessage, - state: JobState, - ) { - switch (message.kind) { - case JobOutboundMessageKind.OnReady: - return state == JobState.Queued; - case JobOutboundMessageKind.Start: - return state == JobState.Ready; - - case JobOutboundMessageKind.End: - return state == JobState.Started || state == JobState.Ready; - } - - return true; - } - - /** - * Return a new state. This is just to simplify the reading of the _createJob method. - * @private - */ - private _updateState( - message: JobOutboundMessage, - state: JobState, - ): JobState { - switch (message.kind) { - case JobOutboundMessageKind.OnReady: - return JobState.Ready; - case JobOutboundMessageKind.Start: - return JobState.Started; - case JobOutboundMessageKind.End: - return JobState.Ended; - } - - return state; - } - - /** - * Create the job. - * @private - */ - private _createJob( - name: JobName, - argument: A, - handler: Observable, - inboundBus: Observer>, - outboundBus: Observable>, - options: ScheduleJobOptions, - ): Job { - const schemaRegistry = this._schemaRegistry; - - const channelsSubject = new Map>(); - const channels = new Map>(); - - let state = JobState.Queued; - let pingId = 0; - - // Create the input channel by having a filter. - const input = new Subject(); - input.pipe( - switchMap(message => handler.pipe( - switchMap(handler => { - if (handler === null) { - throw new JobDoesNotExistException(name); - } else { - return handler.inputV.pipe( - switchMap(validate => validate(message)), - ); - } - }), - )), - filter(result => result.success), - map(result => result.data as I), - ).subscribe( - value => inboundBus.next({ kind: JobInboundMessageKind.Input, value }), - ); - - outboundBus = concat( - outboundBus, - // Add an End message at completion. This will be filtered out if the job actually send an - // End. - handler.pipe(switchMap(handler => { - if (handler) { - return of>({ - kind: JobOutboundMessageKind.End, description: handler.jobDescription, - }); - } else { - return EMPTY as Observable>; - } - })), - ).pipe( - filter(message => this._filterJobOutboundMessages(message, state)), - // Update internal logic and Job<> members. - tap(message => { - // Update the state. - state = this._updateState(message, state); - - switch (message.kind) { - case JobOutboundMessageKind.ChannelCreate: { - const maybeSubject = channelsSubject.get(message.name); - // If it doesn't exist or it's closed on the other end. - if (!maybeSubject) { - const s = new Subject(); - channelsSubject.set(message.name, s); - channels.set(message.name, s.asObservable()); - } - break; - } - - case JobOutboundMessageKind.ChannelMessage: { - const maybeSubject = channelsSubject.get(message.name); - if (maybeSubject) { - maybeSubject.next(message.message); - } - break; - } - - case JobOutboundMessageKind.ChannelComplete: { - const maybeSubject = channelsSubject.get(message.name); - if (maybeSubject) { - maybeSubject.complete(); - channelsSubject.delete(message.name); - } - break; - } - - case JobOutboundMessageKind.ChannelError: { - const maybeSubject = channelsSubject.get(message.name); - if (maybeSubject) { - maybeSubject.error(message.error); - channelsSubject.delete(message.name); - } - break; - } - } - }, () => { - state = JobState.Errored; - }), - - // Do output validation (might include default values so this might have side - // effects). We keep all messages in order. - concatMap(message => { - if (message.kind !== JobOutboundMessageKind.Output) { - return of(message); - } - - return handler.pipe( - switchMap(handler => { - if (handler === null) { - throw new JobDoesNotExistException(name); - } else { - return handler.outputV.pipe( - switchMap(validate => validate(message.value)), - switchMap(output => { - if (!output.success) { - throw new JobOutputSchemaValidationError(output.errors); - } - - return of({ - ...message, - output: output.data as O, - } as JobOutboundMessageOutput); - }), - ); - } - }), - ) as Observable>; - }), - _jobShare(), - ); - - const output = outboundBus.pipe( - filter(x => x.kind == JobOutboundMessageKind.Output), - map((x: JobOutboundMessageOutput) => x.value), - shareReplay(1), - ); - - // Return the Job. - return { - get state() { return state; }, - argument, - description: handler.pipe( - switchMap(handler => { - if (handler === null) { - throw new JobDoesNotExistException(name); - } else { - return of(handler.jobDescription); - } - }), - ), - output, - getChannel( - name: JobName, - schema: schema.JsonSchema = true, - ): Observable { - let maybeObservable = channels.get(name); - if (!maybeObservable) { - const s = new Subject(); - channelsSubject.set(name, s); - channels.set(name, s.asObservable()); - - maybeObservable = s.asObservable(); - } - - return maybeObservable.pipe( - // Keep the order of messages. - concatMap( - message => { - return schemaRegistry.compile(schema).pipe( - switchMap(validate => validate(message)), - filter(x => x.success), - map(x => x.data as T), - ); - }, - ), - ); - }, - ping() { - const id = pingId++; - inboundBus.next({ kind: JobInboundMessageKind.Ping, id }); - - return outboundBus.pipe( - filter(x => x.kind === JobOutboundMessageKind.Pong && x.id == id), - first(), - ignoreElements(), - ); - }, - stop() { - inboundBus.next({ kind: JobInboundMessageKind.Stop }); - }, - input, - inboundBus, - outboundBus, - }; - } - - protected _scheduleJob< - A extends MinimumArgumentT, - I extends MinimumInputT, - O extends MinimumOutputT, - >( - name: JobName, - argument: A, - options: ScheduleJobOptions, - waitable: Observable, - ): Job { - // Get handler first, since this can error out if there's no handler for the job name. - const handler = this._getInternalDescription(name); - - const optionsDeps = (options && options.dependencies) || []; - const dependencies = Array.isArray(optionsDeps) ? optionsDeps : [optionsDeps]; - - const inboundBus = new Subject>(); - const outboundBus = concat( - // Wait for dependencies, make sure to not report messages from dependencies. Subscribe to - // all dependencies at the same time so they run concurrently. - merge(...dependencies.map(x => x.outboundBus)).pipe(ignoreElements()), - - // Wait for pause() to clear (if necessary). - waitable, - - from(handler).pipe( - switchMap(handler => new Observable>( - (subscriber: Observer>) => { - if (!handler) { - throw new JobDoesNotExistException(name); - } - - // Validate the argument. - return handler.argumentV.pipe( - switchMap(validate => validate(argument)), - switchMap(output => { - if (!output.success) { - throw new JobArgumentSchemaValidationError(output.errors); - } - - const argument: A = output.data as A; - const description = handler.jobDescription; - subscriber.next({ kind: JobOutboundMessageKind.OnReady, description }); - - const context = { - description, - dependencies: [...dependencies], - inboundBus: inboundBus.asObservable(), - scheduler: this as Scheduler, - }; - - return handler(argument, context); - }), - ).subscribe(subscriber); - })), - ), - ); - - return this._createJob(name, argument, handler, inboundBus, outboundBus, options); - } -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler_spec.ts b/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler_spec.ts deleted file mode 100644 index 48d7443dfcf6..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/simple-scheduler_spec.ts +++ /dev/null @@ -1,633 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function no-non-null-assertion -import { EMPTY, Observable, of, timer } from 'rxjs'; -import { map, take, toArray } from 'rxjs/operators'; -import { JobHandlerContext, JobOutboundMessage, JobOutboundMessageKind, JobState } from './api'; -import { createJobHandler } from './create-job-handler'; -import { SimpleJobRegistry } from './simple-registry'; -import { SimpleScheduler } from './simple-scheduler'; - -describe('SimpleScheduler', () => { - let registry: SimpleJobRegistry; - let scheduler: SimpleScheduler; - - beforeEach(() => { - registry = new SimpleJobRegistry(); - scheduler = new SimpleScheduler(registry); - }); - - it('works for a simple case', async () => { - registry.register( - 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - }, - ); - - const sum = await (scheduler.schedule('add', [1, 2, 3, 4])).output.toPromise(); - expect(sum).toBe(10); - }); - - it('calls jobs in parallel', async () => { - let started = 0; - let finished = 0; - - registry.register( - 'add', - createJobHandler((argument: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(argument.reduce((a, c) => a + c, 0)); - }, 10), - ); - }), - { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - }, - ); - - const job1 = scheduler.schedule('add', [1, 2, 3, 4]); - const job2 = scheduler.schedule('add', [1, 2, 3, 4, 5]); - expect(started).toBe(0); - - const p1 = job1.output.toPromise(); - expect(started).toBe(1); - - const p2 = job2.output.toPromise(); - expect(started).toBe(2); - expect(finished).toBe(0); - - const [sum, sum2] = await Promise.all([p1, p2]); - expect(started).toBe(2); - expect(finished).toBe(2); - - expect(sum).toBe(10); - expect(sum2).toBe(15); - }); - - it('validates arguments', async () => { - registry.register( - 'add', createJobHandler((arg: number[]) => arg.reduce((a, c) => a + c, 0)), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - }, - ); - - await (scheduler.schedule('add', [1, 2, 3, 4])).output.toPromise(); - try { - await (scheduler.schedule('add', ['1', 2, 3, 4])).output.toPromise(); - expect(true).toBe(false); - } catch (e) { - // TODO: enable this when https://github.com/bazelbuild/rules_typescript/commit/37807e2c4 - // is released, otherwise this breaks because bazel downgrade to ES5 which does not support - // extending Error. - // expect(e instanceof JobInboundMessageSchemaValidationError).toBe(true); - expect(e.message).toMatch(/"\[0\]".*number/); - } - }); - - it('validates outputs', async () => { - registry.register( - 'add', createJobHandler(() => 'hello world'), { - output: { type: 'number' }, - }, - ); - - try { - await (scheduler.schedule('add', [1, 2, 3, 4])).output.toPromise(); - expect(true).toBe(false); - } catch (e) { - // TODO: enable this when https://github.com/bazelbuild/rules_typescript/commit/37807e2c4 - // is released, otherwise this breaks because bazel downgrade to ES5 which does not support - // extending Error. - // expect(e instanceof JobOutputSchemaValidationError).toBe(true); - expect(e.message).toMatch(/"".*number/); - } - }); - - it('works with dependencies', async () => { - const done: number[] = []; - - registry.register( - 'job', - createJobHandler((argument) => { - return new Promise(resolve => setImmediate(() => { - done.push(argument); - resolve(argument); - })); - }), - { argument: true, output: true }, - ); - - // Run jobs. - const job1 = scheduler.schedule('job', 1); - const job2 = scheduler.schedule('job', 2); - const job3 = scheduler.schedule('job', 3); - - // Run a job to wait for 1. - const job4 = scheduler.schedule('job', 4, { dependencies: job1 }); - - // Run a job to wait for 2. - const job5 = scheduler.schedule('job', 5, { dependencies: job2 }); - - // Run a job to wait for 3. - const job6 = scheduler.schedule('job', 6, { dependencies: job3 }); - - // Run a job to wait for 4, 5 and 6. - const job7 = scheduler.schedule('job', 7, { dependencies: [job4, job5, job6] }); - - expect(done.length).toBe(0); - - await job1.output.toPromise(); - expect(done).toContain(1); - expect(done).not.toContain(4); - expect(done).not.toContain(7); - - await job5.output.toPromise(); - expect(done).toContain(1); - expect(done).toContain(2); - expect(done).not.toContain(4); - expect(done).toContain(5); - expect(done).not.toContain(7); - - await job7.output.toPromise(); - expect(done.length).toBe(7); - // Might be out of order. - expect(done).toEqual(jasmine.arrayContaining([1, 2, 3, 4, 5, 6, 7])); - // Verify at least partial order. - expect(done[done.length - 1]).toBe(7); - expect(done.indexOf(4)).toBeGreaterThan(done.indexOf(1)); - expect(done.indexOf(5)).toBeGreaterThan(done.indexOf(2)); - expect(done.indexOf(6)).toBeGreaterThan(done.indexOf(3)); - }); - - it('does not start dependencies until the last one is subscribed to', async () => { - // This test creates the following graph of dependencies: - // 1 <-.-- 2 <-.-- 4 <-.---------.-- 6 - // +-- 3 <-+-- 5 <-' - // Which can result only in the execution orders: [1, 2, 3, 4, 5, 6] - // Only subscribe to the last one. - - const started: number[] = []; - const done: number[] = []; - - registry.register( - 'job', - createJobHandler((argument: number) => { - started.push(argument); - - return new Promise(resolve => setImmediate(() => { - done.push(argument); - resolve(argument); - })); - }), - { argument: true, output: true }, - ); - - // Run jobs. - const job1 = scheduler.schedule('job', 1); - const job2 = scheduler.schedule('job', 2, { dependencies: job1 }); - const job3 = scheduler.schedule('job', 3, { dependencies: job2 }); - const job4 = scheduler.schedule('job', 4, { dependencies: [job2, job3] }); - const job5 = scheduler.schedule('job', 5, { dependencies: [job1, job2, job4] }); - const job6 = scheduler.schedule('job', 6, { dependencies: [job4, job5] }); - - // Just subscribe to the last job in the lot. - job6.outboundBus.subscribe(); - // Expect the first one to start. - expect(started).toEqual([1]); - // Wait for the first one to finish. - await job1.output.toPromise(); - // Expect the second one to have started, and the first one to be done. - expect(started).toEqual([1, 2]); - expect(done).toEqual([1]); - - // Rinse and repeat. - await job2.output.toPromise(); - expect(started).toEqual([1, 2, 3]); - expect(done).toEqual([1, 2]); - - await job3.output.toPromise(); - expect(started).toEqual([1, 2, 3, 4]); - expect(done).toEqual([1, 2, 3]); - - await job4.output.toPromise(); - expect(started).toEqual([1, 2, 3, 4, 5]); - expect(done).toEqual([1, 2, 3, 4]); - - // Just skip job 5. - await job6.output.toPromise(); - expect(done).toEqual(started); - }); - - it('can be paused', async () => { - let resume: (() => void) | null = null; - - registry.register( - 'job', - createJobHandler((argument, context) => { - return Promise.resolve() - .then(() => { - expect(resume).toBeNull(); - resume = context.scheduler.pause(); - }) - .then(() => argument); - }), - ); - - // Run the job once. Wait for it to finish. We should have a `resume()` and the scheduler will - // be paused. - const p0 = (scheduler.schedule('job', 0)).output.toPromise(); - expect(await p0).toBe(0); - - // This will wait. - const p1 = (scheduler.schedule('job', 1)).output.toPromise(); - await Promise.resolve(); - - expect(resume).not.toBeNull(); - resume !(); - resume = null; - - // Running p1. - expect(await p1).toBe(1); - expect(resume).not.toBeNull(); - - const p2 = (scheduler.schedule('job', 2)).output.toPromise(); - - await Promise.resolve(); - resume !(); - resume = null; - expect(await p2).toBe(2); - expect(resume).not.toBeNull(); - - resume !(); - // Should not error since all jobs have run. - await Promise.resolve(); - }); - - it('can be paused (multiple)', async () => { - const done: number[] = []; - - registry.register( - 'jobA', - createJobHandler((argument: number) => { - done.push(argument); - - return Promise.resolve() - .then(() => argument); - }), - ); - - // Pause manually. - const resume = scheduler.pause(); - const p10 = (scheduler.schedule('jobA', 10)).output.toPromise(); - const p11 = (scheduler.schedule('jobA', 11)).output.toPromise(); - const p12 = (scheduler.schedule('jobA', 12)).output.toPromise(); - await Promise.resolve(); - - expect(done).toEqual([]); - resume(); - await Promise.resolve(); - expect(done).not.toEqual([]); - expect(await p10).toBe(10); - expect(await p11).toBe(11); - expect(await p12).toBe(12); - expect(done).toEqual([10, 11, 12]); - }); - - it('can be cancelled by unsubscribing from the raw output', async () => { - const done: number[] = []; - const resolves: (() => void)[] = []; - let keepGoing = true; - - registry.register( - 'job', - createJobHandler((argument: number) => { - return new Observable(observer => { - function fn() { - if (keepGoing) { - const p = new Promise(r => resolves.push(r)); - - observer.next(argument); - done.push(argument); - argument++; - - // tslint:disable-next-line:no-floating-promises - p.then(fn); - } else { - done.push(-1); - observer.complete(); - } - } - - setImmediate(fn); - - return () => { - keepGoing = false; - }; - }); - }), - ); - - const job = scheduler.schedule('job', 0); - await new Promise(r => setTimeout(r, 10)); - expect(job.state).toBe(JobState.Queued); - const subscription = job.output.subscribe(); - - await new Promise(r => setTimeout(r, 10)); - expect(job.state).toBe(JobState.Started); - expect(done).toEqual([0]); - expect(resolves.length).toBe(1); - resolves[0](); - - await new Promise(r => setTimeout(r, 10)); - expect(done).toEqual([0, 1]); - expect(resolves.length).toBe(2); - resolves[1](); - - await new Promise(r => setTimeout(r, 10)); - expect(done).toEqual([0, 1, 2]); - expect(resolves.length).toBe(3); - subscription.unsubscribe(); - resolves[2](); - - job.stop(); - await job.output.toPromise(); - expect(keepGoing).toBe(false); - expect(done).toEqual([0, 1, 2, -1]); - expect(job.state).toBe(JobState.Ended); - }); - - it('sequences raw outputs properly for all use cases', async () => { - registry.register('job-sync', createJobHandler(arg => arg + 1)); - registry.register('job-promise', createJobHandler(arg => { - return Promise.resolve(arg + 1); - })); - registry.register('job-obs-sync', createJobHandler(arg => of(arg + 1))); - registry.register('job-obs-async', createJobHandler(arg => { - return timer(1).pipe( - take(3), - take(1), - map(() => arg + 1), - ); - })); - - const job1 = scheduler.schedule('job-sync', 100); - const job1OutboundBus = await job1.outboundBus.pipe( - // Descriptions are going to differ, so get rid of those. - map(x => ({ ...x, description: null })), - toArray(), - ).toPromise(); - - const job2 = scheduler.schedule('job-promise', 100); - const job2OutboundBus = await job2.outboundBus.pipe( - // Descriptions are going to differ, so get rid of those. - map(x => ({ ...x, description: null })), - toArray(), - ).toPromise(); - - const job3 = scheduler.schedule('job-obs-sync', 100); - const job3OutboundBus = await job3.outboundBus.pipe( - // Descriptions are going to differ, so get rid of those. - map(x => ({ ...x, description: null })), - toArray(), - ).toPromise(); - - const job4 = scheduler.schedule('job-obs-async', 100); - const job4OutboundBus = await job4.outboundBus.pipe( - // Descriptions are going to differ, so get rid of those. - map(x => ({ ...x, description: null })), - toArray(), - ).toPromise(); - - // The should all report the same stuff. - expect(job1OutboundBus).toEqual(job4OutboundBus); - expect(job2OutboundBus).toEqual(job4OutboundBus); - expect(job3OutboundBus).toEqual(job4OutboundBus); - }); - - describe('channels', () => { - it('works', async () => { - registry.register( - 'job', - createJobHandler((argument, context) => { - const channel = context.createChannel('any'); - channel.next('hello world'); - channel.complete(); - - return 0; - }), - ); - - const job = scheduler.schedule('job', 0); - let sideValue = ''; - const c = job.getChannel('any') as Observable; - c.subscribe(x => sideValue = x); - - expect(await job.output.toPromise()).toBe(0); - expect(sideValue).toBe('hello world'); - }); - - it('validates', async () => { - registry.register( - 'job', - createJobHandler((argument, context) => { - const channel = context.createChannel('any'); - channel.next('hello world'); - channel.complete(); - - return 0; - }), { - argument: true, - output: true, - }, - ); - - const job = scheduler.schedule('job', 0); - let sideValue = ''; - const c = job.getChannel('any', { type: 'number' }) as Observable; - expect(c).toBeDefined(null); - - if (c) { - c.subscribe(x => sideValue = x); - } - - expect(await job.output.toPromise()).toBe(0); - expect(sideValue).not.toBe('hello world'); - }); - }); - - describe('lifecycle messages', () => { - it('sequences double start once', async () => { - const fn = (_: never, { description }: JobHandlerContext) => { - return new Observable>(observer => { - observer.next({ kind: JobOutboundMessageKind.Start, description }); - observer.next({ kind: JobOutboundMessageKind.Start, description }); - observer.next({ kind: JobOutboundMessageKind.End, description }); - observer.complete(); - }); - }; - - registry.register('job', Object.assign(fn, { jobDescription: {} })); - const allOutput = await scheduler.schedule('job', 0).outboundBus.pipe( - toArray(), - ).toPromise(); - - expect(allOutput.map(x => ({ ...x, description: null }))).toEqual([ - { kind: JobOutboundMessageKind.OnReady, description: null }, - { kind: JobOutboundMessageKind.Start, description: null }, - { kind: JobOutboundMessageKind.End, description: null }, - ]); - }); - - it('add an End if there is not one', async () => { - const fn = () => EMPTY; - - registry.register('job', Object.assign(fn, { jobDescription: {} })); - const allOutput = await scheduler.schedule('job', 0).outboundBus.pipe( - toArray(), - ).toPromise(); - - expect(allOutput.map(x => ({ ...x, description: null }))).toEqual([ - { kind: JobOutboundMessageKind.OnReady, description: null }, - { kind: JobOutboundMessageKind.End, description: null }, - ]); - }); - - it('only one End', async () => { - const fn = (_: never, { description }: JobHandlerContext) => { - return new Observable>(observer => { - observer.next({ kind: JobOutboundMessageKind.End, description }); - observer.next({ kind: JobOutboundMessageKind.End, description }); - observer.complete(); - }); - }; - - registry.register('job', Object.assign(fn, { jobDescription: {} })); - const allOutput = await scheduler.schedule('job', 0).outboundBus.pipe( - toArray(), - ).toPromise(); - - expect(allOutput.map(x => ({ ...x, description: null }))).toEqual([ - { kind: JobOutboundMessageKind.OnReady, description: null }, - { kind: JobOutboundMessageKind.End, description: null }, - ]); - }); - }); - - describe('input', () => { - it('works', async () => { - registry.register( - 'job', - createJobHandler((argument, context) => { - return new Observable(subscriber => { - context.input.subscribe(x => { - if (x === null) { - subscriber.complete(); - } else { - subscriber.next(parseInt('' + x) + argument); - } - }); - }); - }), - ); - - const job = scheduler.schedule('job', 100); - const outputs: number[] = []; - - job.output.subscribe(x => outputs.push(x as number)); - - job.input.next(1); - job.input.next('2'); - job.input.next(3); - job.input.next(null); - - expect(await job.output.toPromise()).toBe(103); - expect(outputs).toEqual([101, 102, 103]); - }); - - it('validates', async () => { - const handler = createJobHandler((argument, context) => { - return new Observable(subscriber => { - context.input.subscribe(x => { - if (x === null) { - subscriber.complete(); - } else { - subscriber.next(parseInt('' + x) + argument); - } - }); - }); - }, { - input: { anyOf: [{ type: 'number' }, { type: 'null' }] }, - }); - - registry.register('job', handler); - - const job = scheduler.schedule('job', 100); - const outputs: number[] = []; - - job.output.subscribe(x => outputs.push(x as number)); - - job.input.next(1); - job.input.next('2'); - job.input.next(3); - job.input.next(null); - - expect(await job.output.toPromise()).toBe(103); - expect(outputs).toEqual([101, 103]); - }); - - it('works deferred', async () => { - // This is a more complex test. The job returns an output deferred from the input - registry.register( - 'job', - createJobHandler((argument, context) => { - return new Observable(subscriber => { - context.input.subscribe(x => { - if (x === null) { - setTimeout(() => subscriber.complete(), 10); - } else { - setTimeout(() => subscriber.next(parseInt('' + x) + argument), x); - } - }); - }); - }), - ); - - const job = scheduler.schedule('job', 100); - const outputs: number[] = []; - - job.output.subscribe(x => outputs.push(x as number)); - - job.input.next(1); - job.input.next(2); - job.input.next(3); - job.input.next(null); - - expect(await job.output.toPromise()).toBe(103); - expect(outputs).toEqual(jasmine.arrayWithExactContents([101, 102, 103])); - }); - }); - - it('propagates errors', async () => { - registry.register('job', createJobHandler(() => { throw 1; })); - const job = scheduler.schedule('job', 0); - - try { - await job.output.toPromise(); - expect('THE ABOVE LINE SHOULD NOT ERROR').toBe('false'); - } catch (error) { - expect(error).toBe(1); - } - }); -}); diff --git a/packages/angular_devkit/core/src/experimental/jobs/strategy.ts b/packages/angular_devkit/core/src/experimental/jobs/strategy.ts deleted file mode 100644 index e1903aceb8b9..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/strategy.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as stableStringify from 'fast-json-stable-stringify'; -import { Observable, Subject, concat, of } from 'rxjs'; -import { finalize, ignoreElements, share, shareReplay, tap } from 'rxjs/operators'; -import { JsonValue } from '../../json'; -import { - JobDescription, - JobHandler, - JobHandlerContext, JobInboundMessage, - JobOutboundMessage, - JobOutboundMessageKind, -} from './api'; - -export namespace strategy { - - export type JobStrategy< - A extends JsonValue = JsonValue, - I extends JsonValue = JsonValue, - O extends JsonValue = JsonValue, - > = ( - handler: JobHandler, - options?: Partial>, - ) => JobHandler; - - /** - * Creates a JobStrategy that serializes every call. This strategy can be mixed between jobs. - */ - export function serialize< - A extends JsonValue = JsonValue, - I extends JsonValue = JsonValue, - O extends JsonValue = JsonValue, - >(): JobStrategy { - let latest: Observable> = of(); - - return (handler, options) => { - const newHandler = (argument: A, context: JobHandlerContext) => { - const previous = latest; - latest = concat( - previous.pipe(ignoreElements()), - new Observable>(o => handler(argument, context).subscribe(o)), - ).pipe( - shareReplay(0), - ); - - return latest; - }; - - return Object.assign(newHandler, { - jobDescription: Object.assign({}, handler.jobDescription, options), - }); - }; - } - - - /** - * Creates a JobStrategy that will always reuse a running job, and restart it if the job ended. - * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it - * is. - */ - export function reuse< - A extends JsonValue = JsonValue, - I extends JsonValue = JsonValue, - O extends JsonValue = JsonValue, - >(replayMessages = false): JobStrategy { - let inboundBus = new Subject>(); - let runContext: JobHandlerContext | null = null; - let run: Observable> | null = null; - let state: JobOutboundMessage | null = null; - - return (handler, options) => { - const newHandler = (argument: A, context: JobHandlerContext) => { - // Forward inputs. - const subscription = context.inboundBus.subscribe(inboundBus); - - if (run) { - return concat( - // Update state. - of(state), - run, - ).pipe( - finalize(() => subscription.unsubscribe()), - ); - } - - run = handler(argument, { ...context, inboundBus: inboundBus.asObservable() }).pipe( - tap( - message => { - if (message.kind == JobOutboundMessageKind.Start - || message.kind == JobOutboundMessageKind.OnReady - || message.kind == JobOutboundMessageKind.End) { - state = message; - } - }, - undefined, - () => { - subscription.unsubscribe(); - inboundBus = new Subject>(); - run = null; - }, - ), - replayMessages ? shareReplay() : share(), - ); - runContext = context; - - return run; - }; - - return Object.assign(newHandler, handler, options || {}); - }; - } - - - /** - * Creates a JobStrategy that will reuse a running job if the argument matches. - * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it - * is. - */ - export function memoize< - A extends JsonValue = JsonValue, - I extends JsonValue = JsonValue, - O extends JsonValue = JsonValue, - >(replayMessages = false): JobStrategy { - const runs = new Map>>(); - - return (handler, options) => { - const newHandler = (argument: A, context: JobHandlerContext) => { - const argumentJson = stableStringify(argument); - const maybeJob = runs.get(argumentJson); - - if (maybeJob) { - return maybeJob; - } - - const run = handler(argument, context).pipe( - replayMessages ? shareReplay() : share(), - ); - runs.set(argumentJson, run); - - return run; - }; - - return Object.assign(newHandler, handler, options || {}); - }; - } - -} diff --git a/packages/angular_devkit/core/src/experimental/jobs/strategy_spec.ts b/packages/angular_devkit/core/src/experimental/jobs/strategy_spec.ts deleted file mode 100644 index 63bbd20ef2ec..000000000000 --- a/packages/angular_devkit/core/src/experimental/jobs/strategy_spec.ts +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { JobState } from './api'; -import { createJobHandler } from './create-job-handler'; -import { SimpleJobRegistry } from './simple-registry'; -import { SimpleScheduler } from './simple-scheduler'; -import { strategy } from './strategy'; - -describe('strategy.serialize()', () => { - let registry: SimpleJobRegistry; - let scheduler: SimpleScheduler; - - beforeEach(() => { - registry = new SimpleJobRegistry(); - scheduler = new SimpleScheduler(registry); - }); - - it('works', async () => { - let started = 0; - let finished = 0; - - registry.register(strategy.serialize()(createJobHandler((input: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(input.reduce((a, c) => a + c, 0)); - }, 10), - ); - })), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - name: 'add', - }); - - const job1 = scheduler.schedule('add', [1, 2, 3, 4]); - const job2 = scheduler.schedule('add', [1, 2, 3, 4, 5]); - expect(started).toBe(0); - expect(finished).toBe(0); - - job1.output.subscribe(); - expect(started).toBe(1); - - job2.output.subscribe(); - expect(started).toBe(1); // Job2 starts when Job1 ends. - - expect(finished).toBe(0); - - await Promise.all([ - job1.output.toPromise().then(s => { - expect(finished).toBe(1); - expect(s).toBe(10); - }), - job2.output.toPromise().then(s => { - expect(finished).toBe(2); - expect(s).toBe(15); - }), - ]); - - expect(started).toBe(2); - expect(finished).toBe(2); - }); - - it('works across jobs', async () => { - let started = 0; - let finished = 0; - - const strategy1 = strategy.serialize(); - - registry.register(strategy1(createJobHandler((input: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(input.reduce((a, c) => a + c, 0)); - }, 10), - ); - })), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - name: 'add', - }); - registry.register(strategy1(createJobHandler((input: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(input.reduce((a, c) => a + c, 100)); - }, 10), - ); - })), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - name: 'add100', - }); - - const job1 = scheduler.schedule('add', [1, 2, 3, 4]); - const job2 = scheduler.schedule('add100', [1, 2, 3, 4, 5]); - expect(started).toBe(0); - expect(finished).toBe(0); - - job1.output.subscribe(); - expect(started).toBe(1); - - job2.output.subscribe(); - expect(started).toBe(1); // Job2 starts when Job1 ends. - - expect(finished).toBe(0); - - await Promise.all([ - job1.output.toPromise().then(s => { - expect(finished).toBe(1); - expect(s).toBe(10); - }), - job2.output.toPromise().then(s => { - expect(finished).toBe(2); - expect(s).toBe(115); - }), - ]); - - expect(started).toBe(2); - expect(finished).toBe(2); - }); -}); - -describe('strategy.reuse()', () => { - let registry: SimpleJobRegistry; - let scheduler: SimpleScheduler; - - beforeEach(() => { - registry = new SimpleJobRegistry(); - scheduler = new SimpleScheduler(registry); - }); - - it('works', async () => { - let started = 0; - let finished = 0; - - registry.register(strategy.reuse()(createJobHandler((input: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(input.reduce((a, c) => a + c, 0)); - }, 10), - ); - })), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - name: 'add', - }); - - const job1 = scheduler.schedule('add', [1, 2, 3, 4]); - const job2 = scheduler.schedule('add', []); - expect(started).toBe(0); - expect(finished).toBe(0); - - job1.output.subscribe(); - expect(started).toBe(1); - expect(finished).toBe(0); - - job2.output.subscribe(); - expect(started).toBe(1); // job2 is reusing job1. - expect(finished).toBe(0); - - let result = await job1.output.toPromise(); - expect(result).toBe(10); - expect(started).toBe(1); - expect(finished).toBe(1); - expect(job1.state).toBe(JobState.Ended); - expect(job2.state).toBe(JobState.Ended); - - const job3 = scheduler.schedule('add', [1, 2, 3, 4, 5]); - const job4 = scheduler.schedule('add', []); - job3.output.subscribe(); - expect(started).toBe(2); - expect(finished).toBe(1); - - job4.output.subscribe(); - expect(started).toBe(2); // job4 is reusing job3. - expect(finished).toBe(1); - - result = await job3.output.toPromise(); - expect(result).toBe(15); - expect(started).toBe(2); - expect(finished).toBe(2); - expect(job3.state).toBe(JobState.Ended); - expect(job4.state).toBe(JobState.Ended); - }); -}); - -describe('strategy.memoize()', () => { - let registry: SimpleJobRegistry; - let scheduler: SimpleScheduler; - - beforeEach(() => { - registry = new SimpleJobRegistry(); - scheduler = new SimpleScheduler(registry); - }); - - it('works', async () => { - let started = 0; - let finished = 0; - - registry.register(strategy.memoize()(createJobHandler((input: number[]) => { - started++; - - return new Promise( - resolve => setTimeout(() => { - finished++; - resolve(input.reduce((a, c) => a + c, 0)); - }, 10), - ); - })), { - argument: { items: { type: 'number' } }, - output: { type: 'number' }, - name: 'add', - }); - - const job1 = scheduler.schedule('add', [1, 2, 3, 4]); - const job2 = scheduler.schedule('add', [1, 2, 3, 4]); - const job3 = scheduler.schedule('add', [1, 2, 3, 4, 5]); - const job4 = scheduler.schedule('add', [1, 2, 3, 4, 5]); - expect(started).toBe(0); - expect(finished).toBe(0); - - job1.output.subscribe(); - expect(started).toBe(1); - expect(finished).toBe(0); - - job2.output.subscribe(); - expect(started).toBe(1); // job2 is reusing job1. - expect(finished).toBe(0); - - job3.output.subscribe(); - expect(started).toBe(2); - expect(finished).toBe(0); - - job4.output.subscribe(); - expect(started).toBe(2); // job4 is reusing job3. - expect(finished).toBe(0); - - await Promise.all([ - job1.output.toPromise().then(s => { - // This is hard since job3 and job1 might finish out of order. - expect(finished).toBeGreaterThanOrEqual(1); - expect(s).toBe(10); - }), - job2.output.toPromise().then(s => { - // This is hard since job3 and job1 might finish out of order. - expect(finished).toBeGreaterThanOrEqual(1); - expect(job1.state).toBe(JobState.Ended); - expect(job2.state).toBe(JobState.Ended); - expect(s).toBe(10); - }), - job3.output.toPromise().then(s => { - // This is hard since job3 and job1 might finish out of order. - expect(finished).toBeGreaterThanOrEqual(1); - expect(s).toBe(15); - }), - job4.output.toPromise().then(s => { - expect(job3.state).toBe(JobState.Ended); - expect(job4.state).toBe(JobState.Ended); - // This is hard since job3 and job1 might finish out of order. - expect(finished).toBeGreaterThanOrEqual(1); - expect(s).toBe(15); - }), - ]); - - expect(started).toBe(2); - expect(finished).toBe(2); - }); -}); diff --git a/packages/angular_devkit/core/src/experimental/workspace/index.ts b/packages/angular_devkit/core/src/experimental/workspace/index.ts deleted file mode 100644 index 13517e107f8d..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export * from './workspace'; -export * from './workspace-schema'; diff --git a/packages/angular_devkit/core/src/experimental/workspace/test/test-workspace.json b/packages/angular_devkit/core/src/experimental/workspace/test/test-workspace.json deleted file mode 100644 index bf01c8c02db9..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/test/test-workspace.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "version": 1, - "newProjectRoot": "./projects", - "defaultProject": "app", - "cli": { - "$globalOverride": "${HOME}/.angular-cli.json", - "schematics": { - "defaultCollection": "@schematics/angular" - }, - "warnings": { - "showDeprecation": false - } - }, - "schematics": { - "@schematics/angular": { - "*": { - "skipImport": true, - "packageManager": "yarn" - }, - "application": { - "spec": false - } - } - }, - "architect": {}, - "projects": { - "app": { - "root": "projects/app", - "projectType": "application", - "cli": {}, - "schematics": { - "@schematics/angular": { - "*": { - "spec": false - } - } - }, - "architect": { - "build": { - "builder": "@angular-devkit/build-angular:browser", - "transforms": [ - { - "plugin": "@angular-devkit/architect-transforms:replacement", - "file": "environments/environment.ts", - "configurations": { - "production": "environments/environment.prod.ts" - } - } - ], - "options": { - "outputPath": "../dist", - "index": "index.html", - "main": "main.ts", - "polyfills": "polyfills.ts", - "tsConfig": "tsconfig.app.json", - "progress": false - }, - "configurations": { - "production": { - "optimization": true, - "outputHashing": "all", - "sourceMap": false, - "extractCss": true, - "namedChunks": false, - "aot": true, - "extractLicenses": true, - "vendorChunk": false, - "buildOptimizer": true - } - } - } - } - } - } -} \ No newline at end of file diff --git a/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.json b/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.json deleted file mode 100644 index de7b5abec537..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.json +++ /dev/null @@ -1,152 +0,0 @@ -{ - "$schema": "http://json-schema.org/schema", - "id": "AngularDevkitWorkspaceSchema", - "title": "Angular Devkit Workspace Schema for validating workspace JSON.", - "type": "object", - "properties": { - "$schema": { - "type": "string", - "description": "Link to schema." - }, - "version": { - "type": "number", - "description": "Workspace Schema version." - }, - "newProjectRoot": { - "type": "string", - "description": "New project root.", - "default": "./" - }, - "defaultProject": { - "type": "string", - "description": "The default project." - }, - "cli": { - "$ref": "#/definitions/tool", - "default": {} - }, - "schematics": { - "$ref": "#/definitions/tool", - "default": {} - }, - "architect": { - "$ref": "#/definitions/tool", - "default": {} - }, - "targets": { - "$ref": "#/definitions/tool", - "default": {} - }, - "projects": { - "type": "object", - "description": "A map of project names to project options.", - "additionalProperties": { - "$ref": "#/definitions/project" - }, - "default": {} - } - }, - "additionalProperties": false, - "required": [ - "version" - ], - "definitions": { - "project": { - "type": "object", - "description": "Project options.", - "properties": { - "projectType": { - "type": "string", - "description": "Project type.", - "enum": [ - "application", - "library" - ] - }, - "root": { - "type": "string", - "description": "Root of the project sourcefiles." - }, - "sourceRoot": { - "type": "string", - "description": "The root of the source files, assets and index.html file structure." - }, - "prefix": { - "type": "string", - "description": "The prefix to apply to generated selectors." - }, - "cli": { - "$ref": "#/definitions/tool", - "default": {} - }, - "schematics": { - "$ref": "#/definitions/tool", - "default": {} - }, - "architect": { - "$ref": "#/definitions/tool", - "default": {} - }, - "targets": { - "$ref": "#/definitions/tool", - "default": {} - }, - "i18n": { - "$ref": "#/definitions/i18n", - "default": {} - } - }, - "additionalProperties": false, - "required": [ - "root", - "projectType" - ], - "if": { - "properties": { - "projectType": { - "const": "library" - } - } - }, - "then": { - "not": { - "required": [ - "i18n" - ] - } - } - }, - "tool": { - "type": "object", - "description": "Tool options.", - "properties": { - "$schema": { - "type": "string", - "description": "Link to schema." - } - }, - "additionalProperties": true - }, - "i18n": { - "type": "object", - "properties": { - "sourceLocale": { - "type": "string", - "description": "Specifies the source language of the application.", - "default": "en-US" - }, - "locales": { - "type": "object", - "additionalProperties": false, - "patternProperties": { - "^[a-z]{2}(-[a-zA-Z]{2,})?$": { - "type": "string", - "description": "Localization file to use for i18n." - } - } - } - }, - "additionalProperties": false - } - } -} diff --git a/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.ts b/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.ts deleted file mode 100644 index 84769ee96389..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/workspace-schema.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable -export interface WorkspaceSchema { - /** - * Link to schema. - */ - $schema?: string; - /** - * Workspace Schema version. - */ - version: number; - /** - * New project root. - */ - newProjectRoot?: string; - /** - * The default project. - */ - defaultProject?: string; - /** - * Tool options. - */ - cli?: WorkspaceTool; - /** - * Tool options. - */ - schematics?: WorkspaceTool; - /** - * Tool options. - */ - architect?: WorkspaceTool; - /** - * Tool options. - */ - targets?: WorkspaceTool; - /** - * A map of project names to project options. - */ - projects: { - [k: string]: WorkspaceProject; - }; -} -/** - * Project options. - */ -export interface WorkspaceProject { - /** - * Project type. - */ - projectType: "application" | "library"; - /** - * Root of the project sourcefiles. - */ - root: string; - /** - * The root of the source files, assets and index.html file structure. - */ - sourceRoot?: string; - /** - * The prefix to apply to generated selectors. - */ - prefix: string; - /** - * Tool options. - */ - cli?: WorkspaceTool; - /** - * Tool options. - */ - schematics?: WorkspaceTool; - /** - * Tool options. - */ - architect?: WorkspaceTool; - /** - * Tool options. - */ - targets?: WorkspaceTool; - /** - * i18n options. - */ - i18n?: WorkspaceProjectI18n; -} -/** - * Architect options. - */ -export interface WorkspaceTool { - /** - * Link to schema. - */ - $schema?: string; - [k: string]: any; -} - -export interface WorkspaceProjectI18n { - /** - * Specifies the source language of the application. - */ - sourceLocale?: string; - /** - * Localization file to use for i18n. - */ - locales: Record; -} diff --git a/packages/angular_devkit/core/src/experimental/workspace/workspace.ts b/packages/angular_devkit/core/src/experimental/workspace/workspace.ts deleted file mode 100644 index 805938706e1a..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/workspace.ts +++ /dev/null @@ -1,362 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { existsSync } from 'fs'; -import * as path from 'path'; -import { Observable, of, throwError } from 'rxjs'; -import { concatMap, first, map, tap } from 'rxjs/operators'; -import { BaseException } from '../../exception'; -import { - JsonObject, - JsonParseMode, - parseJson, - schema, -} from '../../json'; -import { SchemaValidatorResult } from '../../json/schema/interface'; -import { - Path, - basename, - dirname, - isAbsolute, - join, - normalize, - relative, - resolve, - virtualFs, -} from '../../virtual-fs'; -import { WorkspaceProject, WorkspaceSchema, WorkspaceTool } from './workspace-schema'; - - -export class WorkspaceFileNotFoundException extends BaseException { - constructor(path: Path) { - super(`Workspace could not be found from path ${path}.`); - } -} - -export class ProjectNotFoundException extends BaseException { - constructor(name: string) { - super(`Project '${name}' could not be found in workspace.`); - } -} - -export class WorkspaceToolNotFoundException extends BaseException { - constructor(name: string) { - super(`Tool ${name} could not be found in workspace.`); - } -} - -export class ProjectToolNotFoundException extends BaseException { - constructor(name: string) { - super(`Tool ${name} could not be found in project.`); - } -} - -export class WorkspaceNotYetLoadedException extends BaseException { - constructor() { super(`Workspace needs to be loaded before it is used.`); } -} - -export class AmbiguousProjectPathException extends BaseException { - constructor(public readonly path: Path, public readonly projects: ReadonlyArray) { - super(`Current active project is ambiguous (${projects.join(',')}) using path: '${path}'`); - } -} - -async function _findUp(host: virtualFs.Host, names: string[], from: Path): Promise { - if (!Array.isArray(names)) { - names = [names]; - } - - do { - for (const name of names) { - const p = join(from, name); - if (await host.exists(p).toPromise()) { - return p; - } - } - - from = dirname(from); - } while (from && from !== dirname(from)); - - return null; -} - -export class Workspace { - protected static _workspaceFileNames = [ - 'angular.json', - '.angular.json', - ]; - - private readonly _workspaceSchemaPath = normalize(require.resolve('./workspace-schema.json')); - private _workspaceSchema: JsonObject; - private _workspace: WorkspaceSchema; - private _registry: schema.CoreSchemaRegistry; - - constructor( - private _root: Path, - private _host: virtualFs.Host<{}>, - registry?: schema.CoreSchemaRegistry, - ) { - if (registry) { - this._registry = registry; - } else { - this._registry = new schema.CoreSchemaRegistry(); - this._registry.addPostTransform(schema.transforms.addUndefinedDefaults); - } - } - - static async findWorkspaceFile(host: virtualFs.Host<{}>, path: Path): Promise { - return await _findUp(host, this._workspaceFileNames, path); - } - static async fromPath( - host: virtualFs.Host<{}>, - path: Path, - registry: schema.CoreSchemaRegistry, - ): Promise { - const maybePath = await this.findWorkspaceFile(host, path); - - if (!maybePath) { - throw new WorkspaceFileNotFoundException(path); - } - - return new Workspace(dirname(maybePath), host, registry) - .loadWorkspaceFromHost(basename(maybePath)) - .pipe(first()) - .toPromise(); - } - - loadWorkspaceFromJson(json: {}) { - return this._loadWorkspaceSchema().pipe( - concatMap((workspaceSchema) => this.validateAgainstSchema(json, workspaceSchema)), - tap((validatedWorkspace: WorkspaceSchema) => this._workspace = validatedWorkspace), - map(() => this), - ); - } - - loadWorkspaceFromHost(workspacePath: Path) { - return this._loadWorkspaceSchema().pipe( - concatMap(() => this._loadJsonFile(join(this._root, workspacePath))), - concatMap(json => this.loadWorkspaceFromJson(json)), - ); - } - - private _loadWorkspaceSchema() { - if (this._workspaceSchema) { - return of(this._workspaceSchema); - } else { - return this._loadJsonFile(this._workspaceSchemaPath).pipe( - tap((workspaceSchema) => this._workspaceSchema = workspaceSchema), - ); - } - } - - private _assertLoaded() { - if (!this._workspace) { - throw new WorkspaceNotYetLoadedException(); - } - } - - get root() { - return this._root; - } - - get host() { - return this._host; - } - - get version() { - this._assertLoaded(); - - return this._workspace.version; - } - - get newProjectRoot() { - this._assertLoaded(); - - return this._workspace.newProjectRoot; - } - - listProjectNames(): string[] { - return Object.keys(this._workspace.projects); - } - - getProject(projectName: string): WorkspaceProject { - this._assertLoaded(); - - const workspaceProject = this._workspace.projects[projectName]; - - if (!workspaceProject) { - throw new ProjectNotFoundException(projectName); - } - - // Return only the project properties, and remove the tools. - const workspaceProjectClone = {...workspaceProject}; - delete workspaceProjectClone['cli']; - delete workspaceProjectClone['schematics']; - delete workspaceProjectClone['architect']; - delete workspaceProjectClone['targets']; - - return workspaceProjectClone; - } - - getDefaultProjectName(): string | null { - this._assertLoaded(); - - if (this._workspace.defaultProject) { - // If there is a default project name, return it. - return this._workspace.defaultProject; - } else if (this.listProjectNames().length === 1) { - // If there is only one project, return that one. - return this.listProjectNames()[0]; - } - - // Otherwise return null. - return null; - } - - getProjectByPath(path: Path): string | null { - this._assertLoaded(); - - const projectNames = this.listProjectNames(); - if (projectNames.length === 1) { - return projectNames[0]; - } - - const isInside = (base: Path, potential: Path): boolean => { - const absoluteBase = resolve(this.root, base); - const absolutePotential = resolve(this.root, potential); - const relativePotential = relative(absoluteBase, absolutePotential); - if (!relativePotential.startsWith('..') && !isAbsolute(relativePotential)) { - return true; - } - - return false; - }; - - const projects = this.listProjectNames() - .map(name => [this.getProject(name).root, name] as [Path, string]) - .filter(tuple => isInside(tuple[0], path)) - // Sort tuples by depth, with the deeper ones first. Since the first member is a path and - // we filtered all invalid paths, the longest will be the deepest (and in case of equality - // the sort is stable and the first declared project will win). - .sort((a, b) => b[0].length - a[0].length); - - if (projects.length === 0) { - return null; - } else if (projects.length > 1) { - const found = new Set(); - const sameRoots = projects.filter(v => { - if (!found.has(v[0])) { - found.add(v[0]); - - return false; - } - - return true; - }); - if (sameRoots.length > 0) { - throw new AmbiguousProjectPathException(path, sameRoots.map(v => v[1])); - } - } - - return projects[0][1]; - } - - getCli() { - return this._getTool('cli'); - } - - getSchematics() { - return this._getTool('schematics'); - } - - getTargets() { - return this._getTool('targets'); - } - - getProjectCli(projectName: string) { - return this._getProjectTool(projectName, 'cli'); - } - - getProjectSchematics(projectName: string) { - return this._getProjectTool(projectName, 'schematics'); - } - - getProjectTargets(projectName: string) { - return this._getProjectTool(projectName, 'targets'); - } - - private _getTool(toolName: 'cli' | 'schematics' | 'targets'): WorkspaceTool { - this._assertLoaded(); - - let workspaceTool = this._workspace[toolName]; - - // Try falling back to 'architect' if 'targets' is not there or is empty. - if ((!workspaceTool || Object.keys(workspaceTool).length === 0) - && toolName === 'targets' - && this._workspace['architect']) { - workspaceTool = this._workspace['architect']; - } - - if (!workspaceTool) { - throw new WorkspaceToolNotFoundException(toolName); - } - - return workspaceTool; - } - - private _getProjectTool( - projectName: string, toolName: 'cli' | 'schematics' | 'targets', - ): WorkspaceTool { - this._assertLoaded(); - - const workspaceProject = this._workspace.projects[projectName]; - - if (!workspaceProject) { - throw new ProjectNotFoundException(projectName); - } - - let projectTool = workspaceProject[toolName]; - - // Try falling back to 'architect' if 'targets' is not there or is empty. - if ((!projectTool || Object.keys(projectTool).length === 0) - && workspaceProject['architect'] - && toolName === 'targets') { - projectTool = workspaceProject['architect']; - } - - if (!projectTool) { - throw new ProjectToolNotFoundException(toolName); - } - - return projectTool; - } - - // TODO: add transforms to resolve paths. - validateAgainstSchema(contentJson: {}, schemaJson: JsonObject): Observable { - // JSON validation modifies the content, so we validate a copy of it instead. - const contentJsonCopy = JSON.parse(JSON.stringify(contentJson)); - - return this._registry.compile(schemaJson).pipe( - concatMap(validator => validator(contentJsonCopy)), - concatMap((validatorResult: SchemaValidatorResult) => { - if (validatorResult.success) { - return of(contentJsonCopy as T); - } else { - return throwError(new schema.SchemaValidationException(validatorResult.errors)); - } - }), - ); - } - - private _loadJsonFile(path: Path): Observable { - return this._host.read(normalize(path)).pipe( - map(buffer => virtualFs.fileBufferToString(buffer)), - map(str => parseJson(str, JsonParseMode.Loose) as {} as JsonObject), - ); - } -} diff --git a/packages/angular_devkit/core/src/experimental/workspace/workspace_spec.ts b/packages/angular_devkit/core/src/experimental/workspace/workspace_spec.ts deleted file mode 100644 index a4e725990be9..000000000000 --- a/packages/angular_devkit/core/src/experimental/workspace/workspace_spec.ts +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function - -import { tap } from 'rxjs/operators'; -import { schema } from '../..'; -import { NodeJsSyncHost } from '../../../node'; -import { AdditionalPropertiesValidatorError } from '../../json/schema/interface'; -import { dirname, join, normalize } from '../../virtual-fs'; -import { - ProjectNotFoundException, - Workspace, - WorkspaceNotYetLoadedException, -} from './workspace'; -import { WorkspaceSchema, WorkspaceTool } from './workspace-schema'; - - -describe('Workspace', () => { - const host = new NodeJsSyncHost(); - const root = normalize(__dirname); - // The content of this JSON object should be kept in sync with the path below: - // tests/angular_devkit/core/workspace/angular-workspace.json - const workspaceJson: WorkspaceSchema = { - version: 1, - newProjectRoot: './projects', - defaultProject: 'app', - cli: { - '$globalOverride': '${HOME}/.angular-cli.json', - 'schematics': { - 'defaultCollection': '@schematics/angular', - }, - 'warnings': { - 'showDeprecation': false, - }, - }, - schematics: { - '@schematics/angular': { - '*': { - skipImport: true, - 'packageManager': 'yarn', - }, - 'application': { - spec: false, - }, - }, - }, - targets: {}, - projects: { - app: { - root: 'projects/app', - sourceRoot: 'projects/app/src', - projectType: 'application', - prefix: 'app', - cli: {}, - i18n: { - sourceLocale: 'en-US', - locales: { - 'fr': 'src/locale/messages.fr.xlf', - }, - }, - schematics: { - '@schematics/angular': { - '*': { - spec: false, - }, - }, - }, - targets: { - build: { - builder: '@angular-devkit/build-angular:browser', - transforms: [ - { - plugin: '@angular-devkit/architect-transforms:replacement', - file: 'environments/environment.ts', - configurations: { - production: 'environments/environment.prod.ts', - }, - }, - ], - options: { - outputPath: '../dist', - index: 'index.html', - main: 'main.ts', - polyfills: 'polyfills.ts', - tsConfig: 'tsconfig.app.json', - progress: false, - }, - configurations: { - production: { - optimize: true, - outputHashing: 'all', - sourceMap: false, - extractCss: true, - namedChunks: false, - aot: true, - extractLicenses: true, - vendorChunk: false, - buildOptimizer: true, - }, - }, - }, - }, - }, - }, - }; - // Tools should not be returned when getting a project. - const appProject = { ...workspaceJson.projects['app'] }; - delete appProject['cli']; - delete appProject['schematics']; - delete appProject['targets']; - - it('loads workspace from json', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProject('app').root).toEqual(workspaceJson.projects['app'].root)), - ).toPromise().then(done, done.fail); - }); - - it('loads workspace from host', (done) => { - const workspacePath = require.resolve('./test/test-workspace.json'); - const workspaceRoot = dirname(normalize(workspacePath)); - const workspace = new Workspace(workspaceRoot, host); - workspace.loadWorkspaceFromHost(normalize('test-workspace.json')).pipe( - tap((ws) => expect(ws.getProject('app').root).toEqual(workspaceJson.projects['app'].root)), - ).toPromise().then(done, done.fail); - }); - - it('errors when workspace fails validation', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson({ foo: 'bar' }) - .toPromise().then(() => done.fail, (err) => { - const validationErrors = [{ - keyword: 'additionalProperties', - dataPath: '', - schemaPath: '#/additionalProperties', - params: { additionalProperty: 'foo' }, - message: 'should NOT have additional properties', - } as AdditionalPropertiesValidatorError]; - expect(err).toEqual(new schema.SchemaValidationException(validationErrors)); - done(); - }); - }); - - it('throws when getting information before workspace is loaded', () => { - const workspace = new Workspace(root, host); - expect(() => workspace.version).toThrow(new WorkspaceNotYetLoadedException()); - }); - - it('throws when getting workspace tool before workspace is loaded', () => { - const workspace = new Workspace(root, host); - expect(() => workspace.getCli()).toThrow(new WorkspaceNotYetLoadedException()); - }); - - it('gets workspace root', () => { - const workspace = new Workspace(root, host); - expect(workspace.root).toBe(root); - }); - - it('gets workspace host', () => { - const workspace = new Workspace(root, host); - expect(workspace.host).toBe(host); - }); - - it('gets workspace version', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.version).toEqual(workspaceJson.version)), - ).toPromise().then(done, done.fail); - }); - - it('gets workspace new project root', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.newProjectRoot).toEqual(workspaceJson.newProjectRoot)), - ).toPromise().then(done, done.fail); - }); - - it('lists project names', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.listProjectNames()).toEqual(['app'])), - ).toPromise().then(done, done.fail); - }); - - it('gets project by name', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProject('app')).toEqual(appProject)), - ).toPromise().then(done, done.fail); - }); - - it('throws on missing project', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(() => ws.getProject('abc')).toThrow(new ProjectNotFoundException('abc'))), - ).toPromise().then(done, done.fail); - }); - - it('gets default project', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getDefaultProjectName()).toEqual('app')), - ).toPromise().then(done, done.fail); - }); - - it('gets default project when there is a single one', (done) => { - const customWorkspaceJson = { ...workspaceJson, defaultProject: undefined }; - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(customWorkspaceJson).pipe( - tap((ws) => expect(ws.getDefaultProjectName()).toEqual('app')), - ).toPromise().then(done, done.fail); - }); - - it('gets default project returns null when there is none', (done) => { - const customWorkspaceJson = { ...workspaceJson, defaultProject: undefined, projects: {} }; - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(customWorkspaceJson).pipe( - tap((ws) => expect(ws.getDefaultProjectName()).toEqual(null)), - ).toPromise().then(done, done.fail); - }); - - it('gets project by path', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProjectByPath(ws.root)).toEqual('app')), - ).toPromise().then(done, done.fail); - }); - - it('gets closest project by path', (done) => { - const app = workspaceJson.projects['app']; - const anotherAppRoot = join(normalize(app.root), 'folder'); - const customWorkspaceJson = { ...workspaceJson, projects: { - 'app': app, - 'another-app': { ...app, root: anotherAppRoot}, - } }; - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(customWorkspaceJson).pipe( - tap((ws) => expect(ws.getProjectByPath(anotherAppRoot)).toEqual('another-app')), - ).toPromise().then(done, done.fail); - }); - - it('gets workspace cli', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getCli()).toEqual(workspaceJson.cli as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets workspace schematics', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getSchematics()).toEqual(workspaceJson.schematics as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets workspace targets', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getTargets()).toEqual(workspaceJson.targets as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets workspace architect when targets is not there', (done) => { - const workspace = new Workspace(root, host); - const workspaceJsonClone = { ...workspaceJson }; - workspaceJsonClone['architect'] = workspaceJsonClone['targets']; - delete workspaceJsonClone['targets']; - workspace.loadWorkspaceFromJson(workspaceJsonClone).pipe( - tap((ws) => expect(ws.getTargets()).toEqual(workspaceJson.targets as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets project cli', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProjectCli('app')) - .toEqual(workspaceJson.projects.app.cli as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets project schematics', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProjectSchematics('app')) - .toEqual(workspaceJson.projects.app.schematics as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets project targets', (done) => { - const workspace = new Workspace(root, host); - workspace.loadWorkspaceFromJson(workspaceJson).pipe( - tap((ws) => expect(ws.getProjectTargets('app')) - .toEqual(workspaceJson.projects.app.targets as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - - it('gets project architect when targets is not there', (done) => { - const workspace = new Workspace(root, host); - const appJsonClone = { ...workspaceJson.projects.app }; - appJsonClone['architect'] = appJsonClone['targets']; - delete appJsonClone['targets']; - const simpleWorkspace = { - version: 1, - projects: { app: appJsonClone }, - }; - workspace.loadWorkspaceFromJson(simpleWorkspace).pipe( - tap((ws) => expect(ws.getProjectTargets('app')) - .toEqual(workspaceJson.projects.app.targets as WorkspaceTool)), - ).toPromise().then(done, done.fail); - }); - -}); diff --git a/packages/angular_devkit/core/src/index.ts b/packages/angular_devkit/core/src/index.ts index b30525e2d2fb..c3242a9e3af9 100644 --- a/packages/angular_devkit/core/src/index.ts +++ b/packages/angular_devkit/core/src/index.ts @@ -1,29 +1,18 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as analytics from './analytics'; -import * as experimental from './experimental'; + import * as json from './json/index'; import * as logging from './logger/index'; -import * as ɵterminal from './terminal/index'; import * as workspaces from './workspace'; -export * from './exception/exception'; +export * from './exception'; export * from './json/index'; export * from './utils/index'; export * from './virtual-fs/index'; - /** @deprecated since version 8 - Instead use other 3rd party libraries like `colors` and `chalk`. */ -export const terminal = ɵterminal; - -export { - analytics, - experimental, - json, - logging, - workspaces, -}; +export { json, logging, workspaces }; diff --git a/packages/angular_devkit/core/src/json/index.ts b/packages/angular_devkit/core/src/json/index.ts index 16bc0d1ff55c..e41ad50617cf 100644 --- a/packages/angular_devkit/core/src/json/index.ts +++ b/packages/angular_devkit/core/src/json/index.ts @@ -1,12 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -export * from './interface'; -export * from './parser'; import * as schema from './schema/index'; + +export * from './utils'; export { schema }; diff --git a/packages/angular_devkit/core/src/json/interface.ts b/packages/angular_devkit/core/src/json/interface.ts deleted file mode 100644 index 8769239695cf..000000000000 --- a/packages/angular_devkit/core/src/json/interface.ts +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export interface Position { - readonly offset: number; - - readonly line: number; - readonly character: number; -} - - -export type JsonAstNode = JsonAstNumber - | JsonAstString - | JsonAstIdentifier - | JsonAstArray - | JsonAstObject - | JsonAstConstantFalse - | JsonAstConstantNull - | JsonAstConstantTrue; - - -export interface JsonAstNodeBase { - readonly start: Position; - readonly end: Position; - readonly text: string; - - readonly comments?: (JsonAstComment | JsonAstMultilineComment)[]; -} - - -export interface JsonAstNumber extends JsonAstNodeBase { - readonly kind: 'number'; - readonly value: number; -} - - -export interface JsonAstString extends JsonAstNodeBase { - readonly kind: 'string'; - readonly value: string; -} - - -export interface JsonAstIdentifier extends JsonAstNodeBase { - readonly kind: 'identifier'; - readonly value: string; -} - - -export interface JsonArray extends Array {} - - -export interface JsonAstArray extends JsonAstNodeBase { - readonly kind: 'array'; - readonly elements: JsonAstNode[]; - readonly value: JsonArray; -} - - -export interface JsonObject { - [prop: string]: JsonValue; -} - - -export interface JsonAstKeyValue extends JsonAstNodeBase { - readonly kind: 'keyvalue'; - readonly key: JsonAstString | JsonAstIdentifier; - readonly value: JsonAstNode; -} - - -export interface JsonAstObject extends JsonAstNodeBase { - readonly kind: 'object'; - readonly properties: JsonAstKeyValue[]; - readonly value: JsonObject; -} - - -export interface JsonAstConstantFalse extends JsonAstNodeBase { - readonly kind: 'false'; - readonly value: false; -} - - -export interface JsonAstConstantNull extends JsonAstNodeBase { - readonly kind: 'null'; - readonly value: null; -} - - -export interface JsonAstConstantTrue extends JsonAstNodeBase { - readonly kind: 'true'; - readonly value: true; -} - - -// Loose mode AST. -export interface JsonAstMultilineComment extends JsonAstNodeBase { - readonly kind: 'multicomment'; - readonly content: string; -} -export interface JsonAstComment extends JsonAstNodeBase { - readonly kind: 'comment'; - readonly content: string; -} - - -export type JsonValue = JsonAstNode['value']; - -export function isJsonObject(value: JsonValue): value is JsonObject { - return value != null && typeof value === 'object' && !Array.isArray(value); -} - -export function isJsonArray(value: JsonValue): value is JsonArray { - return Array.isArray(value); -} diff --git a/packages/angular_devkit/core/src/json/parser.ts b/packages/angular_devkit/core/src/json/parser.ts deleted file mode 100644 index cdf83e20771d..000000000000 --- a/packages/angular_devkit/core/src/json/parser.ts +++ /dev/null @@ -1,909 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { BaseException } from '../exception'; -import { - JsonArray, - JsonAstArray, - JsonAstComment, - JsonAstConstantFalse, - JsonAstConstantNull, - JsonAstConstantTrue, - JsonAstIdentifier, - JsonAstKeyValue, - JsonAstMultilineComment, - JsonAstNode, - JsonAstNumber, - JsonAstObject, - JsonAstString, - JsonObject, - JsonValue, - Position, -} from './interface'; - -export class JsonException extends BaseException {} - -/** - * A character was invalid in this context. - */ -export class InvalidJsonCharacterException extends JsonException { - invalidChar: string; - line: number; - character: number; - offset: number; - - constructor(context: JsonParserContext) { - const pos = context.previous; - const invalidChar = JSON.stringify(_peek(context)); - super(`Invalid JSON character: ${invalidChar} at ${pos.line}:${pos.character}.`); - - this.invalidChar = invalidChar; - this.line = pos.line; - this.offset = pos.offset; - this.character = pos.character; - } -} - - -/** - * More input was expected, but we reached the end of the stream. - */ -export class UnexpectedEndOfInputException extends JsonException { - constructor(_context: JsonParserContext) { - super(`Unexpected end of file.`); - } -} - -/** - * An error happened within a file. - */ -export class PathSpecificJsonException extends JsonException { - constructor(public path: string, public exception: JsonException) { - super(`An error happened at file path ${JSON.stringify(path)}: ${exception.message}`); - } -} - -/** - * Context passed around the parser with information about where we currently are in the parse. - */ -export interface JsonParserContext { - position: Position; - previous: Position; - readonly original: string; - readonly mode: JsonParseMode; -} - - -/** - * Peek and return the next character from the context. - * @private - */ -function _peek(context: JsonParserContext): string | undefined { - return context.original[context.position.offset]; -} - - -/** - * Move the context to the next character, including incrementing the line if necessary. - * @private - */ -function _next(context: JsonParserContext) { - context.previous = context.position; - - let {offset, line, character} = context.position; - const char = context.original[offset]; - offset++; - if (char == '\n') { - line++; - character = 0; - } else { - character++; - } - context.position = {offset, line, character}; -} - - -/** - * Read a single character from the input. If a `valid` string is passed, validate that the - * character is included in the valid string. - * @private - */ -function _token(context: JsonParserContext, valid: string): string; -function _token(context: JsonParserContext): string | undefined; -function _token(context: JsonParserContext, valid?: string): string | undefined { - const char = _peek(context); - if (valid) { - if (!char) { - throw new UnexpectedEndOfInputException(context); - } - if (valid.indexOf(char) == -1) { - throw new InvalidJsonCharacterException(context); - } - } - - // Move the position of the context to the next character. - _next(context); - - return char; -} - - -/** - * Read the exponent part of a number. The exponent part is looser for JSON than the number - * part. `str` is the string of the number itself found so far, and start the position - * where the full number started. Returns the node found. - * @private - */ -function _readExpNumber(context: JsonParserContext, - start: Position, - str: string, - comments: (JsonAstComment | JsonAstMultilineComment)[]): JsonAstNumber { - let char; - let signed = false; - - while (true) { - char = _token(context); - if (char == '+' || char == '-') { - if (signed) { - break; - } - signed = true; - str += char; - } else if (char == '0' || char == '1' || char == '2' || char == '3' || char == '4' - || char == '5' || char == '6' || char == '7' || char == '8' || char == '9') { - signed = true; - str += char; - } else { - break; - } - } - - // We're done reading this number. - context.position = context.previous; - - return { - kind: 'number', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - value: Number.parseFloat(str), - comments: comments, - }; -} - - -/** - * Read the hexa part of a 0xBADCAFE hexadecimal number. - * @private - */ -function _readHexaNumber(context: JsonParserContext, - isNegative: boolean, - start: Position, - comments: (JsonAstComment | JsonAstMultilineComment)[]): JsonAstNumber { - // Read an hexadecimal number, until it's not hexadecimal. - let hexa = ''; - const valid = '0123456789abcdefABCDEF'; - - for (let ch = _peek(context); ch && valid.includes(ch); ch = _peek(context)) { - // Add it to the hexa string. - hexa += ch; - // Move the position of the context to the next character. - _next(context); - } - - const value = Number.parseInt(hexa, 16); - - // We're done reading this number. - return { - kind: 'number', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - value: isNegative ? -value : value, - comments, - }; -} - -/** - * Read a number from the context. - * @private - */ -function _readNumber(context: JsonParserContext, comments = _readBlanks(context)): JsonAstNumber { - let str = ''; - let dotted = false; - const start = context.position; - - // read until `e` or end of line. - while (true) { - const char = _token(context); - - // Read tokens, one by one. - if (char == '-') { - if (str != '') { - throw new InvalidJsonCharacterException(context); - } - } else if (char == 'I' - && (str == '-' || str == '' || str == '+') - && (context.mode & JsonParseMode.NumberConstantsAllowed) != 0) { - // Infinity? - // _token(context, 'I'); Already read. - _token(context, 'n'); - _token(context, 'f'); - _token(context, 'i'); - _token(context, 'n'); - _token(context, 'i'); - _token(context, 't'); - _token(context, 'y'); - - str += 'Infinity'; - break; - } else if (char == '0') { - if (str == '0' || str == '-0') { - throw new InvalidJsonCharacterException(context); - } - } else if (char == '1' || char == '2' || char == '3' || char == '4' || char == '5' - || char == '6' || char == '7' || char == '8' || char == '9') { - if (str == '0' || str == '-0') { - throw new InvalidJsonCharacterException(context); - } - } else if (char == '+' && str == '') { - // Pass over. - } else if (char == '.') { - if (dotted) { - throw new InvalidJsonCharacterException(context); - } - dotted = true; - } else if (char == 'e' || char == 'E') { - return _readExpNumber(context, start, str + char, comments); - } else if (char == 'x' && (str == '0' || str == '-0') - && (context.mode & JsonParseMode.HexadecimalNumberAllowed) != 0) { - return _readHexaNumber(context, str == '-0', start, comments); - } else { - // We read one too many characters, so rollback the last character. - context.position = context.previous; - break; - } - - str += char; - } - - // We're done reading this number. - if (str.endsWith('.') && (context.mode & JsonParseMode.HexadecimalNumberAllowed) == 0) { - throw new InvalidJsonCharacterException(context); - } - - return { - kind: 'number', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - value: Number.parseFloat(str), - comments, - }; -} - - -/** - * Read a string from the context. Takes the comments of the string or read the blanks before the - * string. - * @private - */ -function _readString(context: JsonParserContext, comments = _readBlanks(context)): JsonAstString { - const start = context.position; - - // Consume the first string delimiter. - const delim = _token(context); - if ((context.mode & JsonParseMode.SingleQuotesAllowed) == 0) { - if (delim == '\'') { - throw new InvalidJsonCharacterException(context); - } - } - - let str = ''; - while (true) { - let char = _token(context); - if (char == delim) { - return { - kind: 'string', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - value: str, - comments: comments, - }; - } else if (char == '\\') { - char = _token(context); - switch (char) { - case '\\': - case '\/': - case '"': - case delim: - str += char; - break; - - case 'b': str += '\b'; break; - case 'f': str += '\f'; break; - case 'n': str += '\n'; break; - case 'r': str += '\r'; break; - case 't': str += '\t'; break; - case 'u': - const [c0] = _token(context, '0123456789abcdefABCDEF'); - const [c1] = _token(context, '0123456789abcdefABCDEF'); - const [c2] = _token(context, '0123456789abcdefABCDEF'); - const [c3] = _token(context, '0123456789abcdefABCDEF'); - str += String.fromCharCode(parseInt(c0 + c1 + c2 + c3, 16)); - break; - - case undefined: - throw new UnexpectedEndOfInputException(context); - - case '\n': - // Only valid when multiline strings are allowed. - if ((context.mode & JsonParseMode.MultiLineStringAllowed) == 0) { - throw new InvalidJsonCharacterException(context); - } - str += char; - break; - - default: - throw new InvalidJsonCharacterException(context); - } - } else if (char === undefined) { - throw new UnexpectedEndOfInputException(context); - } else if (char == '\b' || char == '\f' || char == '\n' || char == '\r' || char == '\t') { - throw new InvalidJsonCharacterException(context); - } else { - str += char; - } - } -} - - -/** - * Read the constant `true` from the context. - * @private - */ -function _readTrue(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstConstantTrue { - const start = context.position; - _token(context, 't'); - _token(context, 'r'); - _token(context, 'u'); - _token(context, 'e'); - - const end = context.position; - - return { - kind: 'true', - start, - end, - text: context.original.substring(start.offset, end.offset), - value: true, - comments, - }; -} - - -/** - * Read the constant `false` from the context. - * @private - */ -function _readFalse(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstConstantFalse { - const start = context.position; - _token(context, 'f'); - _token(context, 'a'); - _token(context, 'l'); - _token(context, 's'); - _token(context, 'e'); - - const end = context.position; - - return { - kind: 'false', - start, - end, - text: context.original.substring(start.offset, end.offset), - value: false, - comments, - }; -} - - -/** - * Read the constant `null` from the context. - * @private - */ -function _readNull(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstConstantNull { - const start = context.position; - - _token(context, 'n'); - _token(context, 'u'); - _token(context, 'l'); - _token(context, 'l'); - - const end = context.position; - - return { - kind: 'null', - start, - end, - text: context.original.substring(start.offset, end.offset), - value: null, - comments: comments, - }; -} - - -/** - * Read the constant `NaN` from the context. - * @private - */ -function _readNaN(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstNumber { - const start = context.position; - - _token(context, 'N'); - _token(context, 'a'); - _token(context, 'N'); - - const end = context.position; - - return { - kind: 'number', - start, - end, - text: context.original.substring(start.offset, end.offset), - value: NaN, - comments: comments, - }; -} - - -/** - * Read an array of JSON values from the context. - * @private - */ -function _readArray(context: JsonParserContext, comments = _readBlanks(context)): JsonAstArray { - const start = context.position; - - // Consume the first delimiter. - _token(context, '['); - const value: JsonArray = []; - const elements: JsonAstNode[] = []; - - _readBlanks(context); - if (_peek(context) != ']') { - const node = _readValue(context); - elements.push(node); - value.push(node.value); - } - - while (_peek(context) != ']') { - _token(context, ','); - - const valueComments = _readBlanks(context); - if ((context.mode & JsonParseMode.TrailingCommasAllowed) !== 0 && _peek(context) === ']') { - break; - } - const node = _readValue(context, valueComments); - elements.push(node); - value.push(node.value); - } - - _token(context, ']'); - - return { - kind: 'array', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - value, - elements, - comments, - }; -} - - -/** - * Read an identifier from the context. An identifier is a valid JavaScript identifier, and this - * function is only used in Loose mode. - * @private - */ -function _readIdentifier(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstIdentifier { - const start = context.position; - - let char = _peek(context); - if (char && '0123456789'.indexOf(char) != -1) { - const identifierNode = _readNumber(context); - - return { - kind: 'identifier', - start, - end: identifierNode.end, - text: identifierNode.text, - value: identifierNode.value.toString(), - }; - } - - const identValidFirstChar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ'; - const identValidChar = '_$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ0123456789'; - let first = true; - let value = ''; - - while (true) { - char = _token(context); - if (char == undefined - || (first ? identValidFirstChar.indexOf(char) : identValidChar.indexOf(char)) == -1) { - context.position = context.previous; - - return { - kind: 'identifier', - start, - end: context.position, - text: context.original.substr(start.offset, context.position.offset), - value, - comments, - }; - } - - value += char; - first = false; - } -} - - -/** - * Read a property from the context. A property is a string or (in Loose mode only) a number or - * an identifier, followed by a colon `:`. - * @private - */ -function _readProperty(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstKeyValue { - const start = context.position; - - let key; - if ((context.mode & JsonParseMode.IdentifierKeyNamesAllowed) != 0) { - const top = _peek(context); - if (top == '"' || top == '\'') { - key = _readString(context); - } else { - key = _readIdentifier(context); - } - } else { - key = _readString(context); - } - - _readBlanks(context); - _token(context, ':'); - const value = _readValue(context); - const end = context.position; - - return { - kind: 'keyvalue', - key, - value, - start, - end, - text: context.original.substring(start.offset, end.offset), - comments, - }; -} - - -/** - * Read an object of properties -> JSON values from the context. - * @private - */ -function _readObject(context: JsonParserContext, - comments = _readBlanks(context)): JsonAstObject { - const start = context.position; - // Consume the first delimiter. - _token(context, '{'); - const value: JsonObject = {}; - const properties: JsonAstKeyValue[] = []; - - _readBlanks(context); - if (_peek(context) != '}') { - const property = _readProperty(context); - value[property.key.value] = property.value.value; - properties.push(property); - - while (_peek(context) != '}') { - _token(context, ','); - - const propertyComments = _readBlanks(context); - if ((context.mode & JsonParseMode.TrailingCommasAllowed) !== 0 && _peek(context) === '}') { - break; - } - const property = _readProperty(context, propertyComments); - value[property.key.value] = property.value.value; - properties.push(property); - } - } - - _token(context, '}'); - - return { - kind: 'object', - properties, - start, - end: context.position, - value, - text: context.original.substring(start.offset, context.position.offset), - comments, - }; -} - - -/** - * Remove any blank character or comments (in Loose mode) from the context, returning an array - * of comments if any are found. - * @private - */ -function _readBlanks(context: JsonParserContext): (JsonAstComment | JsonAstMultilineComment)[] { - if ((context.mode & JsonParseMode.CommentsAllowed) != 0) { - const comments: (JsonAstComment | JsonAstMultilineComment)[] = []; - while (true) { - const char = context.original[context.position.offset]; - if (char == '/' && context.original[context.position.offset + 1] == '*') { - const start = context.position; - // Multi line comment. - _next(context); - _next(context); - - while (context.original[context.position.offset] != '*' - || context.original[context.position.offset + 1] != '/') { - _next(context); - if (context.position.offset >= context.original.length) { - throw new UnexpectedEndOfInputException(context); - } - } - // Remove "*/". - _next(context); - _next(context); - - comments.push({ - kind: 'multicomment', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - content: context.original.substring(start.offset + 2, context.position.offset - 2), - }); - } else if (char == '/' && context.original[context.position.offset + 1] == '/') { - const start = context.position; - // Multi line comment. - _next(context); - _next(context); - - while (context.original[context.position.offset] != '\n') { - _next(context); - if (context.position.offset >= context.original.length) { - break; - } - } - - // Remove "\n". - if (context.position.offset < context.original.length) { - _next(context); - } - comments.push({ - kind: 'comment', - start, - end: context.position, - text: context.original.substring(start.offset, context.position.offset), - content: context.original.substring(start.offset + 2, context.position.offset - 1), - }); - } else if (char == ' ' || char == '\t' || char == '\n' || char == '\r' || char == '\f') { - _next(context); - } else { - break; - } - } - - return comments; - } else { - let char = context.original[context.position.offset]; - while (char == ' ' || char == '\t' || char == '\n' || char == '\r' || char == '\f') { - _next(context); - char = context.original[context.position.offset]; - } - - return []; - } -} - - -/** - * Read a JSON value from the context, which can be any form of JSON value. - * @private - */ -function _readValue(context: JsonParserContext, comments = _readBlanks(context)): JsonAstNode { - let result: JsonAstNode; - - // Clean up before. - const char = _peek(context); - switch (char) { - case undefined: - throw new UnexpectedEndOfInputException(context); - - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - result = _readNumber(context, comments); - break; - - case '.': - case '+': - if ((context.mode & JsonParseMode.LaxNumberParsingAllowed) == 0) { - throw new InvalidJsonCharacterException(context); - } - result = _readNumber(context, comments); - break; - - case '\'': - case '"': - result = _readString(context, comments); - break; - - case 'I': - if ((context.mode & JsonParseMode.NumberConstantsAllowed) == 0) { - throw new InvalidJsonCharacterException(context); - } - result = _readNumber(context, comments); - break; - - case 'N': - if ((context.mode & JsonParseMode.NumberConstantsAllowed) == 0) { - throw new InvalidJsonCharacterException(context); - } - result = _readNaN(context, comments); - break; - - case 't': - result = _readTrue(context, comments); - break; - case 'f': - result = _readFalse(context, comments); - break; - case 'n': - result = _readNull(context, comments); - break; - - case '[': - result = _readArray(context, comments); - break; - - case '{': - result = _readObject(context, comments); - break; - - default: - throw new InvalidJsonCharacterException(context); - } - - // Clean up after. - _readBlanks(context); - - return result; -} - - -/** - * The Parse mode used for parsing the JSON string. - */ -export enum JsonParseMode { - Strict = 0, // Standard JSON. - CommentsAllowed = 1 << 0, // Allows comments, both single or multi lines. - SingleQuotesAllowed = 1 << 1, // Allow single quoted strings. - IdentifierKeyNamesAllowed = 1 << 2, // Allow identifiers as objectp properties. - TrailingCommasAllowed = 1 << 3, - HexadecimalNumberAllowed = 1 << 4, - MultiLineStringAllowed = 1 << 5, - LaxNumberParsingAllowed = 1 << 6, // Allow `.` or `+` as the first character of a number. - NumberConstantsAllowed = 1 << 7, // Allow -Infinity, Infinity and NaN. - - Default = Strict, - Loose = CommentsAllowed | SingleQuotesAllowed | - IdentifierKeyNamesAllowed | TrailingCommasAllowed | - HexadecimalNumberAllowed | MultiLineStringAllowed | - LaxNumberParsingAllowed | NumberConstantsAllowed, - - Json = Strict, - Json5 = Loose, -} - - -/** - * Parse the JSON string and return its AST. The AST may be losing data (end comments are - * discarded for example, and space characters are not represented in the AST), but all values - * will have a single node in the AST (a 1-to-1 mapping). - * @param input The string to use. - * @param mode The mode to parse the input with. {@see JsonParseMode}. - * @returns {JsonAstNode} The root node of the value of the AST. - */ -export function parseJsonAst(input: string, mode = JsonParseMode.Default): JsonAstNode { - if (mode == JsonParseMode.Default) { - mode = JsonParseMode.Strict; - } - - const context = { - position: { offset: 0, line: 0, character: 0 }, - previous: { offset: 0, line: 0, character: 0 }, - original: input, - comments: undefined, - mode, - }; - - const ast = _readValue(context); - if (context.position.offset < input.length) { - const rest = input.substr(context.position.offset); - const i = rest.length > 20 ? rest.substr(0, 20) + '...' : rest; - throw new Error(`Expected end of file, got "${i}" at ` - + `${context.position.line}:${context.position.character}.`); - } - - return ast; -} - - -/** - * Options for the parseJson() function. - */ -export interface ParseJsonOptions { - /** - * If omitted, will only emit errors related to the content of the JSON. If specified, any - * JSON errors will also include the path of the file that caused the error. - */ - path?: string; -} - - -/** - * Parse a JSON string into its value. This discards the AST and only returns the value itself. - * - * If a path option is pass, it also absorbs JSON parsing errors and return a new error with the - * path in it. Useful for showing errors when parsing from a file. - * - * @param input The string to parse. - * @param mode The mode to parse the input with. {@see JsonParseMode}. - * @param options Additional optinos for parsing. - * @returns {JsonValue} The value represented by the JSON string. - */ -export function parseJson( - input: string, - mode = JsonParseMode.Default, - options?: ParseJsonOptions, -): JsonValue { - try { - // Try parsing for the fastest path available, if error, uses our own parser for better errors. - if (mode == JsonParseMode.Strict) { - try { - return JSON.parse(input); - } catch (err) { - return parseJsonAst(input, mode).value; - } - } - - return parseJsonAst(input, mode).value; - } catch (e) { - if (options && options.path && e instanceof JsonException) { - throw new PathSpecificJsonException(options.path, e); - } - throw e; - } -} diff --git a/packages/angular_devkit/core/src/json/parser_benchmark.ts b/packages/angular_devkit/core/src/json/parser_benchmark.ts deleted file mode 100644 index 3c06ec3738ed..000000000000 --- a/packages/angular_devkit/core/src/json/parser_benchmark.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-implicit-dependencies -import { benchmark } from '@_/benchmark'; -import { parseJson, parseJsonAst } from './parser'; - - -const testCase = { - 'hello': [0, 1, 'world', 2], - 'world': { - 'great': 123E-12, - }, -}; -const testCaseJson = JSON.stringify(testCase); - - -describe('parserJson', () => { - benchmark('parseJsonAst', () => parseJsonAst(testCaseJson), () => JSON.parse(testCaseJson)); - benchmark('parseJson', () => parseJson(testCaseJson)); -}); diff --git a/packages/angular_devkit/core/src/json/parser_spec.ts b/packages/angular_devkit/core/src/json/parser_spec.ts deleted file mode 100644 index 56405eb03aed..000000000000 --- a/packages/angular_devkit/core/src/json/parser_spec.ts +++ /dev/null @@ -1,347 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-big-function -import { JsonParseMode, parseJson, parseJsonAst } from './parser'; - - -// Node 6 compatibility. -function entries(x: {[key: string]: any}): any { // tslint:disable-line:no-any - return Object.keys(x).map(k => [k, x[k]]); -} - - -describe('parseJson and parseJsonAst', () => { - describe('generic', () => { - const numbers = { - }; - const errors = [ - '', - '-abcdefghijklmnopqrstuvwxyz', - ]; - - for (const [n, [start, end, text]] of entries(numbers)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(JSON.parse(n)); - expect(parseJson(n)).toEqual(JSON.parse(n)); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('numbers', () => { - const numbers = { - '1234': [[0, 0, 0], [4, 0, 4]], - '12E34': [[0, 0, 0], [5, 0, 5]], - '12E+4': [[0, 0, 0], [5, 0, 5]], - '12E-4': [[0, 0, 0], [5, 0, 5]], - '12E-0004': [[0, 0, 0], [8, 0, 8]], - ' 1234 ': [[3, 0, 3], [7, 0, 7], '1234'], - '\r1234\t': [[1, 0, 1], [5, 0, 5], '1234'], - '\n1234\n': [[1, 1, 0], [5, 1, 4], '1234'], - '0.123': [[0, 0, 0], [5, 0, 5]], - '0': [[0, 0, 0], [1, 0, 1]], - '\n\n\n\n\n0': [[5, 5, 0], [6, 5, 1], '0'], - }; - const errors = [ - '000', - '01', - '1E1+1', - '--', - '0-0', - '-0-0', - '0.0.0', - '0\n.0\n.0', - '0.', - '+1', - 'Infinity', - 'NaN', - '-Infinity', - '+Infinity', - ]; - - for (const [n, [start, end, text]] of entries(numbers)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.kind).toBe('number'); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(JSON.parse(n)); - expect(parseJson(n)).toEqual(JSON.parse(n)); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('strings', () => { - const strings = { - '""': [[0, 0, 0], [2, 0, 2]], - '"hello"': [[0, 0, 0], [7, 0, 7]], - '"a\\nb"': [[0, 0, 0], [6, 0, 6]], - '"a\\nb\\tc\\rd\\\\e\\/f\\\"g\\bh\\fi"': [[0, 0, 0], [27, 0, 27]], - '"a\\u1234b"': [[0, 0, 0], [10, 0, 10]], - }; - const errors = [ - '"\\z"', - '\'hello\'', - '"\\', - '"a\\zb"', - '"a', - '"a\nb"', - '"\\\n "', - ]; - - for (const [n, [start, end, text]] of entries(strings)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.kind).toBe('string'); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(JSON.parse(n)); - expect(parseJson(n)).toEqual(JSON.parse(n)); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('constants', () => { - const strings = { - 'true': ['true', [0, 0, 0], [4, 0, 4], true], - 'false': ['false', [0, 0, 0], [5, 0, 5], false], - 'null': ['null', [0, 0, 0], [4, 0, 4], null], - }; - const errors = [ - 'undefined', - ]; - - for (const [n, [kind, start, end, value, text]] of entries(strings)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.kind).toBe(kind); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(value); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('arrays', () => { - const strings = { - '[0,1,2,3]': [[0, 0, 0], [9, 0, 9]], - '[[0],1,2,3]': [[0, 0, 0], [11, 0, 11]], - '[0\n,\n1,2,3]': [[0, 0, 0], [11, 2, 6]], - '[]': [[0, 0, 0], [2, 0, 2]], - '\n[\n]\n': [[1, 1, 0], [4, 2, 1], '[\n]'], - '[\n]': [[0, 0, 0], [3, 1, 1]], - '[\n\n]': [[0, 0, 0], [4, 2, 1]], - }; - const errors = [ - '[', - '[,]', - '[0,]', - '[,0]', - ]; - - for (const [n, [start, end, text]] of entries(strings)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.kind).toBe('array'); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(JSON.parse(n)); - expect(parseJson(n)).toEqual(JSON.parse(n)); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('objects', () => { - const strings = { - '{}': [[0, 0, 0], [2, 0, 2]], - '{\n}': [[0, 0, 0], [3, 1, 1]], - '{"hello": "world"}': [[0, 0, 0], [18, 0, 18]], - '{"hello": 0, "world": 1}': [[0, 0, 0], [24, 0, 24]], - '{"hello": {"hello": {"hello": "world"}}}': [[0, 0, 0], [40, 0, 40]], - }; - const errors = [ - '{', - '{,}', - '{"hello": 0', - ]; - - for (const [n, [start, end, text]] of entries(strings)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n); - expect(ast.kind).toBe('object'); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(JSON.parse(n)); - expect(parseJson(n)).toEqual(JSON.parse(n)); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n)).toThrow(); - expect(() => parseJson(n)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('loose', () => { - const strings = { - '{\'hello\': 0}': [[0, 0, 0], [12, 0, 12], {'hello': 0}], - '{hello: 0}': [[0, 0, 0], [10, 0, 10], {hello: 0}], - '{1: 0}': [[0, 0, 0], [6, 0, 6], {1: 0}], - '{hello\n:/**/ 0}': [[0, 0, 0], [15, 1, 8], {hello: 0}], - '{\n// hello\n}': [[0, 0, 0], [12, 2, 1], {}], - '{\n/* hello\n*/ }': [[0, 0, 0], [15, 2, 4], {}], - '{}// ': [[0, 0, 0], [2, 0, 2], {}, '{}'], - '{}//': [[0, 0, 0], [2, 0, 2], {}, '{}'], - '{hello:0,}': [[0, 0, 0], [10, 0, 10], {hello: 0}], - '{hello:0/**/,}': [[0, 0, 0], [14, 0, 14], {hello: 0}], - '{hello:0,/**/}': [[0, 0, 0], [14, 0, 14], {hello: 0}], - '{hi:["hello",]}': [[0, 0, 0], [15, 0, 15], {hi: ['hello']}], - '{hi:["hello",/* */]}': [[0, 0, 0], [20, 0, 20], {hi: ['hello']}], - '{hi:["hello"/* */,]}': [[0, 0, 0], [20, 0, 20], {hi: ['hello']}], - '{hi:["hello" , ] , }': [[0, 0, 0], [20, 0, 20], {hi: ['hello']}], - '{hi:"\\\n "}': [[0, 0, 0], [10, 1, 3], {hi: '\n '}], - '{d: -0xdecaf, e: Infinity, f: -Infinity, g: +Infinity, h: NaN,}': [[0, 0, 0], [63, 0, 63], { - d: -0xdecaf, - e: Infinity, - f: -Infinity, - g: Infinity, - h: NaN, - }], - }; - const errors = [ - '{1b: 0}', - ' /*', - '', - '.Infinity', - ]; - - for (const [n, [start, end, value, text]] of entries(strings)) { - it(`works for ${JSON.stringify(n)}`, () => { - const ast = parseJsonAst(n, JsonParseMode.Loose); - expect(ast.kind).toBe('object'); - expect(ast.start).toEqual({offset: start[0], line: start[1], character: start[2]}); - expect(ast.end).toEqual({offset: end[0], line: end[1], character: end[2]}); - expect(ast.value).toEqual(value); - expect(parseJson(n, JsonParseMode.Loose)).toEqual(value); - expect(ast.text).toBe(text === undefined ? n : text); - }); - } - - for (const n of errors) { - it(`errors for ${JSON.stringify(n)}`, () => { - expect(() => parseJsonAst(n, JsonParseMode.Loose)).toThrow(); - expect(() => parseJson(n, JsonParseMode.Loose)).toThrow(); - expect(() => JSON.parse(n)).toThrow(); - }); - } - }); - - describe('complex', () => { - it('strips comments', () => { - expect(parseJson(` - // THIS IS A COMMENT - { - /* THIS IS ALSO A COMMENT */ // IGNORED BECAUSE COMMENT - // AGAIN, COMMENT /* THIS SHOULD NOT BE WEIRD - "a": "this // should not be a comment", - "a2": "this /* should also not be a comment", - /* MULTIPLE - LINE - COMMENT - \o/ */ - "b" /* COMMENT */: /* YOU GUESSED IT */ 1 // COMMENT - , /* STILL VALID */ - "c": 2 - } - `, JsonParseMode.Loose)).toEqual({ - a: 'this // should not be a comment', - a2: 'this /* should also not be a comment', - b: 1, - c: 2, - }); - }); - - it('works with json5.org example', () => { - const input = `{ - // comments - unquoted: 'and you can quote me on that', - 'singleQuotes': 'I can use "double quotes" here', - lineBreaks: "Look, Mom! \\ -No \\\\n's!", - hexadecimal: 0xdecaf, - leadingDecimalPoint: .8675309, andTrailing: 8675309., - positiveSign: +1, - trailingComma: 'in objects', andIn: ['arrays',], - "backwardsCompatible": "with JSON", - }`; - - expect(parseJson(input, JsonParseMode.Json5)).toEqual({ - unquoted: 'and you can quote me on that', - singleQuotes: 'I can use "double quotes" here', - lineBreaks: "Look, Mom! \nNo \\n's!", - hexadecimal: 0xdecaf, - leadingDecimalPoint: .8675309, andTrailing: 8675309., - positiveSign: +1, - trailingComma: 'in objects', - andIn: ['arrays'], - backwardsCompatible: 'with JSON', - }); - }); - }); -}); diff --git a/packages/angular_devkit/core/src/json/schema/index.ts b/packages/angular_devkit/core/src/json/schema/index.ts index 92a977ffe736..706c6d3a281e 100644 --- a/packages/angular_devkit/core/src/json/schema/index.ts +++ b/packages/angular_devkit/core/src/json/schema/index.ts @@ -1,10 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + +import * as transforms from './transforms'; + export * from './interface'; export * from './pointer'; export * from './registry'; @@ -12,6 +15,4 @@ export * from './schema'; export * from './visitor'; export * from './utility'; -import * as transforms from './transforms'; - export { transforms }; diff --git a/packages/angular_devkit/core/src/json/schema/interface.ts b/packages/angular_devkit/core/src/json/schema/interface.ts index 59e0530714e9..8974746319f7 100644 --- a/packages/angular_devkit/core/src/json/schema/interface.ts +++ b/packages/angular_devkit/core/src/json/schema/interface.ts @@ -1,62 +1,26 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { Observable, SubscribableOrPromise } from 'rxjs'; -import { JsonArray, JsonObject, JsonValue } from '../interface'; + +import { ErrorObject, Format } from 'ajv'; +import { Observable, ObservableInput } from 'rxjs'; +import { JsonArray, JsonObject, JsonValue } from '../utils'; export type JsonPointer = string & { __PRIVATE_DEVKIT_JSON_POINTER: void; }; - -export type SchemaValidatorError = - RefValidatorError | - LimitValidatorError | - AdditionalPropertiesValidatorError | - FormatValidatorError | - RequiredValidatorError; - -export interface SchemaValidatorErrorBase { - keyword: string; - dataPath: string; - message?: string; - data?: JsonValue; -} - -export interface RefValidatorError extends SchemaValidatorErrorBase { - keyword: '$ref'; - params: { ref: string }; -} - -export interface LimitValidatorError extends SchemaValidatorErrorBase { - keyword: 'maxItems' | 'minItems' | 'maxLength' | 'minLength' | 'maxProperties' | 'minProperties'; - params: { limit: number }; -} - -export interface AdditionalPropertiesValidatorError extends SchemaValidatorErrorBase { - keyword: 'additionalProperties'; - params: { additionalProperty: string }; -} - -export interface FormatValidatorError extends SchemaValidatorErrorBase { - keyword: 'format'; - params: { format: string }; -} - -export interface RequiredValidatorError extends SchemaValidatorErrorBase { - keyword: 'required'; - params: { missingProperty: string }; -} - export interface SchemaValidatorResult { data: JsonValue; success: boolean; errors?: SchemaValidatorError[]; } +export type SchemaValidatorError = Partial; + export interface SchemaValidatorOptions { applyPreTransforms?: boolean; applyPostTransforms?: boolean; @@ -64,14 +28,10 @@ export interface SchemaValidatorOptions { } export interface SchemaValidator { - (data: JsonValue, options?: SchemaValidatorOptions): Observable; + (data: JsonValue, options?: SchemaValidatorOptions): Promise; } -export interface SchemaFormatter { - readonly async: boolean; - // tslint:disable-next-line:no-any - validate(data: any): boolean | Observable; -} +export type SchemaFormatter = Format; export interface SchemaFormat { name: string; @@ -84,13 +44,11 @@ export interface SmartDefaultProvider { export interface SchemaKeywordValidator { ( - // tslint:disable-next-line:no-any data: JsonValue, schema: JsonValue, parent: JsonObject | JsonArray | undefined, parentProperty: string | number | undefined, pointer: JsonPointer, - // tslint:disable-next-line:no-any rootData: JsonValue, ): boolean | Observable; } @@ -102,26 +60,32 @@ export interface PromptDefinition { default?: string | string[] | number | boolean | null; validator?: (value: JsonValue) => boolean | string | Promise; - items?: Array; + items?: Array; raw?: string | JsonObject; multiselect?: boolean; + propertyTypes: Set; } -export type PromptProvider = (definitions: Array) - => SubscribableOrPromise<{ [id: string]: JsonValue }>; +export type PromptProvider = ( + definitions: Array, +) => ObservableInput<{ [id: string]: JsonValue }>; export interface SchemaRegistry { - compile(schema: Object): Observable; - flatten(schema: JsonObject | string): Observable; + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types + compile(schema: Object): Promise; + + /** @private */ + ɵflatten(schema: JsonObject | string): Promise; addFormat(format: SchemaFormat): void; addSmartDefaultProvider(source: string, provider: SmartDefaultProvider): void; usePromptProvider(provider: PromptProvider): void; + useXDeprecatedProvider(onUsage: (message: string) => void): void; /** * Add a transformation step before the validation of any Json. * @param {JsonVisitor} visitor The visitor to transform every value. - * @param {JsonVisitor[]} deps A list of other visitors to run before. + * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; @@ -130,7 +94,7 @@ export interface SchemaRegistry { * after the POST, so if transformations are not compatible with the Schema it will not result * in an error. * @param {JsonVisitor} visitor The visitor to transform every value. - * @param {JsonVisitor[]} deps A list of other visitors to run before. + * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void; } diff --git a/packages/angular_devkit/core/src/json/schema/pointer.ts b/packages/angular_devkit/core/src/json/schema/pointer.ts index 39d054169801..ebd51bad80a7 100644 --- a/packages/angular_devkit/core/src/json/schema/pointer.ts +++ b/packages/angular_devkit/core/src/json/schema/pointer.ts @@ -1,20 +1,20 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonPointer } from './interface'; +import { JsonPointer } from './interface'; export function buildJsonPointer(fragments: string[]): JsonPointer { - return ( - '/' + fragments.map(f => { - return f.replace(/~/g, '~0') - .replace(/\//g, '~1'); - }).join('/') - ) as JsonPointer; + return ('/' + + fragments + .map((f) => { + return f.replace(/~/g, '~0').replace(/\//g, '~1'); + }) + .join('/')) as JsonPointer; } export function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer { if (root == '/') { @@ -24,8 +24,15 @@ export function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPoi return (root + buildJsonPointer(others)) as JsonPointer; } export function parseJsonPointer(pointer: JsonPointer): string[] { - if (pointer === '') { return []; } - if (pointer.charAt(0) !== '/') { throw new Error('Relative pointer: ' + pointer); } + if (pointer === '') { + return []; + } + if (pointer.charAt(0) !== '/') { + throw new Error('Relative pointer: ' + pointer); + } - return pointer.substring(1).split(/\//).map(str => str.replace(/~1/g, '/').replace(/~0/g, '~')); + return pointer + .substring(1) + .split(/\//) + .map((str) => str.replace(/~1/g, '/').replace(/~0/g, '~')); } diff --git a/packages/angular_devkit/core/src/json/schema/prompt_spec.ts b/packages/angular_devkit/core/src/json/schema/prompt_spec.ts index b22b26b7a567..355de12b1dcb 100644 --- a/packages/angular_devkit/core/src/json/schema/prompt_spec.ts +++ b/packages/angular_devkit/core/src/json/schema/prompt_spec.ts @@ -1,47 +1,41 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any no-big-function -import { map, mergeMap } from 'rxjs/operators'; -import { CoreSchemaRegistry } from './registry'; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { CoreSchemaRegistry } from './registry'; describe('Prompt Provider', () => { - it('sets properties with answer', done => { + it('sets properties with answer', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { return { [definitions[0].id]: true }; }); - registry - .compile({ - properties: { - test: { - type: 'boolean', - 'x-prompt': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'boolean', + 'x-prompt': 'test-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(() => { - expect(data.test).toBe(true); - }), - ) - .toPromise().then(done, done.fail); + }, }); - it('supports mixed schema references', done => { + await validator(data); + expect(data.test).toBe(true); + }); + + it('supports mixed schema references', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { return { '/bool': true, '/test': 'two', @@ -49,127 +43,103 @@ describe('Prompt Provider', () => { }; }); - registry - .compile({ - properties: { - bool: { - $ref: '#/definitions/example', - }, - test: { - type: 'string', - enum: [ - 'one', - 'two', - 'three', - ], - 'x-prompt': { - type: 'list', - 'message': 'other-message', - }, + const validator = await registry.compile({ + properties: { + bool: { + $ref: '#/definitions/example', + }, + test: { + type: 'string', + enum: ['one', 'two', 'three'], + 'x-prompt': { + type: 'list', + 'message': 'other-message', }, - obj: { - properties: { - deep: { - properties: { - three: { - $ref: '#/definitions/test3', - }, + }, + obj: { + properties: { + deep: { + properties: { + three: { + $ref: '#/definitions/test3', }, }, }, }, }, - definitions: { - example: { - type: 'boolean', - 'x-prompt': 'example-message', - }, - test3: { - type: 'string', - 'x-prompt': 'test3-message', - }, + }, + definitions: { + example: { + type: 'boolean', + 'x-prompt': 'example-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.bool).toBe(true); - expect(data.test).toBe('two'); - expect(data.obj.deep.three).toEqual('test3-answer'); - }), - ) - .toPromise().then(done, done.fail); + test3: { + type: 'string', + 'x-prompt': 'test3-message', + }, + }, + }); + + const result = await validator(data); + expect(result.success).toBe(true); + expect(data.bool).toBe(true); + expect(data.test).toBe('two'); + expect(data.obj.deep.three).toEqual('test3-answer'); }); describe('with shorthand', () => { - it('supports message value', done => { + it('supports message value', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].message).toBe('test-message'); return {}; }); - registry - .compile({ - properties: { - test: { - type: 'string', - 'x-prompt': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'string', + 'x-prompt': 'test-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + + await validator(data); }); - it('analyzes enums', done => { + it('analyzes enums', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); - expect(definitions[0].items).toEqual([ - 'one', - 'two', - 'three', - ]); + expect(definitions[0].items).toEqual(['one', 'two', 'three']); return {}; }); - registry - .compile({ - properties: { - test: { - type: 'string', - enum: [ - 'one', - 'two', - 'three', - ], - 'x-prompt': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'string', + enum: ['one', 'two', 'three'], + 'x-prompt': 'test-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes boolean properties', done => { + it('analyzes boolean properties', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('confirmation'); expect(definitions[0].items).toBeUndefined(); @@ -177,96 +147,75 @@ describe('Prompt Provider', () => { return {}; }); - registry - .compile({ - properties: { - test: { - type: 'boolean', - 'x-prompt': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'boolean', + 'x-prompt': 'test-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - }); describe('with longhand', () => { - it('supports message option', done => { + it('supports message option', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].message).toBe('test-message'); return {}; }); - registry - .compile({ - properties: { - test: { - type: 'string', - 'x-prompt': { - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'string', + 'x-prompt': { + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes enums WITH explicit list type', done => { + it('analyzes enums WITH explicit list type', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); - expect(definitions[0].items).toEqual([ - 'one', - 'two', - 'three', - ]); + expect(definitions[0].items).toEqual(['one', 'two', 'three']); return { [definitions[0].id]: 'one' }; }); - registry - .compile({ - properties: { - test: { - type: 'string', - enum: [ - 'one', - 'two', - 'three', - ], - 'x-prompt': { - 'type': 'list', - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'string', + enum: ['one', 'two', 'three'], + 'x-prompt': { + 'type': 'list', + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes list with true multiselect option and object items', done => { + it('analyzes list with true multiselect option and object items', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); expect(definitions[0].multiselect).toBe(true); @@ -278,34 +227,30 @@ describe('Prompt Provider', () => { return { [definitions[0].id]: { 'value': 'one', 'label': 'one' } }; }); - registry - .compile({ - properties: { - test: { - type: 'array', - 'x-prompt': { - 'type': 'list', - 'multiselect': true, - 'items': [ - { 'value': 'one', 'label': 'one' }, - { 'value': 'two', 'label': 'two' }, - ], - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'array', + 'x-prompt': { + 'type': 'list', + 'multiselect': true, + 'items': [ + { 'value': 'one', 'label': 'one' }, + { 'value': 'two', 'label': 'two' }, + ], + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes list with false multiselect option and object items', done => { + it('analyzes list with false multiselect option and object items', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); expect(definitions[0].multiselect).toBe(false); @@ -317,34 +262,30 @@ describe('Prompt Provider', () => { return { [definitions[0].id]: { 'value': 'one', 'label': 'one' } }; }); - registry - .compile({ - properties: { - test: { - type: 'array', - 'x-prompt': { - 'type': 'list', - 'multiselect': false, - 'items': [ - { 'value': 'one', 'label': 'one' }, - { 'value': 'two', 'label': 'two' }, - ], - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'array', + 'x-prompt': { + 'type': 'list', + 'multiselect': false, + 'items': [ + { 'value': 'one', 'label': 'one' }, + { 'value': 'two', 'label': 'two' }, + ], + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes list without multiselect option and object items', done => { + it('analyzes list without multiselect option and object items', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); expect(definitions[0].multiselect).toBe(true); @@ -356,111 +297,82 @@ describe('Prompt Provider', () => { return { [definitions[0].id]: { 'value': 'two', 'label': 'two' } }; }); - registry - .compile({ - properties: { - test: { - type: 'array', - 'x-prompt': { - 'type': 'list', - 'items': [ - { 'value': 'one', 'label': 'one' }, - { 'value': 'two', 'label': 'two' }, - ], - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'array', + 'x-prompt': { + 'type': 'list', + 'items': [ + { 'value': 'one', 'label': 'one' }, + { 'value': 'two', 'label': 'two' }, + ], + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes enums WITHOUT explicit list type', done => { + it('analyzes enums WITHOUT explicit list type', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); expect(definitions[0].multiselect).toBeFalsy(); - expect(definitions[0].items).toEqual([ - 'one', - 'two', - 'three', - ]); + expect(definitions[0].items).toEqual(['one', 'two', 'three']); return {}; }); - - registry - .compile({ - properties: { - test: { - type: 'string', - enum: [ - 'one', - 'two', - 'three', - ], - 'x-prompt': { - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'string', + enum: ['one', 'two', 'three'], + 'x-prompt': { + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes enums WITHOUT explicit list type and multiselect', done => { + it('analyzes enums WITHOUT explicit list type and multiselect', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('list'); expect(definitions[0].multiselect).toBe(true); - expect(definitions[0].items).toEqual([ - 'one', - 'two', - 'three', - ]); + expect(definitions[0].items).toEqual(['one', 'two', 'three']); return {}; }); - registry - .compile({ - properties: { - test: { - type: 'array', - items: { - enum: [ - 'one', - 'two', - 'three', - ], - }, - 'x-prompt': 'test-message', + const validator = await registry.compile({ + properties: { + test: { + type: 'array', + items: { + enum: ['one', 'two', 'three'], }, + 'x-prompt': 'test-message', }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('analyzes boolean properties', done => { + it('analyzes boolean properties', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('confirmation'); expect(definitions[0].items).toBeUndefined(); @@ -468,28 +380,24 @@ describe('Prompt Provider', () => { return {}; }); - registry - .compile({ - properties: { - test: { - type: 'boolean', - 'x-prompt': { - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'boolean', + 'x-prompt': { + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - it('allows prompt type override', done => { + it('allows prompt type override', async () => { const registry = new CoreSchemaRegistry(); const data: any = {}; - registry.usePromptProvider(async definitions => { + registry.usePromptProvider(async (definitions) => { expect(definitions.length).toBe(1); expect(definitions[0].type).toBe('input'); expect(definitions[0].items).toBeUndefined(); @@ -497,24 +405,18 @@ describe('Prompt Provider', () => { return {}; }); - registry - .compile({ - properties: { - test: { - type: 'boolean', - 'x-prompt': { - 'type': 'input', - 'message': 'test-message', - }, + const validator = await registry.compile({ + properties: { + test: { + type: 'boolean', + 'x-prompt': { + 'type': 'input', + 'message': 'test-message', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - ) - .toPromise().then(done, done.fail); + }, + }); + await validator(data); }); - }); - }); diff --git a/packages/angular_devkit/core/src/json/schema/registry.ts b/packages/angular_devkit/core/src/json/schema/registry.ts index c16fb5f1b9d5..891259e03ee0 100644 --- a/packages/angular_devkit/core/src/json/schema/registry.ts +++ b/packages/angular_devkit/core/src/json/schema/registry.ts @@ -1,25 +1,29 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as ajv from 'ajv'; -import * as http from 'http'; -import { Observable, from, isObservable, of, throwError } from 'rxjs'; -import { concatMap, map, switchMap, tap } from 'rxjs/operators'; -import * as Url from 'url'; -import { BaseException } from '../../exception/exception'; -import { PartiallyOrderedSet, deepCopy } from '../../utils'; -import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../interface'; + +import Ajv, { SchemaObjCxt, ValidateFunction } from 'ajv'; +import ajvAddFormats from 'ajv-formats'; +import * as http from 'node:http'; +import * as https from 'node:https'; +import * as Url from 'node:url'; +import { Observable, from, isObservable, lastValueFrom } from 'rxjs'; +import { + BaseException, + CircularDependencyFoundException, + DependencyNotFoundException, +} from '../../exception'; +import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../utils'; import { JsonPointer, JsonVisitor, PromptDefinition, PromptProvider, SchemaFormat, - SchemaFormatter, SchemaRegistry, SchemaValidator, SchemaValidatorError, @@ -31,22 +35,9 @@ import { JsonSchema } from './schema'; import { getTypesOfSchema } from './utility'; import { visitJson, visitJsonSchema } from './visitor'; -// This interface should be exported from ajv, but they only export the class and not the type. -interface AjvValidationError { - message: string; - errors: Array; - ajv: true; - validation: true; -} - -interface AjvRefMap { - refs: string[]; - refVal: any; // tslint:disable-line:no-any - schema: JsonObject; -} - -export type UriHandler = (uri: string) => - Observable | Promise | null | undefined; +export type UriHandler = ( + uri: string, +) => Observable | Promise | null | undefined; export class SchemaValidationException extends BaseException { public readonly errors: SchemaValidatorError[]; @@ -57,6 +48,7 @@ export class SchemaValidationException extends BaseException { ) { if (!errors || errors.length === 0) { super('Schema validation failed.'); + this.errors = []; return; } @@ -72,9 +64,24 @@ export class SchemaValidationException extends BaseException { } const messages = errors.map((err) => { - let message = `Data path ${JSON.stringify(err.dataPath)} ${err.message}`; if (err.keyword === 'additionalProperties') { - message += `(${err.params.additionalProperty})`; + const unknown = err.params?.additionalProperty; + // `parentSchema` is the schema that rejected the property, which ajv only attaches when + // the validator was created with `verbose: true`. A schema that declares no `properties` + // of its own, such as one using only `patternProperties`, has no options to offer. + const known = Object.keys(err.parentSchema?.properties ?? {}); + + return ( + `Unknown option "${unknown}"${err.instancePath ? ` at "${err.instancePath}"` : ''}.` + + (known.length ? ` Valid options are: ${known.join(', ')}.` : '') + ); + } + + let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`; + if (err.keyword === 'enum' && err.params) { + message += `. Allowed values are: ${(err.params.allowedValues as string[] | undefined) + ?.map((v) => `"${v}"`) + .join(', ')}`; } return message + '.'; @@ -89,12 +96,46 @@ interface SchemaInfo { promptDefinitions: Array; } +/** + * Adds a transform to an ordered list of transforms. + * + * Transforms run in insertion order and each transform is only present once. Dependencies + * must already be in the list, which guarantees that they run before the added transform. + */ +function addTransform( + transforms: JsonVisitor[], + visitor: JsonVisitor, + deps: JsonVisitor[] = [], +): void { + const existingIndex = transforms.indexOf(visitor); + const position = existingIndex === -1 ? transforms.length : existingIndex; + + for (const dep of deps) { + const depIndex = transforms.indexOf(dep); + if (depIndex === -1) { + throw new DependencyNotFoundException(); + } + if (depIndex === position) { + throw new CircularDependencyFoundException(); + } + if (depIndex > position) { + throw new Error( + 'The transform is already registered and runs before one of the provided dependencies.', + ); + } + } + + if (existingIndex === -1) { + transforms.push(visitor); + } +} + export class CoreSchemaRegistry implements SchemaRegistry { - private _ajv: ajv.Ajv; + private _ajv: Ajv; private _uriCache = new Map(); private _uriHandlers = new Set(); - private _pre = new PartiallyOrderedSet(); - private _post = new PartiallyOrderedSet(); + private _pre: JsonVisitor[] = []; + private _post: JsonVisitor[] = []; private _currentCompilationSchemaInfo?: SchemaInfo; @@ -103,48 +144,50 @@ export class CoreSchemaRegistry implements SchemaRegistry { private _sourceMap = new Map>(); constructor(formats: SchemaFormat[] = []) { - /** - * Build an AJV instance that will be used to validate schemas. - */ - - const formatsObj: { [name: string]: SchemaFormatter } = {}; - - for (const format of formats) { - formatsObj[format.name] = format.formatter; - } - - this._ajv = ajv({ - formats: formatsObj, + this._ajv = new Ajv({ + strict: false, loadSchema: (uri: string) => this._fetch(uri), - schemaId: 'auto', passContext: true, + // Needed to list the valid options of the object an unknown option was found in. + verbose: true, }); - this._ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); - this._ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); + ajvAddFormats(this._ajv); + + for (const format of formats) { + this.addFormat(format); + } } - private _fetch(uri: string): Promise { + private async _fetch(uri: string): Promise { const maybeSchema = this._uriCache.get(uri); if (maybeSchema) { - return Promise.resolve(maybeSchema); + return maybeSchema; } // Try all handlers, one after the other. - for (const maybeHandler of this._uriHandlers) { - const handler = maybeHandler(uri); - if (handler) { - // The AJV API only understands Promises. - return from(handler).pipe( - tap(json => this._uriCache.set(uri, json)), - ).toPromise(); + for (const handler of this._uriHandlers) { + let handlerResult = handler(uri); + if (handlerResult === null || handlerResult === undefined) { + continue; + } + + if (isObservable(handlerResult)) { + handlerResult = lastValueFrom(handlerResult); } + + const value = await handlerResult; + this._uriCache.set(uri, value); + + return value; } // If none are found, handle using http client. return new Promise((resolve, reject) => { - http.get(uri, res => { + const url = new Url.URL(uri); + const client = url.protocol === 'https:' ? https : http; + client.get(url, (res) => { if (!res.statusCode || res.statusCode >= 300) { // Consume the rest of the data to free memory. res.resume(); @@ -152,12 +195,12 @@ export class CoreSchemaRegistry implements SchemaRegistry { } else { res.setEncoding('utf8'); let data = ''; - res.on('data', chunk => { + res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { try { - const json = JSON.parse(data); + const json = JSON.parse(data) as JsonObject; this._uriCache.set(uri, json); resolve(json); } catch (err) { @@ -172,10 +215,10 @@ export class CoreSchemaRegistry implements SchemaRegistry { /** * Add a transformation step before the validation of any Json. * @param {JsonVisitor} visitor The visitor to transform every value. - * @param {JsonVisitor[]} deps A list of other visitors to run before. + * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ - addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]) { - this._pre.add(visitor, deps); + addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void { + addTransform(this._pre, visitor, deps); } /** @@ -183,115 +226,85 @@ export class CoreSchemaRegistry implements SchemaRegistry { * after the POST, so if transformations are not compatible with the Schema it will not result * in an error. * @param {JsonVisitor} visitor The visitor to transform every value. - * @param {JsonVisitor[]} deps A list of other visitors to run before. + * @param {JsonVisitor[]} deps [Deprecated] A list of other visitors to run before. Add transforms in the desired execution order instead. */ - addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]) { - this._post.add(visitor, deps); + addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void { + addTransform(this._post, visitor, deps); } protected _resolver( ref: string, - validate: ajv.ValidateFunction, - ): { context?: ajv.ValidateFunction, schema?: JsonObject } { - if (!validate || !validate.refs || !validate.refVal || !ref) { + validate?: ValidateFunction, + ): { context?: ValidateFunction; schema?: JsonObject } { + if (!validate || !ref) { return {}; } - let refMap = validate as AjvRefMap; - const rootRefMap = validate.root as AjvRefMap; - - // Resolve from the root if it's different. - if (validate.root && validate.schema !== rootRefMap.schema) { - refMap = rootRefMap; - } - - const schema = refMap.schema ? typeof refMap.schema == 'object' && refMap.schema : null; - const maybeId = schema ? (schema as JsonObject).id || (schema as JsonObject).$id : null; + const schema = validate.schemaEnv.root.schema; + const id = typeof schema === 'object' ? schema.$id : null; - if (typeof maybeId == 'string') { - ref = Url.resolve(maybeId, ref); - } + let fullReference = ref; + if (typeof id === 'string') { + fullReference = Url.resolve(id, ref); - let fullReference = (ref[0] === '#' && maybeId) ? maybeId + ref : ref; - if (fullReference.endsWith('#')) { - fullReference = fullReference.slice(0, -1); + if (ref.startsWith('#')) { + fullReference = id + fullReference; + } } - // tslint:disable-next-line:no-any - const context = validate.refVal[(validate.refs as any)[fullReference]]; + const resolvedSchema = this._ajv.getSchema(fullReference); - if (typeof context == 'function') { - // Context will be a function if the schema isn't loaded yet, and an actual schema if it's - // synchronously available. - return { context, schema: context && context.schema as JsonObject }; - } else { - return { context: validate, schema: context as JsonObject }; - } + return { + context: resolvedSchema?.schemaEnv.validate, + schema: resolvedSchema?.schema as JsonObject, + }; } /** * Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema * that is also easier to traverse. Does not cache the result. * + * Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original. + * See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2 + * * @param schema The schema or URI to flatten. - * @returns An Observable of the flattened schema object. + * @return A Promise that resolves to the flattened schema object. + * @private since 11.2 without replacement. */ - flatten(schema: JsonObject): Observable { + async ɵflatten(schema: JsonObject): Promise { this._ajv.removeSchema(schema); - - // Supports both synchronous and asynchronous compilation, by trying the synchronous - // version first, then if refs are missing this will fails. - // We also add any refs from external fetched schemas so that those will also be used - // in synchronous (if available). - let validator: Observable; - try { - this._currentCompilationSchemaInfo = undefined; - validator = of(this._ajv.compile(schema)).pipe( - tap(() => this._currentCompilationSchemaInfo = undefined), - ); - } catch (e) { - // Propagate the error. - if (!(e instanceof (ajv.MissingRefError as {} as Function))) { - return throwError(e); + this._currentCompilationSchemaInfo = undefined; + const validate = await this._ajv.compileAsync(schema); + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + + function visitor( + current: JsonObject | JsonArray, + pointer: JsonPointer, + parentSchema?: JsonObject | JsonArray, + index?: string, + ) { + if ( + current && + parentSchema && + index && + isJsonObject(current) && + Object.prototype.hasOwnProperty.call(current, '$ref') && + typeof current['$ref'] == 'string' + ) { + const resolved = self._resolver(current['$ref'], validate); + + if (resolved.schema) { + (parentSchema as JsonObject)[index] = resolved.schema; + } } - - this._currentCompilationSchemaInfo = undefined; - validator = from(this._ajv.compileAsync(schema)).pipe( - tap(() => this._currentCompilationSchemaInfo = undefined), - ); } - return validator.pipe( - switchMap(validate => { - const self = this; - - function visitor( - current: JsonObject | JsonArray, - pointer: JsonPointer, - parentSchema?: JsonObject | JsonArray, - index?: string, - ) { - if (current - && parentSchema - && index - && isJsonObject(current) - && current.hasOwnProperty('$ref') - && typeof current['$ref'] == 'string' - ) { - const resolved = self._resolver(current['$ref'] as string, validate); + const schemaCopy = structuredClone(validate.schema as JsonObject); + visitJsonSchema(schemaCopy, visitor); - if (resolved.schema) { - (parentSchema as JsonObject)[index] = resolved.schema; - } - } - } - - const schema = deepCopy(validate.schema as JsonObject); - visitJsonSchema(schema, visitor); - - return of(schema); - }), - ); + return schemaCopy; } /** @@ -299,181 +312,136 @@ export class CoreSchemaRegistry implements SchemaRegistry { * * @param schema The schema to validate. If a string, will fetch the schema before compiling it * (using schema as a URI). - * @returns An Observable of the Validation function. */ - compile(schema: JsonSchema): Observable { + async compile(schema: JsonSchema): Promise { + const validate = await this._compile(schema); + + return (value, options) => validate(value, options); + } + + private async _compile( + schema: JsonSchema, + ): Promise< + (data: JsonValue, options?: SchemaValidatorOptions) => Promise + > { + if (typeof schema === 'boolean') { + return async (data) => ({ success: schema, data }); + } + const schemaInfo: SchemaInfo = { smartDefaultRecord: new Map(), promptDefinitions: [], }; this._ajv.removeSchema(schema); + let validator: ValidateFunction; - // Supports both synchronous and asynchronous compilation, by trying the synchronous - // version first, then if refs are missing this will fails. - // We also add any refs from external fetched schemas so that those will also be used - // in synchronous (if available). - let validator: Observable; try { this._currentCompilationSchemaInfo = schemaInfo; - validator = of(this._ajv.compile(schema)); + validator = this._ajv.compile(schema); } catch (e) { - // Propagate the error. - if (!(e instanceof (ajv.MissingRefError as {} as Function))) { - return throwError(e); + // This should eventually be refactored so that we we handle race condition where the same schema is validated at the same time. + if (!(e instanceof Ajv.MissingRefError)) { + throw e; } - try { - validator = from(this._ajv.compileAsync(schema)); - } catch (e) { - return throwError(e); - } + validator = await this._ajv.compileAsync(schema); + } finally { + this._currentCompilationSchemaInfo = undefined; } - return validator - .pipe( - map(validate => (data: JsonValue, options?: SchemaValidatorOptions) => { - const validationOptions: SchemaValidatorOptions = { - withPrompts: true, - applyPostTransforms: true, - applyPreTransforms: true, - ...options, - }; - const validationContext = { - promptFieldsWithValue: new Set(), - }; - - let result = of(data); - if (validationOptions.applyPreTransforms) { - // tslint:disable-next-line:no-any https://github.com/ReactiveX/rxjs/issues/3989 - result = (result as any).pipe( - ...[...this._pre].map(visitor => concatMap((data: JsonValue) => { - return visitJson(data, visitor, schema, this._resolver, validate); - })), - ); + return async (data: JsonValue, options?: SchemaValidatorOptions) => { + const validationOptions: SchemaValidatorOptions = { + withPrompts: true, + applyPostTransforms: true, + applyPreTransforms: true, + ...options, + }; + const validationContext = { + promptFieldsWithValue: new Set(), + }; + + // Apply pre-validation transforms + if (validationOptions.applyPreTransforms) { + for (const visitor of this._pre) { + data = await lastValueFrom( + visitJson(data, visitor, schema, this._resolver.bind(this), validator), + ); + } + } + + // Apply smart defaults + await this._applySmartDefaults(data, schemaInfo.smartDefaultRecord); + + // Apply prompts + if (validationOptions.withPrompts) { + const visitor: JsonVisitor = (value, pointer) => { + if (value !== undefined) { + validationContext.promptFieldsWithValue.add(pointer); } - return result.pipe( - switchMap(updateData => this._applySmartDefaults( - updateData, - schemaInfo.smartDefaultRecord, - )), - switchMap(updatedData => { - if (validationOptions.withPrompts === false) { - return of(updatedData); - } + return value; + }; + if (typeof schema === 'object') { + await lastValueFrom( + visitJson(data, visitor, schema, this._resolver.bind(this), validator), + ); + } - const visitor: JsonVisitor = (value, pointer) => { - if (value !== undefined) { - validationContext.promptFieldsWithValue.add(pointer); - } + const definitions = schemaInfo.promptDefinitions.filter( + (def) => !validationContext.promptFieldsWithValue.has(def.id), + ); - return value; - }; - if (schema === false || schema === true) { - return of(updatedData); - } + if (definitions.length > 0) { + await this._applyPrompts(data, definitions); + } + } - return visitJson(updatedData, visitor, schema, this._resolver, validate); - }), - switchMap(updatedData => { - if (validationOptions.withPrompts === false) { - return of(updatedData); - } + // Validate using ajv + try { + // eslint-disable-next-line @typescript-eslint/await-thenable + const success = await validator.call(validationContext, data); - const definitions = schemaInfo.promptDefinitions - .filter(def => !validationContext.promptFieldsWithValue.has(def.id)); + if (!success) { + return { data, success, errors: validator.errors ?? [] }; + } + } catch (error) { + if (error instanceof Ajv.ValidationError) { + return { data, success: false, errors: error.errors }; + } - if (this._promptProvider && definitions.length > 0) { - return from(this._applyPrompts(updatedData, definitions)); - } else { - return of(updatedData); - } - }), - switchMap(updatedData => { - const result = validate.call(validationContext, updatedData); - - return typeof result == 'boolean' - ? of([updatedData, result]) - : from((result as Promise) - .then(r => [updatedData, true]) - .catch((err: Error | AjvValidationError) => { - if ((err as AjvValidationError).ajv) { - validate.errors = (err as AjvValidationError).errors; - - return Promise.resolve([updatedData, false]); - } - - return Promise.reject(err); - })); - }), - switchMap(([data, valid]: [JsonValue, boolean]) => { - if (valid) { - let result = of(data); - - if (validationOptions.applyPostTransforms) { - // tslint:disable-next-line:no-any https://github.com/ReactiveX/rxjs/issues/3989 - result = (result as any).pipe( - ...[...this._post].map(visitor => concatMap((data: JsonValue) => { - return visitJson(data, visitor, schema, this._resolver, validate); - })), - ); - } - - return result.pipe( - map(data => [data, valid]), - ); - } else { - return of([data, valid]); - } - }), - map(([data, valid]: [JsonValue, boolean]) => { - if (valid) { - return { data, success: true } as SchemaValidatorResult; - } + throw error; + } - return { - data, - success: false, - errors: (validate.errors || []), - } as SchemaValidatorResult; - }), + // Apply post-validation transforms + if (validationOptions.applyPostTransforms) { + for (const visitor of this._post) { + data = await lastValueFrom( + visitJson(data, visitor, schema, this._resolver.bind(this), validator), ); - }), - ); - } - - addFormat(format: SchemaFormat): void { - // tslint:disable-next-line:no-any - const validate = (data: any) => { - const result = format.formatter.validate(data); - - if (typeof result == 'boolean') { - return result; - } else { - return result.toPromise(); + } } + + return { data, success: true }; }; + } - this._ajv.addFormat(format.name, { - async: format.formatter.async, - validate, - // AJV typings list `compare` as required, but it is optional. - // tslint:disable-next-line:no-any - } as any); + addFormat(format: SchemaFormat): void { + this._ajv.addFormat(format.name, format.formatter); } - addSmartDefaultProvider(source: string, provider: SmartDefaultProvider) { + addSmartDefaultProvider(source: string, provider: SmartDefaultProvider): void { if (this._sourceMap.has(source)) { throw new Error(source); } - this._sourceMap.set(source, provider); + this._sourceMap.set(source, provider as unknown as SmartDefaultProvider<{}>); if (!this._smartDefaultKeyword) { this._smartDefaultKeyword = true; - this._ajv.addKeyword('$default', { + this._ajv.addKeyword({ + keyword: '$default', errors: false, valid: true, compile: (schema, _parentSchema, it) => { @@ -483,11 +451,8 @@ export class CoreSchemaRegistry implements SchemaRegistry { } // We cheat, heavily. - compilationSchemInfo.smartDefaultRecord.set( - // tslint:disable-next-line:no-any - JSON.stringify((it as any).dataPathArr.slice(1, (it as any).dataLevel + 1) as string[]), - schema, - ); + const pathArray = this.normalizeDataPathArr(it); + compilationSchemInfo.smartDefaultRecord.set(JSON.stringify(pathArray), schema); return () => true; }, @@ -497,17 +462,17 @@ export class CoreSchemaRegistry implements SchemaRegistry { '$source': { type: 'string' }, }, additionalProperties: true, - required: [ '$source' ], + required: ['$source'], }, }); } } - registerUriHandler(handler: UriHandler) { + registerUriHandler(handler: UriHandler): void { this._uriHandlers.add(handler); } - usePromptProvider(provider: PromptProvider) { + usePromptProvider(provider: PromptProvider): void { const isSetup = !!this._promptProvider; this._promptProvider = provider; @@ -516,21 +481,20 @@ export class CoreSchemaRegistry implements SchemaRegistry { return; } - this._ajv.addKeyword('x-prompt', { + this._ajv.addKeyword({ + keyword: 'x-prompt', errors: false, valid: true, - compile: (schema, parentSchema: JsonObject, it) => { + compile: (schema, parentSchema, it) => { const compilationSchemInfo = this._currentCompilationSchemaInfo; if (!compilationSchemInfo) { return () => true; } - // tslint:disable-next-line:no-any - const pathArray = ((it as any).dataPathArr as string[]).slice(1, it.dataLevel + 1); - const path = '/' + pathArray.map(p => p.replace(/^\'/, '').replace(/\'$/, '')).join('/'); + const path = '/' + this.normalizeDataPathArr(it).join('/'); let type: string | undefined; - let items: Array | undefined; + let items: Array | undefined; let message: string; if (typeof schema == 'string') { message = schema; @@ -540,17 +504,17 @@ export class CoreSchemaRegistry implements SchemaRegistry { items = schema.items; } - const propertyTypes = getTypesOfSchema(parentSchema); + const propertyTypes = getTypesOfSchema(parentSchema as JsonObject); if (!type) { if (propertyTypes.size === 1 && propertyTypes.has('boolean')) { type = 'confirmation'; - } else if (Array.isArray(parentSchema.enum)) { + } else if (Array.isArray((parentSchema as JsonObject).enum)) { type = 'list'; } else if ( propertyTypes.size === 1 && propertyTypes.has('array') && - parentSchema.items && - Array.isArray((parentSchema.items as JsonObject).enum) + (parentSchema as JsonObject).items && + Array.isArray(((parentSchema as JsonObject).items as JsonObject).enum) ) { type = 'list'; } else { @@ -566,8 +530,9 @@ export class CoreSchemaRegistry implements SchemaRegistry { : schema.multiselect; const enumValues = multiselect - ? parentSchema.items && (parentSchema.items as JsonObject).enum - : parentSchema.enum; + ? (parentSchema as JsonObject).items && + ((parentSchema as JsonObject).items as JsonObject).enum + : (parentSchema as JsonObject).enum; if (!items && Array.isArray(enumValues)) { items = []; for (const value of enumValues) { @@ -589,24 +554,38 @@ export class CoreSchemaRegistry implements SchemaRegistry { raw: schema, items, multiselect, + propertyTypes, default: - typeof parentSchema.default == 'object' && - parentSchema.default !== null && - !Array.isArray(parentSchema.default) + typeof (parentSchema as JsonObject).default == 'object' && + (parentSchema as JsonObject).default !== null && + !Array.isArray((parentSchema as JsonObject).default) ? undefined - : parentSchema.default as string[], - async validator(data: JsonValue) { + : ((parentSchema as JsonObject).default as string[]), + async validator(data: JsonValue): Promise { try { - return await it.self.validate(parentSchema, data); - } catch { - return false; + const result = await it.self.validate(parentSchema, data); + // If the schema is sync then false will be returned on validation failure + if (result) { + return result as boolean | string; + } else if (it.self.errors?.length) { + // Validation errors will be present on the Ajv instance when sync + return it.self.errors[0].message as string; + } + } catch (e) { + const validationError = e as { errors?: Error[] }; + // If the schema is async then an error will be thrown on validation failure + if (Array.isArray(validationError.errors) && validationError.errors.length) { + return validationError.errors[0].message; + } } + + return false; }, }; compilationSchemInfo.promptDefinitions.push(definition); - return function(this: { promptFieldsWithValue: Set }) { + return function (this: { promptFieldsWithValue: Set }) { // If 'this' is undefined in the call, then it defaults to the global // 'this'. if (this && this.promptFieldsWithValue) { @@ -626,130 +605,112 @@ export class CoreSchemaRegistry implements SchemaRegistry { 'message': { type: 'string' }, }, additionalProperties: true, - required: [ 'message' ], + required: ['message'], }, ], }, }); } - private _applyPrompts(data: T, prompts: Array): Observable { + private async _applyPrompts(data: JsonValue, prompts: Array): Promise { const provider = this._promptProvider; if (!provider) { - return of(data); + return; } - return from(provider(prompts)).pipe( - map(answers => { - for (const path in answers) { - const pathFragments = path.split('/').map(pf => { - if (/^\d+$/.test(pf)) { - return pf; - } else { - return '\'' + pf + '\''; - } - }); - - CoreSchemaRegistry._set( - data, - pathFragments.slice(1), - answers[path] as {}, - null, - undefined, - true, - ); - } + const answers = await lastValueFrom(from(provider(prompts))); + for (const path in answers) { + const pathFragments = path.split('/').slice(1); - return data; - }), - ); + await CoreSchemaRegistry._set(data, pathFragments, answers[path], null, undefined, true); + } } - private static _set( - // tslint:disable-next-line:no-any + private static async _set( + // eslint-disable-next-line @typescript-eslint/no-explicit-any data: any, fragments: string[], - value: {}, - // tslint:disable-next-line:no-any - parent: any | null = null, + value: unknown, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parent: any = null, parentProperty?: string, force?: boolean, - ): void { - for (let i = 0; i < fragments.length; i++) { - const f = fragments[i]; - - if (f[0] == 'i') { + ): Promise { + for (let index = 0; index < fragments.length; index++) { + const fragment = fragments[index]; + if (/^i\d+$/.test(fragment)) { if (!Array.isArray(data)) { return; } - for (let j = 0; j < data.length; j++) { - CoreSchemaRegistry._set(data[j], fragments.slice(i + 1), value, data, '' + j); - } - - return; - } else if (f.startsWith('key')) { - if (typeof data !== 'object') { - return; + for (let dataIndex = 0; dataIndex < data.length; dataIndex++) { + await CoreSchemaRegistry._set( + data[dataIndex], + fragments.slice(index + 1), + value, + data, + `${dataIndex}`, + ); } - Object.getOwnPropertyNames(data).forEach(property => { - CoreSchemaRegistry._set(data[property], fragments.slice(i + 1), value, data, property); - }); - return; - } else if (f.startsWith('\'') && f[f.length - 1] == '\'') { - const property = f - .slice(1, -1) - .replace(/\\'/g, '\'') - .replace(/\\n/g, '\n') - .replace(/\\r/g, '\r') - .replace(/\\f/g, '\f') - .replace(/\\t/g, '\t'); - - // We know we need an object because the fragment is a property key. - if (!data && parent !== null && parentProperty) { - data = parent[parentProperty] = {}; - } - parent = data; - parentProperty = property; + } - data = data[property]; - } else { - return; + if (!data && parent !== null && parentProperty) { + data = parent[parentProperty] = {}; } + + parent = data; + parentProperty = fragment; + data = data[fragment]; } if (parent && parentProperty && (force || parent[parentProperty] === undefined)) { - parent[parentProperty] = value; + let resolvedValue = typeof value === 'function' ? value() : value; + if (isObservable(resolvedValue)) { + resolvedValue = await lastValueFrom(resolvedValue); + } + + parent[parentProperty] = resolvedValue; } } - private _applySmartDefaults( + private async _applySmartDefaults( data: T, smartDefaults: Map, - ): Observable { - // tslint:disable-next-line:no-any https://github.com/ReactiveX/rxjs/issues/3989 - return (of(data) as any).pipe( - ...[...smartDefaults.entries()].map(([pointer, schema]) => { - return concatMap(data => { - const fragments = JSON.parse(pointer); - const source = this._sourceMap.get((schema as JsonObject).$source as string); - - let value = source ? source(schema) : of(undefined); - - if (!isObservable(value)) { - value = of(value); - } + ): Promise { + for (const [pointer, schema] of smartDefaults.entries()) { + const fragments = JSON.parse(pointer) as string[]; + const source = this._sourceMap.get(schema.$source as string); + if (!source) { + continue; + } + + await CoreSchemaRegistry._set(data, fragments, () => source(schema)); + } + } - return (value as Observable<{}>).pipe( - // Synchronously set the new data at the proper JsonSchema path. - tap(x => CoreSchemaRegistry._set(data, fragments, x)), - // But return the data object. - map(() => data), + useXDeprecatedProvider(onUsage: (message: string) => void): void { + this._ajv.addKeyword({ + keyword: 'x-deprecated', + validate: (schema, _data, _parentSchema, dataCxt) => { + if (schema) { + onUsage( + `Option "${dataCxt?.parentDataProperty}" is deprecated${ + typeof schema == 'string' ? ': ' + schema : '.' + }`, ); - }); - }), - ); + } + + return true; + }, + errors: false, + }); + } + + private normalizeDataPathArr(it: SchemaObjCxt): (number | string)[] { + return it.dataPathArr + .slice(1, it.dataLevel + 1) + .map((p) => (typeof p === 'number' ? p : p.str.replace(/"/g, ''))); } } diff --git a/packages/angular_devkit/core/src/json/schema/registry_spec.ts b/packages/angular_devkit/core/src/json/schema/registry_spec.ts index 0f6f49a96263..82b0b44b9947 100644 --- a/packages/angular_devkit/core/src/json/schema/registry_spec.ts +++ b/packages/angular_devkit/core/src/json/schema/registry_spec.ts @@ -1,54 +1,51 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any non-null-operator no-big-function -import { of as observableOf } from 'rxjs'; -import { map, mergeMap } from 'rxjs/operators'; -import { CoreSchemaRegistry } from './registry'; -import { addUndefinedDefaults } from './transforms'; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { CircularDependencyFoundException, DependencyNotFoundException } from '../../exception'; +import { JsonValue } from '../utils'; +import { JsonVisitor, SchemaFormat } from './interface'; +import { CoreSchemaRegistry, SchemaValidationException } from './registry'; +import { JsonSchema } from './schema'; +import { addUndefinedDefaults } from './transforms'; describe('CoreSchemaRegistry', () => { - it('works asynchronously', done => { + it('works asynchronously', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); - const data: any = {}; // tslint:disable-line:no-any - - registry - .compile({ - properties: { - bool: { type: 'boolean' }, - str: { type: 'string', default: 'someString' }, - obj: { - properties: { - num: { type: 'number' }, - other: { type: 'number', default: 0 }, - }, - }, - tslint: { - $ref: 'http://json.schemastore.org/tslint#', + const data: any = {}; + + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean' }, + str: { type: 'string', default: 'someString' }, + obj: { + properties: { + num: { type: 'number' }, + other: { type: 'number', default: 0 }, }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.obj.num).toBeUndefined(); - expect(data.tslint).not.toBeUndefined(); - }), - ) - .toPromise().then(done, done.fail); + tslint: { + $ref: 'https://raw.githubusercontent.com/SchemaStore/schemastore/734c0e5/src/schemas/json/tslint.json#', + }, + }, + }); + + const result = await validator(data); + expect(result.success).toBe(true); + expect(data.obj.num).toBeUndefined(); + expect(data.tslint).not.toBeUndefined(); }); - it('supports pre transforms', done => { + it('supports pre transforms', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); - const data: any = {}; // tslint:disable-line:no-any + const data = {}; registry.addPreTransform((data, ptr) => { if (ptr == '/') { @@ -58,203 +55,149 @@ describe('CoreSchemaRegistry', () => { return data; }); - registry - .compile({ - properties: { - bool: { type: 'boolean' }, - str: { type: 'string', default: 'someString' }, - obj: { - properties: { - num: { type: 'number' }, - other: { type: 'number', default: 0 }, - }, + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean' }, + str: { type: 'string', default: 'someString' }, + obj: { + properties: { + num: { type: 'number' }, + other: { type: 'number', default: 0 }, }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - const data = result.data as any; - expect(result.success).toBe(true); - expect(data.str).toBe('string'); - expect(data.obj.num).toBeUndefined(); - }), - ) - .toPromise().then(done, done.fail); + }, + }); + + const result = await validator(data); + const resultData = result.data as any; + expect(result.success).toBe(true); + expect(resultData.str).toBe('string'); + expect(resultData.obj.num).toBeUndefined(); }); - it('supports local references', done => { + it('supports local references', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { numbers: { one: 1 } }; - registry - .compile({ - properties: { - numbers: { - type: 'object', - additionalProperties: { '$ref': '#/definitions/myRef' }, - }, - }, - definitions: { - myRef: { type: 'integer' }, + const validator = await registry.compile({ + properties: { + numbers: { + type: 'object', + additionalProperties: { '$ref': '#/definitions/myRef' }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.numbers.one).not.toBeUndefined(); - }), - ) - .toPromise().then(done, done.fail); + }, + definitions: { + myRef: { type: 'integer' }, + }, + }); + const result = await validator(data); + expect(result.success).toBe(true); + expect(data.numbers.one).not.toBeUndefined(); }); - it('fails on invalid additionalProperties', done => { + it('fails on invalid additionalProperties', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); const data = { notNum: 'foo' }; + const validator = await registry.compile({ + properties: { + num: { type: 'number' }, + }, + additionalProperties: false, + }); - registry - .compile({ - properties: { - num: { type: 'number' }, - }, - additionalProperties: false, - }).pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(false); - expect(result.errors && result.errors[0].message).toContain( - 'should NOT have additional properties'); - }), - ) - .toPromise().then(done, done.fail); + const result = await validator(data); + expect(result.success).toBe(false); + expect(result.errors && result.errors[0].message).toContain( + 'must NOT have additional properties', + ); }); - it('fails on invalid additionalProperties async', done => { + it('fails on invalid enum value', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); - const data = { notNum: 'foo' }; + const data = { packageManager: 'foo' }; - registry - .compile({ - $async: true, - properties: { - num: { type: 'number' }, - }, - additionalProperties: false, - }).pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(false); - expect(result.errors && result.errors[0].message).toContain( - 'should NOT have additional properties'); - expect(result.errors && result.errors[0].keyword).toBe('additionalProperties'); - }), - ) - .toPromise().then(done, done.fail); - }); + const validator = await registry.compile({ + properties: { + packageManager: { type: 'string', enum: ['npm', 'yarn', 'pnpm'] }, + }, + additionalProperties: false, + }); + const result = await validator(data); + expect(result.success).toBe(false); + expect(new SchemaValidationException(result.errors).message).toContain( + `Data path "/packageManager" must be equal to one of the allowed values. Allowed values are: "npm", "yarn", "pnpm".`, + ); + }); - // Synchronous failure is only used internally. - // If it's meant to be used externally then this test should change to truly be synchronous - // (i.e. not relyign on the observable). - it('works synchronously', done => { + it('fails on invalid additionalProperties async', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); - const data: any = {}; // tslint:disable-line:no-any - let isDone = false; - - registry - .compile({ - properties: { - bool: { type: 'boolean' }, - str: { type: 'string', default: 'someString' }, - obj: { - properties: { - num: { type: 'number' }, - other: { type: 'number', default: 0 }, - }, - }, - }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.obj.num).toBeUndefined(); - }), - ) - .subscribe(() => { - isDone = true; - }, done.fail); - - expect(isDone).toBe(true); - done(); + const data = { notNum: 'foo' }; + const validator = await registry.compile({ + $async: true, + properties: { + num: { type: 'number' }, + }, + additionalProperties: false, + }); + const result = await validator(data); + expect(result.success).toBe(false); + expect(result.errors?.[0].message).toContain('must NOT have additional properties'); + expect(result.errors?.[0].keyword).toBe('additionalProperties'); }); - it('supports sync format', done => { + it('supports sync format', async () => { const registry = new CoreSchemaRegistry(); const data = { str: 'hotdog' }; const format = { name: 'is-hotdog', formatter: { - async: false, validate: (str: string) => str === 'hotdog', }, }; registry.addFormat(format); - - registry - .compile({ - properties: { - str: { type: 'string', format: 'is-hotdog' }, - }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - }), - ) - .toPromise().then(done, done.fail); + const validator = await registry.compile({ + properties: { + str: { type: 'string', format: 'is-hotdog' }, + }, + }); + const result = await validator(data); + expect(result.success).toBe(true); }); - it('supports async format', done => { + it('supports async format', async () => { const registry = new CoreSchemaRegistry(); const data = { str: 'hotdog' }; - const format = { + + const format: SchemaFormat = { name: 'is-hotdog', formatter: { async: true, - validate: (str: string) => observableOf(str === 'hotdog'), + validate: async (str: string) => str === 'hotdog', }, }; registry.addFormat(format); - registry - .compile({ - $async: true, - properties: { - str: { type: 'string', format: 'is-hotdog' }, - }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - }), - ) - .toPromise().then(done, done.fail); + const validator = await registry.compile({ + $async: true, + properties: { + str: { type: 'string', format: 'is-hotdog' }, + }, + }); + const result = await validator(data); + expect(result.success).toBe(true); }); - it('shows dataPath and message on error', done => { + it('shows dataPath and message on error', async () => { const registry = new CoreSchemaRegistry(); const data = { hotdot: 'hotdog', banana: 'banana' }; - const format = { + const format: SchemaFormat = { name: 'is-hotdog', formatter: { async: false, @@ -264,27 +207,22 @@ describe('CoreSchemaRegistry', () => { registry.addFormat(format); - registry - .compile({ - properties: { - hotdot: { type: 'string', format: 'is-hotdog' }, - banana: { type: 'string', format: 'is-hotdog' }, - }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(false); - expect(result.errors && result.errors[0]).toBeTruthy(); - expect(result.errors && result.errors[0].keyword).toBe('format'); - expect(result.errors && result.errors[0].dataPath).toBe('.banana'); - expect(result.errors && (result.errors[0].params as any).format).toBe('is-hotdog'); - }), - ) - .toPromise().then(done, done.fail); + const validator = await registry.compile({ + properties: { + hotdot: { type: 'string', format: 'is-hotdog' }, + banana: { type: 'string', format: 'is-hotdog' }, + }, + }); + + const result = await validator(data); + expect(result.success).toBe(false); + expect(result.errors && result.errors[0]).toBeTruthy(); + expect(result.errors && result.errors[0].keyword).toBe('format'); + expect(result.errors && result.errors[0].instancePath).toBe('/banana'); + expect(result.errors && (result.errors[0].params as any).format).toBe('is-hotdog'); }); - it('supports smart defaults', done => { + it('supports smart defaults', async () => { const registry = new CoreSchemaRegistry(); const data: any = { arr: [{}], @@ -306,179 +244,303 @@ describe('CoreSchemaRegistry', () => { return schema['blue']; }); registry.addSmartDefaultProvider('test3', () => { - return [ 1, 2, 3 ]; + return [1, 2, 3]; }); - registry - .compile({ - properties: { - bool: { - $ref: '#/definitions/example', - }, - arr: { - items: { - properties: { - 'test': { - $ref: '#/definitions/other', - }, + const validator = await registry.compile({ + properties: { + bool: { + $ref: '#/definitions/example', + }, + arr: { + items: { + properties: { + 'test': { + $ref: '#/definitions/other', }, }, }, - arr2: { - $ref: '#/definitions/test3', - }, - obj: { - properties: { - deep: { - properties: { - arr: { - $ref: '#/definitions/test3', - }, + }, + arr2: { + $ref: '#/definitions/test3', + }, + obj: { + properties: { + deep: { + properties: { + arr: { + $ref: '#/definitions/test3', }, }, }, }, }, - definitions: { - example: { - type: 'boolean', - $default: { - $source: 'test', - }, + }, + definitions: { + example: { + type: 'boolean', + $default: { + $source: 'test', }, - other: { - type: 'string', - $default: { - $source: 'test2', - blue: 'yep', - }, + }, + other: { + type: 'string', + $default: { + $source: 'test2', + blue: 'yep', }, - test3: { - type: 'array', - $default: { - $source: 'test3', - }, + }, + test3: { + type: 'array', + $default: { + $source: 'test3', }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.bool).toBe(true); - expect(data.arr[0].test).toBe('yep'); - expect(data.arr2).toEqual([1, 2, 3]); - expect(data.obj.deep.arr).toEqual([1, 2, 3]); - }), - ) - .toPromise().then(done, done.fail); + }, + }); + const result = await validator(data); + expect(result.success).toBe(true); + expect(data.bool).toBe(true); + expect(data.arr[0].test).toBe('yep'); + expect(data.arr2).toEqual([1, 2, 3]); + expect(data.obj.deep.arr).toEqual([1, 2, 3]); + }); + + it('does not call smart default provider when value is already defined', async () => { + const registry = new CoreSchemaRegistry(); + const provider = jasmine.createSpy('provider').and.returnValue('default-val'); + registry.addSmartDefaultProvider('test', provider); + + const validator = await registry.compile({ + properties: { + prop: { + type: 'string', + $default: { + $source: 'test', + }, + }, + }, + }); + + const data = { prop: 'explicit-val' }; + const result = await validator(data); + expect(result.success).toBe(true); + expect(data.prop).toBe('explicit-val'); + expect(provider).not.toHaveBeenCalled(); }); it('works with true as a schema and post-transforms', async () => { const registry = new CoreSchemaRegistry(); registry.addPostTransform(addUndefinedDefaults); - const data: any = { a: 1, b: 2 }; // tslint:disable-line:no-any + const data = { a: 1, b: 2 }; - const validate = await registry.compile(true).toPromise(); - const result = await validate(data).toPromise(); + const validate = await registry.compile(true); + const result = await validate(data); expect(result.success).toBe(true); expect(result.data).toBe(data); }); - it('adds undefined properties', done => { + it('adds deprecated options usage', async () => { const registry = new CoreSchemaRegistry(); - registry.addPostTransform(addUndefinedDefaults); - const data: any = {}; // tslint:disable-line:no-any - - registry - .compile({ - properties: { - bool: { type: 'boolean' }, - str: { type: 'string', default: 'someString' }, - obj: { - properties: { - num: { type: 'number' }, - other: { type: 'number', default: 0 }, + const deprecatedMessages: string[] = []; + registry.useXDeprecatedProvider((m) => deprecatedMessages.push(m)); + + const data = { + foo: true, + bar: true, + bat: true, + }; + + const validator = await registry.compile({ + properties: { + foo: { type: 'boolean', 'x-deprecated': 'Use bar instead.' }, + bar: { type: 'boolean', 'x-deprecated': true }, + buz: { type: 'boolean', 'x-deprecated': true }, + bat: { type: 'boolean', 'x-deprecated': false }, + }, + }); + const result = await validator(data); + expect(deprecatedMessages.length).toBe(2); + expect(deprecatedMessages[0]).toBe('Option "foo" is deprecated: Use bar instead.'); + expect(deprecatedMessages[1]).toBe('Option "bar" is deprecated.'); + expect(result.success).toBe(true, result.errors); + }); + + describe('error messages', () => { + async function messagesFor(schema: JsonSchema, data: JsonValue): Promise { + const registry = new CoreSchemaRegistry(); + const validator = await registry.compile(schema); + const result = await validator(data); + expect(result.success).toBe(false); + + return SchemaValidationException.createMessages(result.errors); + } + + it('names an unknown option and the options that are valid there', async () => { + const messages = await messagesFor( + { + properties: { version: { type: 'number' }, projects: { type: 'object' } }, + additionalProperties: false, + }, + { allowedCommonJsDependencies: [] }, + ); + + expect(messages).toEqual([ + 'Unknown option "allowedCommonJsDependencies". Valid options are: version, projects.', + ]); + }); + + it('points at the object an unknown option was found in', async () => { + const messages = await messagesFor( + { + properties: { + cli: { + type: 'object', + properties: { cache: { type: 'object' }, packageManager: { type: 'string' } }, + additionalProperties: false, }, }, - objAllOk: { - allOf: [ - { type: 'object' }, - ], - }, - objAllBad: { - allOf: [ - { type: 'object' }, - { type: 'number' }, - ], - }, - objOne: { - oneOf: [ - { type: 'object' }, - ], - }, - objNotOk: { - not: { not: { type: 'object' } }, - }, - objNotBad: { - type: 'object', - not: { type: 'object' }, + }, + { cli: { completion: true } }, + ); + + expect(messages).toEqual([ + 'Unknown option "completion" at "/cli". Valid options are: cache, packageManager.', + ]); + }); + + it('looks through a $ref for the valid options', async () => { + const messages = await messagesFor( + { + $ref: '#/definitions/global', + definitions: { + global: { + type: 'object', + properties: { cli: { type: 'object' }, schematics: { type: 'object' } }, + additionalProperties: false, + }, }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.bool).toBeUndefined(); - expect(data.str).toBe('someString'); - expect(data.obj.num).toBeUndefined(); - expect(data.obj.other).toBe(0); - expect(data.objAllOk).toEqual({}); - expect(data.objOne).toEqual({}); - expect(data.objAllBad).toBeUndefined(); - expect(data.objNotOk).toEqual({}); - expect(data.objNotBad).toBeUndefined(); - }), - ) - .toPromise().then(done, done.fail); - }); + { version: 1 }, + ); - it('adds defaults to undefined properties', done => { - const registry = new CoreSchemaRegistry(); - registry.addPostTransform(addUndefinedDefaults); - // tslint:disable-line:no-any - const data: any = { - bool: undefined, - str: undefined, - obj: { - num: undefined, - }, - }; + expect(messages).toEqual(['Unknown option "version". Valid options are: cli, schematics.']); + }); - registry - .compile({ - properties: { - bool: { type: 'boolean', default: true }, - str: { type: 'string', default: 'someString' }, - obj: { - properties: { - num: { type: 'number', default: 0 }, + it('omits the valid options when the schema does not list any', async () => { + const messages = await messagesFor( + { + $ref: '#/definitions/cli', + definitions: { + cli: { + type: 'object', + patternProperties: { '^x-': { type: 'string' } }, + additionalProperties: false, }, }, }, - }) - .pipe( - mergeMap(validator => validator(data)), - map(result => { - expect(result.success).toBe(true); - expect(data.bool).toBe(true); - expect(data.str).toBe('someString'); - expect(data.obj.num).toBe(0); - }), - ) - .toPromise().then(done, done.fail); + { completion: true }, + ); + + expect(messages).toEqual(['Unknown option "completion".']); + }); + + it('leaves an error that is not about an unknown option alone', async () => { + const messages = await messagesFor( + { properties: { outputPath: { type: 'string' } } }, + { outputPath: 42 }, + ); + + expect(messages).toEqual(['Data path "/outputPath" must be string.']); + }); }); + describe('transform ordering', () => { + function createVisitor(name: string, calls: string[]): JsonVisitor { + return (value) => { + calls.push(name); + + return value; + }; + } + + async function run(registry: CoreSchemaRegistry): Promise { + const validator = await registry.compile({ type: 'string' }); + const result = await validator('value'); + expect(result.success).toBe(true); + } + + it('runs transforms in the order they were added', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(createVisitor('pre1', calls)); + registry.addPreTransform(createVisitor('pre2', calls)); + registry.addPostTransform(createVisitor('post1', calls)); + registry.addPostTransform(createVisitor('post2', calls)); + + await run(registry); + + expect(calls).toEqual(['pre1', 'pre2', 'post1', 'post2']); + }); + + it('only runs a transform once when it is added multiple times', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', calls); + registry.addPostTransform(first); + registry.addPostTransform(createVisitor('second', calls)); + registry.addPostTransform(first); + + await run(registry); + + expect(calls).toEqual(['first', 'second']); + }); + + it('runs a transform after its dependencies', async () => { + const calls: string[] = []; + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', calls); + const second = createVisitor('second', calls); + registry.addPostTransform(first); + registry.addPostTransform(second, [first]); + // Adding again with dependencies that already run earlier is a no-op. + registry.addPostTransform(second, [first]); + + await run(registry); + + expect(calls).toEqual(['first', 'second']); + }); + + it('throws when a dependency has not been added', () => { + const registry = new CoreSchemaRegistry(); + const missing = createVisitor('missing', []); + + expect(() => registry.addPreTransform(createVisitor('visitor', []), [missing])).toThrowError( + DependencyNotFoundException, + ); + }); + + it('throws when a transform depends on itself', () => { + const registry = new CoreSchemaRegistry(); + const visitor = createVisitor('visitor', []); + registry.addPreTransform(visitor); + + expect(() => registry.addPreTransform(visitor, [visitor])).toThrowError( + CircularDependencyFoundException, + ); + }); + + it('throws when an existing transform is given a dependency that runs after it', () => { + const registry = new CoreSchemaRegistry(); + const first = createVisitor('first', []); + const second = createVisitor('second', []); + registry.addPreTransform(first); + registry.addPreTransform(second); + + expect(() => registry.addPreTransform(first, [second])).toThrowError( + /already registered and runs before/, + ); + }); + }); }); diff --git a/packages/angular_devkit/core/src/json/schema/schema.ts b/packages/angular_devkit/core/src/json/schema/schema.ts index d7c5a653ebdc..1444d5aef1a9 100644 --- a/packages/angular_devkit/core/src/json/schema/schema.ts +++ b/packages/angular_devkit/core/src/json/schema/schema.ts @@ -1,12 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { clean } from '../../utils'; -import { JsonObject, isJsonObject } from '../interface'; + +import { JsonObject, JsonValue, isJsonObject } from '../utils'; /** * A specialized interface for JsonSchema (to come). JsonSchemas are also JsonObject. @@ -15,11 +15,8 @@ import { JsonObject, isJsonObject } from '../interface'; */ export type JsonSchema = JsonObject | boolean; - -// TODO: this should be unknown -// tslint:disable-next-line:no-any -export function isJsonSchema(value: any): value is JsonSchema { - return isJsonObject(value) || value === false || value === true; +export function isJsonSchema(value: unknown): value is JsonSchema { + return isJsonObject(value as JsonValue) || value === false || value === true; } /** @@ -29,7 +26,11 @@ export function isJsonSchema(value: any): value is JsonSchema { * @param schemas All schemas to be merged. */ export function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema { - return clean(schemas).reduce((prev, curr) => { + return schemas.reduce((prev, curr) => { + if (curr === undefined) { + return prev; + } + if (prev === false || curr === false) { return false; } else if (prev === true) { @@ -47,5 +48,5 @@ export function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema } else { return { ...prev, allOf: [prev, curr] }; } - }, true as JsonSchema); + }, true); } diff --git a/packages/angular_devkit/core/src/json/schema/transforms.ts b/packages/angular_devkit/core/src/json/schema/transforms.ts index 0407c62b63b5..1c97b7d1e9cc 100644 --- a/packages/angular_devkit/core/src/json/schema/transforms.ts +++ b/packages/angular_devkit/core/src/json/schema/transforms.ts @@ -1,27 +1,44 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonObject, JsonValue, isJsonObject } from '../interface'; + +import { JsonObject, JsonValue, isJsonArray, isJsonObject } from '../utils'; import { JsonPointer } from './interface'; import { JsonSchema } from './schema'; import { getTypesOfSchema } from './utility'; +export function addUndefinedObjectDefaults( + value: JsonValue, + _pointer: JsonPointer, + schema?: JsonSchema, +): JsonValue { + return transformUndefined(value, _pointer, schema, true); +} + export function addUndefinedDefaults( value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema, ): JsonValue { - if (schema === true || schema === false) { - return value; - } - if (schema === undefined) { + return transformUndefined(value, _pointer, schema, false); +} + +function transformUndefined( + value: JsonValue, + _pointer: JsonPointer, + schema?: JsonSchema, + onlyObjects?: boolean, +): JsonValue { + if (typeof schema === 'boolean' || schema === undefined) { return value; } + value ??= schema.default; + const types = getTypesOfSchema(schema); if (types.size === 0) { return value; @@ -45,7 +62,7 @@ export function addUndefinedDefaults( return value; } - if (type === 'array') { + if (!onlyObjects && type === 'array') { return value == undefined ? [] : value; } @@ -64,14 +81,39 @@ export function addUndefinedDefaults( } for (const [propName, schemaObject] of Object.entries(schema.properties)) { - if (newValue[propName] !== undefined || propName === '$schema') { + if (propName === '$schema' || !isJsonObject(schemaObject)) { continue; } - // TODO: Does not currently handle more complex schemas (oneOf/anyOf/etc.) - const defaultValue = (schemaObject as JsonObject).default; + const value = newValue[propName]; + if (value === undefined) { + newValue[propName] = schemaObject.default; + } else if (isJsonObject(value)) { + // Basic support for oneOf and anyOf. + const propertySchemas = schemaObject.oneOf || schemaObject.anyOf; + const allProperties = Object.keys(value); + // Locate a schema which declares all the properties that the object contains. + const adjustedSchema = + isJsonArray(propertySchemas) && + propertySchemas.find((s) => { + if (!isJsonObject(s)) { + return false; + } + + const schemaType = getTypesOfSchema(s); + if (schemaType.size === 1 && schemaType.has('object') && isJsonObject(s.properties)) { + const properties = Object.keys(s.properties); + + return allProperties.every((key) => properties.includes(key)); + } - newValue[propName] = defaultValue; + return false; + }); + + if (adjustedSchema && isJsonObject(adjustedSchema)) { + newValue[propName] = transformUndefined(value, _pointer, adjustedSchema, onlyObjects); + } + } } return newValue; diff --git a/packages/angular_devkit/core/src/json/schema/transforms_spec.ts b/packages/angular_devkit/core/src/json/schema/transforms_spec.ts new file mode 100644 index 000000000000..aa3de8c82471 --- /dev/null +++ b/packages/angular_devkit/core/src/json/schema/transforms_spec.ts @@ -0,0 +1,252 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { CoreSchemaRegistry } from './registry'; +import { addUndefinedDefaults } from './transforms'; + +describe('addUndefinedDefaults', () => { + it('should add defaults to undefined properties (1)', async () => { + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(addUndefinedDefaults); + const data: any = {}; // eslint-disable-line @typescript-eslint/no-explicit-any + + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean' }, + str: { type: 'string', default: 'someString' }, + obj: { + properties: { + num: { type: 'number' }, + other: { type: 'number', default: 0 }, + }, + }, + objAllOk: { + allOf: [{ type: 'object' }], + }, + objAllBad: { + allOf: [{ type: 'object' }, { type: 'number' }], + }, + objOne: { + oneOf: [{ type: 'object' }], + }, + objNotOk: { + not: { not: { type: 'object' } }, + }, + objNotBad: { + type: 'object', + not: { type: 'object' }, + }, + }, + }); + + const result = await validator(data); + + expect(result.success).toBeTrue(); + expect(data.bool).toBeUndefined(); + expect(data.str).toBe('someString'); + expect(data.obj.num).toBeUndefined(); + expect(data.obj.other).toBe(0); + expect(data.objAllOk).toEqual({}); + expect(data.objOne).toEqual({}); + expect(data.objAllBad).toBeUndefined(); + expect(data.objNotOk).toEqual({}); + expect(data.objNotBad).toBeUndefined(); + }); + + it('should add defaults to undefined properties (2)', async () => { + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(addUndefinedDefaults); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const data: any = { + bool: undefined, + str: undefined, + obj: { + num: undefined, + }, + }; + + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean', default: true }, + str: { type: 'string', default: 'someString' }, + obj: { + properties: { + num: { type: 'number', default: 0 }, + }, + }, + }, + }); + + const result = await validator(data); + + expect(result.success).toBeTrue(); + expect(data.bool).toBeTrue(); + expect(data.str).toBe('someString'); + expect(data.obj.num).toBe(0); + }); + + it('should add defaults to undefined properties when using oneOf', async () => { + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(addUndefinedDefaults); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dataNoObj: any = { + bool: undefined, + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dataObj: any = { + bool: undefined, + obj: { + a: false, + }, + }; + + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean', default: true }, + obj: { + default: true, + oneOf: [ + { + type: 'object', + properties: { + a: { type: 'boolean', default: true }, + b: { type: 'boolean', default: true }, + c: { type: 'boolean', default: false }, + }, + }, + { + type: 'boolean', + }, + ], + }, + noDefaultOneOf: { + oneOf: [ + { + type: 'object', + properties: { + a: { type: 'boolean', default: true }, + b: { type: 'boolean', default: true }, + c: { type: 'boolean', default: false }, + }, + }, + { + type: 'boolean', + }, + ], + }, + }, + }); + + const result1 = await validator(dataNoObj); + expect(result1.success).toBeTrue(); + expect(dataNoObj.bool).toBeTrue(); + expect(dataNoObj.obj).toBeTrue(); + expect(dataNoObj.noDefaultOneOf).toBeUndefined(); + + const result2 = await validator(dataObj); + expect(result2.success).toBeTrue(); + expect(dataObj.bool).toBeTrue(); + expect(dataObj.obj.a).toBeFalse(); + expect(dataObj.obj.b).toBeTrue(); + expect(dataObj.obj.c).toBeFalse(); + }); + + it('should add defaults to undefined properties when using anyOf', async () => { + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(addUndefinedDefaults); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dataNoObj: any = { + bool: undefined, + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dataObj: any = { + bool: undefined, + obj: { + a: false, + }, + }; + + const validator = await registry.compile({ + properties: { + bool: { type: 'boolean', default: true }, + obj: { + default: true, + anyOf: [ + { + type: 'object', + properties: { + d: { type: 'boolean', default: false }, + }, + }, + { + type: 'object', + properties: { + a: { type: 'boolean', default: true }, + b: { type: 'boolean', default: true }, + c: { type: 'boolean', default: false }, + }, + }, + { + type: 'boolean', + }, + ], + }, + }, + }); + + const result1 = await validator(dataNoObj); + expect(result1.success).toBeTrue(); + expect(dataNoObj.bool).toBeTrue(); + expect(dataNoObj.obj).toBeTrue(); + + const result2 = await validator(dataObj); + expect(result2.success).toBeTrue(); + expect(dataObj.bool).toBeTrue(); + expect(dataObj.obj.a).toBeFalse(); + expect(dataObj.obj.b).toBeTrue(); + expect(dataObj.obj.c).toBeFalse(); + }); + + it('should add defaults to undefined properties when using $refs', async () => { + const registry = new CoreSchemaRegistry(); + registry.addPreTransform(addUndefinedDefaults); + const dataNoObj: Record = {}; + + const dataObj: Record = { + boolRef: true, + }; + + const validator = await registry.compile({ + definitions: { + boolRef: { + default: false, + type: 'boolean', + }, + }, + properties: { + bool: { + default: false, + type: 'boolean', + }, + boolRef: { + $ref: '#/definitions/boolRef', + }, + }, + }); + + const result1 = await validator(dataNoObj); + expect(result1.success).toBeTrue(); + expect(dataNoObj['bool']).toBeFalse(); + expect(dataNoObj['boolRef']).toBeFalse(); + + const result2 = await validator(dataObj); + expect(result2.success).toBeTrue(); + expect(dataObj['bool']).toBeFalse(); + expect(dataObj['boolRef']).toBeTrue(); + }); +}); diff --git a/packages/angular_devkit/core/src/json/schema/utility.ts b/packages/angular_devkit/core/src/json/schema/utility.ts index 00b4a8278343..83bc336e0952 100644 --- a/packages/angular_devkit/core/src/json/schema/utility.ts +++ b/packages/angular_devkit/core/src/json/schema/utility.ts @@ -1,13 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonObject, isJsonArray, isJsonObject } from '../interface'; -import { JsonSchema } from './schema'; +import { JsonObject, isJsonArray, isJsonObject } from '../utils'; +import { JsonSchema } from './schema'; const allTypes = ['string', 'integer', 'number', 'object', 'array', 'boolean', 'null']; @@ -53,13 +53,13 @@ export function getTypesOfSchema(schema: JsonSchema): Set { if (isJsonObject(schema.not)) { const notTypes = getTypesOfSchema(schema.not); - potentials = new Set([...potentials].filter(p => !notTypes.has(p))); + potentials = potentials.difference(notTypes); } if (Array.isArray(schema.allOf)) { for (const sub of schema.allOf) { const types = getTypesOfSchema(sub as JsonObject); - potentials = new Set([...types].filter(t => potentials.has(t))); + potentials = new Set([...types].filter((t) => potentials.has(t))); } } @@ -67,18 +67,18 @@ export function getTypesOfSchema(schema: JsonSchema): Set { let options = new Set(); for (const sub of schema.oneOf) { const types = getTypesOfSchema(sub as JsonObject); - options = new Set([...options, ...types]); + options = options.union(types); } - potentials = new Set([...options].filter(o => potentials.has(o))); + potentials = new Set([...options].filter((o) => potentials.has(o))); } if (Array.isArray(schema.anyOf)) { let options = new Set(); for (const sub of schema.anyOf) { const types = getTypesOfSchema(sub as JsonObject); - options = new Set([...options, ...types]); + options = options.union(types); } - potentials = new Set([...options].filter(o => potentials.has(o))); + potentials = new Set([...options].filter((o) => potentials.has(o))); } if (schema.properties) { diff --git a/packages/angular_devkit/core/src/json/schema/visitor.ts b/packages/angular_devkit/core/src/json/schema/visitor.ts index 194c29eef4fe..f7094615e56e 100644 --- a/packages/angular_devkit/core/src/json/schema/visitor.ts +++ b/packages/angular_devkit/core/src/json/schema/visitor.ts @@ -1,13 +1,23 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { Observable, concat, from, isObservable, of as observableOf } from 'rxjs'; -import { concatMap, ignoreElements, mergeMap, tap } from 'rxjs/operators'; -import { JsonArray, JsonObject, JsonValue } from '../interface'; + +import { + Observable, + concat, + concatMap, + from, + ignoreElements, + isObservable, + mergeMap, + of as observableOf, + tap, +} from 'rxjs'; +import { JsonArray, JsonObject, JsonValue } from '../utils'; import { JsonPointer, JsonSchemaVisitor, JsonVisitor } from './interface'; import { buildJsonPointer, joinJsonPointer } from './pointer'; import { JsonSchema } from './schema'; @@ -57,9 +67,10 @@ function _visitJsonRecursive( // There's no schema definition, so just visit the JSON recursively. schema = undefined; } + // eslint-disable-next-line no-prototype-builtins if (schema && schema.hasOwnProperty('$ref') && typeof schema['$ref'] == 'string') { if (refResolver) { - const resolved = refResolver(schema['$ref'] as string, context); + const resolved = refResolver(schema['$ref'], context); schema = resolved.schema; context = resolved.context; } @@ -67,8 +78,8 @@ function _visitJsonRecursive( const value = visitor(json, ptr, schema as JsonObject, root); - return (isObservable(value) ? value : observableOf(value)).pipe( - concatMap(value => { + return (isObservable(value) ? value : observableOf(value)).pipe( + concatMap((value) => { if (Array.isArray(value)) { return concat( from(value).pipe( @@ -81,7 +92,7 @@ function _visitJsonRecursive( refResolver, context, root || value, - ).pipe(tap(x => (value[i] = x))); + ).pipe(tap((x) => (value[i] = x))); }), ignoreElements(), ), @@ -90,7 +101,7 @@ function _visitJsonRecursive( } else if (typeof value == 'object' && value !== null) { return concat( from(Object.getOwnPropertyNames(value)).pipe( - mergeMap(key => { + mergeMap((key) => { return _visitJsonRecursive( value[key], visitor, @@ -100,7 +111,7 @@ function _visitJsonRecursive( context, root || value, ).pipe( - tap(x => { + tap((x) => { const descriptor = Object.getOwnPropertyDescriptor(value, key); if (descriptor && descriptor.writable && value[key] !== x) { value[key] = x; @@ -144,7 +155,7 @@ export function visitJson( return _visitJsonRecursive(json, visitor, buildJsonPointer([]), schema, refResolver, context); } -export function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor) { +export function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor): void { if (schema === false || schema === true) { // Nothing to visit. return; diff --git a/packages/angular_devkit/core/src/json/schema/visitor_spec.ts b/packages/angular_devkit/core/src/json/schema/visitor_spec.ts index e938ccd56216..38cde5732e3e 100644 --- a/packages/angular_devkit/core/src/json/schema/visitor_spec.ts +++ b/packages/angular_devkit/core/src/json/schema/visitor_spec.ts @@ -1,37 +1,36 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable, from } from 'rxjs'; import { JsonObject, JsonValue } from '..'; import { visitJson } from './visitor'; - function syncObs(obs: Observable): T { let value: T; let set = false; obs - .forEach(x => { + .forEach((x) => { if (set) { throw new Error('Multiple value.'); } value = x; set = true; }) - .catch(err => fail(err)); + .catch((err) => fail(err)); if (!set) { throw new Error('Async observable.'); } - return value !; // tslint:disable-line:no-non-null-assertion + return value!; // eslint-disable-line @typescript-eslint/no-non-null-assertion } - describe('visitJson', () => { it('works to replace the root', () => { const json = { a: 1 }; @@ -45,13 +44,15 @@ describe('visitJson', () => { const json = { a: 1 }; const newJson = { b: 'hello ' }; - const result = syncObs(visitJson(json, value => { - if (typeof value == 'object') { - return newJson; - } else { - return value + 'world'; - } - })); + const result = syncObs( + visitJson(json, (value) => { + if (typeof value == 'object') { + return newJson; + } else { + return value + 'world'; + } + }), + ); expect(result).toEqual({ b: 'hello world' }); expect(newJson).toEqual({ b: 'hello world' }); }); @@ -62,32 +63,34 @@ describe('visitJson', () => { const newJson2 = { c: [] }; const newJson3 = [1, 2, 3]; - const result = syncObs(visitJson(json, (value, ptr) => { - if (ptr.endsWith('a')) { - return newJson; - } else if (ptr.endsWith('b')) { - return newJson2; - } else if (ptr.endsWith('c')) { - return newJson3; - } else if (typeof value == 'number') { - return '_' + value; - } else if (ptr == '/') { - return value; - } else { - return 'abc'; - } - })); + const result = syncObs( + visitJson(json, (value, ptr) => { + if (ptr.endsWith('a')) { + return newJson; + } else if (ptr.endsWith('b')) { + return newJson2; + } else if (ptr.endsWith('c')) { + return newJson3; + } else if (typeof value == 'number') { + return '_' + value; + } else if (ptr == '/') { + return value; + } else { + return 'abc'; + } + }), + ); expect(result).toEqual({ a: { b: { c: ['_1', '_2', '_3'] } } }); }); - it('goes through all replacements recursively (async)', done => { + it('goes through all replacements recursively (async)', async () => { const json = { a: 1 }; const newJson = { b: '' }; const newJson2 = { c: [] }; const newJson3 = [1, 2, 3]; - visitJson(json, (value, ptr) => { + const result = await visitJson(json, (value, ptr) => { if (ptr.endsWith('a')) { return from(Promise.resolve(newJson)); } else if (ptr.endsWith('b')) { @@ -101,13 +104,9 @@ describe('visitJson', () => { } else { return from(Promise.resolve('abc')); } - }).toPromise().then( - result => { - expect(result).toEqual({ a: { b: { c: ['_1', '_2', '_3'] } } }); - done(); - }, - done.fail, - ); + }).toPromise(); + + expect(result).toEqual({ a: { b: { c: ['_1', '_2', '_3'] } } }); }); it('works with schema', () => { diff --git a/packages/angular_devkit/core/src/json/utils.ts b/packages/angular_devkit/core/src/json/utils.ts new file mode 100644 index 000000000000..8233fe9670a2 --- /dev/null +++ b/packages/angular_devkit/core/src/json/utils.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface JsonArray extends Array {} + +export interface JsonObject { + [prop: string]: JsonValue; +} + +export type JsonValue = boolean | string | number | JsonArray | JsonObject | null; + +export function isJsonObject(value: JsonValue): value is JsonObject { + return value != null && typeof value === 'object' && !Array.isArray(value); +} + +export function isJsonArray(value: JsonValue): value is JsonArray { + return Array.isArray(value); +} diff --git a/packages/angular_devkit/core/src/logger/indent.ts b/packages/angular_devkit/core/src/logger/indent.ts index 7eb1958fc855..e1174137cfca 100644 --- a/packages/angular_devkit/core/src/logger/indent.ts +++ b/packages/angular_devkit/core/src/logger/indent.ts @@ -1,13 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { map } from 'rxjs/operators'; -import { Logger } from './logger'; +import { map } from 'rxjs'; +import { Logger } from './logger'; /** * Keep an map of indentation => array of indentations based on the level. @@ -16,8 +16,7 @@ import { Logger } from './logger'; * loggers. Also, string concatenation is expensive so performing concats for every log entries * is expensive; this alleviates it. */ -const indentationMap: {[indentationType: string]: string[]} = {}; - +const indentationMap: { [indentationType: string]: string[] } = {}; export class IndentLogger extends Logger { constructor(name: string, parent: Logger | null = null, indentation = ' ') { @@ -26,19 +25,21 @@ export class IndentLogger extends Logger { indentationMap[indentation] = indentationMap[indentation] || ['']; const indentMap = indentationMap[indentation]; - this._observable = this._observable.pipe(map(entry => { - const l = entry.path.filter(x => !!x).length; - if (l >= indentMap.length) { - let current = indentMap[indentMap.length - 1]; - while (l >= indentMap.length) { - current += indentation; - indentMap.push(current); + this._observable = this._observable.pipe( + map((entry) => { + const l = entry.path.filter((x) => !!x).length; + if (l >= indentMap.length) { + let current = indentMap[indentMap.length - 1]; + while (l >= indentMap.length) { + current += indentation; + indentMap.push(current); + } } - } - entry.message = indentMap[l] + entry.message.split(/\n/).join('\n' + indentMap[l]); + entry.message = indentMap[l] + entry.message.split(/\n/).join('\n' + indentMap[l]); - return entry; - })); + return entry; + }), + ); } } diff --git a/packages/angular_devkit/core/src/logger/indent_spec.ts b/packages/angular_devkit/core/src/logger/indent_spec.ts index a35ed3307a96..c457bb1619d2 100644 --- a/packages/angular_devkit/core/src/logger/indent_spec.ts +++ b/packages/angular_devkit/core/src/logger/indent_spec.ts @@ -1,21 +1,20 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any -import { toArray } from 'rxjs/operators'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { lastValueFrom, toArray } from 'rxjs'; import { IndentLogger } from './indent'; import { LogEntry, Logger } from './logger'; - describe('IndentSpec', () => { it('works', (done: DoneFn) => { const logger = new IndentLogger('test'); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: LogEntry[]) => { expect(observed).toEqual([ jasmine.objectContaining({ message: 'test', level: 'info', name: 'test' }) as any, @@ -25,7 +24,10 @@ describe('IndentSpec', () => { jasmine.objectContaining({ message: 'test5', level: 'info', name: 'test' }) as any, ]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); const logger2 = new Logger('test2', logger); const logger3 = new Logger('test3', logger2); const logger4 = new Logger('test4', logger); diff --git a/packages/angular_devkit/core/src/logger/index.ts b/packages/angular_devkit/core/src/logger/index.ts index 63bc0860b0c8..3615d593f1da 100644 --- a/packages/angular_devkit/core/src/logger/index.ts +++ b/packages/angular_devkit/core/src/logger/index.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + export * from './indent'; export * from './level'; export * from './logger'; diff --git a/packages/angular_devkit/core/src/logger/level.ts b/packages/angular_devkit/core/src/logger/level.ts index 7de3255d90c5..244c48fe56d4 100644 --- a/packages/angular_devkit/core/src/logger/level.ts +++ b/packages/angular_devkit/core/src/logger/level.ts @@ -1,33 +1,34 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonObject } from '../json/interface'; + +import { JsonObject } from '../json/utils'; import { LogLevel, Logger } from './logger'; export class LevelTransformLogger extends Logger { constructor( - public readonly name: string, - public readonly parent: Logger | null = null, + public override readonly name: string, + public override readonly parent: Logger | null, public readonly levelTransform: (level: LogLevel) => LogLevel, ) { super(name, parent); } - log(level: LogLevel, message: string, metadata: JsonObject = {}): void { + override log(level: LogLevel, message: string, metadata: JsonObject = {}): void { return super.log(this.levelTransform(level), message, metadata); } - createChild(name: string): Logger { + override createChild(name: string): Logger { return new LevelTransformLogger(name, this, this.levelTransform); } } export class LevelCapLogger extends LevelTransformLogger { - static levelMap: {[cap: string]: {[level: string]: string}} = { + static levelMap: { [cap: string]: { [level: string]: string } } = { debug: { debug: 'debug', info: 'debug', warn: 'debug', error: 'debug', fatal: 'debug' }, info: { debug: 'debug', info: 'info', warn: 'info', error: 'info', fatal: 'info' }, warn: { debug: 'debug', info: 'info', warn: 'warn', error: 'warn', fatal: 'warn' }, @@ -36,8 +37,8 @@ export class LevelCapLogger extends LevelTransformLogger { }; constructor( - public readonly name: string, - public readonly parent: Logger | null = null, + public override readonly name: string, + public override readonly parent: Logger | null, public readonly levelCap: LogLevel, ) { super(name, parent, (level: LogLevel) => { diff --git a/packages/angular_devkit/core/src/logger/logger.ts b/packages/angular_devkit/core/src/logger/logger.ts index 08bb66a117cd..256e6b219e5e 100644 --- a/packages/angular_devkit/core/src/logger/logger.ts +++ b/packages/angular_devkit/core/src/logger/logger.ts @@ -1,13 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { Observable, Operator, PartialObserver, Subject, Subscription } from 'rxjs'; -import { JsonObject } from '../json/interface'; +import { EMPTY, Observable, Operator, PartialObserver, Subject, Subscription } from 'rxjs'; +import { JsonObject } from '../json/utils'; export interface LoggerMetadata extends JsonObject { name: string; @@ -30,39 +30,47 @@ export interface LoggerApi { export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; - export class Logger extends Observable implements LoggerApi { protected readonly _subject: Subject = new Subject(); protected _metadata: LoggerMetadata; - private _obs: Observable; - private _subscription: Subscription | null; + private _obs: Observable = EMPTY; + private _subscription: Subscription | null = null; - protected get _observable() { return this._obs; } + protected get _observable() { + return this._obs; + } protected set _observable(v: Observable) { if (this._subscription) { this._subscription.unsubscribe(); } this._obs = v; if (this.parent) { - this._subscription = this.subscribe((value: LogEntry) => { - if (this.parent) { - this.parent._subject.next(value); - } - }, (error: Error) => { - if (this.parent) { - this.parent._subject.error(error); - } - }, () => { - if (this._subscription) { - this._subscription.unsubscribe(); - } - this._subscription = null; - }); + this._subscription = this.subscribe( + (value: LogEntry) => { + if (this.parent) { + this.parent._subject.next(value); + } + }, + (error: Error) => { + if (this.parent) { + this.parent._subject.error(error); + } + }, + () => { + if (this._subscription) { + this._subscription.unsubscribe(); + } + this._subscription = null; + }, + ); } } - constructor(public readonly name: string, public readonly parent: Logger | null = null) { + constructor( + public readonly name: string, + public readonly parent: Logger | null = null, + ) { super(); const path: string[] = []; @@ -93,17 +101,19 @@ export class Logger extends Observable implements LoggerApi { }; } - createChild(name: string) { + createChild(name: string): Logger { return new (this.constructor as typeof Logger)(name, this); } - complete() { + complete(): void { this._subject.complete(); } log(level: LogLevel, message: string, metadata: JsonObject = {}): void { const entry: LogEntry = Object.assign({}, metadata, this._metadata, { - level, message, timestamp: +Date.now(), + level, + message, + timestamp: +Date.now(), }); this._subject.next(entry); } @@ -111,40 +121,54 @@ export class Logger extends Observable implements LoggerApi { this._subject.next(entry); } - debug(message: string, metadata: JsonObject = {}) { - return this.log('debug', message, metadata); + debug(message: string, metadata: JsonObject = {}): void { + this.log('debug', message, metadata); } - info(message: string, metadata: JsonObject = {}) { - return this.log('info', message, metadata); + info(message: string, metadata: JsonObject = {}): void { + this.log('info', message, metadata); } - warn(message: string, metadata: JsonObject = {}) { - return this.log('warn', message, metadata); + warn(message: string, metadata: JsonObject = {}): void { + this.log('warn', message, metadata); } - error(message: string, metadata: JsonObject = {}) { - return this.log('error', message, metadata); + error(message: string, metadata: JsonObject = {}): void { + this.log('error', message, metadata); } - fatal(message: string, metadata: JsonObject = {}) { - return this.log('fatal', message, metadata); + fatal(message: string, metadata: JsonObject = {}): void { + this.log('fatal', message, metadata); } - toString() { + override toString() { return ``; } - lift(operator: Operator): Observable { + override lift(operator: Operator): Observable { return this._observable.lift(operator); } - subscribe(): Subscription; - subscribe(observer: PartialObserver): Subscription; - subscribe(next?: (value: LogEntry) => void, error?: (error: Error) => void, - complete?: () => void): Subscription; - subscribe(_observerOrNext?: PartialObserver | ((value: LogEntry) => void), - _error?: (error: Error) => void, - _complete?: () => void): Subscription { - return this._observable.subscribe.apply(this._observable, arguments); - } - forEach(next: (value: LogEntry) => void, PromiseCtor?: typeof Promise): Promise { - return this._observable.forEach(next, PromiseCtor); + override subscribe(): Subscription; + override subscribe(observer: PartialObserver): Subscription; + override subscribe( + next?: (value: LogEntry) => void, + error?: (error: Error) => void, + complete?: () => void, + ): Subscription; + override subscribe( + _observerOrNext?: PartialObserver | ((value: LogEntry) => void), + _error?: (error: Error) => void, + _complete?: () => void, + ): Subscription { + // eslint-disable-next-line prefer-spread + return this._observable.subscribe.apply( + this._observable, + // eslint-disable-next-line prefer-rest-params + arguments as unknown as Parameters['subscribe']>, + ); + } + + override forEach( + next: (value: LogEntry) => void, + promiseCtor: PromiseConstructorLike = Promise, + ): Promise { + return this._observable.forEach(next, promiseCtor); } } diff --git a/packages/angular_devkit/core/src/logger/logger_spec.ts b/packages/angular_devkit/core/src/logger/logger_spec.ts index 50439ca9a452..1060d3f5b247 100644 --- a/packages/angular_devkit/core/src/logger/logger_spec.ts +++ b/packages/angular_devkit/core/src/logger/logger_spec.ts @@ -1,28 +1,30 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any -import { toArray } from 'rxjs/operators'; -import { JsonValue } from '../json/interface'; -import { Logger } from './logger'; +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { lastValueFrom, toArray } from 'rxjs'; +import { JsonValue } from '../json/utils'; +import { Logger } from './logger'; describe('Logger', () => { it('works', (done: DoneFn) => { const logger = new Logger('test'); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: JsonValue[]) => { expect(observed).toEqual([ - jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'test' }) as any, - jasmine.objectContaining({ message: 'world', level: 'info', name: 'test' }) as any, + jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'test' }), + jasmine.objectContaining({ message: 'world', level: 'info', name: 'test' }), ]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); logger.debug('hello'); logger.info('world'); @@ -32,8 +34,7 @@ describe('Logger', () => { it('works with children', (done: DoneFn) => { const logger = new Logger('test'); let hasCompleted = false; - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: JsonValue[]) => { expect(observed).toEqual([ jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'child' }) as any, @@ -41,10 +42,13 @@ describe('Logger', () => { ]); expect(hasCompleted).toBe(true); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); const childLogger = new Logger('child', logger); - childLogger.subscribe(undefined, undefined, () => hasCompleted = true); + childLogger.subscribe(undefined, undefined, () => (hasCompleted = true)); childLogger.debug('hello'); childLogger.info('world'); logger.complete(); @@ -54,14 +58,16 @@ describe('Logger', () => { const logger = new Logger('test'); logger.debug('woah'); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: JsonValue[]) => { expect(observed).toEqual([ jasmine.objectContaining({ message: 'hello', level: 'debug', name: 'test' }) as any, ]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); logger.debug('hello'); logger.complete(); diff --git a/packages/angular_devkit/core/src/logger/null-logger.ts b/packages/angular_devkit/core/src/logger/null-logger.ts index 4a687840a1c3..f5f40dfb0f7b 100644 --- a/packages/angular_devkit/core/src/logger/null-logger.ts +++ b/packages/angular_devkit/core/src/logger/null-logger.ts @@ -1,21 +1,21 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { EMPTY } from 'rxjs'; import { Logger, LoggerApi } from './logger'; - export class NullLogger extends Logger { constructor(parent: Logger | null = null) { super('', parent); this._observable = EMPTY; } - asApi(): LoggerApi { + override asApi(): LoggerApi { return { createChild: () => new NullLogger(this), log() {}, diff --git a/packages/angular_devkit/core/src/logger/null-logger_spec.ts b/packages/angular_devkit/core/src/logger/null-logger_spec.ts index 52f1936e48f9..3d99cf674da9 100644 --- a/packages/angular_devkit/core/src/logger/null-logger_spec.ts +++ b/packages/angular_devkit/core/src/logger/null-logger_spec.ts @@ -1,24 +1,26 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { toArray } from 'rxjs/operators'; + +import { lastValueFrom, toArray } from 'rxjs'; import { LogEntry, Logger } from './logger'; import { NullLogger } from './null-logger'; - describe('NullLogger', () => { it('works', (done: DoneFn) => { const logger = new NullLogger(); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: LogEntry[]) => { expect(observed).toEqual([]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); logger.debug('hello'); logger.info('world'); @@ -27,12 +29,14 @@ describe('NullLogger', () => { it('nullifies children', (done: DoneFn) => { const logger = new Logger('test'); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: LogEntry[]) => { expect(observed).toEqual([]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); const nullLogger = new NullLogger(logger); const child = new Logger('test', nullLogger); diff --git a/packages/angular_devkit/core/src/logger/transform-logger.ts b/packages/angular_devkit/core/src/logger/transform-logger.ts index 4d024fd2ffb2..de4c1ba449cb 100644 --- a/packages/angular_devkit/core/src/logger/transform-logger.ts +++ b/packages/angular_devkit/core/src/logger/transform-logger.ts @@ -1,18 +1,20 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable } from 'rxjs'; import { LogEntry, Logger } from './logger'; - export class TransformLogger extends Logger { - constructor(name: string, - transform: (stream: Observable) => Observable, - parent: Logger | null = null) { + constructor( + name: string, + transform: (stream: Observable) => Observable, + parent: Logger | null = null, + ) { super(name, parent); this._observable = transform(this._observable); } diff --git a/packages/angular_devkit/core/src/logger/transform-logger_spec.ts b/packages/angular_devkit/core/src/logger/transform-logger_spec.ts index d99e2f87269c..2d8b04be7f7b 100644 --- a/packages/angular_devkit/core/src/logger/transform-logger_spec.ts +++ b/packages/angular_devkit/core/src/logger/transform-logger_spec.ts @@ -1,31 +1,34 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any -import { filter, map, toArray } from 'rxjs/operators'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { filter, lastValueFrom, map, toArray } from 'rxjs'; import { LogEntry } from './logger'; import { TransformLogger } from './transform-logger'; - describe('TransformLogger', () => { it('works', (done: DoneFn) => { - const logger = new TransformLogger('test', stream => { + const logger = new TransformLogger('test', (stream) => { return stream.pipe( - filter(entry => entry.message != 'hello'), - map(entry => (entry.message += '1', entry))); + filter((entry) => entry.message != 'hello'), + map((entry) => ((entry.message += '1'), entry)), + ); }); - logger.pipe(toArray()) - .toPromise() + lastValueFrom(logger.pipe(toArray())) .then((observed: LogEntry[]) => { expect(observed).toEqual([ jasmine.objectContaining({ message: 'world1', level: 'info', name: 'test' }) as any, ]); }) - .then(() => done(), err => done.fail(err)); + .then( + () => done(), + (err) => done.fail(err), + ); logger.debug('hello'); logger.info('world'); diff --git a/packages/angular_devkit/core/src/terminal/caps.ts b/packages/angular_devkit/core/src/terminal/caps.ts deleted file mode 100644 index 2dc11534a0f0..000000000000 --- a/packages/angular_devkit/core/src/terminal/caps.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import ReadableStream = NodeJS.ReadableStream; -import WriteStream = NodeJS.WriteStream; -import Socket = NodeJS.Socket; -const supportsColor = require('../../third_party/github.com/chalk/supports-color'); - -/** - * Node specific stuff. - */ -declare const process: { - env: { [name: string]: string }; - platform: string; - versions: { - node: string; - }; - - stdin: ReadableStream; - stdout: WriteStream; - stderr: WriteStream; -}; -declare const os: { - release: () => string; -}; - - -const streamMap = new WeakMap<{}, StreamCapabilities>(); - - -export interface StreamCapabilities { - readable: boolean; - writable: boolean; - - /** - * Supports text. This should be true for any streams. - */ - text: boolean; - - /** - * Supports colors (16 colors). - */ - colors: boolean; - - /** - * Supports 256 colors. - */ - color256: boolean; - - /** - * Supports 16 millions (3x8-bit channels) colors. - */ - color16m: boolean; - - /** - * Height of the terminal. If the stream is not tied to a terminal, will be null. - */ - rows: number | null; - - /** - * Width of the terminal. If the stream is not tied to a terminal, will be null. - */ - columns: number | null; -} - -function _getRows() { - return typeof process == 'object' && process.stdout.rows || null; -} -function _getColumns() { - return typeof process == 'object' && process.stdout.columns || null; -} - - -function _createCapabilities( - stream: Socket, - isTerminalStream: boolean, - level: 0|1|2|3 = supportsColor.stdout.level, -): StreamCapabilities { - return { - readable: stream.readable, - writable: stream.writable, - text: true, - - colors: level > 0, - color256: level > 1, - color16m: level > 2, - - rows: isTerminalStream ? _getRows() : null, - columns: isTerminalStream ? _getColumns() : null, - }; -} - - -export function getCapabilities( - stream: Socket, - isTerminalStream = !!stream.isTTY, -): StreamCapabilities { - let maybeCaps = streamMap.get(stream); - if (!maybeCaps) { - maybeCaps = _createCapabilities(stream, isTerminalStream); - streamMap.set(stream, maybeCaps); - } - - return maybeCaps; -} diff --git a/packages/angular_devkit/core/src/terminal/colors.ts b/packages/angular_devkit/core/src/terminal/colors.ts deleted file mode 100644 index 1494ec04bcb6..000000000000 --- a/packages/angular_devkit/core/src/terminal/colors.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { mapObject } from '../utils/object'; - -const kColors = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - }, -}; -const kColorFunctions = mapObject(kColors, (_, v) => { - return mapObject(v, (_, vv) => (x: string) => `\u001b[${vv[0]}m${x}\u001b[${vv[1]}m`); -}); - -export namespace colors { - export const reset = kColorFunctions.modifiers.reset; - export const bold = kColorFunctions.modifiers.bold; - export const dim = kColorFunctions.modifiers.dim; - export const italic = kColorFunctions.modifiers.italic; - export const underline = kColorFunctions.modifiers.underline; - export const inverse = kColorFunctions.modifiers.inverse; - export const hidden = kColorFunctions.modifiers.hidden; - export const strikethrough = kColorFunctions.modifiers.strikethrough; - - export const black = kColorFunctions.colors.black; - export const red = kColorFunctions.colors.red; - export const green = kColorFunctions.colors.green; - export const yellow = kColorFunctions.colors.yellow; - export const blue = kColorFunctions.colors.blue; - export const magenta = kColorFunctions.colors.magenta; - export const cyan = kColorFunctions.colors.cyan; - export const white = kColorFunctions.colors.white; - export const grey = kColorFunctions.colors.gray; - export const gray = kColorFunctions.colors.gray; - - export const bgBlack = kColorFunctions.bgColors.bgBlack; - export const bgRed = kColorFunctions.bgColors.bgRed; - export const bgGreen = kColorFunctions.bgColors.bgGreen; - export const bgYellow = kColorFunctions.bgColors.bgYellow; - export const bgBlue = kColorFunctions.bgColors.bgBlue; - export const bgMagenta = kColorFunctions.bgColors.bgMagenta; - export const bgCyan = kColorFunctions.bgColors.bgCyan; - export const bgWhite = kColorFunctions.bgColors.bgWhite; -} diff --git a/packages/angular_devkit/core/src/terminal/index.ts b/packages/angular_devkit/core/src/terminal/index.ts deleted file mode 100644 index d853f3c1c9bb..000000000000 --- a/packages/angular_devkit/core/src/terminal/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -export * from './text'; -export * from './caps'; -export * from './colors'; diff --git a/packages/angular_devkit/core/src/terminal/text.ts b/packages/angular_devkit/core/src/terminal/text.ts deleted file mode 100644 index 4d1654e36ad3..000000000000 --- a/packages/angular_devkit/core/src/terminal/text.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import * as caps from './caps'; -import { colors } from './colors'; - -const stdout = typeof process == 'object' - ? caps.getCapabilities(process.stdout) : { colors: false }; - -export const reset = stdout.colors ? colors.reset : (x: string) => x; -export const bold = stdout.colors ? colors.bold : (x: string) => x; -export const dim = stdout.colors ? colors.dim : (x: string) => x; -export const italic = stdout.colors ? colors.italic : (x: string) => x; -export const underline = stdout.colors ? colors.underline : (x: string) => x; -export const inverse = stdout.colors ? colors.inverse : (x: string) => x; -export const hidden = stdout.colors ? colors.hidden : (x: string) => x; -export const strikethrough = stdout.colors ? colors.strikethrough : (x: string) => x; - -export const black = stdout.colors ? colors.black : (x: string) => x; -export const red = stdout.colors ? colors.red : (x: string) => x; -export const green = stdout.colors ? colors.green : (x: string) => x; -export const yellow = stdout.colors ? colors.yellow : (x: string) => x; -export const blue = stdout.colors ? colors.blue : (x: string) => x; -export const magenta = stdout.colors ? colors.magenta : (x: string) => x; -export const cyan = stdout.colors ? colors.cyan : (x: string) => x; -export const white = stdout.colors ? colors.white : (x: string) => x; -export const grey = stdout.colors ? colors.gray : (x: string) => x; -export const gray = stdout.colors ? colors.gray : (x: string) => x; - -export const bgBlack = stdout.colors ? colors.bgBlack : (x: string) => x; -export const bgRed = stdout.colors ? colors.bgRed : (x: string) => x; -export const bgGreen = stdout.colors ? colors.bgGreen : (x: string) => x; -export const bgYellow = stdout.colors ? colors.bgYellow : (x: string) => x; -export const bgBlue = stdout.colors ? colors.bgBlue : (x: string) => x; -export const bgMagenta = stdout.colors ? colors.bgMagenta : (x: string) => x; -export const bgCyan = stdout.colors ? colors.bgCyan : (x: string) => x; -export const bgWhite = stdout.colors ? colors.bgWhite : (x: string) => x; diff --git a/packages/angular_devkit/core/src/utils/array.ts b/packages/angular_devkit/core/src/utils/array.ts deleted file mode 100644 index e1969c175723..000000000000 --- a/packages/angular_devkit/core/src/utils/array.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export function clean(array: Array): Array { - return array.filter(x => x !== undefined) as Array; -} diff --git a/packages/angular_devkit/core/src/utils/index.ts b/packages/angular_devkit/core/src/utils/index.ts index 5e6749ee9b95..cf9570c91858 100644 --- a/packages/angular_devkit/core/src/utils/index.ts +++ b/packages/angular_devkit/core/src/utils/index.ts @@ -1,14 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import * as tags from './literals'; import * as strings from './strings'; -export * from './array'; export * from './object'; export * from './template'; export * from './partially-ordered-set'; @@ -16,20 +16,3 @@ export * from './priority-queue'; export * from './lang'; export { tags, strings }; - -export type DeepReadonly = - T extends (infer R)[] ? DeepReadonlyArray : - T extends Function ? T : - T extends object ? DeepReadonlyObject : - T; - -// This should be ReadonlyArray but it has implications. -export interface DeepReadonlyArray extends Array> {} - -export type DeepReadonlyObject = { - readonly [P in keyof T]: DeepReadonly; -}; - -export type Readwrite = { - -readonly [P in keyof T]: T[P]; -}; diff --git a/packages/angular_devkit/core/src/utils/lang.ts b/packages/angular_devkit/core/src/utils/lang.ts index cca193771732..ca59b945cbc8 100644 --- a/packages/angular_devkit/core/src/utils/lang.ts +++ b/packages/angular_devkit/core/src/utils/lang.ts @@ -1,36 +1,21 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + // Borrowed from @angular/core -import { Observable } from 'rxjs'; /** * Determine if the argument is shaped like a Promise + * + * @deprecated Use `typeof obj?.then === 'function'` instead. */ -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function isPromise(obj: any): obj is Promise { // allow any Promise/A+ compliant thenable. // It's up to the caller to ensure that obj.then conforms to the spec return !!obj && typeof obj.then === 'function'; } - -/** - * Determine if the argument is an Observable - * @deprecated as of 8.0; use rxjs' built-in version - */ -// tslint:disable-next-line:no-any -export function isObservable(obj: any | Observable): obj is Observable { - if (!obj || typeof obj !== 'object') { - return false; - } - - if (Symbol.observable && Symbol.observable in obj) { - return true; - } - - return typeof obj.subscribe === 'function'; -} diff --git a/packages/angular_devkit/core/src/utils/literals.ts b/packages/angular_devkit/core/src/utils/literals.ts index bfa16c201c98..5dc8f2a1dfeb 100644 --- a/packages/angular_devkit/core/src/utils/literals.ts +++ b/packages/angular_devkit/core/src/utils/literals.ts @@ -1,18 +1,18 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + export interface TemplateTag { // Any is the only way here. - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any (template: TemplateStringsArray, ...substitutions: any[]): R; } - -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function oneLine(strings: TemplateStringsArray, ...values: any[]) { const endResult = String.raw(strings, ...values); @@ -30,8 +30,7 @@ export function indentBy(indentations: number): TemplateTag { }; } - -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function stripIndent(strings: TemplateStringsArray, ...values: any[]) { const endResult = String.raw(strings, ...values); @@ -43,29 +42,30 @@ export function stripIndent(strings: TemplateStringsArray, ...values: any[]) { return endResult; } - const indent = Math.min(...match.map(el => el.length)); + const indent = Math.min(...match.map((el) => el.length)); const regexp = new RegExp('^[ \\t]{' + indent + '}', 'gm'); return (indent > 0 ? endResult.replace(regexp, '') : endResult).trim(); } - -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function stripIndents(strings: TemplateStringsArray, ...values: any[]) { return String.raw(strings, ...values) .split('\n') - .map(line => line.trim()) + .map((line) => line.trim()) .join('\n') .trim(); } -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function trimNewlines(strings: TemplateStringsArray, ...values: any[]) { const endResult = String.raw(strings, ...values); - return endResult - // Remove the newline at the start. - .replace(/^(?:\r?\n)+/, '') - // Remove the newline at the end and following whitespace. - .replace(/(?:\r?\n(?:\s*))$/, ''); + return ( + endResult + // Remove the newline at the start. + .replace(/^(?:\r?\n)+/, '') + // Remove the newline at the end and following whitespace. + .replace(/(?:\r?\n(?:\s*))$/, '') + ); } diff --git a/packages/angular_devkit/core/src/utils/literals_spec.ts b/packages/angular_devkit/core/src/utils/literals_spec.ts index 0883eb685535..a880eac7547c 100644 --- a/packages/angular_devkit/core/src/utils/literals_spec.ts +++ b/packages/angular_devkit/core/src/utils/literals_spec.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { oneLine, stripIndent, stripIndents, trimNewlines } from './literals'; describe('literals', () => { diff --git a/packages/angular_devkit/core/src/utils/object.ts b/packages/angular_devkit/core/src/utils/object.ts index 3d5d9edf2475..9e7e5b78d3ad 100644 --- a/packages/angular_devkit/core/src/utils/object.ts +++ b/packages/angular_devkit/core/src/utils/object.ts @@ -1,42 +1,42 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -export function mapObject(obj: {[k: string]: T}, - mapper: (k: string, v: T) => V): {[k: string]: V} { - return Object.keys(obj).reduce((acc: {[k: string]: V}, k: string) => { - acc[k] = mapper(k, obj[k]); - - return acc; - }, {}); -} - - const copySymbol = Symbol(); -// tslint:disable-next-line:no-any -export function deepCopy (value: T): T { +/** + * @deprecated Use `structuredClone` instead. + */ +export function deepCopy(value: T): T { if (Array.isArray(value)) { - return value.map((o: T) => deepCopy(o)); + return value.map((o) => deepCopy(o)) as unknown as T; } else if (value && typeof value === 'object') { - if (value[copySymbol]) { + const valueCasted = value as unknown as { + [copySymbol]?: T; + toJSON?: () => string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; + }; + + if (valueCasted[copySymbol]) { // This is a circular dependency. Just return the cloned value. - return value[copySymbol]; + return valueCasted[copySymbol] as T; } - if (value['toJSON']) { - return JSON.parse((value['toJSON'] as () => string)()); + + if (valueCasted['toJSON']) { + return JSON.parse(valueCasted['toJSON']()) as T; } - const copy = new (Object.getPrototypeOf(value).constructor)(); - value[copySymbol] = copy; - for (const key of Object.getOwnPropertyNames(value)) { - copy[key] = deepCopy(value[key]); + const copy = Object.create(Object.getPrototypeOf(valueCasted)); + valueCasted[copySymbol] = copy; + for (const key of Object.getOwnPropertyNames(valueCasted)) { + copy[key] = deepCopy(valueCasted[key]); } - value[copySymbol] = undefined; + delete valueCasted[copySymbol]; return copy; } else { diff --git a/packages/angular_devkit/core/src/utils/object_spec.ts b/packages/angular_devkit/core/src/utils/object_spec.ts index 635c783c5f1d..da09820f2053 100644 --- a/packages/angular_devkit/core/src/utils/object_spec.ts +++ b/packages/angular_devkit/core/src/utils/object_spec.ts @@ -1,11 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any + +/* eslint-disable @typescript-eslint/no-explicit-any */ import { deepCopy } from './object'; describe('object', () => { @@ -32,7 +33,11 @@ describe('object', () => { it('works with simple classes', () => { class Data { - constructor(private _x = 1, protected _y = 2, public _z = 3) {} + constructor( + private _x = 1, + protected _y = 2, + public _z = 3, + ) {} } const data = new Data(); expect(deepCopy(data)).toEqual(data); @@ -50,5 +55,11 @@ describe('object', () => { expect(result.b).not.toBe(data1); expect(result.b).toBe(result.b.circular.b); }); + + it('works with null prototype', () => { + const data = Object.create(null); + data['a'] = 1; + expect(deepCopy(data)).toEqual(data); + }); }); }); diff --git a/packages/angular_devkit/core/src/utils/partially-ordered-set.ts b/packages/angular_devkit/core/src/utils/partially-ordered-set.ts index 2127f521eef2..2e5b124c61ed 100644 --- a/packages/angular_devkit/core/src/utils/partially-ordered-set.ts +++ b/packages/angular_devkit/core/src/utils/partially-ordered-set.ts @@ -1,42 +1,39 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { BaseException } from '../exception'; -export class DependencyNotFoundException extends BaseException { - constructor() { super('One of the dependencies is not part of the set.'); } -} -export class CircularDependencyFoundException extends BaseException { - constructor() { super('Circular dependencies found.'); } -} +import { CircularDependencyFoundException, DependencyNotFoundException } from '../exception'; -export class PartiallyOrderedSet implements Set { +/** + * @deprecated Use standard arrays and ensure correct insertion order instead. + */ +export class PartiallyOrderedSet { private _items = new Map>(); - protected _checkCircularDependencies(item: T, deps: Set) { + protected _checkCircularDependencies(item: T, deps: Set): void { if (deps.has(item)) { throw new CircularDependencyFoundException(); } - deps.forEach(dep => this._checkCircularDependencies(item, this._items.get(dep) || new Set())); + deps.forEach((dep) => this._checkCircularDependencies(item, this._items.get(dep) || new Set())); } - clear() { + clear(): void { this._items.clear(); } - has(item: T) { + has(item: T): boolean { return this._items.has(item); } - get size() { + get size(): number { return this._items.size; } forEach( callbackfn: (value: T, value2: T, set: PartiallyOrderedSet) => void, - thisArg?: any, // tslint:disable-line:no-any + thisArg?: any, // eslint-disable-line @typescript-eslint/no-explicit-any ): void { for (const x of this) { callbackfn.call(thisArg, x, x, this); @@ -66,8 +63,7 @@ export class PartiallyOrderedSet implements Set { return this[Symbol.iterator](); } - - add(item: T, deps: (Set | T[]) = new Set()) { + add(item: T, deps: Set | T[] = new Set()): this { if (Array.isArray(deps)) { deps = new Set(deps); } @@ -77,23 +73,7 @@ export class PartiallyOrderedSet implements Set { const itemDeps = this._items.get(item) || new Set(); // If the dependency list is equal, just return, otherwise remove and keep going. - let equal = true; - for (const dep of deps) { - if (!itemDeps.has(dep)) { - equal = false; - break; - } - } - if (equal) { - for (const dep of itemDeps) { - if (!deps.has(dep)) { - equal = false; - break; - } - } - } - - if (equal) { + if (deps.size === itemDeps.size && deps.isSubsetOf(itemDeps)) { return this; } else { this._items.delete(item); @@ -101,10 +81,8 @@ export class PartiallyOrderedSet implements Set { } // Verify all dependencies are part of the Set. - for (const dep of deps) { - if (!this._items.has(dep)) { - throw new DependencyNotFoundException(); - } + if (!deps.isSubsetOf(this._items)) { + throw new DependencyNotFoundException(); } // Verify there's no dependency cycle. @@ -115,18 +93,18 @@ export class PartiallyOrderedSet implements Set { return this; } - delete(item: T) { + delete(item: T): boolean { if (!this._items.has(item)) { return false; } // Remove it from all dependencies if force == true. - this._items.forEach(value => value.delete(item)); + this._items.forEach((value) => value.delete(item)); return this._items.delete(item); } - *[Symbol.iterator]() { + *[Symbol.iterator](): IterableIterator { const copy: Map> = new Map(this._items); for (const [key, value] of copy.entries()) { @@ -134,7 +112,7 @@ export class PartiallyOrderedSet implements Set { } while (copy.size > 0) { - const run = []; + const run: T[] = []; // Take the first item without dependencies. for (const [item, deps] of copy.entries()) { if (deps.size == 0) { @@ -143,7 +121,7 @@ export class PartiallyOrderedSet implements Set { } for (const item of run) { - copy.forEach(s => s.delete(item)); + copy.forEach((s) => s.delete(item)); copy.delete(item); yield item; } @@ -153,9 +131,11 @@ export class PartiallyOrderedSet implements Set { throw new CircularDependencyFoundException(); } } + + return undefined; } - get [Symbol.toStringTag](): 'Set' { - return 'Set'; + get [Symbol.toStringTag](): 'PartiallyOrderedSet' { + return 'PartiallyOrderedSet'; } } diff --git a/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts b/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts index 31aa667cb54e..d9d49457d110 100644 --- a/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts +++ b/packages/angular_devkit/core/src/utils/partially-ordered-set_spec.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { PartiallyOrderedSet } from './partially-ordered-set'; describe('PartiallyOrderedSet', () => { diff --git a/packages/angular_devkit/core/src/utils/priority-queue.ts b/packages/angular_devkit/core/src/utils/priority-queue.ts index 9d5008487d47..e2baae889d1f 100644 --- a/packages/angular_devkit/core/src/utils/priority-queue.ts +++ b/packages/angular_devkit/core/src/utils/priority-queue.ts @@ -1,9 +1,9 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ /** Naive priority queue; not intended for large datasets */ @@ -12,12 +12,12 @@ export class PriorityQueue { constructor(private _comparator: (x: T, y: T) => number) {} - clear() { + clear(): void { this._items = new Array(); } - push(item: T) { - const index = this._items.findIndex(existing => this._comparator(item, existing) <= 0); + push(item: T): void { + const index = this._items.findIndex((existing) => this._comparator(item, existing) <= 0); if (index === -1) { this._items.push(item); diff --git a/packages/angular_devkit/core/src/utils/priority-queue_spec.ts b/packages/angular_devkit/core/src/utils/priority-queue_spec.ts index ef850273de4e..454e7ddff936 100644 --- a/packages/angular_devkit/core/src/utils/priority-queue_spec.ts +++ b/packages/angular_devkit/core/src/utils/priority-queue_spec.ts @@ -1,12 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { PriorityQueue } from './priority-queue'; +import { PriorityQueue } from './priority-queue'; describe('PriorityQueue', () => { it('adds an item', () => { diff --git a/packages/angular_devkit/core/src/utils/strings.ts b/packages/angular_devkit/core/src/utils/strings.ts index ff3c0ce7cec3..2dbc40970941 100644 --- a/packages/angular_devkit/core/src/utils/strings.ts +++ b/packages/angular_devkit/core/src/utils/strings.ts @@ -1,15 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -const STRING_DASHERIZE_REGEXP = (/[ _]/g); -const STRING_DECAMELIZE_REGEXP = (/([a-z\d])([A-Z])/g); -const STRING_CAMELIZE_REGEXP = (/(-|_|\.|\s)+(.)?/g); -const STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); -const STRING_UNDERSCORE_REGEXP_2 = (/-|\s+/g); + +const STRING_DASHERIZE_REGEXP = /[ _]/g; +const STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g; +const STRING_CAMELIZE_REGEXP = /(-|_|\.|\s)+(.)?/g; +const STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g; +const STRING_UNDERSCORE_REGEXP_2 = /-|\s+/g; /** * Converts a camelized string into all lower case separated by underscores. @@ -73,23 +74,27 @@ export function camelize(str: string): string { /** Returns the UpperCamelCase form of a string. + @example ```javascript 'innerHTML'.classify(); // 'InnerHTML' 'action_name'.classify(); // 'ActionName' 'css-class-name'.classify(); // 'CssClassName' 'my favorite items'.classify(); // 'MyFavoriteItems' + 'app.component'.classify(); // 'AppComponent' ``` - @method classify @param {String} str the string to classify @return {String} the classified string */ export function classify(str: string): string { - return str.split('.').map(part => capitalize(camelize(part))).join('.'); + return str + .split('.') + .map((part) => capitalize(camelize(part))) + .join(''); } /** - More general than decamelize. Returns the lower\_case\_and\_underscored + More general than decamelize. Returns the lower_case_and_underscored form of a string. ```javascript @@ -125,7 +130,7 @@ export function underscore(str: string): string { @return {String} The capitalized string. */ export function capitalize(str: string): string { - return str.charAt(0).toUpperCase() + str.substr(1); + return str.charAt(0).toUpperCase() + str.slice(1); } /** @@ -147,7 +152,7 @@ export function levenshtein(a: string, b: string): number { return a.length; } - const matrix = []; + const matrix: number[][] = []; // increment along the first column of each row for (let i = 0; i <= b.length; i++) { diff --git a/packages/angular_devkit/core/src/utils/template.ts b/packages/angular_devkit/core/src/utils/template.ts index 1ed86bd81098..f28bbf7ad417 100644 --- a/packages/angular_devkit/core/src/utils/template.ts +++ b/packages/angular_devkit/core/src/utils/template.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Position, SourceNode } from 'source-map'; // Matches <%= expr %>. This does not support structural JavaScript (for/if/...). @@ -19,7 +20,7 @@ const kEscapeRe = /<%-([\s\S]+?)%>/g; const kEvaluateRe = /<%([\s\S]+?)%>/g; /** Used to map characters to HTML entities. */ -const kHtmlEscapes: {[char: string]: string} = { +const kHtmlEscapes: { [char: string]: string } = { '&': '&', '<': '<', '>': '>', @@ -40,7 +41,6 @@ export interface TemplateOptions { fileName?: string; } - function _positionFor(content: string, offset: number): Position { let line = 1; let column = 0; @@ -117,21 +117,22 @@ export interface TemplateAstInterpolate extends TemplateAstBase { expression: string; } -export type TemplateAstNode = TemplateAstContent - | TemplateAstEvaluate - | TemplateAstComment - | TemplateAstEscape - | TemplateAstInterpolate; +export type TemplateAstNode = + | TemplateAstContent + | TemplateAstEvaluate + | TemplateAstComment + | TemplateAstEscape + | TemplateAstInterpolate; /** * Given a source text (and a fileName), returns a TemplateAst. */ export function templateParser(sourceText: string, fileName: string): TemplateAst { - const children = []; + const children: TemplateAstNode[] = []; // Compile the regexp to match each delimiter. const reExpressions = [kEscapeRe, kCommentRe, kInterpolateRe, kEvaluateRe]; - const reDelimiters = RegExp(reExpressions.map(x => x.source).join('|') + '|$', 'g'); + const reDelimiters = RegExp(reExpressions.map((x) => x.source).join('|') + '|$', 'g'); const parsed = sourceText.split(reDelimiters); let offset = 0; @@ -193,7 +194,7 @@ export function templateParser(sourceText: string, fileName: string): TemplateAs */ function templateFast(ast: TemplateAst, options?: TemplateOptions): string { const module = options && options.module ? 'module.exports.default =' : ''; - const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, '\\\\\\\''); + const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'"); return ` return ${module} function(obj) { @@ -207,7 +208,8 @@ function templateFast(ast: TemplateAst, options?: TemplateOptions): string { return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : ''; }; with (obj) { - ${ast.children.map(node => { + ${ast.children + .map((node) => { switch (node.kind) { case 'content': return `__p += ${JSON.stringify(node.content)};`; @@ -218,8 +220,8 @@ function templateFast(ast: TemplateAst, options?: TemplateOptions): string { case 'evaluate': return node.expression; } - }).join('\n') - } + }) + .join('\n')} } return __p; @@ -233,10 +235,10 @@ function templateFast(ast: TemplateAst, options?: TemplateOptions): string { function templateWithSourceMap(ast: TemplateAst, options?: TemplateOptions): string { const sourceUrl = ast.fileName; const module = options && options.module ? 'module.exports.default =' : ''; - const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, '\\\\\\\''); + const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'"); - const preamble = (new SourceNode(1, 0, sourceUrl, '')) - .add(new SourceNode(1, 0, sourceUrl, [ + const preamble = new SourceNode(1, 0, sourceUrl, '').add( + new SourceNode(1, 0, sourceUrl, [ `return ${module} function(obj) {\n`, ' obj || (obj = {});\n', ' let __t;\n', @@ -248,96 +250,93 @@ function templateWithSourceMap(ast: TemplateAst, options?: TemplateOptions): str ` return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';`, ` };\n`, ` with (obj) {\n`, - ])); - - const end = ast.children.length - ? ast.children[ast.children.length - 1].end - : { line: 0, column: 0 }; - const nodes = ast.children.reduce((chunk, node) => { - let code: string | SourceNode | (SourceNode | string)[] = ''; - switch (node.kind) { - case 'content': - code = [ - new SourceNode(node.start.line, node.start.column, sourceUrl, '__p = __p'), - ...node.content.split('\n').map((line, i, arr) => { - return new SourceNode( - node.start.line + i, - i == 0 ? node.start.column : 0, - sourceUrl, - '\n + ' - + JSON.stringify(line + (i == arr.length - 1 ? '' : '\n')), - ); - }), - new SourceNode(node.end.line, node.end.column, sourceUrl, ';\n'), - ]; - break; - case 'interpolate': - code = [ - new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += ((__t = '), - ...node.expression.split('\n').map((line, i, arr) => { - return new SourceNode( - node.start.line + i, - i == 0 ? node.start.column : 0, - sourceUrl, - line + ((i == arr.length - 1) ? '' : '\n'), - ); - }), - new SourceNode(node.end.line, node.end.column, sourceUrl, ') == null ? "" : __t);\n'), - ]; - break; - case 'escape': - code = [ - new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += __e('), - ...node.expression.split('\n').map((line, i, arr) => { - return new SourceNode( - node.start.line + i, - i == 0 ? node.start.column : 0, - sourceUrl, - line + ((i == arr.length - 1) ? '' : '\n'), - ); - }), - new SourceNode(node.end.line, node.end.column, sourceUrl, ');\n'), - ]; - break; - case 'evaluate': - code = [ - ...node.expression.split('\n').map((line, i, arr) => { - return new SourceNode( - node.start.line + i, - i == 0 ? node.start.column : 0, - sourceUrl, - line + ((i == arr.length - 1) ? '' : '\n'), - ); - }), - new SourceNode(node.end.line, node.end.column, sourceUrl, '\n'), - ]; - break; - } + ]), + ); + + const end = ast.children.at(-1)?.end ?? { line: 0, column: 0 }; + const nodes = ast.children + .reduce((chunk, node) => { + let code: string | SourceNode | (SourceNode | string)[] = ''; + switch (node.kind) { + case 'content': + code = [ + new SourceNode(node.start.line, node.start.column, sourceUrl, '__p = __p'), + ...node.content.split('\n').map((line, i, arr) => { + return new SourceNode( + node.start.line + i, + i == 0 ? node.start.column : 0, + sourceUrl, + '\n + ' + JSON.stringify(line + (i == arr.length - 1 ? '' : '\n')), + ); + }), + new SourceNode(node.end.line, node.end.column, sourceUrl, ';\n'), + ]; + break; + case 'interpolate': + code = [ + new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += ((__t = '), + ...node.expression.split('\n').map((line, i, arr) => { + return new SourceNode( + node.start.line + i, + i == 0 ? node.start.column : 0, + sourceUrl, + line + (i == arr.length - 1 ? '' : '\n'), + ); + }), + new SourceNode(node.end.line, node.end.column, sourceUrl, ') == null ? "" : __t);\n'), + ]; + break; + case 'escape': + code = [ + new SourceNode(node.start.line, node.start.column, sourceUrl, '__p += __e('), + ...node.expression.split('\n').map((line, i, arr) => { + return new SourceNode( + node.start.line + i, + i == 0 ? node.start.column : 0, + sourceUrl, + line + (i == arr.length - 1 ? '' : '\n'), + ); + }), + new SourceNode(node.end.line, node.end.column, sourceUrl, ');\n'), + ]; + break; + case 'evaluate': + code = [ + ...node.expression.split('\n').map((line, i, arr) => { + return new SourceNode( + node.start.line + i, + i == 0 ? node.start.column : 0, + sourceUrl, + line + (i == arr.length - 1 ? '' : '\n'), + ); + }), + new SourceNode(node.end.line, node.end.column, sourceUrl, '\n'), + ]; + break; + } - return chunk.add(new SourceNode(node.start.line, node.start.column, sourceUrl, code)); - }, preamble) - .add(new SourceNode(end.line, end.column, sourceUrl, [ - ' };\n', - '\n', - ' return __p;\n', - '}\n', - ])); + return chunk.add(new SourceNode(node.start.line, node.start.column, sourceUrl, code)); + }, preamble) + .add( + new SourceNode(end.line, end.column, sourceUrl, [' };\n', '\n', ' return __p;\n', '}\n']), + ); const code = nodes.toStringWithSourceMap({ file: sourceUrl, - sourceRoot: options && options.sourceRoot || '.', + sourceRoot: (options && options.sourceRoot) || '.', }); // Set the source content in the source map, otherwise the sourceUrl is not enough // to find the content. code.map.setSourceContent(sourceUrl, ast.content); - return code.code - + '\n//# sourceMappingURL=data:application/json;base64,' - + Buffer.from(code.map.toString()).toString('base64'); + return ( + code.code + + '\n//# sourceMappingURL=data:application/json;base64,' + + Buffer.from(code.map.toString()).toString('base64') + ); } - /** * An equivalent of EJS templates, which is based on John Resig's `tmpl` implementation * (http://ejohn.org/blog/javascript-micro-templating/) and Laura Doktorova's doT.js @@ -354,7 +353,7 @@ function templateWithSourceMap(ast: TemplateAst, options?: TemplateOptions): str * of the template with the input applied. */ export function template(content: string, options?: TemplateOptions): (input: T) => string { - const sourceUrl = options && options.sourceURL || 'ejs'; + const sourceUrl = (options && options.sourceURL) || 'ejs'; const ast = templateParser(content, sourceUrl); let source: string; @@ -369,9 +368,8 @@ export function template(content: string, options?: TemplateOptions): (input: // need to only use the source, not the function itself. Otherwise expect a module object to be // passed, and we use that one. const fn = Function('module', source); - const module = options && options.module - ? (options.module === true ? { exports: {} } : options.module) - : null; + const module = + options && options.module ? (options.module === true ? { exports: {} } : options.module) : null; const result = fn(module); // Provide the compiled function's source by its `toString` method or diff --git a/packages/angular_devkit/core/src/virtual-fs/host/alias.ts b/packages/angular_devkit/core/src/virtual-fs/host/alias.ts index 4df9c6b1fbe2..1b8c88e08b6b 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/alias.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/alias.ts @@ -1,14 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { NormalizedRoot, Path, PathFragment, join, split } from '../path'; import { ResolverHost } from './resolver'; - /** * A Virtual Host that allow to alias some paths to other paths. * @@ -56,9 +56,9 @@ import { ResolverHost } from './resolver'; * .subscribe(x => expect(x).toBe(content2)); */ export class AliasHost extends ResolverHost { - protected _aliases = new Map(); + protected _aliases: Map = new Map(); - protected _resolve(path: Path) { + protected _resolve(path: Path): Path { let maybeAlias = this._aliases.get(path); const sp = split(path); const remaining: PathFragment[] = []; @@ -74,11 +74,13 @@ export class AliasHost extends ResolverHost maybeAlias = join(maybeAlias, ...remaining); } // Allow non-null-operator because we know sp.length > 0 (condition on while). - remaining.unshift(sp.pop() !); // tslint:disable-line:no-non-null-assertion + remaining.unshift(sp.pop()!); // eslint-disable-line @typescript-eslint/no-non-null-assertion } return maybeAlias || path; } - get aliases(): Map { return this._aliases; } + get aliases(): Map { + return this._aliases; + } } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts b/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts index ff852af9910e..66ae4b0137f4 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/alias_spec.ts @@ -1,59 +1,56 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { normalize } from '..'; import { AliasHost } from './alias'; -import { stringToFileBuffer } from './buffer'; import { SimpleMemoryHost } from './memory'; describe('AliasHost', () => { it('works as in the example', () => { - const content = stringToFileBuffer('hello world'); + const content = new TextEncoder().encode('hello world').buffer; const host = new SimpleMemoryHost(); host.write(normalize('/some/file'), content).subscribe(); const aHost = new AliasHost(host); - aHost.read(normalize('/some/file')) - .subscribe(x => expect(x).toBe(content)); + aHost.read(normalize('/some/file')).subscribe((x) => expect(x).toBe(content)); aHost.aliases.set(normalize('/some/file'), normalize('/other/path')); // This file will not exist because /other/path does not exist. try { - aHost.read(normalize('/some/file')) - .subscribe(undefined, err => { - expect(err.message).toMatch(/does not exist/); - }); + aHost.read(normalize('/some/file')).subscribe(undefined, (err) => { + expect(err.message).toMatch(/does not exist/); + }); } catch { // Ignore it. RxJS <6 still throw errors when they happen synchronously. } }); it('works as in the example (2)', () => { - const content = stringToFileBuffer('hello world'); - const content2 = stringToFileBuffer('hello world 2'); + const content = new TextEncoder().encode('hello world').buffer; + const content2 = new TextEncoder().encode('hello world 2').buffer; const host = new SimpleMemoryHost(); host.write(normalize('/some/folder/file'), content).subscribe(); const aHost = new AliasHost(host); - aHost.read(normalize('/some/folder/file')) - .subscribe(x => expect(x).toBe(content)); + aHost.read(normalize('/some/folder/file')).subscribe((x) => expect(x).toBe(content)); aHost.aliases.set(normalize('/some'), normalize('/other')); // This file will not exist because /other/path does not exist. try { - aHost.read(normalize('/some/folder/file')) - .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/)); + aHost + .read(normalize('/some/folder/file')) + .subscribe(undefined, (err) => expect(err.message).toMatch(/does not exist/)); } catch {} // Create the file with new content and verify that this has the new content. aHost.write(normalize('/other/folder/file'), content2).subscribe(); - aHost.read(normalize('/some/folder/file')) - .subscribe(x => expect(x).toBe(content2)); + aHost.read(normalize('/some/folder/file')).subscribe((x) => expect(x).toBe(content2)); }); }); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts b/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts index 318a7d8b321b..becaa3ecdffd 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/buffer.ts @@ -1,81 +1,27 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { TemplateTag } from '../../utils/literals'; -import { FileBuffer } from './interface'; - -declare const TextEncoder: { - new (encoding: string): { - encode(str: string): Uint8Array; - }; -}; -declare const TextDecoder: { - new(encoding: string): { - decode(bytes: Uint8Array): string; - }; -}; +import { FileBuffer } from './interface'; +/** + * @deprecated Use `new TextEncoder().encode(str).buffer` instead. + */ export function stringToFileBuffer(str: string): FileBuffer { - // If we're in Node... - if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') { - const buf = Buffer.from(str); - const ab = new ArrayBuffer(buf.length); - const view = new Uint8Array(ab); - for (let i = 0; i < buf.length; ++i) { - view[i] = buf[i]; - } - - return ab; - } else if (typeof TextEncoder !== 'undefined') { - // Modern browsers implement TextEncode. - return new TextEncoder('utf-8').encode(str).buffer as ArrayBuffer; - } else { - // Slowest method but sure to be compatible with every platform. - const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char - const bufView = new Uint16Array(buf); - for (let i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - - return buf; - } + return new TextEncoder().encode(str).buffer; } - -export const fileBuffer: TemplateTag = (strings, ...values) => { - return stringToFileBuffer(String.raw(strings, ...values)); -}; - - +/** + * @deprecated Use `new TextDecoder().decode(fileBuffer)` instead. + */ export function fileBufferToString(fileBuffer: FileBuffer): string { - if (fileBuffer.toString.length == 1) { + if (fileBuffer.toString.length === 1) { return (fileBuffer.toString as (enc: string) => string)('utf-8'); - } else if (typeof Buffer !== 'undefined') { - return Buffer.from(fileBuffer).toString('utf-8'); - } else if (typeof TextDecoder !== 'undefined') { - // Modern browsers implement TextEncode. - return new TextDecoder('utf-8').decode(new Uint8Array(fileBuffer)); - } else { - // Slowest method but sure to be compatible with every platform. - const bufView = new Uint8Array(fileBuffer); - const bufLength = bufView.length; - let result = ''; - let chunkLength = Math.pow(2, 16) - 1; - - // We have to chunk it because String.fromCharCode.apply will throw - // `Maximum call stack size exceeded` on big inputs. - for (let i = 0; i < bufLength; i += chunkLength) { - if (i + chunkLength > bufLength) { - chunkLength = bufLength - i; - } - result += String.fromCharCode.apply(null, bufView.subarray(i, i + chunkLength)); - } - - return result; } + + return new TextDecoder('utf-8').decode(new Uint8Array(fileBuffer)); } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/create.ts b/packages/angular_devkit/core/src/virtual-fs/host/create.ts new file mode 100644 index 000000000000..342f54e7870b --- /dev/null +++ b/packages/angular_devkit/core/src/virtual-fs/host/create.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { Observable } from 'rxjs'; +import { Path, PathFragment } from '../path'; +import { FileBuffer, FileBufferLike, Host, HostCapabilities, Stats } from './interface'; + +export interface SyncHostHandler { + read(path: Path): FileBuffer; + list(path: Path): PathFragment[]; + + exists(path: Path): boolean; + isDirectory(path: Path): boolean; + isFile(path: Path): boolean; + + stat(path: Path): Stats | null; + + write(path: Path, content: FileBufferLike): void; + delete(path: Path): void; + rename(from: Path, to: Path): void; +} + +function wrapAction(action: () => T): Observable { + return new Observable((subscriber) => { + subscriber.next(action()); + subscriber.complete(); + }); +} + +export function createSyncHost( + handler: SyncHostHandler, +): Host { + return new (class { + get capabilities(): HostCapabilities { + return { synchronous: true }; + } + + read(path: Path): Observable { + return wrapAction(() => handler.read(path)); + } + + list(path: Path): Observable { + return wrapAction(() => handler.list(path)); + } + + exists(path: Path): Observable { + return wrapAction(() => handler.exists(path)); + } + + isDirectory(path: Path): Observable { + return wrapAction(() => handler.isDirectory(path)); + } + + isFile(path: Path): Observable { + return wrapAction(() => handler.isFile(path)); + } + + stat(path: Path): Observable | null> { + return wrapAction(() => handler.stat(path)); + } + + write(path: Path, content: FileBufferLike): Observable { + return wrapAction(() => handler.write(path, content)); + } + + delete(path: Path): Observable { + return wrapAction(() => handler.delete(path)); + } + + rename(from: Path, to: Path): Observable { + return wrapAction(() => handler.rename(from, to)); + } + + watch(): null { + return null; + } + })(); +} diff --git a/packages/angular_devkit/core/src/virtual-fs/host/empty.ts b/packages/angular_devkit/core/src/virtual-fs/host/empty.ts index 791b27c6e7cf..6b70c6906261 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/empty.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/empty.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable, of, throwError } from 'rxjs'; import { FileDoesNotExistException } from '../../exception'; import { Path, PathFragment } from '../path'; diff --git a/packages/angular_devkit/core/src/virtual-fs/host/index.ts b/packages/angular_devkit/core/src/virtual-fs/host/index.ts index c17b0c50f952..a7e9d554e41e 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/index.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/index.ts @@ -1,13 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ +import * as test from './test'; + export * from './alias'; export * from './buffer'; +export * from './create'; export * from './empty'; export * from './interface'; export * from './memory'; @@ -17,4 +20,4 @@ export * from './safe'; export * from './scoped'; export * from './sync'; export * from './resolver'; -export * from './test'; +export { test }; diff --git a/packages/angular_devkit/core/src/virtual-fs/host/interface.ts b/packages/angular_devkit/core/src/virtual-fs/host/interface.ts index 9c48e58f5d0d..f8ce6f9eb020 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/interface.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/interface.ts @@ -1,14 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable } from 'rxjs'; import { Path, PathFragment } from '../path'; - export type FileBuffer = ArrayBuffer; export type FileBufferLike = ArrayBufferLike; @@ -17,12 +17,11 @@ export interface HostWatchOptions { readonly recursive?: boolean; } - -export const enum HostWatchEventType { +export enum HostWatchEventType { Changed = 0, Created = 1, Deleted = 2, - Renamed = 3, // Applied to the original file path. + Renamed = 3, // Applied to the original file path. } export type Stats = T & { diff --git a/packages/angular_devkit/core/src/virtual-fs/host/memory.ts b/packages/angular_devkit/core/src/virtual-fs/host/memory.ts index ca80bc7ea916..0b9e1285b6ad 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/memory.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/memory.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable, Subject } from 'rxjs'; import { FileAlreadyExistException, @@ -33,21 +34,27 @@ import { Stats, } from './interface'; - export interface SimpleMemoryHostStats { readonly content: FileBuffer | null; + inspect(): string; } export class SimpleMemoryHost implements Host<{}> { - protected _cache = new Map>(); + protected _cache: Map> = new Map(); private _watchers = new Map][]>(); - protected _newDirStats() { + protected _newDirStats(): Stats { return { - inspect() { return ''; }, - - isFile() { return false; }, - isDirectory() { return true; }, + inspect(): string { + return ''; + }, + + isFile() { + return false; + }, + isDirectory() { + return true; + }, size: 0, atime: new Date(), @@ -58,12 +65,21 @@ export class SimpleMemoryHost implements Host<{}> { content: null, }; } - protected _newFileStats(content: FileBuffer, oldStats?: Stats) { + protected _newFileStats( + content: FileBuffer, + oldStats?: Stats, + ): Stats { return { - inspect() { return ``; }, - - isFile() { return true; }, - isDirectory() { return false; }, + inspect() { + return ``; + }, + + isFile() { + return true; + }, + isDirectory() { + return false; + }, size: content.byteLength, atime: oldStats ? oldStats.atime : new Date(), @@ -79,11 +95,11 @@ export class SimpleMemoryHost implements Host<{}> { this._cache.set(normalize('/'), this._newDirStats()); } - protected _toAbsolute(path: Path) { + protected _toAbsolute(path: Path): Path { return isAbsolute(path) ? path : normalize('/' + path); } - protected _updateWatchers(path: Path, type: HostWatchEventType) { + protected _updateWatchers(path: Path, type: HostWatchEventType): void { const time = new Date(); let currentPath = path; let parent: Path | null = null; @@ -95,7 +111,7 @@ export class SimpleMemoryHost implements Host<{}> { const maybeWatcher = this._watchers.get(currentPath); if (maybeWatcher) { - maybeWatcher.forEach(watcher => { + maybeWatcher.forEach((watcher) => { const [options, subject] = watcher; subject.next({ path, time, type }); @@ -112,7 +128,7 @@ export class SimpleMemoryHost implements Host<{}> { const maybeWatcher = this._watchers.get(currentPath); if (maybeWatcher) { - maybeWatcher.forEach(watcher => { + maybeWatcher.forEach((watcher) => { const [options, subject] = watcher; if (!options.recursive) { return; @@ -212,7 +228,7 @@ export class SimpleMemoryHost implements Host<{}> { const content = this._cache.get(from); if (content) { const fragments = split(to); - const newDirectories = []; + const newDirectories: Path[] = []; let curr: Path = normalize('/'); for (const fr of fragments) { curr = join(curr, fr); @@ -301,7 +317,7 @@ export class SimpleMemoryHost implements Host<{}> { } write(path: Path, content: FileBuffer): Observable { - return new Observable(obs => { + return new Observable((obs) => { this._write(path, content); obs.next(); obs.complete(); @@ -309,7 +325,7 @@ export class SimpleMemoryHost implements Host<{}> { } read(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { const content = this._read(path); obs.next(content); obs.complete(); @@ -317,7 +333,7 @@ export class SimpleMemoryHost implements Host<{}> { } delete(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { this._delete(path); obs.next(); obs.complete(); @@ -325,7 +341,7 @@ export class SimpleMemoryHost implements Host<{}> { } rename(from: Path, to: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { this._rename(from, to); obs.next(); obs.complete(); @@ -333,28 +349,28 @@ export class SimpleMemoryHost implements Host<{}> { } list(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { obs.next(this._list(path)); obs.complete(); }); } exists(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { obs.next(this._exists(path)); obs.complete(); }); } isDirectory(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { obs.next(this._isDirectory(path)); obs.complete(); }); } isFile(path: Path): Observable { - return new Observable(obs => { + return new Observable((obs) => { obs.next(this._isFile(path)); obs.complete(); }); @@ -362,7 +378,7 @@ export class SimpleMemoryHost implements Host<{}> { // Some hosts may not support stat. stat(path: Path): Observable | null> | null { - return new Observable | null>(obs => { + return new Observable | null>((obs) => { obs.next(this._stat(path)); obs.complete(); }); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts b/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts index bf9df7a106c9..fce1623737a1 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/memory_spec.ts @@ -1,42 +1,40 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-implicit-dependencies -// tslint:disable:no-non-null-assertion -import { fragment, normalize } from '@angular-devkit/core'; -import { stringToFileBuffer } from './buffer'; + +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { fragment, normalize } from '../path'; import { SimpleMemoryHost } from './memory'; import { SyncDelegateHost } from './sync'; describe('SimpleMemoryHost', () => { - it('can watch', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - host.write(normalize('/sub/file1'), stringToFileBuffer('')); + host.write(normalize('/sub/file1'), new TextEncoder().encode('').buffer); let recursiveCalled = 0; let noRecursiveCalled = 0; let noRecursiveFileCalled = 0; let diffFile = 0; - host.watch(normalize('/sub'), { recursive: true }) !.subscribe(() => recursiveCalled++); - host.watch(normalize('/sub')) !.subscribe(() => noRecursiveCalled++); - host.watch(normalize('/sub/file2')) !.subscribe(() => noRecursiveFileCalled++); - host.watch(normalize('/sub/file3')) !.subscribe(() => diffFile++); + host.watch(normalize('/sub'), { recursive: true })!.subscribe(() => recursiveCalled++); + host.watch(normalize('/sub'))!.subscribe(() => noRecursiveCalled++); + host.watch(normalize('/sub/file2'))!.subscribe(() => noRecursiveFileCalled++); + host.watch(normalize('/sub/file3'))!.subscribe(() => diffFile++); - host.write(normalize('/sub/file2'), stringToFileBuffer('')); + host.write(normalize('/sub/file2'), new TextEncoder().encode('').buffer); expect(recursiveCalled).toBe(1); expect(noRecursiveCalled).toBe(0); expect(noRecursiveFileCalled).toBe(1); expect(diffFile).toBe(0); - host.write(normalize('/sub/file3'), stringToFileBuffer('')); + host.write(normalize('/sub/file3'), new TextEncoder().encode('').buffer); expect(recursiveCalled).toBe(2); expect(noRecursiveCalled).toBe(0); @@ -47,7 +45,7 @@ describe('SimpleMemoryHost', () => { it('can read', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; host.write(normalize('/hello'), buffer); expect(host.read(normalize('/hello'))).toBe(buffer); @@ -56,7 +54,7 @@ describe('SimpleMemoryHost', () => { it('can delete', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; expect(host.exists(normalize('/sub/file1'))).toBe(false); host.write(normalize('/sub/file1'), buffer); @@ -68,7 +66,7 @@ describe('SimpleMemoryHost', () => { it('can delete directory', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; expect(host.exists(normalize('/sub/file1'))).toBe(false); host.write(normalize('/sub/file1'), buffer); @@ -84,7 +82,7 @@ describe('SimpleMemoryHost', () => { it('can rename', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; expect(host.exists(normalize('/sub/file1'))).toBe(false); host.write(normalize('/sub/file1'), buffer); @@ -98,24 +96,26 @@ describe('SimpleMemoryHost', () => { it('can list', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; host.write(normalize('/sub/file1'), buffer); host.write(normalize('/sub/file2'), buffer); host.write(normalize('/sub/sub1/file3'), buffer); host.write(normalize('/file4'), buffer); - expect(host.list(normalize('/sub'))) - .toEqual([fragment('file1'), fragment('file2'), fragment('sub1')]); - expect(host.list(normalize('/'))) - .toEqual([fragment('sub'), fragment('file4')]); + expect(host.list(normalize('/sub'))).toEqual([ + fragment('file1'), + fragment('file2'), + fragment('sub1'), + ]); + expect(host.list(normalize('/'))).toEqual([fragment('sub'), fragment('file4')]); expect(host.list(normalize('/inexistent'))).toEqual([]); }); it('supports isFile / isDirectory', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); + const buffer = new TextEncoder().encode('hello').buffer; host.write(normalize('/sub/file1'), buffer); host.write(normalize('/sub/file2'), buffer); @@ -134,8 +134,8 @@ describe('SimpleMemoryHost', () => { it('makes every path absolute', () => { const host = new SyncDelegateHost(new SimpleMemoryHost()); - const buffer = stringToFileBuffer('hello'); - const buffer2 = stringToFileBuffer('hello 2'); + const buffer = new TextEncoder().encode('hello').buffer; + const buffer2 = new TextEncoder().encode('hello 2').buffer; host.write(normalize('file1'), buffer); host.write(normalize('/sub/file2'), buffer); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts b/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts index 9880c1e67903..f34899cf1d7c 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/pattern.ts @@ -1,40 +1,31 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + +import { parse as parseGlob } from 'picomatch'; import { Path } from '../path'; import { ResolverHost } from './resolver'; - export type ReplacementFunction = (path: Path) => Path; - /** */ export class PatternMatchingHost extends ResolverHost { - protected _patterns = new Map(); - - addPattern(pattern: string | string[], replacementFn: ReplacementFunction) { - // Simple GLOB pattern replacement. - const reString = '^(' - + (Array.isArray(pattern) ? pattern : [pattern]) - .map(ex => '(' - + ex.split(/[\/\\]/g).map(f => f - .replace(/[\-\[\]{}()+?.^$|]/g, '\\$&') - .replace(/^\*\*/g, '(.+?)?') - .replace(/\*/g, '[^/\\\\]*')) - .join('[\/\\\\]') - + ')') - .join('|') - + ')($|/|\\\\)'; - - this._patterns.set(new RegExp(reString), replacementFn); + protected _patterns: Map = new Map(); + + addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void { + const patterns = Array.isArray(pattern) ? pattern : [pattern]; + for (const glob of patterns) { + const { output } = parseGlob(glob); + this._patterns.set(new RegExp(`^${output}$`), replacementFn); + } } - protected _resolve(path: Path) { + protected _resolve(path: Path): Path { let newPath = path; this._patterns.forEach((fn, re) => { if (re.test(path)) { diff --git a/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts b/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts index eb10ea21c1e0..56abcff14ef2 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/pattern_spec.ts @@ -1,44 +1,41 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { normalize } from '..'; -import { stringToFileBuffer } from './buffer'; import { SimpleMemoryHost } from './memory'; import { PatternMatchingHost } from './pattern'; describe('PatternMatchingHost', () => { it('works for NativeScript', () => { - const content = stringToFileBuffer('hello world'); - const content2 = stringToFileBuffer('hello world 2'); + const content = new TextEncoder().encode('hello world').buffer; + const content2 = new TextEncoder().encode('hello world 2').buffer; const host = new SimpleMemoryHost(); host.write(normalize('/some/file.tns.ts'), content).subscribe(); const pHost = new PatternMatchingHost(host); - pHost.read(normalize('/some/file.tns.ts')) - .subscribe(x => expect(x).toBe(content)); + pHost.read(normalize('/some/file.tns.ts')).subscribe((x) => expect(x).toBe(content)); - pHost.addPattern('**/*.tns.ts', path => { + pHost.addPattern('**/*.tns.ts', (path) => { return normalize(path.replace(/\.tns\.ts$/, '.ts')); }); // This file will not exist because /some/file.ts does not exist. try { - pHost.read(normalize('/some/file.tns.ts')) - .subscribe(undefined, err => { - expect(err.message).toMatch(/does not exist/); - }); + pHost.read(normalize('/some/file.tns.ts')).subscribe(undefined, (err) => { + expect(err.message).toMatch(/does not exist/); + }); } catch { // Ignore it. RxJS <6 still throw errors when they happen synchronously. } // Create the file, it should exist now. pHost.write(normalize('/some/file.ts'), content2).subscribe(); - pHost.read(normalize('/some/file.tns.ts')) - .subscribe(x => expect(x).toBe(content2)); + pHost.read(normalize('/some/file.tns.ts')).subscribe((x) => expect(x).toBe(content2)); }); }); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/record.ts b/packages/angular_devkit/core/src/virtual-fs/host/record.ts index 899c445d735e..98a445385bbb 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/record.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/record.ts @@ -1,19 +1,24 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { EMPTY, Observable, concat, + concatMap, + map, from as observableFrom, of, + reduce, + switchMap, throwError, + toArray, } from 'rxjs'; -import { concatMap, map, reduce, switchMap, toArray } from 'rxjs/operators'; import { FileAlreadyExistException, FileDoesNotExistException, @@ -31,7 +36,6 @@ import { } from './interface'; import { SimpleMemoryHost } from './memory'; - export interface CordHostCreate { kind: 'create'; path: Path; @@ -51,11 +55,7 @@ export interface CordHostDelete { kind: 'delete'; path: Path; } -export type CordHostRecord = CordHostCreate - | CordHostOverwrite - | CordHostRename - | CordHostDelete; - +export type CordHostRecord = CordHostCreate | CordHostOverwrite | CordHostRename | CordHostDelete; /** * A Host that records changes to the underlying Host, while keeping a record of Create, Overwrite, @@ -68,16 +68,20 @@ export type CordHostRecord = CordHostCreate * the create/overwrite records IIF the files does/doesn't already exist. */ export class CordHost extends SimpleMemoryHost { - protected _filesToCreate = new Set(); - protected _filesToRename = new Map(); - protected _filesToRenameRevert = new Map(); - protected _filesToDelete = new Set(); - protected _filesToOverwrite = new Set(); - - constructor(protected _back: ReadonlyHost) { super(); } + protected _filesToCreate: Set = new Set(); + protected _filesToRename: Map = new Map(); + protected _filesToRenameRevert: Map = new Map(); + protected _filesToDelete: Set = new Set(); + protected _filesToOverwrite: Set = new Set(); + + constructor(protected _back: ReadonlyHost) { + super(); + } - get backend(): ReadonlyHost { return this._back; } - get capabilities(): HostCapabilities { + get backend(): ReadonlyHost { + return this._back; + } + override get capabilities(): HostCapabilities { // Our own host is always Synchronous, but the backend might not be. return { synchronous: this._back.capabilities.synchronous, @@ -113,13 +117,15 @@ export class CordHost extends SimpleMemoryHost { commit(host: Host, force = false): Observable { // Really commit everything to the actual host. return observableFrom(this.records()).pipe( - concatMap(record => { + concatMap((record) => { switch (record.kind) { - case 'delete': return host.delete(record.path); - case 'rename': return host.rename(record.from, record.to); + case 'delete': + return host.delete(record.path); + case 'rename': + return host.rename(record.from, record.to); case 'create': return host.exists(record.path).pipe( - switchMap(exists => { + switchMap((exists) => { if (exists && !force) { return throwError(new FileAlreadyExistException(record.path)); } else { @@ -129,7 +135,7 @@ export class CordHost extends SimpleMemoryHost { ); case 'overwrite': return host.exists(record.path).pipe( - switchMap(exists => { + switchMap((exists) => { if (!exists && !force) { return throwError(new FileDoesNotExistException(record.path)); } else { @@ -145,18 +151,37 @@ export class CordHost extends SimpleMemoryHost { records(): CordHostRecord[] { return [ - ...[...this._filesToDelete.values()].map(path => ({ - kind: 'delete', path, - }) as CordHostRecord), - ...[...this._filesToRename.entries()].map(([from, to]) => ({ - kind: 'rename', from, to, - }) as CordHostRecord), - ...[...this._filesToCreate.values()].map(path => ({ - kind: 'create', path, content: this._read(path), - }) as CordHostRecord), - ...[...this._filesToOverwrite.values()].map(path => ({ - kind: 'overwrite', path, content: this._read(path), - }) as CordHostRecord), + ...[...this._filesToDelete.values()].map( + (path) => + ({ + kind: 'delete', + path, + }) as CordHostRecord, + ), + ...[...this._filesToRename.entries()].map( + ([from, to]) => + ({ + kind: 'rename', + from, + to, + }) as CordHostRecord, + ), + ...[...this._filesToCreate.values()].map( + (path) => + ({ + kind: 'create', + path, + content: this._read(path), + }) as CordHostRecord, + ), + ...[...this._filesToOverwrite.values()].map( + (path) => + ({ + kind: 'overwrite', + path, + content: this._read(path), + }) as CordHostRecord, + ), ]; } @@ -184,14 +209,14 @@ export class CordHost extends SimpleMemoryHost { overwrite(path: Path, content: FileBuffer): Observable { return this.isDirectory(path).pipe( - switchMap(isDir => { + switchMap((isDir) => { if (isDir) { return throwError(new PathIsDirectoryException(path)); } return this.exists(path); }), - switchMap(exists => { + switchMap((exists) => { if (!exists) { return throwError(new FileDoesNotExistException(path)); } @@ -205,9 +230,9 @@ export class CordHost extends SimpleMemoryHost { ); } - write(path: Path, content: FileBuffer): Observable { + override write(path: Path, content: FileBuffer): Observable { return this.exists(path).pipe( - switchMap(exists => { + switchMap((exists) => { if (exists) { // It exists, but might be being renamed or deleted. In that case we want to create it. if (this.willRename(path) || this.willDelete(path)) { @@ -222,7 +247,7 @@ export class CordHost extends SimpleMemoryHost { ); } - read(path: Path): Observable { + override read(path: Path): Observable { if (this._exists(path)) { return super.read(path); } @@ -230,7 +255,7 @@ export class CordHost extends SimpleMemoryHost { return this._back.read(path); } - delete(path: Path): Observable { + override delete(path: Path): Observable { if (this._exists(path)) { if (this._filesToCreate.has(path)) { this._filesToCreate.delete(path); @@ -253,7 +278,7 @@ export class CordHost extends SimpleMemoryHost { return super.delete(path); } else { return this._back.exists(path).pipe( - switchMap(exists => { + switchMap((exists) => { if (exists) { this._filesToDelete.add(path); @@ -266,11 +291,8 @@ export class CordHost extends SimpleMemoryHost { } } - rename(from: Path, to: Path): Observable { - return concat( - this.exists(to), - this.exists(from), - ).pipe( + override rename(from: Path, to: Path): Observable { + return concat(this.exists(to), this.exists(from)).pipe( toArray(), switchMap(([existTo, existFrom]) => { if (!existFrom) { @@ -298,7 +320,7 @@ export class CordHost extends SimpleMemoryHost { // if will be by-passed because we just deleted the `from` path from files to overwrite. return concat( this.rename(from, to), - new Observable(x => { + new Observable((x) => { this._filesToOverwrite.add(to); x.complete(); }), @@ -310,9 +332,7 @@ export class CordHost extends SimpleMemoryHost { this._filesToOverwrite.add(to); // We need to delete the original and write the new one. - return this.read(from).pipe( - map(content => this._write(to, content)), - ); + return this.read(from).pipe(map((content) => this._write(to, content))); } const maybeTo1 = this._filesToRenameRevert.get(from); @@ -332,66 +352,67 @@ export class CordHost extends SimpleMemoryHost { return super.rename(from, to); } else { // Create a file with the same content. - return this._back.read(from).pipe( - switchMap(content => super.write(to, content)), - ); + return this._back.read(from).pipe(switchMap((content) => super.write(to, content))); } }), ); } - list(path: Path): Observable { - return concat( - super.list(path), - this._back.list(path), - ).pipe( + override list(path: Path): Observable { + return concat(super.list(path), this._back.list(path)).pipe( reduce((list: Set, curr: PathFragment[]) => { - curr.forEach(elem => list.add(elem)); + curr.forEach((elem) => list.add(elem)); return list; }, new Set()), - map(set => [...set]), + map((set) => [...set]), ); } - exists(path: Path): Observable { + override exists(path: Path): Observable { return this._exists(path) ? of(true) - : ((this.willDelete(path) || this.willRename(path)) ? of(false) : this._back.exists(path)); + : this.willDelete(path) || this.willRename(path) + ? of(false) + : this._back.exists(path); } - isDirectory(path: Path): Observable { + override isDirectory(path: Path): Observable { return this._exists(path) ? super.isDirectory(path) : this._back.isDirectory(path); } - isFile(path: Path): Observable { + override isFile(path: Path): Observable { return this._exists(path) ? super.isFile(path) - : ((this.willDelete(path) || this.willRename(path)) ? of(false) : this._back.isFile(path)); + : this.willDelete(path) || this.willRename(path) + ? of(false) + : this._back.isFile(path); } - stat(path: Path): Observable | null { + override stat(path: Path): Observable | null { return this._exists(path) ? super.stat(path) - : ((this.willDelete(path) || this.willRename(path)) ? of(null) : this._back.stat(path)); + : this.willDelete(path) || this.willRename(path) + ? of(null) + : this._back.stat(path); } - watch(path: Path, options?: HostWatchOptions) { + override watch(path: Path, options?: HostWatchOptions) { // Watching not supported. return null; } - willCreate(path: Path) { + willCreate(path: Path): boolean { return this._filesToCreate.has(path); } - willOverwrite(path: Path) { + willOverwrite(path: Path): boolean { return this._filesToOverwrite.has(path); } - willDelete(path: Path) { + willDelete(path: Path): boolean { return this._filesToDelete.has(path); } - willRename(path: Path) { + willRename(path: Path): boolean { return this._filesToRename.has(path); } - willRenameTo(path: Path, to: Path) { + willRenameTo(path: Path, to: Path): boolean { return this._filesToRename.get(path) === to; } } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts b/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts index 2500cc66bb5d..dd50be84f966 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/record_spec.ts @@ -1,33 +1,31 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-any no-big-function + import { path } from '../path'; -import { fileBuffer } from './buffer'; import { CordHost } from './record'; -import { test } from './test'; - +import * as test from './test'; describe('CordHost', () => { const TestHost = test.TestHost; const mutatingTestRecord = ['write', 'delete', 'rename']; - it('works (create)', done => { + it('works (create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); @@ -36,19 +34,21 @@ describe('CordHost', () => { done(); }); - it('works (create -> create)', done => { + it('works (create -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); - host.write(path`/blue`, fileBuffer`hi again`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); + host + .write(path`/blue`, new TextEncoder().encode(`hi again`).buffer) + .subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); @@ -58,40 +58,39 @@ describe('CordHost', () => { done(); }); - it('works (create -> delete)', done => { + it('works (create -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); host.delete(path`/blue`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ - ]); + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([]); expect(target.$exists('/hello')).toBe(false); expect(target.$exists('/blue')).toBe(false); done(); }); - it('works (create -> rename)', done => { + it('works (create -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/red` }, ]); @@ -102,20 +101,20 @@ describe('CordHost', () => { done(); }); - it('works (create -> rename (identity))', done => { + it('works (create -> rename (identity))', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/blue`).subscribe(undefined, done.fail); const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/blue` }, ]); @@ -125,13 +124,13 @@ describe('CordHost', () => { done(); }); - it('works (create -> rename -> rename)', done => { + it('works (create -> rename -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(undefined, done.fail); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(undefined, done.fail); host.rename(path`/blue`, path`/red`).subscribe(undefined, done.fail); host.rename(path`/red`, path`/yellow`).subscribe(undefined, done.fail); @@ -139,7 +138,7 @@ describe('CordHost', () => { host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/yellow` }, ]); @@ -151,7 +150,7 @@ describe('CordHost', () => { done(); }); - it('works (rename)', done => { + it('works (rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); @@ -163,7 +162,7 @@ describe('CordHost', () => { host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, ]); @@ -173,7 +172,7 @@ describe('CordHost', () => { done(); }); - it('works (rename -> rename)', done => { + it('works (rename -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); @@ -186,7 +185,7 @@ describe('CordHost', () => { host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/red` }, ]); @@ -197,20 +196,22 @@ describe('CordHost', () => { done(); }); - it('works (rename -> create)', done => { + it('works (rename -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/hello` }, ]); @@ -221,19 +222,21 @@ describe('CordHost', () => { done(); }); - it('works (overwrite)', done => { + it('works (overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); @@ -243,20 +246,24 @@ describe('CordHost', () => { done(); }); - it('works (overwrite -> overwrite)', done => { + it('works (overwrite -> overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); - host.write(path`/hello`, fileBuffer`again`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`again`).buffer) + .subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); // Check that there's only 1 write done. - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); @@ -266,19 +273,21 @@ describe('CordHost', () => { done(); }); - it('works (overwrite -> rename)', done => { + it('works (overwrite -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/blue` }, ]); @@ -290,19 +299,21 @@ describe('CordHost', () => { done(); }); - it('works (overwrite -> delete)', done => { + it('works (overwrite -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); host.delete(path`/hello`).subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); @@ -310,19 +321,21 @@ describe('CordHost', () => { done(); }); - it('works (rename -> overwrite)', done => { + it('works (rename -> overwrite)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.rename(path`/hello`, path`/blue`).subscribe(undefined, done.fail); - host.write(path`/blue`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/blue`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'rename', from: path`/hello`, to: path`/blue` }, { kind: 'write', path: path`/blue` }, ]); @@ -334,7 +347,7 @@ describe('CordHost', () => { done(); }); - it('works (delete)', done => { + it('works (delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); @@ -345,7 +358,7 @@ describe('CordHost', () => { const target = new TestHost(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); @@ -353,19 +366,21 @@ describe('CordHost', () => { done(); }); - it('works (delete -> create)', done => { + it('works (delete -> create)', (done) => { const base = new TestHost({ '/hello': 'world', }); const host = new CordHost(base); host.delete(path`/hello`).subscribe(undefined, done.fail); - host.write(path`/hello`, fileBuffer`beautiful world`).subscribe(undefined, done.fail); + host + .write(path`/hello`, new TextEncoder().encode(`beautiful world`).buffer) + .subscribe(undefined, done.fail); const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'write', path: path`/hello` }, ]); @@ -374,7 +389,7 @@ describe('CordHost', () => { done(); }); - it('works (rename -> delete)', done => { + it('works (rename -> delete)', (done) => { const base = new TestHost({ '/hello': 'world', }); @@ -386,7 +401,7 @@ describe('CordHost', () => { const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, ]); @@ -394,7 +409,7 @@ describe('CordHost', () => { done(); }); - it('works (delete -> rename)', done => { + it('works (delete -> rename)', (done) => { const base = new TestHost({ '/hello': 'world', '/blue': 'foo', @@ -406,7 +421,7 @@ describe('CordHost', () => { const target = base.clone(); host.commit(target).subscribe(undefined, done.fail); - expect(target.records.filter(x => mutatingTestRecord.includes(x.kind))).toEqual([ + expect(target.records.filter((x) => mutatingTestRecord.includes(x.kind))).toEqual([ { kind: 'delete', path: path`/hello` }, { kind: 'write', path: path`/blue` }, ]); @@ -422,14 +437,18 @@ describe('CordHost', () => { }); const host = new CordHost(base); - host.write(path`/blue`, fileBuffer`hi`).subscribe(); + host.write(path`/blue`, new TextEncoder().encode(`hi`).buffer).subscribe(); const target = new TestHost({ '/blue': 'test', }); let error = false; - host.commit(target).subscribe(undefined, () => error = true, () => error = false); + host.commit(target).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); @@ -439,12 +458,16 @@ describe('CordHost', () => { }); const host = new CordHost(base); - host.write(path`/hello`, fileBuffer`hi`).subscribe(); + host.write(path`/hello`, new TextEncoder().encode(`hi`).buffer).subscribe(); const target = new TestHost({}); let error = false; - host.commit(target).subscribe(undefined, () => error = true, () => error = false); + host.commit(target).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); @@ -459,7 +482,11 @@ describe('CordHost', () => { const target = new TestHost({}); let error = false; - host.commit(target).subscribe(undefined, () => error = true, () => error = false); + host.commit(target).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); @@ -476,7 +503,11 @@ describe('CordHost', () => { }); let error = false; - host.commit(target).subscribe(undefined, () => error = true, () => error = false); + host.commit(target).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); @@ -487,20 +518,25 @@ describe('CordHost', () => { const host = new CordHost(base); let error = false; - host.write(path`/dir`, fileBuffer`beautiful world`) - .subscribe(undefined, () => error = true, () => error = false); + host.write(path`/dir`, new TextEncoder().encode(`beautiful world`).buffer).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); it('errors (delete: not exist)', () => { - const base = new TestHost({ - }); + const base = new TestHost({}); const host = new CordHost(base); let error = false; - host.delete(path`/hello`) - .subscribe(undefined, () => error = true, () => error = false); + host.delete(path`/hello`).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); @@ -513,20 +549,25 @@ describe('CordHost', () => { const host = new CordHost(base); let error = false; - host.rename(path`/hello`, path`/blue`) - .subscribe(undefined, () => error = true, () => error = false); + host.rename(path`/hello`, path`/blue`).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); it('errors (rename: not exist)', () => { - const base = new TestHost({ - }); + const base = new TestHost({}); const host = new CordHost(base); let error = false; - host.rename(path`/hello`, path`/blue`) - .subscribe(undefined, () => error = true, () => error = false); + host.rename(path`/hello`, path`/blue`).subscribe( + undefined, + () => (error = true), + () => (error = false), + ); expect(error).toBe(true); }); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts b/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts index 69c53d642e2f..3002290918a0 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/resolver.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable } from 'rxjs'; import { Path, PathFragment } from '../path'; import { @@ -25,7 +26,9 @@ export abstract class ResolverHost implements Host { constructor(protected _delegate: Host) {} - get capabilities(): HostCapabilities { return this._delegate.capabilities; } + get capabilities(): HostCapabilities { + return this._delegate.capabilities; + } write(path: Path, content: FileBuffer): Observable { return this._delegate.write(this._resolve(path), content); diff --git a/packages/angular_devkit/core/src/virtual-fs/host/safe.ts b/packages/angular_devkit/core/src/virtual-fs/host/safe.ts index fd4ef719261c..a260a98e2717 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/safe.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/safe.ts @@ -1,12 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { Observable, of } from 'rxjs'; -import { catchError } from 'rxjs/operators'; + +import { Observable, catchError, of } from 'rxjs'; import { Path, PathFragment } from '../path'; import { FileBuffer, HostCapabilities, ReadonlyHost, Stats } from './interface'; @@ -26,31 +26,23 @@ export class SafeReadonlyHost implements ReadonlyHos } list(path: Path): Observable { - return this._delegate.list(path).pipe( - catchError(() => of([])), - ); + return this._delegate.list(path).pipe(catchError(() => of([]))); } exists(path: Path): Observable { return this._delegate.exists(path); } isDirectory(path: Path): Observable { - return this._delegate.isDirectory(path).pipe( - catchError(() => of(false)), - ); + return this._delegate.isDirectory(path).pipe(catchError(() => of(false))); } isFile(path: Path): Observable { - return this._delegate.isFile(path).pipe( - catchError(() => of(false)), - ); + return this._delegate.isFile(path).pipe(catchError(() => of(false))); } // Some hosts may not support stats. stat(path: Path): Observable | null> | null { const maybeStat = this._delegate.stat(path); - return maybeStat && maybeStat.pipe( - catchError(() => of(null)), - ); + return maybeStat && maybeStat.pipe(catchError(() => of(null))); } } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts b/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts index da6e884bc266..425b603a4903 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/scoped.ts @@ -1,16 +1,20 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { NormalizedRoot, Path, join } from '../path'; import { Host } from './interface'; import { ResolverHost } from './resolver'; export class ScopedHost extends ResolverHost { - constructor(delegate: Host, protected _root: Path = NormalizedRoot) { + constructor( + delegate: Host, + protected _root: Path = NormalizedRoot, + ) { super(delegate); } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/sync.ts b/packages/angular_devkit/core/src/virtual-fs/host/sync.ts index d28097c69bf1..0e34f9c551d0 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/sync.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/sync.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable } from 'rxjs'; import { BaseException } from '../../exception'; import { Path, PathFragment } from '../path'; @@ -18,9 +19,10 @@ import { Stats, } from './interface'; - export class SynchronousDelegateExpectedException extends BaseException { - constructor() { super(`Expected a synchronous delegate but got an asynchronous one.`); } + constructor() { + super(`Expected a synchronous delegate but got an asynchronous one.`); + } } /** @@ -37,11 +39,13 @@ export class SyncDelegateHost { let completed = false; let result: ResultT | undefined = undefined; let errorResult: Error | undefined = undefined; - observable.subscribe({ - next(x: ResultT) { result = x; }, - error(err: Error) { errorResult = err; }, - complete() { completed = true; }, - }); + // Perf note: this is not using an observer object to avoid a performance penalty in RxJS. + // See https://github.com/ReactiveX/rxjs/pull/5646 for details. + observable.subscribe( + (x: ResultT) => (result = x), + (err: Error) => (errorResult = err), + () => (completed = true), + ); if (errorResult !== undefined) { throw errorResult; @@ -53,14 +57,14 @@ export class SyncDelegateHost { // The non-null operation is to work around `void` type. We don't allow to return undefined // but ResultT could be void, which is undefined in JavaScript, so this doesn't change the // behaviour. - // tslint:disable-next-line:no-non-null-assertion - return result !; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return result!; } get capabilities(): HostCapabilities { return this._delegate.capabilities; } - get delegate() { + get delegate(): Host { return this._delegate; } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/test.ts b/packages/angular_devkit/core/src/virtual-fs/host/test.ts index 55179384b5f6..4e7b083d8bdc 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/test.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/test.ts @@ -1,156 +1,162 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Observable } from 'rxjs'; import { Path, PathFragment, join, normalize } from '../path'; -import { fileBufferToString, stringToFileBuffer } from './buffer'; import { FileBuffer, HostWatchEvent, HostWatchOptions, Stats } from './interface'; import { SimpleMemoryHost, SimpleMemoryHostStats } from './memory'; import { SyncDelegateHost } from './sync'; -export namespace test { - - export type TestLogRecord = { - kind: 'write' | 'read' | 'delete' | 'list' | 'exists' | 'isDirectory' | 'isFile' | 'stat' - | 'watch'; - path: Path; - } | { - kind: 'rename'; - from: Path; - to: Path; - }; - - - export class TestHost extends SimpleMemoryHost { - protected _records: TestLogRecord[] = []; - protected _sync: SyncDelegateHost<{}>; - - constructor(map: { [path: string]: string } = {}) { - super(); - - for (const filePath of Object.getOwnPropertyNames(map)) { - this._write(normalize(filePath), stringToFileBuffer(map[filePath])); - } - } - - get records(): TestLogRecord[] { - return [...this._records]; - } - clearRecords() { - this._records = []; +export type TestLogRecord = + | { + kind: + | 'write' + | 'read' + | 'delete' + | 'list' + | 'exists' + | 'isDirectory' + | 'isFile' + | 'stat' + | 'watch'; + path: Path; + } + | { + kind: 'rename'; + from: Path; + to: Path; + }; + +export class TestHost extends SimpleMemoryHost { + protected _records: TestLogRecord[] = []; + protected _sync: SyncDelegateHost<{}> | null = null; + + constructor(map: { [path: string]: string } = {}) { + super(); + + for (const filePath of Object.getOwnPropertyNames(map)) { + this._write(normalize(filePath), new TextEncoder().encode(map[filePath]).buffer); } + } - get files(): Path[] { - const sync = this.sync; - function _visit(p: Path): Path[] { - return sync.list(p) - .map(fragment => join(p, fragment)) - .reduce((files, path) => { - if (sync.isDirectory(path)) { - return files.concat(_visit(path)); - } else { - return files.concat(path); - } - }, [] as Path[]); - } - - return _visit(normalize('/')); - } + get records(): TestLogRecord[] { + return [...this._records]; + } + clearRecords(): void { + this._records = []; + } - get sync() { - if (!this._sync) { - this._sync = new SyncDelegateHost<{}>(this); - } + get files(): Path[] { + const sync = this.sync; + function _visit(p: Path): Path[] { + return sync + .list(p) + .map((fragment) => join(p, fragment)) + .reduce((files, path) => { + if (sync.isDirectory(path)) { + return files.concat(_visit(path)); + } else { + return files.concat(path); + } + }, [] as Path[]); + } + + return _visit(normalize('/')); + } - return this._sync; + get sync(): SyncDelegateHost<{}> { + if (!this._sync) { + this._sync = new SyncDelegateHost<{}>(this); } - clone() { - const newHost = new TestHost(); - newHost._cache = new Map(this._cache); + return this._sync; + } - return newHost; - } + clone(): TestHost { + const newHost = new TestHost(); + newHost._cache = new Map(this._cache); - // Override parents functions to keep a record of all operators that were done. - protected _write(path: Path, content: FileBuffer) { - this._records.push({ kind: 'write', path }); + return newHost; + } - return super._write(path, content); - } - protected _read(path: Path) { - this._records.push({ kind: 'read', path }); + // Override parents functions to keep a record of all operators that were done. + protected override _write(path: Path, content: FileBuffer): void { + this._records.push({ kind: 'write', path }); - return super._read(path); - } - protected _delete(path: Path) { - this._records.push({ kind: 'delete', path }); + return super._write(path, content); + } + protected override _read(path: Path): ArrayBuffer { + this._records.push({ kind: 'read', path }); - return super._delete(path); - } - protected _rename(from: Path, to: Path) { - this._records.push({ kind: 'rename', from, to }); + return super._read(path); + } + protected override _delete(path: Path): void { + this._records.push({ kind: 'delete', path }); - return super._rename(from, to); - } - protected _list(path: Path): PathFragment[] { - this._records.push({ kind: 'list', path }); + return super._delete(path); + } + protected override _rename(from: Path, to: Path): void { + this._records.push({ kind: 'rename', from, to }); - return super._list(path); - } - protected _exists(path: Path) { - this._records.push({ kind: 'exists', path }); + return super._rename(from, to); + } + protected override _list(path: Path): PathFragment[] { + this._records.push({ kind: 'list', path }); - return super._exists(path); - } - protected _isDirectory(path: Path) { - this._records.push({ kind: 'isDirectory', path }); + return super._list(path); + } + protected override _exists(path: Path): boolean { + this._records.push({ kind: 'exists', path }); - return super._isDirectory(path); - } - protected _isFile(path: Path) { - this._records.push({ kind: 'isFile', path }); + return super._exists(path); + } + protected override _isDirectory(path: Path): boolean { + this._records.push({ kind: 'isDirectory', path }); - return super._isFile(path); - } - protected _stat(path: Path): Stats | null { - this._records.push({ kind: 'stat', path }); + return super._isDirectory(path); + } + protected override _isFile(path: Path): boolean { + this._records.push({ kind: 'isFile', path }); - return super._stat(path); - } - protected _watch(path: Path, options?: HostWatchOptions): Observable { - this._records.push({ kind: 'watch', path }); + return super._isFile(path); + } + protected override _stat(path: Path): Stats | null { + this._records.push({ kind: 'stat', path }); - return super._watch(path, options); - } + return super._stat(path); + } + protected override _watch(path: Path, options?: HostWatchOptions): Observable { + this._records.push({ kind: 'watch', path }); - $write(path: string, content: string) { - return super._write(normalize(path), stringToFileBuffer(content)); - } + return super._watch(path, options); + } - $read(path: string): string { - return fileBufferToString(super._read(normalize(path))); - } + $write(path: string, content: string): void { + return super._write(normalize(path), new TextEncoder().encode(content).buffer); + } - $list(path: string): PathFragment[] { - return super._list(normalize(path)); - } + $read(path: string): string { + return new TextDecoder().decode(super._read(normalize(path))); + } - $exists(path: string) { - return super._exists(normalize(path)); - } + $list(path: string): PathFragment[] { + return super._list(normalize(path)); + } - $isDirectory(path: string) { - return super._isDirectory(normalize(path)); - } + $exists(path: string): boolean { + return super._exists(normalize(path)); + } - $isFile(path: string) { - return super._isFile(normalize(path)); - } + $isDirectory(path: string): boolean { + return super._isDirectory(normalize(path)); } + $isFile(path: string): boolean { + return super._isFile(normalize(path)); + } } diff --git a/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts b/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts index 4e0cb296a155..044db5725729 100644 --- a/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/host/test_spec.ts @@ -1,16 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { test } from './test'; +import * as test from './test'; // Yes, we realize the irony of testing a test host. describe('TestHost', () => { - it('can list files', () => { const files = { '/x/y/z': '', @@ -22,5 +21,4 @@ describe('TestHost', () => { const host = new test.TestHost(files); expect(host.files.sort() as string[]).toEqual(Object.keys(files).sort()); }); - }); diff --git a/packages/angular_devkit/core/src/virtual-fs/index.ts b/packages/angular_devkit/core/src/virtual-fs/index.ts index 988c3b40d449..e062418e6b54 100644 --- a/packages/angular_devkit/core/src/virtual-fs/index.ts +++ b/packages/angular_devkit/core/src/virtual-fs/index.ts @@ -1,11 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -export * from './path'; import * as virtualFs from './host/index'; + +export * from './path'; export { virtualFs }; diff --git a/packages/angular_devkit/core/src/virtual-fs/path.ts b/packages/angular_devkit/core/src/virtual-fs/path.ts index d5edd6da300a..783bfe9d4402 100644 --- a/packages/angular_devkit/core/src/virtual-fs/path.ts +++ b/packages/angular_devkit/core/src/virtual-fs/path.ts @@ -1,25 +1,30 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { BaseException } from '../exception'; import { TemplateTag } from '../utils/literals'; - export class InvalidPathException extends BaseException { - constructor(path: string) { super(`Path ${JSON.stringify(path)} is invalid.`); } + constructor(path: string) { + super(`Path ${JSON.stringify(path)} is invalid.`); + } } export class PathMustBeAbsoluteException extends BaseException { - constructor(path: string) { super(`Path ${JSON.stringify(path)} must be absolute.`); } + constructor(path: string) { + super(`Path ${JSON.stringify(path)} must be absolute.`); + } } export class PathCannotBeFragmentException extends BaseException { - constructor(path: string) { super(`Path ${JSON.stringify(path)} cannot be made a fragment.`); } + constructor(path: string) { + super(`Path ${JSON.stringify(path)} cannot be made a fragment.`); + } } - /** * A Path recognized by most methods in the DevKit. */ @@ -34,20 +39,15 @@ export type PathFragment = Path & { __PRIVATE_DEVKIT_PATH_FRAGMENT: void; }; - /** * The Separator for normalized path. - * @type {Path} */ -export const NormalizedSep = '/' as Path; - +export const NormalizedSep: Path = '/' as Path; /** * The root of a normalized path. - * @type {Path} */ -export const NormalizedRoot = NormalizedSep as Path; - +export const NormalizedRoot: Path = NormalizedSep; /** * Split a path into multiple path fragments. Each fragments except the last one will end with @@ -56,8 +56,8 @@ export const NormalizedRoot = NormalizedSep as Path; * @returns {Path[]} An array of path fragments. */ export function split(path: Path): PathFragment[] { - const fragments = path.split(NormalizedSep).map(x => fragment(x)); - if (fragments[fragments.length - 1].length === 0) { + const fragments = path.split(NormalizedSep).map((x) => fragment(x)); + if (fragments.at(-1)?.length === 0) { fragments.pop(); } @@ -73,11 +73,10 @@ export function extname(path: Path): string { if (i < 1) { return ''; } else { - return base.substr(i); + return base.slice(i); } } - /** * Return the basename of the path, as a Path. See path.basename */ @@ -86,11 +85,10 @@ export function basename(path: Path): PathFragment { if (i == -1) { return fragment(path); } else { - return fragment(path.substr(path.lastIndexOf(NormalizedSep) + 1)); + return fragment(path.slice(path.lastIndexOf(NormalizedSep) + 1)); } } - /** * Return the dirname of the path, as a Path. See path.dirname */ @@ -102,10 +100,9 @@ export function dirname(path: Path): Path { const endIndex = index === 0 ? 1 : index; // case of file under root: '/file' - return normalize(path.substr(0, endIndex)); + return normalize(path.slice(0, endIndex)); } - /** * Join multiple paths together, and normalize the result. Accepts strings that will be * normalized as well (but the original must be a path). @@ -118,15 +115,13 @@ export function join(p1: Path, ...others: string[]): Path { } } - /** * Returns true if a path is absolute. */ -export function isAbsolute(p: Path) { +export function isAbsolute(p: Path): boolean { return p.startsWith(NormalizedSep); } - /** * Returns a path such that `join(from, relative(from, to)) == to`. * Both paths must be absolute, otherwise it does not make much sense. @@ -155,19 +150,21 @@ export function relative(from: Path, to: Path): Path { if (splitFrom.length == 0) { p = splitTo.join(NormalizedSep); } else { - p = splitFrom.map(_ => '..').concat(splitTo).join(NormalizedSep); + p = splitFrom + .map(() => '..') + .concat(splitTo) + .join(NormalizedSep); } } return normalize(p); } - /** * Returns a Path that is the resolution of p2, from p1. If p2 is absolute, it will return p2, * otherwise will join both p1 and p2. */ -export function resolve(p1: Path, p2: Path) { +export function resolve(p1: Path, p2: Path): Path { if (isAbsolute(p2)) { return p2; } else { @@ -175,7 +172,6 @@ export function resolve(p1: Path, p2: Path) { } } - export function fragment(path: string): PathFragment { if (path.indexOf(NormalizedSep) != -1) { throw new PathCannotBeFragmentException(path); @@ -184,23 +180,20 @@ export function fragment(path: string): PathFragment { return path as PathFragment; } - /** * normalize() cache to reduce computation. For now this grows and we never flush it, but in the * future we might want to add a few cache flush to prevent this from growing too large. */ let normalizedCache = new Map(); - /** * Reset the cache. This is only useful for testing. * @private */ -export function resetNormalizeCache() { +export function resetNormalizeCache(): void { normalizedCache = new Map(); } - /** * Normalize a string into a Path. This is the only mean to get a Path type from a string that * represents a system path. This method cache the results as real world paths tend to be @@ -225,7 +218,6 @@ export function normalize(path: string): Path { return maybePath; } - /** * The no cache version of the normalize() function. Used for benchmarking and testing. */ @@ -238,12 +230,12 @@ export function noCacheNormalize(path: string): Path { // Match absolute windows path. const original = path; - if (path.match(/^[A-Z]:[\/\\]/i)) { - path = '\\' + path[0] + '\\' + path.substr(3); + if (path.match(/^[A-Z]:[/\\]/i)) { + path = '\\' + path[0].toUpperCase() + '\\' + path.slice(3); } // We convert Windows paths as well here. - const p = path.split(/[\/\\]/g); + const p = path.split(/[/\\]/g); let relative = false; let i = 1; @@ -273,7 +265,7 @@ export function noCacheNormalize(path: string): Path { } if (p.length == 1) { - return p[0] == '' ? NormalizedSep : '' as Path; + return p[0] == '' ? NormalizedSep : ('' as Path); } else { if (p[0] == '.') { p.shift(); @@ -283,12 +275,10 @@ export function noCacheNormalize(path: string): Path { } } - export const path: TemplateTag = (strings, ...values) => { return normalize(String.raw(strings, ...values)); }; - // Platform-specific paths. export type WindowsPath = string & { __PRIVATE_DEVKIT_WINDOWS_PATH: void; diff --git a/packages/angular_devkit/core/src/virtual-fs/path_benchmark.ts b/packages/angular_devkit/core/src/virtual-fs/path_benchmark.ts deleted file mode 100644 index 9973c625bae7..000000000000 --- a/packages/angular_devkit/core/src/virtual-fs/path_benchmark.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-implicit-dependencies -import { benchmark } from '@_/benchmark'; -import { join, noCacheNormalize, normalize, resetNormalizeCache } from './path'; - -const seedrandom = require('seedrandom'); - - -const p1 = '/b/././a/tt/../../../a/b/./d/../c'; -const p2 = '/a/tt/../../../a/b/./d'; - - -const numRandomIter = 10000; - - -describe('Virtual FS Path', () => { - benchmark('join', () => join(normalize(p1), p2)); - - describe('normalize', () => { - let rng: () => number; - let cases: string[]; - - // Math.random() doesn't allow us to set a seed, so we use a library. - beforeEach(() => { - rng = seedrandom('some fixed value'); - - function _str(len: number) { - let r = ''; - const space = 'abcdefghijklmnopqrstuvwxyz0123456789'; - for (let i = 0; i < len; i++) { - r += space[Math.floor(rng() * space.length)]; - } - - return r; - } - - // Build test cases. - cases = new Array(numRandomIter) - .fill(0) - .map(() => { - return new Array(Math.floor(rng() * 20 + 5)) - .fill(0) - .map(() => _str(rng() * 20 + 3)) - .join('/'); - }); - - resetNormalizeCache(); - }); - - describe('random (0 cache hits)', () => { - benchmark('', i => normalize(cases[i]), i => noCacheNormalize(cases[i])); - }); - - describe('random (10% cache hits)', () => { - beforeEach(() => { - cases = cases.map(x => (rng() < 0.1) ? cases[0] : x); - }); - benchmark('', i => normalize(cases[i]), i => noCacheNormalize(cases[i])); - }); - - describe('random (30% cache hits)', () => { - beforeEach(() => { - cases = cases.map(x => (rng() < 0.3) ? cases[0] : x); - }); - benchmark('', i => normalize(cases[i]), i => noCacheNormalize(cases[i])); - }); - - describe('random (50% cache hits)', () => { - beforeEach(() => { - cases = cases.map(x => (rng() < 0.5) ? cases[0] : x); - }); - benchmark('', i => normalize(cases[i]), i => noCacheNormalize(cases[i])); - }); - - describe('random (80% cache hits)', () => { - beforeEach(() => { - cases = cases.map(x => (rng() < 0.8) ? cases[0] : x); - }); - benchmark('', i => normalize(cases[i]), i => noCacheNormalize(cases[i])); - }); - }); -}); diff --git a/packages/angular_devkit/core/src/virtual-fs/path_spec.ts b/packages/angular_devkit/core/src/virtual-fs/path_spec.ts index a3b3f2433a2f..e5da5e66e838 100644 --- a/packages/angular_devkit/core/src/virtual-fs/path_spec.ts +++ b/packages/angular_devkit/core/src/virtual-fs/path_spec.ts @@ -1,13 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { InvalidPathException, Path, + PathFragment, asWindowsPath, basename, dirname, @@ -17,7 +19,6 @@ import { split, } from './path'; - describe('path', () => { it('normalize', () => { expect(normalize('////')).toBe('/'); @@ -57,12 +58,13 @@ describe('path', () => { expect(normalize('./a/../../a/b/c')).toBe('../a/b/c'); // Invalid use cases. - expect(() => normalize('/./././../././/')) - .toThrow(new InvalidPathException('/./././../././/')); - expect(() => normalize('/./././../././/../')) - .toThrow(new InvalidPathException('/./././../././/../')); - expect(() => normalize('/./././../././a/.')) - .toThrow(new InvalidPathException('/./././../././a/.')); + expect(() => normalize('/./././../././/')).toThrow(new InvalidPathException('/./././../././/')); + expect(() => normalize('/./././../././/../')).toThrow( + new InvalidPathException('/./././../././/../'), + ); + expect(() => normalize('/./././../././a/.')).toThrow( + new InvalidPathException('/./././../././a/.'), + ); expect(() => normalize('/c/../../')).toThrow(new InvalidPathException('/c/../../')); @@ -71,10 +73,9 @@ describe('path', () => { expect(normalize('\\a\\b\\c')).toBe('/a/b/c'); expect(normalize('.\\a\\b\\c')).toBe('a/b/c'); expect(normalize('C:\\a\\b\\c')).toBe('/C/a/b/c'); - expect(normalize('c:\\a\\b\\c')).toBe('/c/a/b/c'); + expect(normalize('c:\\a\\b\\c')).toBe('/C/a/b/c'); expect(normalize('A:\\a\\b\\c')).toBe('/A/a/b/c'); - expect(() => normalize('A:\\..\\..')) - .toThrow(new InvalidPathException('A:\\..\\..')); + expect(() => normalize('A:\\..\\..')).toThrow(new InvalidPathException('A:\\..\\..')); expect(normalize('\\.\\a\\b\\c')).toBe('/a/b/c'); expect(normalize('\\.\\a\\b\\.\\c')).toBe('/a/b/c'); expect(normalize('\\.\\a\\b\\d\\..\\c')).toBe('/a/b/c'); @@ -83,7 +84,7 @@ describe('path', () => { }); describe('split', () => { - const tests = [ + const tests: [string, string[]][] = [ ['a', ['a']], ['/a/b', ['', 'a', 'b']], ['a/b', ['a', 'b']], @@ -92,31 +93,29 @@ describe('path', () => { ['/', ['']], ]; - for (const goldens of tests) { - const result = goldens.pop(); - const args = goldens.map((x: string) => normalize(x)) as Path[]; + for (const [input, result] of tests) { + it(`(${input}) == "${result}"`, () => { + const normalizedInput = normalize(input); - it(`(${JSON.stringify(args)}) == "${result}"`, () => { - expect(split.apply(null, args)).toEqual(result); + expect(split(normalizedInput)).toEqual(result as PathFragment[]); }); } }); describe('join', () => { - const tests = [ - ['a', 'a'], - ['/a', '/b', '/a/b'], - ['/a', '/b', '/c', '/a/b/c'], - ['/a', 'b', 'c', '/a/b/c'], - ['a', 'b', 'c', 'a/b/c'], + const tests: [string[], string][] = [ + [['a'], 'a'], + [['/a', '/b'], '/a/b'], + [['/a', '/b', '/c'], '/a/b/c'], + [['/a', 'b', 'c'], '/a/b/c'], + [['a', 'b', 'c'], 'a/b/c'], ]; - for (const goldens of tests) { - const result = goldens.pop(); - const args = goldens.map(x => normalize(x)) as Path[]; + for (const [input, result] of tests) { + const args = input.map((x) => normalize(x)) as [Path, ...Path[]]; it(`(${JSON.stringify(args)}) == "${result}"`, () => { - expect(join.apply(null, args)).toBe(result); + expect(join(...args)).toBe(result); }); } }); @@ -129,12 +128,10 @@ describe('path', () => { ['/a/b/c', '/a/b', '..'], ['/a/b/c', '/a/b/d', '../d'], ['/a/b/c/d/e', '/a/f/g', '../../../../f/g'], - [ - '/src/app/sub1/test1', '/src/app/sub2/test2', - '../../sub2/test2', - ], + ['/src/app/sub1/test1', '/src/app/sub2/test2', '../../sub2/test2'], ['/', '/a/b/c', 'a/b/c'], ['/a/b/c', '/d', '../../../d'], + ['E:\\abc', 'e:\\abc\\def', 'def'], ]; for (const [from, to, result] of tests) { @@ -165,9 +162,8 @@ describe('path', () => { }); it('asWindowsPath', () => { - expect(asWindowsPath(normalize('c:/'))).toBe('c:\\'); - expect(asWindowsPath(normalize('c:/b/'))).toBe('c:\\b'); - expect(asWindowsPath(normalize('c:/b/c'))).toBe('c:\\b\\c'); + expect(asWindowsPath(normalize('c:/'))).toBe('C:\\'); + expect(asWindowsPath(normalize('c:/b/'))).toBe('C:\\b'); + expect(asWindowsPath(normalize('c:/b/c'))).toBe('C:\\b\\c'); }); - }); diff --git a/packages/angular_devkit/core/src/workspace/core.ts b/packages/angular_devkit/core/src/workspace/core.ts index ad5ae8be981f..261781ba05fa 100644 --- a/packages/angular_devkit/core/src/workspace/core.ts +++ b/packages/angular_devkit/core/src/workspace/core.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { basename, getSystemPath, join, normalize } from '../virtual-fs'; import { WorkspaceDefinition } from './definitions'; import { WorkspaceHost } from './host'; @@ -80,7 +81,10 @@ export async function readWorkspace( } } if (!found) { - throw new Error('Unable to locate a workspace file for workspace path.'); + throw new Error( + 'Unable to locate a workspace file for workspace path. Are you missing an `angular.json`' + + ' or `.angular.json` file?', + ); } } else if (format === undefined) { const filename = basename(normalize(path)); diff --git a/packages/angular_devkit/core/src/workspace/core_spec.ts b/packages/angular_devkit/core/src/workspace/core_spec.ts index f92170be2586..5f953e98c912 100644 --- a/packages/angular_devkit/core/src/workspace/core_spec.ts +++ b/packages/angular_devkit/core/src/workspace/core_spec.ts @@ -1,11 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-big-function + +/* eslint-disable @typescript-eslint/no-empty-function */ import { getSystemPath, join, normalize } from '../virtual-fs'; import { WorkspaceFormat, @@ -17,9 +18,8 @@ import { import { WorkspaceDefinition } from './definitions'; import { WorkspaceHost } from './host'; - describe('readWorkspace', () => { - it('attempts to read from specified file path [angular.json]', async (done) => { + it('attempts to read from specified file path [angular.json]', async () => { const requestedPath = '/path/to/workspace/angular.json'; const host: WorkspaceHost = { @@ -42,11 +42,9 @@ describe('readWorkspace', () => { }; await readWorkspace(requestedPath, host); - - done(); }); - it('attempts to read from specified file path [.angular.json]', async (done) => { + it('attempts to read from specified file path [.angular.json]', async () => { const requestedPath = '/path/to/workspace/.angular.json'; const host: WorkspaceHost = { @@ -69,11 +67,9 @@ describe('readWorkspace', () => { }; await readWorkspace(requestedPath, host); - - done(); }); - it('attempts to read from specified non-standard file path with format', async (done) => { + it('attempts to read from specified non-standard file path with format', async () => { const requestedPath = '/path/to/workspace/abc.json'; const host: WorkspaceHost = { @@ -96,11 +92,9 @@ describe('readWorkspace', () => { }; await readWorkspace(requestedPath, host, WorkspaceFormat.JSON); - - done(); }); - it('errors when reading from specified non-standard file path without format', async (done) => { + it('errors when reading from specified non-standard file path without format', async () => { const requestedPath = '/path/to/workspace/abc.json'; const host: WorkspaceHost = { @@ -122,17 +116,12 @@ describe('readWorkspace', () => { }, }; - try { - await readWorkspace(requestedPath, host); - fail(); - } catch (e) { - expect(e.message).toContain('Unable to determine format for workspace path'); - } - - done(); + await expectAsync(readWorkspace(requestedPath, host)).toBeRejectedWithError( + /Unable to determine format for workspace path/, + ); }); - it('errors when reading from specified file path with invalid specified format', async (done) => { + it('errors when reading from specified file path with invalid specified format', async () => { const requestedPath = '/path/to/workspace/angular.json'; const host: WorkspaceHost = { @@ -154,17 +143,12 @@ describe('readWorkspace', () => { }, }; - try { - await readWorkspace(requestedPath, host, 12 as WorkspaceFormat); - fail(); - } catch (e) { - expect(e.message).toContain('Unsupported workspace format'); - } - - done(); + await expectAsync( + readWorkspace(requestedPath, host, 12 as WorkspaceFormat), + ).toBeRejectedWithError(/Unsupported workspace format/); }); - it('attempts to find/read from directory path', async (done) => { + it('attempts to find/read from directory path', async () => { const requestedPath = getSystemPath(normalize('/path/to/workspace')); const expectedFile = getSystemPath(join(normalize(requestedPath), '.angular.json')); @@ -195,15 +179,15 @@ describe('readWorkspace', () => { await readWorkspace(requestedPath, host); isFileChecks.sort(); - expect(isFileChecks).toEqual([ - getSystemPath(join(normalize(requestedPath), 'angular.json')), - getSystemPath(join(normalize(requestedPath), '.angular.json')), - ].sort()); - - done(); + expect(isFileChecks).toEqual( + [ + getSystemPath(join(normalize(requestedPath), 'angular.json')), + getSystemPath(join(normalize(requestedPath), '.angular.json')), + ].sort(), + ); }); - it('attempts to find/read only files for specified format from directory path', async (done) => { + it('attempts to find/read only files for specified format from directory path', async () => { const requestedPath = '/path/to/workspace'; const isFileChecks: string[] = []; @@ -232,7 +216,7 @@ describe('readWorkspace', () => { }, }; - _test_addWorkspaceFile('wrong.format', 99); + _test_addWorkspaceFile('wrong.format', 99 as WorkspaceFormat); try { await readWorkspace(requestedPath, host, WorkspaceFormat.JSON); } finally { @@ -240,19 +224,13 @@ describe('readWorkspace', () => { } isFileChecks.sort(); - expect(isFileChecks).toEqual([ - getSystemPath(join(normalize(requestedPath), 'angular.json')), - ]); + expect(isFileChecks).toEqual([getSystemPath(join(normalize(requestedPath), 'angular.json'))]); readFileChecks.sort(); - expect(readFileChecks).toEqual([ - getSystemPath(join(normalize(requestedPath), 'angular.json')), - ]); - - done(); + expect(readFileChecks).toEqual([getSystemPath(join(normalize(requestedPath), 'angular.json'))]); }); - it('errors when no file found from specified directory path', async (done) => { + it('errors when no file found from specified directory path', async () => { const requestedPath = '/path/to/workspace'; const host: WorkspaceHost = { @@ -276,20 +254,14 @@ describe('readWorkspace', () => { }, }; - try { - await readWorkspace(requestedPath, host); - fail(); - } catch (e) { - expect(e.message).toContain('Unable to locate a workspace file'); - } - - done(); + await expectAsync(readWorkspace(requestedPath, host)).toBeRejectedWithError( + /Unable to locate a workspace file/, + ); }); - }); describe('writeWorkspace', () => { - it('attempts to write to specified file path', async (done) => { + it('attempts to write to specified file path', async () => { const requestedPath = '/path/to/workspace/angular.json'; let writtenPath: string | undefined; @@ -317,11 +289,9 @@ describe('writeWorkspace', () => { await writeWorkspace({} as WorkspaceDefinition, host, requestedPath, WorkspaceFormat.JSON); expect(writtenPath).toBe(requestedPath); - - done(); }); - it('errors when writing to specified file path with invalid specified format', async (done) => { + it('errors when writing to specified file path with invalid specified format', async () => { const requestedPath = '/path/to/workspace/angular.json'; const host: WorkspaceHost = { @@ -330,30 +300,27 @@ describe('writeWorkspace', () => { return ''; }, - async writeFile() { fail(); }, + async writeFile() { + fail(); + }, async isFile() { fail(); return false; }, async isDirectory() { - fail(); + fail(); - return false; + return false; }, }; - try { - await writeWorkspace({} as WorkspaceDefinition, host, requestedPath, 12 as WorkspaceFormat); - fail(); - } catch (e) { - expect(e.message).toContain('Unsupported workspace format'); - } - - done(); + await expectAsync( + writeWorkspace({} as WorkspaceDefinition, host, requestedPath, 12 as WorkspaceFormat), + ).toBeRejectedWithError(/Unsupported workspace format/); }); - it('errors when writing custom workspace without specified format', async (done) => { + it('errors when writing custom workspace without specified format', async () => { const requestedPath = '/path/to/workspace/angular.json'; const host: WorkspaceHost = { @@ -362,27 +329,23 @@ describe('writeWorkspace', () => { return ''; }, - async writeFile() { fail(); }, + async writeFile() { + fail(); + }, async isFile() { fail(); return false; }, async isDirectory() { - fail(); + fail(); - return false; + return false; }, }; - try { - await writeWorkspace({} as WorkspaceDefinition, host, requestedPath); - fail(); - } catch (e) { - expect(e.message).toContain('A format is required'); - } - - done(); + await expectAsync( + writeWorkspace({} as WorkspaceDefinition, host, requestedPath), + ).toBeRejectedWithError(/A format is required/); }); - }); diff --git a/packages/angular_devkit/core/src/workspace/definitions.ts b/packages/angular_devkit/core/src/workspace/definitions.ts index 53b21259116b..dc3bf4ab4608 100644 --- a/packages/angular_devkit/core/src/workspace/definitions.ts +++ b/packages/angular_devkit/core/src/workspace/definitions.ts @@ -1,15 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { JsonValue } from '../json'; export interface WorkspaceDefinition { readonly extensions: Record; - readonly projects: ProjectDefinitionCollection; } @@ -25,15 +25,13 @@ export interface ProjectDefinition { export interface TargetDefinition { options?: Record; configurations?: Record | undefined>; - + defaultConfiguration?: string; builder: string; } export type DefinitionCollectionListener = ( name: string, - action: 'add' | 'remove' | 'replace', newValue: V | undefined, - oldValue: V | undefined, collection: DefinitionCollection, ) => void; @@ -48,21 +46,21 @@ class DefinitionCollection implements ReadonlyMap { } delete(key: string): boolean { - const value = this._map.get(key); const result = this._map.delete(key); - if (result && value !== undefined && this._listener) { - this._listener(key, 'remove', undefined, value, this); + + if (result) { + this._listener?.(key, undefined, this); } return result; } set(key: string, value: V): this { - const existing = this.get(key); - this._map.set(key, value); + const updatedValue = value !== this.get(key); - if (this._listener) { - this._listener(key, existing !== undefined ? 'replace' : 'add', value, existing, this); + if (updatedValue) { + this._map.set(key, value); + this._listener?.(key, value, this); } return this; @@ -87,19 +85,19 @@ class DefinitionCollection implements ReadonlyMap { return this._map.size; } - [Symbol.iterator](): IterableIterator<[string, V]> { + [Symbol.iterator](): MapIterator<[string, V]> { return this._map[Symbol.iterator](); } - entries(): IterableIterator<[string, V]> { + entries(): MapIterator<[string, V]> { return this._map.entries(); } - keys(): IterableIterator { + keys(): MapIterator { return this._map.keys(); } - values(): IterableIterator { + values(): MapIterator { return this._map.values(); } } @@ -133,7 +131,6 @@ function isJsonValue(value: unknown): value is JsonValue { } export class ProjectDefinitionCollection extends DefinitionCollection { - constructor( initial?: Record, listener?: DefinitionCollectionListener, @@ -141,16 +138,14 @@ export class ProjectDefinitionCollection extends DefinitionCollection, - [key: string]: unknown, - }, - ): ProjectDefinition { + add(definition: { + name: string; + root: string; + sourceRoot?: string; + prefix?: string; + targets?: Record; + [key: string]: unknown; + }): ProjectDefinition { if (this.has(definition.name)) { throw new Error('Project name already exists.'); } @@ -195,7 +190,7 @@ export class ProjectDefinitionCollection extends DefinitionCollection { - constructor( initial?: Record, listener?: DefinitionCollectionListener, @@ -222,7 +215,7 @@ export class TargetDefinitionCollection extends DefinitionCollection { - it('can be created without initial values or a listener', () => { const collection = new ProjectDefinitionCollection(); @@ -54,7 +53,9 @@ describe('ProjectDefinitionCollection', () => { }); it('can be created with a listener', () => { - const listener = () => { fail('listener should not execute on initialization'); }; + const listener = () => { + fail('listener should not execute on initialization'); + }; const collection = new ProjectDefinitionCollection(undefined, listener); @@ -72,7 +73,9 @@ describe('ProjectDefinitionCollection', () => { builder: 'build-builder', }); - const listener = () => { fail('listener should not execute on initialization'); }; + const listener = () => { + fail('listener should not execute on initialization'); + }; const collection = new ProjectDefinitionCollection(initial, listener); @@ -96,27 +99,24 @@ describe('ProjectDefinitionCollection', () => { }); it('listens to an addition via set', () => { - const listener = (name: string, action: string) => { + const listener = (name: string, value?: ProjectDefinition) => { expect(name).toBe('my-app'); - expect(action).toBe('add'); + expect(value?.root).toBe('src/my-app'); }; const collection = new ProjectDefinitionCollection(undefined, listener); - collection.set( - 'my-app', - { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() }, - ); + collection.set('my-app', { + root: 'src/my-app', + extensions: {}, + targets: new TargetDefinitionCollection(), + }); }); it('listens to an addition via add', () => { - const listener = (name: string, action: string, value?: ProjectDefinition) => { + const listener = (name: string, value?: ProjectDefinition) => { expect(name).toBe('my-app'); - expect(action).toBe('add'); - expect(value).not.toBeUndefined(); - if (value) { - expect(value.root).toBe('src/my-app'); - } + expect(value?.root).toBe('src/my-app'); }; const collection = new ProjectDefinitionCollection(undefined, listener); @@ -132,9 +132,9 @@ describe('ProjectDefinitionCollection', () => { 'my-app': { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() }, }; - const listener = (name: string, action: string) => { + const listener = (name: string, value?: ProjectDefinition) => { expect(name).toBe('my-app'); - expect(action).toBe('remove'); + expect(value).toBeUndefined(); }; const collection = new ProjectDefinitionCollection(initial, listener); @@ -147,36 +147,22 @@ describe('ProjectDefinitionCollection', () => { 'my-app': { root: 'src/my-app', extensions: {}, targets: new TargetDefinitionCollection() }, }; - const listener = ( - name: string, - action: string, - newValue?: ProjectDefinition, - oldValue?: ProjectDefinition, - ) => { + const listener = (name: string, value?: ProjectDefinition) => { expect(name).toBe('my-app'); - expect(action).toBe('replace'); - expect(newValue).not.toBeUndefined(); - if (newValue) { - expect(newValue.root).toBe('src/my-app2'); - } - expect(oldValue).not.toBeUndefined(); - if (oldValue) { - expect(oldValue.root).toBe('src/my-app'); - } + expect(value?.root).toBe('src/my-app2'); }; const collection = new ProjectDefinitionCollection(initial, listener); - collection.set( - 'my-app', - { root: 'src/my-app2', extensions: {}, targets: new TargetDefinitionCollection() }, - ); + collection.set('my-app', { + root: 'src/my-app2', + extensions: {}, + targets: new TargetDefinitionCollection(), + }); }); - }); describe('TargetDefinitionCollection', () => { - it('can be created without initial values or a listener', () => { const collection = new TargetDefinitionCollection(); @@ -195,18 +181,16 @@ describe('TargetDefinitionCollection', () => { const build = collection.get('build'); expect(build).not.toBeUndefined(); - if (build) { - expect(build.builder).toBe('builder:build'); - } + expect(build?.builder).toBe('builder:build'); const test = collection.get('test'); expect(test).not.toBeUndefined(); - if (test) { - expect(test.builder).toBe('builder:test'); - } + expect(test?.builder).toBe('builder:test'); }); it('can be created with a listener', () => { - const listener = () => { fail('listener should not execute on initialization'); }; + const listener = () => { + fail('listener should not execute on initialization'); + }; const collection = new TargetDefinitionCollection(undefined, listener); @@ -219,46 +203,35 @@ describe('TargetDefinitionCollection', () => { 'test': { builder: 'builder:test' }, }; - const listener = () => { fail('listener should not execute on initialization'); }; + const listener = () => { + fail('listener should not execute on initialization'); + }; const collection = new TargetDefinitionCollection(initial, listener); expect(collection.size).toBe(2); const build = collection.get('build'); - expect(build).not.toBeUndefined(); - if (build) { - expect(build.builder).toBe('builder:build'); - } + expect(build?.builder).toBe('builder:build'); const test = collection.get('test'); - expect(test).not.toBeUndefined(); - if (test) { - expect(test.builder).toBe('builder:test'); - } + expect(test?.builder).toBe('builder:test'); }); it('listens to an addition via set', () => { - const listener = (name: string, action: string) => { + const listener = (name: string, value?: TargetDefinition) => { expect(name).toBe('build'); - expect(action).toBe('add'); + expect(value?.builder).toBe('builder:build'); }; const collection = new TargetDefinitionCollection(undefined, listener); - collection.set( - 'build', - { builder: 'builder:build' }, - ); + collection.set('build', { builder: 'builder:build' }); }); it('listens to an addition via add', () => { - const listener = (name: string, action: string, value?: TargetDefinition) => { + const listener = (name: string, value?: TargetDefinition) => { expect(name).toBe('build'); - expect(action).toBe('add'); - expect(value).not.toBeUndefined(); - if (value) { - expect(value.builder).toBe('builder:build'); - } + expect(value?.builder).toBe('builder:build'); }; const collection = new TargetDefinitionCollection(undefined, listener); @@ -274,9 +247,8 @@ describe('TargetDefinitionCollection', () => { 'build': { builder: 'builder:build' }, }; - const listener = (name: string, action: string) => { + const listener = (name: string, value?: TargetDefinition) => { expect(name).toBe('build'); - expect(action).toBe('remove'); }; const collection = new TargetDefinitionCollection(initial, listener); @@ -289,30 +261,13 @@ describe('TargetDefinitionCollection', () => { 'build': { builder: 'builder:build' }, }; - const listener = ( - name: string, - action: string, - newValue?: TargetDefinition, - oldValue?: TargetDefinition, - ) => { + const listener = (name: string, value?: TargetDefinition) => { expect(name).toBe('build'); - expect(action).toBe('replace'); - expect(newValue).not.toBeUndefined(); - if (newValue) { - expect(newValue.builder).toBe('builder:test'); - } - expect(oldValue).not.toBeUndefined(); - if (oldValue) { - expect(oldValue.builder).toBe('builder:build'); - } + expect(value?.builder).toBe('builder:test'); }; const collection = new TargetDefinitionCollection(initial, listener); - collection.set( - 'build', - { builder: 'builder:test' }, - ); + collection.set('build', { builder: 'builder:test' }); }); - }); diff --git a/packages/angular_devkit/core/src/workspace/host.ts b/packages/angular_devkit/core/src/workspace/host.ts index d9d75c0cf171..ab973717ba3d 100644 --- a/packages/angular_devkit/core/src/workspace/host.ts +++ b/packages/angular_devkit/core/src/workspace/host.ts @@ -1,10 +1,12 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + +import { lastValueFrom } from 'rxjs'; import { normalize, virtualFs } from '../virtual-fs'; export interface WorkspaceHost { @@ -19,18 +21,21 @@ export interface WorkspaceHost { } export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost { + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + const workspaceHost: WorkspaceHost = { async readFile(path: string): Promise { - const data = await host.read(normalize(path)).toPromise(); + const data = await lastValueFrom(host.read(normalize(path))); - return virtualFs.fileBufferToString(data); + return decoder.decode(data); }, async writeFile(path: string, data: string): Promise { - return host.write(normalize(path), virtualFs.stringToFileBuffer(data)).toPromise(); + return lastValueFrom(host.write(normalize(path), encoder.encode(data).buffer)); }, async isDirectory(path: string): Promise { try { - return await host.isDirectory(normalize(path)).toPromise(); + return await lastValueFrom(host.isDirectory(normalize(path))); } catch { // some hosts throw if path does not exist return false; @@ -38,7 +43,7 @@ export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost { }, async isFile(path: string): Promise { try { - return await host.isFile(normalize(path)).toPromise(); + return await lastValueFrom(host.isFile(normalize(path))); } catch { // some hosts throw if path does not exist return false; diff --git a/packages/angular_devkit/core/src/workspace/host_spec.ts b/packages/angular_devkit/core/src/workspace/host_spec.ts index 079885b60d25..c3af99a36215 100644 --- a/packages/angular_devkit/core/src/workspace/host_spec.ts +++ b/packages/angular_devkit/core/src/workspace/host_spec.ts @@ -1,14 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { test } from '../virtual-fs/host'; import { WorkspaceHost, createWorkspaceHost } from './host'; - describe('createWorkspaceHost', () => { let testHost: test.TestHost; let workspaceHost: WorkspaceHost; @@ -21,18 +21,16 @@ describe('createWorkspaceHost', () => { workspaceHost = createWorkspaceHost(testHost); }); - it('supports isFile', async (done) => { + it('supports isFile', async () => { expect(await workspaceHost.isFile('abc.txt')).toBeTruthy(); expect(await workspaceHost.isFile('foo/bar.json')).toBeTruthy(); expect(await workspaceHost.isFile('foo\\bar.json')).toBeTruthy(); expect(await workspaceHost.isFile('foo')).toBeFalsy(); expect(await workspaceHost.isFile('not.there')).toBeFalsy(); - - done(); }); - it('supports isDirectory', async (done) => { + it('supports isDirectory', async () => { expect(await workspaceHost.isDirectory('foo')).toBeTruthy(); expect(await workspaceHost.isDirectory('foo/')).toBeTruthy(); expect(await workspaceHost.isDirectory('foo\\')).toBeTruthy(); @@ -40,27 +38,16 @@ describe('createWorkspaceHost', () => { expect(await workspaceHost.isDirectory('abc.txt')).toBeFalsy(); expect(await workspaceHost.isDirectory('foo/bar.json')).toBeFalsy(); expect(await workspaceHost.isDirectory('not.there')).toBeFalsy(); - - done(); }); - it('supports readFile', async (done) => { + it('supports readFile', async () => { expect(await workspaceHost.readFile('abc.txt')).toBe('abcdefg'); - - done(); }); - it('supports writeFile', async (done) => { + it('supports writeFile', async () => { await workspaceHost.writeFile('newfile', 'baz'); - expect(testHost.files.sort() as string[]).toEqual([ - '/abc.txt', - '/foo/bar.json', - '/newfile', - ]); + expect(testHost.files.sort() as string[]).toEqual(['/abc.txt', '/foo/bar.json', '/newfile']); expect(testHost.$read('newfile')).toBe('baz'); - - done(); }); - }); diff --git a/packages/angular_devkit/core/src/workspace/index.ts b/packages/angular_devkit/core/src/workspace/index.ts index 88c1071ae2f7..cdecbfafcb0d 100644 --- a/packages/angular_devkit/core/src/workspace/index.ts +++ b/packages/angular_devkit/core/src/workspace/index.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + export * from './definitions'; -export { WorkspaceHost, createWorkspaceHost } from './host'; +export { type WorkspaceHost, createWorkspaceHost } from './host'; export { WorkspaceFormat, readWorkspace, writeWorkspace } from './core'; diff --git a/packages/angular_devkit/core/src/workspace/json/metadata.ts b/packages/angular_devkit/core/src/workspace/json/metadata.ts index bc7d2c58bd5d..dc2965339c82 100644 --- a/packages/angular_devkit/core/src/workspace/json/metadata.ts +++ b/packages/angular_devkit/core/src/workspace/json/metadata.ts @@ -1,14 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonAstArray, JsonAstKeyValue, JsonAstNode, JsonAstObject, JsonValue } from '../../json'; + +import { JSONPath, Node, findNodeAtLocation, getNodeValue } from 'jsonc-parser'; +import { JsonValue } from '../../json'; import { ProjectDefinition, TargetDefinition, WorkspaceDefinition } from '../definitions'; -export const JsonWorkspaceSymbol = Symbol.for('@angular/core:workspace-json'); +export const JsonWorkspaceSymbol: unique symbol = Symbol.for('@angular/core:workspace-json'); export interface JsonWorkspaceDefinition extends WorkspaceDefinition { [JsonWorkspaceSymbol]: JsonWorkspaceMetadata; @@ -22,56 +24,67 @@ interface ChangeValues { targetcollection: Iterable<[string, TargetDefinition]>; } -export interface JsonChange { - // core collections can only be added as they are managed directly by _Collection_ objects - op: T extends 'json' | 'project' | 'target' ? 'add' | 'remove' | 'replace' : 'add'; - path: string; - node: JsonAstNode | JsonAstKeyValue; - value?: ChangeValues[T]; - type: T; +export interface JsonChange { + value?: unknown; + type?: keyof ChangeValues; + jsonPath: string[]; +} + +function escapeKey(key: string): string | number { + return key.replace('~', '~0').replace('/', '~1'); } export class JsonWorkspaceMetadata { - readonly changes: JsonChange[] = []; + readonly changes: Map = new Map(); - constructor(readonly filePath: string, readonly ast: JsonAstObject, readonly raw: string) { } + hasLegacyTargetsName = true; + + constructor( + readonly filePath: string, + private readonly ast: Node, + readonly raw: string, + ) {} get hasChanges(): boolean { - return this.changes.length > 0; + return this.changes.size > 0; } get changeCount(): number { - return this.changes.length; + return this.changes.size; + } + + getNodeValueFromAst(path: JSONPath): unknown { + const node = findNodeAtLocation(this.ast, path); + + return node && getNodeValue(node); } - findChangesForPath(path: string): JsonChange[] { - return this.changes.filter(c => c.path === path); + findChangesForPath(path: string): JsonChange | undefined { + return this.changes.get(path); } addChange( - op: 'add' | 'remove' | 'replace', - path: string, - node: JsonAstArray | JsonAstObject | JsonAstKeyValue, - value?: ChangeValues[T], + jsonPath: string[], + value: ChangeValues[T] | undefined, type?: T, ): void { - // Remove redundant operations - if (op === 'remove' || op === 'replace') { - for (let i = this.changes.length - 1; i >= 0; --i) { - const currentPath = this.changes[i].path; - if (currentPath === path || currentPath.startsWith(path + '/')) { - if (op === 'replace' && currentPath === path && this.changes[i].op === 'add') { - op = 'add'; - } - this.changes.splice(i, 1); - } + let currentPath = ''; + for (let index = 0; index < jsonPath.length - 1; index++) { + currentPath = currentPath + '/' + escapeKey(jsonPath[index]); + if (this.changes.has(currentPath)) { + // Ignore changes on children as parent is updated. + return; } } - this.changes.push({ op, path, node, value, type: op === 'remove' || !type ? 'json' : type }); - } + const pathKey = '/' + jsonPath.map((k) => escapeKey(k)).join('/'); + for (const key of this.changes.keys()) { + if (key.startsWith(pathKey + '/')) { + // changes on the same or child paths are redundant. + this.changes.delete(key); + } + } - reset(): void { - this.changes.length = 0; + this.changes.set(pathKey, { jsonPath, type, value }); } } diff --git a/packages/angular_devkit/core/src/workspace/json/reader.ts b/packages/angular_devkit/core/src/workspace/json/reader.ts index 24c5f34afe74..cc258bf00e08 100644 --- a/packages/angular_devkit/core/src/workspace/json/reader.ts +++ b/packages/angular_devkit/core/src/workspace/json/reader.ts @@ -1,18 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { - JsonAstKeyValue, - JsonAstNode, - JsonAstObject, - JsonParseMode, - JsonValue, - parseJsonAst, -} from '../../json'; + +import { Node, findNodeAtLocation, getNodeValue, parseTree } from 'jsonc-parser'; +import { JsonValue, isJsonObject } from '../../json/utils'; import { DefinitionCollectionListener, ProjectDefinition, @@ -23,51 +18,71 @@ import { } from '../definitions'; import { WorkspaceHost } from '../host'; import { JsonWorkspaceMetadata, JsonWorkspaceSymbol } from './metadata'; -import { createVirtualAstObject, escapeKey } from './utilities'; +import { createVirtualAstObject } from './utilities'; + +const ANGULAR_WORKSPACE_EXTENSIONS = Object.freeze(['cli', 'newProjectRoot', 'schematics']); +const ANGULAR_PROJECT_EXTENSIONS = Object.freeze(['cli', 'schematics', 'projectType', 'i18n']); interface ParserContext { readonly host: WorkspaceHost; readonly metadata: JsonWorkspaceMetadata; readonly trackChanges: boolean; - error(message: string, node: JsonAstNode | JsonAstKeyValue): void; - warn(message: string, node: JsonAstNode | JsonAstKeyValue): void; + readonly unprefixedWorkspaceExtensions: ReadonlySet; + readonly unprefixedProjectExtensions: ReadonlySet; + error(message: string, node: JsonValue): void; + warn(message: string, node: JsonValue): void; +} + +export interface JsonWorkspaceOptions { + allowedProjectExtensions?: string[]; + allowedWorkspaceExtensions?: string[]; } export async function readJsonWorkspace( path: string, host: WorkspaceHost, + options: JsonWorkspaceOptions = {}, ): Promise { const raw = await host.readFile(path); - if (raw === undefined) { throw new Error('Unable to read workspace file.'); } - const ast = parseJsonAst(raw, JsonParseMode.Loose); - if (ast.kind !== 'object') { + const ast = parseTree(raw, undefined, { allowTrailingComma: true, disallowComments: false }); + if (ast?.type !== 'object' || !ast.children) { throw new Error('Invalid workspace file - expected JSON object.'); } // Version check - const versionNode = ast.properties.find(pair => pair.key.value === 'version'); + const versionNode = findNodeAtLocation(ast, ['version']); if (!versionNode) { throw new Error('Unknown format - version specifier not found.'); } - const formatVersion = versionNode.value.value; - if (formatVersion !== 1) { - throw new Error(`Invalid format version detected - Expected:[ 1 ] Found: [ ${formatVersion} ]`); + const version = versionNode.value; + if (version !== 1) { + throw new Error(`Invalid format version detected - Expected:[ 1 ] Found: [ ${version} ]`); } const context: ParserContext = { host, metadata: new JsonWorkspaceMetadata(path, ast, raw), trackChanges: true, + unprefixedWorkspaceExtensions: new Set([ + ...ANGULAR_WORKSPACE_EXTENSIONS, + ...(options.allowedWorkspaceExtensions ?? []), + ]), + unprefixedProjectExtensions: new Set([ + ...ANGULAR_PROJECT_EXTENSIONS, + ...(options.allowedProjectExtensions ?? []), + ]), error(message, _node) { // TODO: Diagnostic reporting support throw new Error(message); }, - warn(_message, _node) { + warn(message, _node) { // TODO: Diagnostic reporting support + // eslint-disable-next-line no-console + console.warn(message); }, }; @@ -76,53 +91,42 @@ export async function readJsonWorkspace( return workspace; } -const specialWorkspaceExtensions = ['cli', 'defaultProject', 'newProjectRoot', 'schematics']; - -const specialProjectExtensions = ['cli', 'schematics', 'projectType']; - -function parseWorkspace(workspaceNode: JsonAstObject, context: ParserContext): WorkspaceDefinition { +function parseWorkspace(workspaceNode: Node, context: ParserContext): WorkspaceDefinition { const jsonMetadata = context.metadata; let projects; - let projectsNode: JsonAstObject | undefined; let extensions: Record | undefined; if (!context.trackChanges) { extensions = Object.create(null); } - for (const { key, value } of workspaceNode.properties) { - const name = key.value; - + // TODO: `getNodeValue` - looks potentially expensive since it walks the whole tree and instantiates the full object structure each time. + // Might be something to look at moving forward to optimize. + const workspaceNodeValue = getNodeValue(workspaceNode); + for (const [name, value] of Object.entries(workspaceNodeValue)) { if (name === '$schema' || name === 'version') { // skip } else if (name === 'projects') { - if (value.kind !== 'object') { + const nodes = findNodeAtLocation(workspaceNode, ['projects']); + if (!isJsonObject(value) || !nodes) { context.error('Invalid "projects" field found; expected an object.', value); continue; } - projectsNode = value; - projects = parseProjectsObject(value, context); + projects = parseProjectsObject(nodes, context); } else { - if (!specialWorkspaceExtensions.includes(name) && !/^[a-z]{1,3}-.*/.test(name)) { - context.warn(`Project extension with invalid name found.`, key); + if (!context.unprefixedWorkspaceExtensions.has(name) && !/^[a-z]{1,3}-.*/.test(name)) { + context.warn(`Workspace extension with invalid name (${name}) found.`, name); } if (extensions) { - extensions[name] = value.value; + extensions[name] = value; } } } let collectionListener: DefinitionCollectionListener | undefined; - if (context.trackChanges && projectsNode) { - const parentNode = projectsNode; - collectionListener = (name, action, newValue) => { - jsonMetadata.addChange( - action, - `/projects/${escapeKey(name)}`, - parentNode, - newValue, - 'project', - ); + if (context.trackChanges) { + collectionListener = (name, newValue) => { + jsonMetadata.addChange(['projects', name], newValue, 'project'); }; } @@ -134,30 +138,30 @@ function parseWorkspace(workspaceNode: JsonAstObject, context: ParserContext): W // If not tracking changes the `extensions` variable will contain the parsed // values. Otherwise the extensions are tracked via a virtual AST object. extensions: - extensions || - createVirtualAstObject(workspaceNode, { + extensions ?? + createVirtualAstObject(workspaceNodeValue, { exclude: ['$schema', 'version', 'projects'], - listener(op, path, node, value) { - jsonMetadata.addChange(op, path, node, value); + listener(path, value) { + jsonMetadata.addChange(path, value); }, }), } as WorkspaceDefinition; } function parseProjectsObject( - projectsNode: JsonAstObject, + projectsNode: Node, context: ParserContext, ): Record { const projects: Record = Object.create(null); - for (const { key, value } of projectsNode.properties) { - if (value.kind !== 'object') { + for (const [name, value] of Object.entries(getNodeValue(projectsNode))) { + const nodes = findNodeAtLocation(projectsNode, [name]); + if (!isJsonObject(value) || !nodes) { context.warn('Skipping invalid project value; expected an object.', value); continue; } - const name = key.value; - projects[name] = parseProject(name, value, context); + projects[name] = parseProject(name, nodes, context); } return projects; @@ -165,12 +169,12 @@ function parseProjectsObject( function parseProject( projectName: string, - projectNode: JsonAstObject, + projectNode: Node, context: ParserContext, ): ProjectDefinition { const jsonMetadata = context.metadata; let targets; - let targetsNode: JsonAstObject | undefined; + let hasTargets = false; let extensions: Record | undefined; let properties: Record<'root' | 'sourceRoot' | 'prefix', string> | undefined; if (!context.trackChanges) { @@ -179,34 +183,44 @@ function parseProject( properties = Object.create(null); } - for (const { key, value } of projectNode.properties) { - const name = key.value; + const projectNodeValue = getNodeValue(projectNode); + if (!('root' in projectNodeValue)) { + throw new Error(`Project "${projectName}" is missing a required property "root".`); + } + + for (const [name, value] of Object.entries(projectNodeValue)) { switch (name) { case 'targets': - case 'architect': - if (value.kind !== 'object') { + case 'architect': { + const nodes = findNodeAtLocation(projectNode, [name]); + if (!isJsonObject(value) || !nodes) { context.error(`Invalid "${name}" field found; expected an object.`, value); break; } - targetsNode = value; - targets = parseTargetsObject(projectName, value, context); + hasTargets = true; + targets = parseTargetsObject(projectName, nodes, context); + jsonMetadata.hasLegacyTargetsName = name === 'architect'; break; + } case 'prefix': case 'root': case 'sourceRoot': - if (value.kind !== 'string') { + if (typeof value !== 'string') { context.warn(`Project property "${name}" should be a string.`, value); } if (properties) { - properties[name] = value.value as string; + properties[name] = value as string; } break; default: - if (!specialProjectExtensions.includes(name) && !/^[a-z]{1,3}-.*/.test(name)) { - context.warn(`Project extension with invalid name found.`, key); + if (!context.unprefixedProjectExtensions.has(name) && !/^[a-z]{1,3}-.*/.test(name)) { + context.warn( + `Project '${projectName}' contains extension with invalid name (${name}).`, + name, + ); } if (extensions) { - extensions[name] = value.value; + extensions[name] = value; } break; } @@ -214,34 +228,17 @@ function parseProject( let collectionListener: DefinitionCollectionListener | undefined; if (context.trackChanges) { - if (targetsNode) { - const parentNode = targetsNode; - collectionListener = (name, action, newValue) => { + collectionListener = (name, newValue, collection) => { + if (hasTargets) { + jsonMetadata.addChange(['projects', projectName, 'targets', name], newValue, 'target'); + } else { jsonMetadata.addChange( - action, - `/projects/${projectName}/targets/${escapeKey(name)}`, - parentNode, - newValue, - 'target', - ); - }; - } else { - let added = false; - collectionListener = (_name, action, _new, _old, collection) => { - if (added || action !== 'add') { - return; - } - - jsonMetadata.addChange( - 'add', - `/projects/${projectName}/targets`, - projectNode, + ['projects', projectName, 'targets'], collection, 'targetcollection', ); - added = true; - }; - } + } + }; } const base = { @@ -249,63 +246,53 @@ function parseProject( // If not tracking changes the `extensions` variable will contain the parsed // values. Otherwise the extensions are tracked via a virtual AST object. extensions: - extensions || - createVirtualAstObject(projectNode, { + extensions ?? + createVirtualAstObject(projectNodeValue, { exclude: ['architect', 'prefix', 'root', 'sourceRoot', 'targets'], - listener(op, path, node, value) { - jsonMetadata.addChange(op, `/projects/${projectName}${path}`, node, value); + listener(path, value) { + jsonMetadata.addChange(['projects', projectName, ...path], value); }, }), }; - let project: ProjectDefinition; - if (context.trackChanges) { - project = createVirtualAstObject(projectNode, { - base, - include: ['prefix', 'root', 'sourceRoot'], - listener(op, path, node, value) { - jsonMetadata.addChange(op, `/projects/${projectName}${path}`, node, value); + const baseKeys = new Set(Object.keys(base)); + const project = + properties ?? + createVirtualAstObject(projectNodeValue, { + include: ['prefix', 'root', 'sourceRoot', ...baseKeys], + listener(path, value) { + if (!baseKeys.has(path[0])) { + jsonMetadata.addChange(['projects', projectName, ...path], value); + } }, }); - } else { - project = { - ...base, - ...properties, - } as ProjectDefinition; - } - return project; + return Object.assign(project, base) as ProjectDefinition; } function parseTargetsObject( projectName: string, - targetsNode: JsonAstObject, + targetsNode: Node, context: ParserContext, ): Record { const jsonMetadata = context.metadata; const targets: Record = Object.create(null); - for (const { key, value } of targetsNode.properties) { - if (value.kind !== 'object') { + for (const [name, value] of Object.entries(getNodeValue(targetsNode))) { + if (!isJsonObject(value)) { context.warn('Skipping invalid target value; expected an object.', value); continue; } - const name = key.value; if (context.trackChanges) { targets[name] = createVirtualAstObject(value, { - include: [ 'builder', 'options', 'configurations' ], - listener(op, path, node, value) { - jsonMetadata.addChange( - op, - `/projects/${projectName}/targets/${name}${path}`, - node, - value, - ); + include: ['builder', 'options', 'configurations', 'defaultConfiguration'], + listener(path, value) { + jsonMetadata.addChange(['projects', projectName, 'targets', name, ...path], value); }, }); } else { - targets[name] = value.value as unknown as TargetDefinition; + targets[name] = value as unknown as TargetDefinition; } } diff --git a/packages/angular_devkit/core/src/workspace/json/reader_spec.ts b/packages/angular_devkit/core/src/workspace/json/reader_spec.ts index c21550b07d07..041cf580ce0b 100644 --- a/packages/angular_devkit/core/src/workspace/json/reader_spec.ts +++ b/packages/angular_devkit/core/src/workspace/json/reader_spec.ts @@ -1,12 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-non-null-assertion no-big-function -import { readFileSync } from 'fs'; + +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { readFileSync } from 'node:fs'; import { JsonObject } from '../../json'; import { stripIndent } from '../../utils/literals'; import { TargetDefinitionCollection, WorkspaceDefinition } from '../definitions'; @@ -28,7 +29,7 @@ const basicFile = stripIndent` "x-bar": 5, }`; -const representativeFile = readFileSync(__dirname + '/test/angular.json', 'utf8'); +const representativeFile = readFileSync(require.resolve(__dirname + '/test/angular.json'), 'utf8'); function createTestHost(content: string, onWrite?: (path: string, data: string) => void) { return { @@ -51,7 +52,7 @@ function createTestHost(content: string, onWrite?: (path: string, data: string) function getMetadata(workspace: WorkspaceDefinition): JsonWorkspaceMetadata { const metadata = (workspace as JsonWorkspaceDefinition)[JsonWorkspaceSymbol]; - expect(metadata).toBeDefined('JSON metadata not found. Invalid workspace definition returned.'); + expect(metadata).toBeDefined(); return metadata; } @@ -74,9 +75,8 @@ describe('readJsonWorkpace Parsing', () => { const workspace = await readJsonWorkspace('', host); - expect(Array.from(workspace.projects.keys())).toEqual(['my-app', 'my-app-e2e']); + expect(Array.from(workspace.projects.keys())).toEqual(['my-app']); expect(workspace.extensions['newProjectRoot']).toBe('projects'); - expect(workspace.extensions['defaultProject']).toBe('my-app'); expect(workspace.projects.get('my-app')!.extensions['schematics']).toEqual({ '@schematics/angular:component': { styleext: 'scss' }, }); @@ -86,19 +86,27 @@ describe('readJsonWorkpace Parsing', () => { ); }); + it(`doesn't remove falsy values when using the spread operator`, async () => { + const host = createTestHost(representativeFile); + const workspace = await readJsonWorkspace('', host); + const prodConfig = workspace.projects.get('my-app')!.targets.get('build')!.configurations! + .production!; + expect({ ...prodConfig }).toEqual(prodConfig); + }); + it('parses extensions only into extensions object', async () => { const host = createTestHost(representativeFile); const workspace = await readJsonWorkspace('', host); expect(workspace.extensions['newProjectRoot']).toBe('projects'); - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((workspace as any)['newProjectRoot']).toBeUndefined(); expect(workspace.projects.get('my-app')!.extensions['schematics']).toEqual({ '@schematics/angular:component': { styleext: 'scss' }, }); - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((workspace.projects.get('my-app') as any)['schematics']).toBeUndefined(); }); @@ -111,12 +119,9 @@ describe('readJsonWorkpace Parsing', () => { } `); - try { - await readJsonWorkspace('', host); - fail(); - } catch (e) { - expect(e.message).toContain('Invalid format version detected'); - } + await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError( + /Invalid format version detected/, + ); }); it('errors on missing version', async () => { @@ -127,12 +132,24 @@ describe('readJsonWorkpace Parsing', () => { } `); - try { - await readJsonWorkspace('', host); - fail(); - } catch (e) { - expect(e.message).toContain('version specifier not found'); - } + await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError( + /version specifier not found/, + ); + }); + + it('warns on missing root property in a project', async () => { + const host = createTestHost(stripIndent` + { + "version": 1, + "projects": { + "foo": {} + } + } + `); + + await expectAsync(readJsonWorkspace('', host)).toBeRejectedWithError( + /Project "foo" is missing a required property "root"/, + ); }); }); @@ -150,10 +167,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-baz')[0]; + const change = metadata.findChangesForPath('/x-baz'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toBe(101); } }); @@ -175,10 +191,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-baz')[0]; + const change = metadata.findChangesForPath('/x-baz'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ a: 1, b: 3, c: { d: 'abc' } }); } }); @@ -193,18 +208,23 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } }); Object.assign(value, { x: 9, y: 8, z: 7 }); - expect(workspace.extensions['x-baz']) - .toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); + expect(workspace.extensions['x-baz']).toEqual({ + a: 1, + b: 2, + c: { d: 'abc' }, + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-baz')[0]; + const change = metadata.findChangesForPath('/x-baz'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); } }); @@ -219,18 +239,23 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } }); workspace.extensions['x-baz'] = Object.assign(value, { x: 9, y: 8, z: 7 }); - expect(workspace.extensions['x-baz']) - .toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); + expect(workspace.extensions['x-baz']).toEqual({ + a: 1, + b: 2, + c: { d: 'abc' }, + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-baz')[0]; + const change = metadata.findChangesForPath('/x-baz'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); } }); @@ -245,18 +270,23 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(workspace.extensions['x-baz']).toEqual({ a: 1, b: 2, c: { d: 'abc' } }); workspace.extensions['x-baz'] = { ...value, ...{ x: 9, y: 8 }, z: 7 }; - expect(workspace.extensions['x-baz']) - .toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); + expect(workspace.extensions['x-baz']).toEqual({ + a: 1, + b: 2, + c: { d: 'abc' }, + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-baz')[0]; + const change = metadata.findChangesForPath('/x-baz'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ a: 1, b: 2, c: { d: 'abc' }, x: 9, y: 8, z: 7 }); } }); @@ -267,20 +297,25 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { const workspace = await readJsonWorkspace('', host); workspace.extensions['x-foo'] = { - ...workspace.extensions['x-foo'] as JsonObject, - ...{ x: 9, y: 8 }, z: 7 }; - expect(workspace.extensions['x-foo']) - .toEqual({ is: ['good', 'great', 'awesome'], x: 9, y: 8, z: 7 }); + ...(workspace.extensions['x-foo'] as JsonObject), + ...{ x: 9, y: 8 }, + z: 7, + }; + expect(workspace.extensions['x-foo']).toEqual({ + is: ['good', 'great', 'awesome'], + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/x-foo')[0]; + const change = metadata.findChangesForPath('/x-foo'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('replace'); expect(change.value).toEqual({ is: ['good', 'great', 'awesome'], x: 9, y: 8, z: 7 }); } }); @@ -290,37 +325,34 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { const workspace = await readJsonWorkspace('', host); - Object.assign( - workspace.extensions['x-foo'], - { x: 9, y: 8 }, - { z: 7 }, - ); - expect(workspace.extensions['x-foo']) - .toEqual({ is: ['good', 'great', 'awesome'], x: 9, y: 8, z: 7 }); + Object.assign(workspace.extensions['x-foo']!, { x: 9, y: 8 }, { z: 7 }); + expect(workspace.extensions['x-foo']).toEqual({ + is: ['good', 'great', 'awesome'], + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(3); - let change = metadata.findChangesForPath('/x-foo/x')[0]; + let change = metadata.findChangesForPath('/x-foo/x'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(9); } - change = metadata.findChangesForPath('/x-foo/y')[0]; + change = metadata.findChangesForPath('/x-foo/y'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(8); } - change = metadata.findChangesForPath('/x-foo/z')[0]; + change = metadata.findChangesForPath('/x-foo/z'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(7); } }); @@ -331,36 +363,37 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { const workspace = await readJsonWorkspace('', host); workspace.extensions['x-foo'] = Object.assign( - workspace.extensions['x-foo'], + workspace.extensions['x-foo']!, { x: 9, y: 8 }, { z: 7 }, ); - expect(workspace.extensions['x-foo']) - .toEqual({ is: ['good', 'great', 'awesome'], x: 9, y: 8, z: 7 }); + expect(workspace.extensions['x-foo']).toEqual({ + is: ['good', 'great', 'awesome'], + x: 9, + y: 8, + z: 7, + }); const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(3); - let change = metadata.findChangesForPath('/x-foo/x')[0]; + let change = metadata.findChangesForPath('/x-foo/x'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(9); } - change = metadata.findChangesForPath('/x-foo/y')[0]; + change = metadata.findChangesForPath('/x-foo/y'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(8); } - change = metadata.findChangesForPath('/x-foo/z')[0]; + change = metadata.findChangesForPath('/x-foo/z'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(7); } }); @@ -384,10 +417,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - let change = metadata.findChangesForPath('/schematics2')[0]; + let change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } }); } @@ -396,11 +428,8 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(2); - change = metadata.findChangesForPath('/schematics')[0]; + change = metadata.findChangesForPath('/schematics'); expect(change).not.toBeUndefined(); - if (change) { - expect(change.op).toBe('remove'); - } }); it('tracks moving and modifying an existing extension object', async () => { @@ -422,10 +451,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - let change = metadata.findChangesForPath('/schematics2')[0]; + let change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } }); } @@ -437,16 +465,12 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(2); - change = metadata.findChangesForPath('/schematics')[0]; + change = metadata.findChangesForPath('/schematics'); expect(change).not.toBeUndefined(); - if (change) { - expect(change.op).toBe('remove'); - } - change = metadata.findChangesForPath('/schematics2')[0]; + change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } }); } }); @@ -470,10 +494,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - let change = metadata.findChangesForPath('/schematics2')[0]; + let change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } }); } @@ -484,17 +507,15 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(2); - change = metadata.findChangesForPath('/schematics/@angular~1schematics:component')[0]; + change = metadata.findChangesForPath('/schematics/@angular~1schematics:component'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('replace'); expect(change.value).toEqual({ prefix: 'xyz' }); } - change = metadata.findChangesForPath('/schematics2')[0]; + change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } }); } }); @@ -518,10 +539,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - let change = metadata.findChangesForPath('/schematics2')[0]; + let change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'abc' } }); } @@ -532,17 +552,15 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(2); - change = metadata.findChangesForPath('/schematics/@angular~1schematics:component')[0]; + change = metadata.findChangesForPath('/schematics/@angular~1schematics:component'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('replace'); expect(change.value).toEqual({ prefix: 'xyz' }); } - change = metadata.findChangesForPath('/schematics2')[0]; + change = metadata.findChangesForPath('/schematics2'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual({ '@angular/schematics:component': { prefix: 'xyz' } }); } @@ -551,18 +569,12 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(2); - change = metadata.findChangesForPath('/schematics')[0]; + change = metadata.findChangesForPath('/schematics'); expect(change).not.toBeUndefined(); - if (change) { - expect(change.op).toBe('remove'); - } const orderedChanges = Array.from(metadata.changes.values()); change = orderedChanges[1]; expect(change).not.toBeUndefined(); - if (change) { - expect(change.op).toBe('remove'); - } }); it('tracks project additions with set', async () => { @@ -588,10 +600,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/new-app')[0]; + const change = metadata.findChangesForPath('/projects/new-app'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(jasmine.objectContaining({ root: 'src' })); } }); @@ -618,10 +629,9 @@ describe('JSON WorkspaceDefinition Tracks Workspace Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/new-app')[0]; + const change = metadata.findChangesForPath('/projects/new-app'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toEqual(jasmine.objectContaining({ root: 'src' })); } }); @@ -641,16 +651,14 @@ describe('JSON ProjectDefinition Tracks Project Changes', () => { project.prefix = 'bar'; expect(project.prefix).toBe('bar'); - const metadata = getMetadata(workspace); expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/my-app/prefix')[0]; + const change = metadata.findChangesForPath('/projects/my-app/prefix'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('replace'); expect(change.value).toBe('bar'); } }); @@ -675,10 +683,9 @@ describe('JSON ProjectDefinition Tracks Project Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/my-app/sourceRoot')[0]; + const change = metadata.findChangesForPath('/projects/my-app/sourceRoot'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toBe('xyz'); } }); @@ -703,10 +710,9 @@ describe('JSON ProjectDefinition Tracks Project Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/my-app/abc-option')[0]; + const change = metadata.findChangesForPath('/projects/my-app/abc-option'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.value).toBe('valueA'); } }); @@ -752,10 +758,9 @@ describe('JSON ProjectDefinition Tracks Project Changes', () => { expect(metadata.hasChanges).toBeTruthy(); expect(metadata.changeCount).toBe(1); - const change = metadata.findChangesForPath('/projects/p1/targets')[0]; + const change = metadata.findChangesForPath('/projects/p1/targets'); expect(change).not.toBeUndefined(); if (change) { - expect(change.op).toBe('add'); expect(change.type).toBe('targetcollection'); } }); diff --git a/packages/angular_devkit/core/src/workspace/json/test/angular.json b/packages/angular_devkit/core/src/workspace/json/test/angular.json index 91355ed28c64..285676999acb 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/angular.json +++ b/packages/angular_devkit/core/src/workspace/json/test/angular.json @@ -104,35 +104,6 @@ } } } - }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayEmpty.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayEmpty.json index 83cfeda3dda7..986639153289 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayEmpty.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayEmpty.json @@ -11,5 +11,5 @@ "is": ["good", "great", "awesome"] }, "x-bar": 5, - "x-array": [] + "x-array": [], } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayPush.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayPush.json index 84b9aeca6359..12a192f8a858 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayPush.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddArrayPush.json @@ -13,5 +13,5 @@ "x-bar": 5, "x-array": [ "value" - ] + ], } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject1.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject1.json index ee1c8db01857..7acd961c8c50 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject1.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject1.json @@ -6,14 +6,14 @@ "prefix": "abc" } }, - "x-baz": 10, + "x-baz": 1, "x-foo": { "is": ["good", "great", "awesome"] }, "x-bar": 5, "projects": { "new": { - "root": "src" + "root": "src7" } - } + }, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject2.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject2.json index 996aa07027b5..55ec083ffa9f 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject2.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject2.json @@ -105,37 +105,8 @@ } } }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } - }, "new": { "root": "src" } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject3.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject3.json new file mode 100644 index 000000000000..cbd98e4c89ef --- /dev/null +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProject3.json @@ -0,0 +1,112 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "my-app": { + "root": "", + "projectType": "application", + "prefix": "app", + "schematics": { + "@schematics/angular:component": { + "styleext": "scss" + } + }, + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/my-app", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.app.json", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.scss" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "extractCss": true, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true, + "budgets": [ + { + "type": "initial", + "maximumWarning": "2mb", + "maximumError": "5mb" + } + ] + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "my-app:build" + }, + "configurations": { + "production": { + "browserTarget": "my-app:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "my-app:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "src/test.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "src/tsconfig.spec.json", + "karmaConfig": "src/karma.conf.js", + "styles": [ + "src/styles.scss" + ], + "scripts": [], + "assets": [ + "src/favicon.ico", + "src/assets" + ] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "src/tsconfig.app.json", + "src/tsconfig.spec.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + } + } + }, + "1": { + "root": "src" + } + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProjectWithTargets.json b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProjectWithTargets.json index 26eadbabf914..d001bfb5d6c8 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/AddProjectWithTargets.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/AddProjectWithTargets.json @@ -6,7 +6,7 @@ "prefix": "abc" } }, - "x-baz": 10, + "x-baz": 1, "x-foo": { "is": ["good", "great", "awesome"] }, @@ -14,7 +14,7 @@ "projects": { "new": { "root": "src", - "targets": { + "architect": { "build": { "builder": "build-builder", "options": { @@ -29,5 +29,5 @@ } } } - } + }, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInner.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInner.json index 111e8e538097..96d7743dde4a 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInner.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInner.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "awesome"] + "is": [ + "good", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInnerAdd.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInnerAdd.json index c6c4ada21046..41f9979607d0 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInnerAdd.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteInnerAdd.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "new", "awesome"] + "is": [ + "good", + "new", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLast.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLast.json index a96c3b8338d4..521fa740d0bd 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLast.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLast.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great"] + "is": [ + "good", + "great" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLastAdd.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLastAdd.json index 6ccb0498b16a..9c27359090c8 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLastAdd.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteLastAdd.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great", "new"] + "is": [ + "good", + "great", + "new" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteZero.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteZero.json index 2c2603005c6e..fc0fd058d98f 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteZero.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayDeleteZero.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["great", "awesome"] + "is": [ + "great", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexInner.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexInner.json index 94fecec93fd8..ac769c3f9444 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexInner.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexInner.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "value", "awesome"] + "is": [ + "good", + "value", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexLast.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexLast.json index b54fe1e5b1c6..083e92bd9853 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexLast.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexLast.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great", "value"] + "is": [ + "good", + "great", + "value" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexZero.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexZero.json index 99ef79d5d0d5..e384556d2fac 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexZero.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayIndexZero.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["value", "great", "awesome"] + "is": [ + "value", + "great", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPop.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPop.json index a96c3b8338d4..521fa740d0bd 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPop.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPop.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great"] + "is": [ + "good", + "great" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPush.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPush.json index c7a8affc6343..8d9105f5c1d2 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPush.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayPush.json @@ -8,7 +8,12 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great", "awesome", "value"] + "is": [ + "good", + "great", + "awesome", + "value" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayShift.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayShift.json index 2c2603005c6e..fc0fd058d98f 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayShift.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayShift.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["great", "awesome"] + "is": [ + "great", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySort.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySort.json index 655912a26e3d..3a98d0c49080 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySort.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySort.json @@ -8,7 +8,11 @@ }, "x-baz": 1, "x-foo": { - "is": ["awesome", "good", "great"] + "is": [ + "awesome", + "good", + "great" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice1.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice1.json index a96c3b8338d4..521fa740d0bd 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice1.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice1.json @@ -8,7 +8,10 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great"] + "is": [ + "good", + "great" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice2.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice2.json index 8e5fa76c48a3..9f8f9a38f2e0 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice2.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArraySplice2.json @@ -8,7 +8,13 @@ }, "x-baz": 1, "x-foo": { - "is": ["good", "great", "value1", "value2", "awesome"] + "is": [ + "good", + "great", + "value1", + "value2", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayUnshift.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayUnshift.json index 8a8b3d923d96..cfffb7e5355d 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayUnshift.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayUnshift.json @@ -8,7 +8,12 @@ }, "x-baz": 1, "x-foo": { - "is": ["value", "good", "great", "awesome"] + "is": [ + "value", + "good", + "great", + "awesome" + ] }, "x-bar": 5, } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayValues.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayValues.json index 79e0d012d399..97b281a873d4 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayValues.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ArrayValues.json @@ -18,5 +18,5 @@ null, true, 9.9 - ] + ], } \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemove.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemove.json new file mode 100644 index 000000000000..3b154abf8bc9 --- /dev/null +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemove.json @@ -0,0 +1,13 @@ +{ + "version": 1, + // Comment + "schematics": { + "@angular/schematics:component": { + "prefix": "abc" + } + }, + "x-foo": { + "is": ["good", "great", "awesome"] + }, + "x-bar": 5, +} \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemoveMultiple.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemoveMultiple.json new file mode 100644 index 000000000000..cf3ae23dcf98 --- /dev/null +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ObjectRemoveMultiple.json @@ -0,0 +1,7 @@ +{ + "version": 1, + "x-foo": { + "is": ["good", "great", "awesome"] + }, + "x-bar": 5, +} \ No newline at end of file diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectAddTarget.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectAddTarget.json index 134b0d3e55f7..e42eb5a70c6f 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectAddTarget.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectAddTarget.json @@ -107,35 +107,6 @@ "builder": "new-builder" } } - }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectDeleteTarget.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectDeleteTarget.json index 86c9abf09947..573a5835564b 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectDeleteTarget.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectDeleteTarget.json @@ -98,35 +98,6 @@ } } } - }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectModifyProperties.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectModifyProperties.json index 1a5487dac5d9..9f6380eb89c0 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectModifyProperties.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectModifyProperties.json @@ -104,35 +104,6 @@ } } } - }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectSetProperties.json b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectSetProperties.json index b80273cdbb0a..7b8b3f85e5c4 100644 --- a/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectSetProperties.json +++ b/packages/angular_devkit/core/src/workspace/json/test/cases/ProjectSetProperties.json @@ -105,35 +105,6 @@ } }, "sourceRoot": "src" - }, - "my-app-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "my-app:serve" - }, - "configurations": { - "production": { - "devServerTarget": "my-app:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } } - }, - "defaultProject": "my-app" -} \ No newline at end of file + } +} diff --git a/packages/angular_devkit/core/src/workspace/json/utilities.ts b/packages/angular_devkit/core/src/workspace/json/utilities.ts index 52d6a72cf9c1..4285d1c84c04 100644 --- a/packages/angular_devkit/core/src/workspace/json/utilities.ts +++ b/packages/angular_devkit/core/src/workspace/json/utilities.ts @@ -1,292 +1,164 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import * as stableStringify from 'fast-json-stable-stringify'; -import { - JsonAstArray, - JsonAstKeyValue, - JsonAstNode, - JsonAstObject, - JsonObject, - JsonValue, -} from '../../json'; -interface CacheEntry { - value?: JsonValue; - node?: JsonAstNode; - parent: JsonAstArray | JsonAstKeyValue | JsonAstObject; -} +import { JsonArray, JsonObject, JsonValue, isJsonObject } from '../../json'; -export type ChangeListener = ( - op: 'add' | 'remove' | 'replace', - path: string, - node: JsonAstArray | JsonAstObject | JsonAstKeyValue, - value?: JsonValue, -) => void; +export type ChangeListener = (path: string[], newValue: JsonValue | undefined) => void; type ChangeReporter = ( - path: string, - parent: JsonAstArray | JsonAstKeyValue | JsonAstObject, - node?: JsonAstNode, - old?: JsonValue, - current?: JsonValue, + path: string[], + target: JsonObject | JsonArray, + oldValue: JsonValue | undefined, + newValue: JsonValue | undefined, ) => void; -function findNode( - parent: JsonAstArray | JsonAstObject, - p: PropertyKey, -): { node?: JsonAstNode; parent: JsonAstArray | JsonAstKeyValue | JsonAstObject } { - if (parent.kind === 'object') { - const entry = parent.properties.find(entry => entry.key.value === p); - if (entry) { - return { node: entry.value, parent: entry }; - } - } else { - const index = Number(p); - if (!isNaN(index)) { - return { node: parent.elements[index], parent }; - } - } - - return { parent }; -} - -function createPropertyDescriptor(value: JsonValue | undefined): PropertyDescriptor { - return { - configurable: true, - enumerable: true, - writable: true, - value, - }; -} - -export function escapeKey(key: string | number): string | number { - if (typeof key === 'number') { - return key; - } - - return key.replace('~', '~0').replace('/', '~1'); -} - -export function unescapeKey(key: string | number): string | number { - if (typeof key === 'number') { - return key; - } - - return key.replace('~1', '/').replace('~0', '~'); -} +// lib.es5 PropertyKey is string | number | symbol which doesn't overlap ProxyHandler PropertyKey which is string | symbol. +// See https://github.com/microsoft/TypeScript/issues/42894 +type ProxyPropertyKey = string | symbol; export function createVirtualAstObject( - root: JsonAstObject, + root: JsonObject | JsonArray, options: { exclude?: string[]; include?: string[]; listener?: ChangeListener; - base?: object; } = {}, ): T { - const reporter: ChangeReporter = (path, parent, node, old, current) => { - if (options.listener) { - if (old === current || stableStringify(old) === stableStringify(current)) { - return; - } + const reporter: ChangeReporter = (path, target, oldValue, newValue) => { + if (!options.listener) { + return; + } - const op = old === undefined ? 'add' : current === undefined ? 'remove' : 'replace'; - options.listener( - op, - path, - parent, - current, - ); + if (oldValue === newValue || JSON.stringify(oldValue) === JSON.stringify(newValue)) { + // same value + return; + } + + if (Array.isArray(target)) { + // For arrays we remove the index and update the entire value as keeping + // track of changes by indices can be rather complex. + options.listener(path.slice(0, -1), target); + } else { + options.listener(path, newValue); } }; return create( - root, - '', + Array.isArray(root) ? [...root] : { ...root }, + [], reporter, new Set(options.exclude), - options.include && options.include.length > 0 ? new Set(options.include) : undefined, - options.base, + options.include?.length ? new Set(options.include) : undefined, ) as T; } function create( - ast: JsonAstObject | JsonAstArray, - path: string, + obj: JsonObject | JsonArray, + path: string[], reporter: ChangeReporter, - excluded = new Set(), - included?: Set, - base?: object, + excluded = new Set(), + included?: Set, ) { - const cache = new Map(); - const alteredNodes = new Set(); - - if (!base) { - if (ast.kind === 'object') { - base = Object.create(null) as object; - } else { - base = []; - (base as Array).length = ast.elements.length; - } - } - - return new Proxy(base, { - getOwnPropertyDescriptor(target: {}, p: PropertyKey): PropertyDescriptor | undefined { - const descriptor = Reflect.getOwnPropertyDescriptor(target, p); - if (descriptor || typeof p === 'symbol') { - return descriptor; - } else if (excluded.has(p) || (included && !included.has(p))) { + return new Proxy(obj, { + getOwnPropertyDescriptor(target: {}, p: ProxyPropertyKey): PropertyDescriptor | undefined { + if (excluded.has(p) || (included && !included.has(p))) { return undefined; } - const propertyPath = path + '/' + escapeKey(p); - const cacheEntry = cache.get(propertyPath); - if (cacheEntry) { - if (cacheEntry.value) { - return createPropertyDescriptor(cacheEntry.value); - } + return Reflect.getOwnPropertyDescriptor(target, p); + }, + has(target: {}, p: ProxyPropertyKey): boolean { + if (typeof p === 'symbol' || excluded.has(p)) { + return false; + } + return Reflect.has(target, p); + }, + get(target: {}, p: ProxyPropertyKey): unknown { + if (excluded.has(p) || (included && !included.has(p))) { return undefined; } - const { node } = findNode(ast, p); - if (node) { - return createPropertyDescriptor(node.value); + const value = Reflect.get(target, p); + if (typeof p === 'symbol') { + return value; } - return undefined; + if ((isJsonObject(value) && !(value instanceof Map)) || Array.isArray(value)) { + return create(value, [...path, p], reporter); + } else { + return value; + } }, - has(target: {}, p: PropertyKey): boolean { - if (Reflect.has(target, p)) { - return true; - } else if (typeof p === 'symbol' || excluded.has(p)) { + set(target: {}, p: ProxyPropertyKey, value: unknown): boolean { + if (excluded.has(p) || (included && !included.has(p))) { return false; } - return cache.has(path + '/' + escapeKey(p)) || findNode(ast, p) !== undefined; - }, - get(target: {}, p: PropertyKey): unknown { - if (typeof p === 'symbol' || Reflect.has(target, p)) { - return Reflect.get(target, p); - } else if (excluded.has(p) || (included && !included.has(p))) { - return undefined; + if (value === undefined) { + // setting to undefined is equivalent to a delete. + return this.deleteProperty?.(target, p) ?? false; } - const propertyPath = path + '/' + escapeKey(p); - const cacheEntry = cache.get(propertyPath); - if (cacheEntry) { - return cacheEntry.value; + if (typeof p === 'symbol') { + return Reflect.set(target, p, value); } - const { node, parent } = findNode(ast, p); - let value; - if (node) { - if (node.kind === 'object' || node.kind === 'array') { - value = create( - node, - propertyPath, - (path, parent, vnode, old, current) => { - if (!alteredNodes.has(node)) { - reporter(path, parent, vnode, old, current); - } - }, - ); - } else { - value = node.value; - } + const existingValue = getCurrentValue(target, p); + if (Reflect.set(target, p, value)) { + reporter([...path, p], target, existingValue, value as JsonValue); - cache.set(propertyPath, { node, parent, value }); + return true; } - return value; + return false; }, - set(target: {}, p: PropertyKey, value: unknown): boolean { - if (typeof p === 'symbol' || Reflect.has(target, p)) { - return Reflect.set(target, p, value); - } else if (excluded.has(p) || (included && !included.has(p))) { + deleteProperty(target: {}, p: ProxyPropertyKey): boolean { + if (excluded.has(p)) { return false; } - // TODO: Check if is JSON value - const jsonValue = value as JsonValue; - - const propertyPath = path + '/' + escapeKey(p); - const cacheEntry = cache.get(propertyPath); - if (cacheEntry) { - const oldValue = cacheEntry.value; - cacheEntry.value = value as JsonValue; - if (cacheEntry.node && oldValue !== value) { - alteredNodes.add(cacheEntry.node); - } - reporter(propertyPath, cacheEntry.parent, cacheEntry.node, oldValue, jsonValue); - } else { - const { node, parent } = findNode(ast, p); - cache.set(propertyPath, { node, parent, value: value as JsonValue }); - if (node && node.value !== value) { - alteredNodes.add(node); - } - reporter(propertyPath, parent, node, node && node.value, value as JsonValue); - } - - return true; - }, - deleteProperty(target: {}, p: PropertyKey): boolean { - if (typeof p === 'symbol' || Reflect.has(target, p)) { + if (typeof p === 'symbol') { return Reflect.deleteProperty(target, p); - } else if (excluded.has(p) || (included && !included.has(p))) { - return false; } - const propertyPath = path + '/' + escapeKey(p); - const cacheEntry = cache.get(propertyPath); - if (cacheEntry) { - const oldValue = cacheEntry.value; - cacheEntry.value = undefined; - if (cacheEntry.node) { - alteredNodes.add(cacheEntry.node); - } - reporter(propertyPath, cacheEntry.parent, cacheEntry.node, oldValue, undefined); - } else { - const { node, parent } = findNode(ast, p); - if (node) { - cache.set(propertyPath, { node, parent, value: undefined }); - alteredNodes.add(node); - reporter(propertyPath, parent, node, node && node.value, undefined); - } + const existingValue = getCurrentValue(target, p); + if (Reflect.deleteProperty(target, p)) { + reporter([...path, p], target, existingValue, undefined); + + return true; } return true; }, - defineProperty(target: {}, p: PropertyKey, attributes: PropertyDescriptor): boolean { + defineProperty(target: {}, p: ProxyPropertyKey, attributes: PropertyDescriptor): boolean { if (typeof p === 'symbol') { return Reflect.defineProperty(target, p, attributes); } return false; }, - ownKeys(target: {}): PropertyKey[] { - let keys: PropertyKey[]; - if (ast.kind === 'object') { - keys = ast.properties - .map(entry => entry.key.value) - .filter(p => !excluded.has(p) && (!included || included.has(p))); - } else { - keys = []; - } - - for (const key of cache.keys()) { - const relativeKey = key.substr(path.length + 1); - if (relativeKey.length > 0 && !relativeKey.includes('/')) { - keys.push(unescapeKey(relativeKey)); - } - } - - return [...new Set([...keys, ...Reflect.ownKeys(target)])]; + ownKeys(target: {}): ProxyPropertyKey[] { + return Reflect.ownKeys(target).filter( + (p) => !excluded.has(p) && (!included || included.has(p)), + ); }, }); } + +function getCurrentValue(target: object, property: string): JsonValue | undefined { + if (Array.isArray(target) && isFinite(+property)) { + return target[+property]; + } + + if (target && property in target) { + return (target as JsonObject)[property]; + } + + return undefined; +} diff --git a/packages/angular_devkit/core/src/workspace/json/writer.ts b/packages/angular_devkit/core/src/workspace/json/writer.ts index 8087d810e5ff..e2b117abbdb1 100644 --- a/packages/angular_devkit/core/src/workspace/json/writer.ts +++ b/packages/angular_devkit/core/src/workspace/json/writer.ts @@ -1,12 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import MagicString from 'magic-string'; -import { JsonAstKeyValue, JsonAstNode, JsonObject, JsonValue } from '../../json'; + +import { applyEdits, modify } from 'jsonc-parser'; +import { EOL } from 'node:os'; +import { JsonObject, JsonValue } from '../../json'; import { ProjectDefinition, TargetDefinition, WorkspaceDefinition } from '../definitions'; import { WorkspaceHost } from '../host'; import { @@ -15,7 +17,6 @@ import { JsonWorkspaceMetadata, JsonWorkspaceSymbol, } from './metadata'; -import { unescapeKey } from './utilities'; export async function writeJsonWorkspace( workspace: WorkspaceDefinition, @@ -29,14 +30,12 @@ export async function writeJsonWorkspace( if (metadata) { if (!metadata.hasChanges) { - // nothing to do return; } - // update existing JSON workspace const data = updateJsonWorkspace(metadata); - return host.writeFile(path || metadata.filePath, data); + return host.writeFile(path ?? metadata.filePath, data); } else { // serialize directly if (!path) { @@ -55,7 +54,9 @@ function convertJsonWorkspace(workspace: WorkspaceDefinition, schema?: string): $schema: schema || './node_modules/@angular/cli/lib/config/schema.json', version: 1, ...workspace.extensions, - projects: workspace.projects ? convertJsonProjectCollection(workspace.projects) : {}, + ...(isEmpty(workspace.projects) + ? {} + : { projects: convertJsonProjectCollection(workspace.projects) }), }; return obj; @@ -93,7 +94,7 @@ function convertJsonProject(project: ProjectDefinition): JsonObject { return obj; } -function isEmpty(obj?: object): boolean { +function isEmpty(obj: object | undefined): boolean { return obj === undefined || Object.keys(obj).length === 0; } @@ -104,12 +105,13 @@ function convertJsonTarget(target: TargetDefinition): JsonObject { ...(isEmpty(target.configurations) ? {} : { configurations: target.configurations as JsonObject }), + ...(target.defaultConfiguration === undefined + ? {} + : { defaultConfiguration: target.defaultConfiguration }), }; } -function convertJsonTargetCollection( - collection: Iterable<[string, TargetDefinition]>, -): JsonObject { +function convertJsonTargetCollection(collection: Iterable<[string, TargetDefinition]>): JsonObject { const targets = Object.create(null) as JsonObject; for (const [projectName, target] of collection) { @@ -119,247 +121,72 @@ function convertJsonTargetCollection( return targets; } -function findFullStart(node: JsonAstNode | JsonAstKeyValue, raw: string): number { - let i = node.start.offset; - while (i > 0 && /\s/.test(raw[i - 1])) { - --i; - } - - return i; -} - -function findFullEnd(node: JsonAstNode | JsonAstKeyValue, raw: string): number { - let i = node.end.offset; - if (i >= raw.length) { - return raw.length; - } else if (raw[i] === ',') { - return i + 1; - } - - while (i > node.start.offset && /\s/.test(raw[i - 1])) { - --i; - } - - return i; -} - -function findPrecedingComma(node: JsonAstNode | JsonAstKeyValue, raw: string): number { - let i = node.start.offset; - if (node.comments && node.comments.length > 0) { - i = node.comments[0].start.offset; - } - while (i > 0 && /\s/.test(raw[i - 1])) { - --i; - } - - if (raw[i - 1] === ',') { - return i - 1; - } - - return -1; -} - -function stringify( - value: JsonValue | undefined, - multiline: boolean, - depth: number, - indent: string, -): string { - if (value === undefined) { - return ''; - } - - if (multiline) { - const content = JSON.stringify(value, null, indent); - const spacing = '\n' + indent.repeat(depth); - - return content.replace(/\n/g, spacing); - } else { - return JSON.stringify(value); - } -} - function normalizeValue( value: JsonChange['value'] | undefined, type: JsonChange['type'], ): JsonValue | undefined { + if (value === undefined) { + return undefined; + } + switch (type) { case 'project': return convertJsonProject(value as ProjectDefinition); - case 'projectcollection': + case 'projectcollection': { const projects = convertJsonProjectCollection(value as Iterable<[string, ProjectDefinition]>); - return Object.keys(projects).length === 0 ? undefined : projects; + return isEmpty(projects) ? undefined : projects; + } case 'target': return convertJsonTarget(value as TargetDefinition); - case 'targetcollection': + case 'targetcollection': { const targets = convertJsonTargetCollection(value as Iterable<[string, TargetDefinition]>); - return Object.keys(targets).length === 0 ? undefined : targets; + return isEmpty(targets) ? undefined : targets; + } default: return value as JsonValue; } } function updateJsonWorkspace(metadata: JsonWorkspaceMetadata): string { - const data = new MagicString(metadata.raw); - const indent = data.getIndentString(); - const removedCommas = new Set(); - const nodeChanges = - new Map(); - - for (const { op, path, node, value, type } of metadata.changes) { - // targets/projects are typically large objects so always use multiline - const multiline = node.start.line !== node.end.line || type !== 'json'; - const pathSegments = path.split('/'); - const depth = pathSegments.length - 1; // TODO: more complete analysis - const propertyOrIndex = unescapeKey(pathSegments[depth]); - const jsonValue = normalizeValue(value, type); - if (op === 'add' && jsonValue === undefined) { - continue; - } + let { raw: content } = metadata; + const { changes, hasLegacyTargetsName } = metadata; - // Track changes to the order/size of any modified objects/arrays - let elements = nodeChanges.get(node); - if (!elements) { - if (node.kind === 'array') { - elements = node.elements.slice(); - nodeChanges.set(node, elements); - } else if (node.kind === 'object') { - elements = node.properties.slice(); - nodeChanges.set(node, elements); - } else { - // keyvalue - elements = []; - } + for (const { jsonPath, value, type } of changes.values()) { + // Determine which key to use if (architect or targets) + if (hasLegacyTargetsName && jsonPath[2] === 'targets') { + jsonPath[2] = 'architect'; } - switch (op) { - case 'add': - let contentPrefix = ''; - if (node.kind === 'object') { - contentPrefix = `"${propertyOrIndex}": `; - } - - const spacing = multiline ? '\n' + indent.repeat(depth) : ' '; - const content = spacing + contentPrefix + stringify(jsonValue, multiline, depth, indent); - - // Additions are handled after analyzing all operations - // This is mainly to support array operations which can occur at arbitrary indices - if (node.kind === 'object') { - // Object property additions are always added at the end for simplicity - elements.push(content); - } else { - // Add place holders if adding an index past the length - // An empty string is an impossible real value - for (let i = elements.length; i < +propertyOrIndex; ++i) { - elements[i] = ''; - } - if (elements[+propertyOrIndex] === '') { - elements[+propertyOrIndex] = content; - } else { - elements.splice(+propertyOrIndex, 0, content); - } - } - break; - case 'remove': - let removalIndex = -1; - if (node.kind === 'object') { - removalIndex = elements.findIndex(e => { - return typeof e != 'string' && e.kind === 'keyvalue' && e.key.value === propertyOrIndex; - }); - } else if (node.kind === 'array') { - removalIndex = +propertyOrIndex; - } - if (removalIndex === -1) { - continue; - } - - const nodeToRemove = elements[removalIndex]; - if (typeof nodeToRemove === 'string') { - // synthetic - elements.splice(removalIndex, 1); - continue; - } - - if (elements.length - 1 === removalIndex) { - // If the element is a terminal element remove the otherwise trailing comma - const commaIndex = findPrecedingComma(nodeToRemove, data.original); - if (commaIndex !== -1) { - data.remove(commaIndex, commaIndex + 1); - removedCommas.add(commaIndex); - } - } - data.remove( - findFullStart(nodeToRemove, data.original), - findFullEnd(nodeToRemove, data.original), - ); - elements.splice(removalIndex, 1); - break; - case 'replace': - let nodeToReplace; - if (node.kind === 'keyvalue') { - nodeToReplace = node.value; - } else if (node.kind === 'array') { - nodeToReplace = elements[+propertyOrIndex]; - if (typeof nodeToReplace === 'string') { - // Was already modified. This is already handled. - continue; - } - } else { - continue; - } - - nodeChanges.delete(nodeToReplace); - - data.overwrite( - nodeToReplace.start.offset, - nodeToReplace.end.offset, - stringify(jsonValue, multiline, depth, indent), - ); - break; - } + // TODO: `modify` re-parses the content every time. + // See: https://github.com/microsoft/node-jsonc-parser/blob/35d94cd71bd48f9784453b2439262c938e21d49b/src/impl/edit.ts#L18 + // Ideally this should accept a string or an AST to avoid the potentially expensive repeat parsing operation. + const edits = modify(content, jsonPath, normalizeValue(value, type), { + formattingOptions: { + insertSpaces: true, + tabSize: 2, + eol: getEOL(content), + }, + }); + + content = applyEdits(content, edits); } - for (const [node, elements] of nodeChanges.entries()) { - let parentPoint = 1 + data.original.indexOf( - node.kind === 'array' ? '[' : '{', - node.start.offset, - ); - - // Short-circuit for simple case - if (elements.length === 1 && typeof elements[0] === 'string') { - data.appendRight(parentPoint, elements[0] as string); - continue; - } + return content; +} - // Combine adjecent element additions to minimize/simplify insertions - const optimizedElements: typeof elements = []; - for (let i = 0; i < elements.length; ++i) { - const element = elements[i]; - if (typeof element === 'string' && i > 0 && typeof elements[i - 1] === 'string') { - optimizedElements[optimizedElements.length - 1] += ',' + element; - } else { - optimizedElements.push(element); - } - } +function getEOL(content: string): string { + const CRLF = '\r\n'; + const LF = '\n'; + const newlines = content.match(/(?:\r?\n)/g); - let prefixComma = false; - for (const element of optimizedElements) { - if (typeof element === 'string') { - data.appendRight( - parentPoint, - (prefixComma ? ',' : '') + element, - ); - } else { - parentPoint = findFullEnd(element, data.original); - prefixComma = data.original[parentPoint - 1] !== ',' || removedCommas.has(parentPoint - 1); - } - } + if (newlines?.length) { + const crlf = newlines.filter((l) => l === CRLF).length; + const lf = newlines.length - crlf; + return crlf > lf ? CRLF : LF; } - const result = data.toString(); - - return result; + return EOL; } diff --git a/packages/angular_devkit/core/src/workspace/json/writer_spec.ts b/packages/angular_devkit/core/src/workspace/json/writer_spec.ts index 26362e626e5a..e0d4a055147a 100644 --- a/packages/angular_devkit/core/src/workspace/json/writer_spec.ts +++ b/packages/angular_devkit/core/src/workspace/json/writer_spec.ts @@ -1,13 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-big-function -import { readFileSync } from 'fs'; -import { join } from 'path'; + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { JsonArray, JsonObject } from '../../json'; import { stripIndent } from '../../utils/literals'; import { ProjectDefinitionCollection, WorkspaceDefinition } from '../definitions'; @@ -30,7 +30,7 @@ const basicFile = stripIndent` "x-bar": 5, }`; -const representativeFile = readFileSync(__dirname + '/test/angular.json', 'utf8'); +const representativeFile = readFileSync(require.resolve(__dirname + '/test/angular.json'), 'utf8'); function createTestCaseHost(inputData = '') { const host = { @@ -39,10 +39,13 @@ function createTestCaseHost(inputData = '') { }, async writeFile(path: string, data: string) { try { - const testCase = readFileSync(join(__dirname, 'test', 'cases', path) + '.json', 'utf8'); - expect(data).toEqual(testCase); + const testCase = readFileSync( + require.resolve(join(__dirname, 'test', 'cases', path) + '.json'), + 'utf8', + ); + expect(data.trim()).toEqual(testCase.trim()); } catch (e) { - fail(`Unable to load test case '${path}': ${e.message || e}`); + fail(`Unable to load test case '${path}': ${e instanceof Error ? e.message : e}`); } }, async isFile() { @@ -59,7 +62,7 @@ function createTestCaseHost(inputData = '') { describe('writeJsonWorkpaceFile', () => { it('does not modify a file without changes', async () => { const host = { - async readFile(path: string) { + async readFile() { return representativeFile; }, async writeFile() { @@ -183,7 +186,6 @@ describe('writeJsonWorkpaceFile', () => { it('retains comments and formatting when modifying the workspace', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-baz'] = 10; @@ -193,7 +195,6 @@ describe('writeJsonWorkpaceFile', () => { it('adds a project to workspace without any projects', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.projects.add({ @@ -206,7 +207,6 @@ describe('writeJsonWorkpaceFile', () => { it('adds a project to workspace with existing projects', async () => { const host = createTestCaseHost(representativeFile); - const workspace = await readJsonWorkspace('', host); workspace.projects.add({ @@ -217,9 +217,20 @@ describe('writeJsonWorkpaceFile', () => { await writeJsonWorkspace(workspace, host, 'AddProject2'); }); + it('adds a project to workspace with existing projects when name is number like', async () => { + const host = createTestCaseHost(representativeFile); + const workspace = await readJsonWorkspace('', host); + + workspace.projects.add({ + name: '1', + root: 'src', + }); + + await writeJsonWorkspace(workspace, host, 'AddProject3'); + }); + it('adds a project with targets', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.projects.add({ @@ -243,7 +254,6 @@ describe('writeJsonWorkpaceFile', () => { it('adds a project with targets using reference to workspace', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.projects.add({ @@ -273,9 +283,8 @@ describe('writeJsonWorkpaceFile', () => { await writeJsonWorkspace(workspace, host, 'AddProjectWithTargets'); }); - it('modifies a project\'s properties', async () => { + it("modifies a project's properties", async () => { const host = createTestCaseHost(representativeFile); - const workspace = await readJsonWorkspace('', host); const project = workspace.projects.get('my-app'); @@ -290,9 +299,8 @@ describe('writeJsonWorkpaceFile', () => { await writeJsonWorkspace(workspace, host, 'ProjectModifyProperties'); }); - it('sets a project\'s properties', async () => { + it("sets a project's properties", async () => { const host = createTestCaseHost(representativeFile); - const workspace = await readJsonWorkspace('', host); const project = workspace.projects.get('my-app'); @@ -309,7 +317,6 @@ describe('writeJsonWorkpaceFile', () => { it('adds a target to an existing project', async () => { const host = createTestCaseHost(representativeFile); - const workspace = await readJsonWorkspace('', host); const project = workspace.projects.get('my-app'); @@ -329,7 +336,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes a target from an existing project', async () => { const host = createTestCaseHost(representativeFile); - const workspace = await readJsonWorkspace('', host); const project = workspace.projects.get('my-app'); @@ -346,7 +352,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports adding an empty array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-array'] = []; @@ -356,7 +361,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports adding an array with values', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-array'] = [5, 'a', false, null, true, 9.9]; @@ -366,7 +370,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports adding an empty array then pushing as an extension', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-array'] = []; @@ -377,7 +380,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports pushing to an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -388,7 +390,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports unshifting to an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -399,7 +400,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports shifting from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -410,7 +410,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports splicing an existing array without new values', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -421,7 +420,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports splicing an existing array with new values', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -432,7 +430,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports popping from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -443,7 +440,6 @@ describe('writeJsonWorkpaceFile', () => { it('supports sorting from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -454,7 +450,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces a value at zero index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -465,7 +460,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces a value at inner index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -476,7 +470,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces a value at last index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -487,7 +480,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes a value at zero index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -498,7 +490,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes a value at inner index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -509,7 +500,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes and then adds a value at inner index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -521,7 +511,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes a value at last index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -532,7 +521,6 @@ describe('writeJsonWorkpaceFile', () => { it('deletes and then adds a value at last index from an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); const array = (workspace.extensions['x-foo'] as JsonObject)['is'] as JsonArray; @@ -544,7 +532,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces an existing array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); (workspace.extensions['x-foo'] as JsonObject)['is'] = ['value']; @@ -554,7 +541,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces an existing array with an empty array', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); (workspace.extensions['x-foo'] as JsonObject)['is'] = []; @@ -564,7 +550,6 @@ describe('writeJsonWorkpaceFile', () => { it('replaces an existing object with a new object', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-foo'] = { replacement: true }; @@ -574,21 +559,47 @@ describe('writeJsonWorkpaceFile', () => { it('replaces an existing object with an empty object', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); - workspace.extensions['x-foo'] = { }; + workspace.extensions['x-foo'] = {}; await writeJsonWorkspace(workspace, host, 'ObjectReplace2'); }); it('replaces an existing object with a different value type', async () => { const host = createTestCaseHost(basicFile); - const workspace = await readJsonWorkspace('', host); workspace.extensions['x-foo'] = null; await writeJsonWorkspace(workspace, host, 'ObjectReplace3'); }); + + it('removes a property when property value is set to undefined', async () => { + const host = createTestCaseHost(basicFile); + const workspace = await readJsonWorkspace('', host); + + workspace.extensions['x-baz'] = undefined; + + await writeJsonWorkspace(workspace, host, 'ObjectRemove'); + }); + + it('removes a property when using delete operator', async () => { + const host = createTestCaseHost(basicFile); + const workspace = await readJsonWorkspace('', host); + + delete workspace.extensions['x-baz']; + + await writeJsonWorkspace(workspace, host, 'ObjectRemove'); + }); + + it('removes multiple properties when using delete operator', async () => { + const host = createTestCaseHost(basicFile); + const workspace = await readJsonWorkspace('', host); + + delete workspace.extensions['x-baz']; + delete workspace.extensions.schematics; + + await writeJsonWorkspace(workspace, host, 'ObjectRemoveMultiple'); + }); }); diff --git a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/BUILD b/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/BUILD deleted file mode 100644 index a20ce77d2e17..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/BUILD +++ /dev/null @@ -1,15 +0,0 @@ -# TODO(alexeagle): move this file to /third_party so Bazel can enforce the licensing -licenses(["notice"]) - -# Downloaded from: https://github.com/chalk/supports-color/tree/17e9579fec886a1058553b6f7529f05e4f7a90dc -# Timestamp: 2019 Feb 14 -exports_files(["license"]) - -filegroup( - name = "supports-color", - srcs = [ - "index.js", - "//packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag", - ], - visibility = ["//:__subpackages__"], -) diff --git a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/LOCAL_MODS.md b/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/LOCAL_MODS.md deleted file mode 100644 index 76d5851aa34f..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/LOCAL_MODS.md +++ /dev/null @@ -1,3 +0,0 @@ -* Added check for `env.MSYSTEM` in windows case, see https://github.com/angular/angular-cli/commit/b8d4e19fc4209ff6a52b6e6a151927f6fe34b60e -* require the locally vendored has-flag rather than npm package -* support browser runtimes by mocking out the process object if it doesn't exist diff --git a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/index.js b/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/index.js deleted file mode 100644 index 06e16d0b740e..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/index.js +++ /dev/null @@ -1,146 +0,0 @@ -'use strict'; -const os = require('os'); -// LOCAL MOD: import the dependency from local vendored location -const hasFlag = require('../../sindresorhus/has-flag'); - -// LOCAL MOD: support loading this file in a browser -const {env, versions, stdout, stderr, platform} = typeof process == 'object' ? process : { - platform: '', - env: {}, - versions: {node: ''}, -}; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === true || env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === false || env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(stream) { - if (forceColor === 0) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - // LOCAL MOD: support mingw - if (stream && !stream.isTTY && forceColor === undefined && !env.MSYSTEM) { - return 0; - } - - const min = forceColor || 0; - - if (env.TERM === 'dumb') { - return min; - } - - // LOCAL MOD: support mingw - if (platform.startsWith('win32') && !env.MSYSTEM) { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(stdout), - stderr: getSupportLevel(stderr) -}; diff --git a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/license b/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/license deleted file mode 100644 index e7af2f77107d..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/chalk/supports-color/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/BUILD b/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/BUILD deleted file mode 100644 index f84eb4fcf292..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/BUILD +++ /dev/null @@ -1,12 +0,0 @@ -# TODO(alexeagle): move this file to /third_party so Bazel can enforce the licensing -licenses(["notice"]) - -# Downloaded from: https://github.com/sindresorhus/has-flag/tree/a6208ceaf26b5e58dbd29cb4f9e62ad02034104d -# Timestamp: 2019 Feb 14 -exports_files(["license"]) - -filegroup( - name = "has-flag", - srcs = ["index.js"], - visibility = ["//:__subpackages__"], -) diff --git a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/index.js b/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/index.js deleted file mode 100644 index 6a1a0e847022..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -module.exports = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 || pos < terminatorPos); -}; diff --git a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/license b/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/license deleted file mode 100644 index e7af2f77107d..000000000000 --- a/packages/angular_devkit/core/third_party/github.com/sindresorhus/has-flag/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/angular_devkit/schematics/BUILD b/packages/angular_devkit/schematics/BUILD deleted file mode 100644 index 4ac938335046..000000000000 --- a/packages/angular_devkit/schematics/BUILD +++ /dev/null @@ -1,260 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -package(default_visibility = ["//visibility:public"]) - -load("@npm_bazel_jasmine//:index.bzl", "jasmine_node_test") -load("@npm_bazel_typescript//:index.bzl", "ts_library") - -# @external_begin -load("@build_bazel_rules_nodejs//:defs.bzl", "npm_package") -# @external_end - -licenses(["notice"]) - -# @angular-devkit/schematics - -ts_library( - name = "schematics", - srcs = glob( - include = ["src/**/*.ts"], - exclude = [ - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - "src/**/*_benchmark.ts", - ], - ), - module_name = "@angular-devkit/schematics", - module_root = "src/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", # TODO: get rid of this for 6.0 - "@npm//@types/node", - "@npm//rxjs", - ], -) - -ts_library( - name = "schematics_test_lib", - testonly = True, - srcs = glob( - include = [ - "src/**/*_spec.ts", - "src/**/*_spec_large.ts", - ], - ), - # @external_begin - tsconfig = "//:tsconfig-test.json", - # @external_end - deps = [ - ":schematics", - ":testing", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -jasmine_node_test( - name = "schematics_test", - srcs = [":schematics_test_lib"], - deps = [ - "@npm//jasmine", - "@npm//source-map", - ], -) - -# @angular-devkit/schematics/tasks - -ts_library( - name = "tasks", - srcs = glob( - include = ["tasks/**/*.ts"], - exclude = [ - "tasks/node/**/*.ts", - "tasks/**/*_spec.ts", - "tasks/**/*_benchmark.ts", - "tasks/tslint-fix/test/**/*", - ], - ), - module_name = "@angular-devkit/schematics/tasks", - module_root = "tasks/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - ":schematics", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "@npm//@types/node", - "@npm//ora", - "@npm//rxjs", - "@npm//tslint", - "@npm//typescript", - ], -) - -# @angular-devkit/schematics/tasks/node - -ts_library( - name = "tasks_node", - srcs = glob( - include = ["tasks/node/**/*.ts"], - exclude = [ - "tasks/node/**/*_spec.ts", - "tasks/node/**/*_benchmark.ts", - ], - ), - module_name = "@angular-devkit/schematics/tasks/node", - module_root = "tasks/node/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - ":schematics", - ":tasks", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -ts_library( - name = "tasks_test_lib", - testonly = True, - srcs = glob( - include = [ - "tasks/**/*_spec.ts", - "tasks/**/*_spec_large.ts", - "tasks/tslint-fix/test/**/*.ts", - ], - ), - data = [ - "tasks/tslint-fix/test/collection.json", - "tasks/tslint-fix/test/rules/customRuleRule.js", - ], - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - # @external_begin - tsconfig = "//:tsconfig-test.json", - # @external_end - deps = [ - ":schematics", - ":tasks", - ":testing", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "//packages/angular_devkit/core:node_testing", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -jasmine_node_test( - name = "tasks_test", - srcs = [":tasks_test_lib"], - deps = [ - "@npm//jasmine", - "@npm//source-map", - ], -) - -# @angular-devkit/schematics/tools - -ts_library( - name = "tools", - srcs = glob( - include = ["tools/**/*.ts"], - exclude = [ - "tools/**/*_spec.ts", - "tools/**/*_benchmark.ts", - "tools/test/**/*.ts", - ], - ), - module_name = "@angular-devkit/schematics/tools", - module_root = "tools/index.d.ts", - # The attribute below is needed in g3 to turn off strict typechecking - # strict_checks = False, - deps = [ - ":schematics", - ":tasks", - ":tasks_node", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -ts_library( - name = "tools_test_lib", - testonly = True, - srcs = glob( - include = [ - "tools/**/*_spec.ts", - "tools/**/*_spec_large.ts", - "tools/test/**/*.ts", - ], - ), - # @external_begin - tsconfig = "//:tsconfig-test.json", - # @external_end - deps = [ - ":schematics", - ":tasks", - ":testing", - ":tools", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core:node", - "//tests/angular_devkit/schematics/tools/file-system-engine-host:file_system_engine_host_test_lib", - "@npm//@types/jasmine", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -jasmine_node_test( - name = "tools_test", - srcs = [":tools_test_lib"], - deps = [ - "@npm//jasmine", - "@npm//source-map", - ], -) - -# @angular-devkit/schematics/testing - -ts_library( - name = "testing", - srcs = glob( - include = ["testing/**/*.ts"], - ), - module_name = "@angular-devkit/schematics/testing", - module_root = "testing/index.d.ts", - deps = [ - ":schematics", - ":tasks", - ":tasks_node", - ":tools", - "//packages/angular_devkit/core", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -# @external_begin -npm_package( - name = "npm_package", - deps = [ - ":schematics", - ":tasks", - ":testing", - ":tools", - ], -) -# @external_end diff --git a/packages/angular_devkit/schematics/BUILD.bazel b/packages/angular_devkit/schematics/BUILD.bazel new file mode 100644 index 000000000000..29b14cd973bb --- /dev/null +++ b/packages/angular_devkit/schematics/BUILD.bazel @@ -0,0 +1,90 @@ +load("@devinfra//bazel/api-golden:index.bzl", "api_golden_test_npm_package") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defaults.bzl", "jasmine_test", "npm_package", "ts_project") + +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +npm_link_all_packages() + +# @angular-devkit/schematics + +ts_project( + name = "schematics", + srcs = glob( + include = ["src/**/*.ts"], + exclude = [ + "src/**/*_spec.ts", + ], + ) + ["index.ts"], + data = [ + "package.json", + ], + deps = [ + ":node_modules/@angular-devkit/core", + ":node_modules/jsonc-parser", + ":node_modules/magic-string", + ":node_modules/rxjs", + "//:node_modules/@types/node", + ], +) + +ts_project( + name = "schematics_test_lib", + testonly = True, + srcs = glob(["src/**/*_spec.ts"]), + deps = [ + ":node_modules/@angular-devkit/core", + ":node_modules/rxjs", + ":schematics", + "//:node_modules/@types/jasmine", + "//packages/angular_devkit/schematics/testing", + ], +) + +jasmine_test( + name = "test", + data = [":schematics_test_lib"], +) + +genrule( + name = "license", + srcs = ["//:LICENSE"], + outs = ["LICENSE"], + cmd = "cp $(execpath //:LICENSE) $@", +) + +npm_package( + name = "pkg", + pkg_deps = [ + "//packages/angular_devkit/core:package.json", + ], + tags = ["release-package"], + deps = [ + ":README.md", + ":collection-schema.json", + ":license", + ":schematics", + "//packages/angular_devkit/schematics/tasks", + "//packages/angular_devkit/schematics/testing", + "//packages/angular_devkit/schematics/tools", + ], +) + +api_golden_test_npm_package( + name = "schematics_api", + data = [ + ":npm_package", + "//goldens:public-api", + ], + golden_dir = "goldens/public-api/angular_devkit/schematics", + npm_package = "packages/angular_devkit/schematics/npm_package", + types = { + "//:node_modules/@types/node": "node", + }, +) diff --git a/packages/angular_devkit/schematics/README.md b/packages/angular_devkit/schematics/README.md index 76e9fa6e8f78..a0b9d8e3e2a4 100644 --- a/packages/angular_devkit/schematics/README.md +++ b/packages/angular_devkit/schematics/README.md @@ -1,33 +1,37 @@ # Schematics + > A scaffolding library for the modern web. ## Description + Schematics are generators that transform an existing filesystem. They can create files, refactor existing files, or move files around. What distinguishes Schematics from other generators, such as Yeoman or Yarn Create, is that schematics are purely descriptive; no changes are applied to the actual filesystem until everything is ready to be committed. There is no side effect, by design, in Schematics. # Glossary -| Term | Description | -|------|-------------| -| **Schematics** | A generator that executes descriptive code without side effects on an existing file system. | -| **Collection** | A list of schematics metadata. Schematics can be referred by name inside a collection. | -| **Tool** | The code using the Schematics library. | -| **Tree** | A staging area for changes, containing the original file system, and a list of changes to apply to it. | -| **Rule** | A function that applies actions to a `Tree`. It returns a new `Tree` that will contain all transformations to be applied. | -| **Source** | A function that creates an entirely new `Tree` from an empty filesystem. For example, a file source could read files from disk and create a Create Action for each of those. -| **Action** | An atomic operation to be validated and committed to a filesystem or a `Tree`. Actions are created by schematics. | -| **Sink** | The final destination of all `Action`s. | +| Term | Description | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Schematics** | A generator that executes descriptive code without side effects on an existing file system. | +| **Collection** | A list of schematics metadata. Schematics can be referred by name inside a collection. | +| **Tool** | The code using the Schematics library. | +| **Tree** | A staging area for changes, containing the original file system, and a list of changes to apply to it. | +| **Rule** | A function that applies actions to a `Tree`. It returns a new `Tree` that will contain all transformations to be applied. | +| **Source** | A function that creates an entirely new `Tree` from an empty filesystem. For example, a file source could read files from disk and create a Create Action for each of those. | +| **Action** | An atomic operation to be validated and committed to a filesystem or a `Tree`. Actions are created by schematics. | +| **Sink** | The final destination of all `Action`s. | +| **Task** | A Task is a way to execute an external command or script in a schematic. A Task can be used to perform actions such as installing dependencies, running tests, or building a project. A Task is created by using the `SchematicContext` object and can be scheduled to run before or after the schematic `Tree` is applied. | # Tooling -Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself. + +Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself. The tooling is responsible for the following tasks: 1. Create the Schematic Engine, and pass in a Collection and Schematic loader. 1. Understand and respect the Schematics metadata and dependencies between collections. Schematics can refer to dependencies, and it's the responsibility of the tool to honor those dependencies. The reference CLI uses NPM packages for its collections. 1. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parses the arguments as a JSON object and validates it with the Schema specified by the collection. - 1. Schematics provides some JSON Schema formats for validation that tooling should add. These validate paths, html selectors and app names. Please check the reference CLI for how these can be added. +1. Schematics provides some JSON Schema formats for validation that tooling should add. These validate paths, html selectors and app names. Please check the reference CLI for how these can be added. 1. Call the schematics with the original Tree. The tree should represent the initial state of the filesystem. The reference CLI uses the current directory for this. 1. Create a Sink and commit the result of the schematics to the Sink. Many sinks are provided by the library; FileSystemSink and DryRunSink are examples. 1. Output any logs propagated by the library, including debugging information. @@ -35,25 +39,30 @@ The tooling is responsible for the following tasks: The tooling API is composed of the following pieces: ## Engine + The `SchematicEngine` is responsible for loading and constructing `Collection`s and `Schematics`. When creating an engine, the tooling provides an `EngineHost` interface that understands how to create a `CollectionDescription` from a name, and how to create a `SchematicDescription`. # Schematics (Generators) + Schematics are generators and part of a `Collection`. ## Collection + A Collection is defined by a `collection.json` file (in the reference CLI). This JSON defines the following properties: -| Prop Name | Type | Description | -|---|---|---| -| **name** | `string` | The name of the collection. | -| **version** | `string` | Unused field. | +| Prop Name | Type | Description | +| ----------- | -------- | --------------------------- | +| **name** | `string` | The name of the collection. | +| **version** | `string` | Unused field. | ## Schematic # Operators, Sources and Rules + A `Source` is a generator of a `Tree`; it creates an entirely new root tree from nothing. A `Rule` is a transformation from one `Tree` to another. A `Schematic` (at the root) is a `Rule` that is normally applied on the filesystem. ## Operators + `FileOperator`s apply changes to a single `FileEntry` and return a new `FileEntry`. The result follows these rules: 1. If the `FileEntry` returned is null, a `DeleteAction` will be added to the action list. @@ -63,66 +72,71 @@ A `Source` is a generator of a `Tree`; it creates an entirely new root tree from It is impossible to create files using a `FileOperator`. ## Provided Operators + The Schematics library provides multiple `Operator` factories by default that cover basic use cases: -| FileOperator | Description | -|---|---| -| `contentTemplate(options: T)` | Apply a content template (see the Template section) | -| `pathTemplate(options: T)` | Apply a path template (see the Template section) | +| FileOperator | Description | +| -------------------------------- | -------------------------------------------------------------------- | +| `contentTemplate(options: T)` | Apply a content template (see the [Templating](#templating) section) | +| `pathTemplate(options: T)` | Apply a path template (see the [Templating](#templating) section) | ## Provided Sources + The Schematics library additionally provides multiple `Source` factories by default: -| Source | Description | -|---|---| -| `empty()` | Creates a source that returns an empty `Tree`. | -| `source(tree: Tree)` | Creates a `Source` that returns the `Tree` passed in as argument. | -| `url(url: string)` | Loads a list of files from the given URL and returns a `Tree` with the files as `CreateAction` applied to an empty `Tree`. | -| `apply(source: Source, rules: Rule[])` | Apply a list of `Rule`s to a source, and return the resulting `Source`. | +| Source | Description | +| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `empty()` | Creates a source that returns an empty `Tree`. | +| `source(tree: Tree)` | Creates a `Source` that returns the `Tree` passed in as argument. | +| `url(url: string)` | Loads a list of files from the given URL and returns a `Tree` with the files as `CreateAction` applied to an empty `Tree`. | +| `apply(source: Source, rules: Rule[])` | Apply a list of `Rule`s to a source, and return the resulting `Source`. | ## Provided Rules -The schematics library also provides `Rule` factories by default: -| Rule | Description | -|---|---| -| `noop()` | Returns the input `Tree` as is. | -| `chain(rules: Rule[])` | Returns a `Rule` that's the concatenation of other `Rule`s. | -| `forEach(op: FileOperator)` | Returns a `Rule` that applies an operator to every file of the input `Tree`. | -| `move(root: string)` | Moves all the files from the input to a subdirectory. | -| `merge(other: Tree)` | Merge the input `Tree` with the other `Tree`. | -| `contentTemplate(options: T)` | Apply a content template (see the Template section) to the entire `Tree`. | -| `pathTemplate(options: T)` | Apply a path template (see the Template section) to the entire `Tree`. | -| `template(options: T)` | Apply both path and content templates (see the Template section) to the entire `Tree`. | -| `filter(predicate: FilePredicate)` | Returns the input `Tree` with files that do not pass the `FilePredicate`. | +The schematics library also provides `Rule` factories by default: +| Rule | Description | +| ------------------------------------------- | -------------------------------------------------------------------------------------- | +| `noop()` | Returns the input `Tree` as is. | +| `chain(rules: Rule[])` | Returns a `Rule` that's the concatenation of other `Rule`s. | +| `forEach(op: FileOperator)` | Returns a `Rule` that applies an operator to every file of the input `Tree`. | +| `move(root: string)` | Moves all the files from the input to a subdirectory. | +| `merge(other: Tree)` | Merge the input `Tree` with the other `Tree`. | +| `contentTemplate(options: T)` | Apply a content template (see the Template section) to the entire `Tree`. | +| `pathTemplate(options: T)` | Apply a path template (see the Template section) to the entire `Tree`. | +| `template(options: T)` | Apply both path and content templates (see the Template section) to the entire `Tree`. | +| `filter(predicate: FilePredicate)` | Returns the input `Tree` with files that do not pass the `FilePredicate`. | # Templating + As referenced above, some functions are based upon a file templating system, which consists of path and content templating. The system operates on placeholders defined inside files or their paths as loaded in the `Tree` and fills these in as defined in the following, using values passed into the `Rule` which applies the templating (i.e. `template(options: T)`). ## Path Templating -| Placeholder | Description | -|---|---| -| __variable__ | Replaced with the value of `variable`. | -| __variable@function__ | Replaced with the result of the call `function(variable)`. Can be chained to the left (`__variable@function1@function2__ ` etc). | + +| Placeholder | Description | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `__variable__` | Replaced with the value of `variable`. | +| `__variable@function__` | Replaced with the result of the call `function(variable)`. Can be chained to the left (`__variable@function1@function2__ ` etc). | ## Content Templating -| Placeholder | Description | -|---|---| -| <%= expression %> | Replaced with the result of the call of the given expression. This only supports direct expressions, no structural (for/if/...) JavaScript. | -| <%- expression %> | Same as above, but the value of the result will be escaped for HTML when inserted (i.e. replacing '<' with '<') | -| <% inline code %> | Inserts the given code into the template structure, allowing to insert structural JavaScript. | -| <%# text %> | A comment, which gets entirely dropped. | +| Placeholder | Description | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `<%= expression %>` | Replaced with the result of the call of the given expression. This only supports direct expressions, no structural (for/if/...) JavaScript. | +| `<%- expression %>` | Same as above, but the value of the result will be escaped for HTML when inserted (i.e. replacing '<' with '\<') | +| `<% inline code %>` | Inserts the given code into the template structure, allowing to insert structural JavaScript. | +| `<%# text %>` | A comment, which gets entirely dropped. | # Examples ## Simple + An example of a simple Schematics which creates a "hello world" file, using an option to determine its path: ```typescript -import {Tree} from '@angular-devkit/schematics'; +import { Tree } from '@angular-devkit/schematics'; export default function MySchematic(options: any) { return (tree: Tree) => { @@ -138,6 +152,7 @@ A few things from this example: 1. It returns a [`Rule`](src/engine/interface.ts#L73), which is a transformation from a `Tree` to another `Tree`. ## Templating + A simplified example of a Schematics which creates a file containing a new Class, using an option to determine its name: ```typescript @@ -152,8 +167,15 @@ export class <%= classify(name) %> { import { strings } from '@angular-devkit/core'; import { - Rule, SchematicContext, SchematicsException, Tree, - apply, branchAndMerge, mergeWith, template, url, + Rule, + SchematicContext, + SchematicsException, + Tree, + apply, + branchAndMerge, + mergeWith, + template, + url, } from '@angular-devkit/schematics'; import { Schema as ClassOptions } from './schema'; @@ -163,15 +185,12 @@ export default function (options: ClassOptions): Rule { throw new SchematicsException('Option (name) is required.'); } - const templateSource = apply( - url('./files'), - [ - template({ - ...strings, - ...options, - }), - ] - ); + const templateSource = apply(url('./files'), [ + template({ + ...strings, + ...options, + }), + ]); return branchAndMerge(mergeWith(templateSource)); }; @@ -179,14 +198,8 @@ export default function (options: ClassOptions): Rule { ``` Additional things from this example: + 1. `strings` provides the used `dasherize` and `classify` functions, among others. 1. The files are on-disk in the same root directory as the `index.ts` and loaded into a `Tree`. 1. Then the `template` `Rule` fills in the specified templating placeholders. For this, it only knows about the variables and functions passed to it via the options-object. 1. Finally, the resulting `Tree`, containing the new file, is merged with the existing files of the project which the Schematic is run on. - -# Future Work -Schematics is not done yet. Here's a list of things we are considering: - -* Smart defaults for Options. Having a JavaScript function for default values based on other default values. -* Prompt for input options. This should only be prompted for the original schematics, dependencies to other schematics should not trigger another prompting. -* Tasks for running tooling-specific jobs before and after a schematics has been scaffolded. Such tasks can involve initialize git, or npm install. A specific list of tasks should be provided by the tool, with unsupported tasks generating an error. diff --git a/packages/angular_devkit/schematics/collection-schema.json b/packages/angular_devkit/schematics/collection-schema.json index 497504442015..6489280417e2 100644 --- a/packages/angular_devkit/schematics/collection-schema.json +++ b/packages/angular_devkit/schematics/collection-schema.json @@ -1,6 +1,6 @@ { - "$schema": "http://json-schema.org/schema", - "id": "SchematicsCollectionSchema", + "$schema": "http://json-schema.org/draft-07/schema", + "$id": "SchematicsCollectionSchema", "title": "Collection Schema for validating a 'collection.json'.", "type": "object", "properties": { @@ -59,17 +59,12 @@ "description": "Whether or not this schematic can be called from an external schematic, or a tool. This implies hidden: true." } }, - "required": [ - "factory", - "description" - ] + "required": ["factory", "description"] } }, "version": { "type": "string" } }, - "required": [ - "schematics" - ] + "required": ["schematics"] } diff --git a/packages/angular_devkit/schematics/index.ts b/packages/angular_devkit/schematics/index.ts new file mode 100644 index 000000000000..e6da94cc7ded --- /dev/null +++ b/packages/angular_devkit/schematics/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +export * from './src/index'; diff --git a/packages/angular_devkit/schematics/package.json b/packages/angular_devkit/schematics/package.json index 9c28bad17ab6..5ccb8d0ff0e4 100644 --- a/packages/angular_devkit/schematics/package.json +++ b/packages/angular_devkit/schematics/package.json @@ -1,9 +1,29 @@ { "name": "@angular-devkit/schematics", - "version": "0.0.0", + "version": "0.0.0-PLACEHOLDER", "description": "Angular Schematics - Library", "main": "src/index.js", "typings": "src/index.d.ts", + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./tasks": { + "types": "./tasks/index.d.ts", + "default": "./tasks/index.js" + }, + "./testing": { + "types": "./testing/index.d.ts", + "default": "./testing/index.js" + }, + "./tools": { + "types": "./tools/index.d.ts", + "default": "./tools/index.js" + }, + "./collection-schema.json": "./collection-schema.json", + "./package.json": "./package.json" + }, "keywords": [ "blueprints", "scaffolding", @@ -13,8 +33,10 @@ "schematics" ], "dependencies": { - "@angular-devkit/core": "0.0.0", - "ora": "4.0.3", - "rxjs": "6.5.3" + "@angular-devkit/core": "workspace:0.0.0-PLACEHOLDER", + "jsonc-parser": "3.3.1", + "magic-string": "1.4.5", + "ora": "10.0.0", + "rxjs": "7.8.2" } } diff --git a/packages/angular_devkit/schematics/src/_golden-api.ts b/packages/angular_devkit/schematics/src/_golden-api.ts deleted file mode 100644 index 9d9ea4ddacbe..000000000000 --- a/packages/angular_devkit/schematics/src/_golden-api.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -export * from './index'; - -export * from './formats/index'; - -export * from './workflow/index'; diff --git a/packages/angular_devkit/schematics/src/engine/engine.ts b/packages/angular_devkit/schematics/src/engine/engine.ts index 0db56c78c11a..c58ccac7877f 100644 --- a/packages/angular_devkit/schematics/src/engine/engine.ts +++ b/packages/angular_devkit/schematics/src/engine/engine.ts @@ -1,14 +1,14 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { BaseException, PriorityQueue, logging } from '@angular-devkit/core'; -import { Observable, from as observableFrom } from 'rxjs'; -import { concatMap } from 'rxjs/operators'; -import { Url } from 'url'; +import { Url } from 'node:url'; +import { Observable, concatMap, from as observableFrom } from 'rxjs'; import { MergeStrategy } from '../tree/interface'; import { NullTree } from '../tree/null'; import { empty } from '../tree/static'; @@ -32,13 +32,16 @@ import { } from './interface'; import { SchematicImpl } from './schematic'; - export class UnknownUrlSourceProtocol extends BaseException { - constructor(url: string) { super(`Unknown Protocol on url "${url}".`); } + constructor(url: string) { + super(`Unknown Protocol on url "${url}".`); + } } export class UnknownCollectionException extends BaseException { - constructor(name: string) { super(`Unknown collection "${name}".`); } + constructor(name: string) { + super(`Unknown collection "${name}".`); + } } export class CircularCollectionException extends BaseException { @@ -60,7 +63,9 @@ export class PrivateSchematicException extends BaseException { } export class SchematicEngineConflictingException extends BaseException { - constructor() { super(`A schematic was called from a different engine as its parent.`); } + constructor() { + super(`A schematic was called from a different engine as its parent.`); + } } export class UnregisteredTaskException extends BaseException { @@ -77,21 +82,27 @@ export class UnknownTaskDependencyException extends BaseException { } export class CollectionImpl - implements Collection { - constructor(private _description: CollectionDescription, - private _engine: SchematicEngine, - public readonly baseDescriptions?: Array>) { + implements Collection +{ + constructor( + private _description: CollectionDescription, + private _engine: SchematicEngine, + public readonly baseDescriptions?: CollectionDescription[] | undefined, + ) {} + + get description(): CollectionDescription { + return this._description; + } + get name(): string { + return this.description.name || ''; } - - get description() { return this._description; } - get name() { return this.description.name || ''; } createSchematic(name: string, allowPrivate = false): Schematic { return this._engine.createSchematic(name, this, allowPrivate); } - listSchematicNames(): string[] { - return this._engine.listSchematicNames(this); + listSchematicNames(includeHidden?: boolean): string[] { + return this._engine.listSchematicNames(this, includeHidden); } } @@ -117,7 +128,7 @@ export class TaskScheduler { return new Set(); } - const tasks = dependencies.map(dep => { + const tasks = dependencies.map((dep) => { const task = this._taskIds.get(dep); if (!task) { throw new UnknownTaskDependencyException(dep); @@ -129,7 +140,7 @@ export class TaskScheduler { return new Set(tasks); } - schedule(taskConfiguration: TaskConfiguration): TaskId { + schedule(taskConfiguration: TaskConfiguration): TaskId { const dependencies = this._mapDependencies(taskConfiguration.dependencies); const priority = this._calculatePriority(dependencies); @@ -155,44 +166,54 @@ export class TaskScheduler { return tasks; } - } - export class SchematicEngine - implements Engine { - + implements Engine +{ private _collectionCache = new Map>(); - private _schematicCache - = new Map>>(); + private _schematicCache = new WeakMap< + Collection, + Map> + >(); private _taskSchedulers = new Array(); - constructor(private _host: EngineHost, protected _workflow?: Workflow) { - } + constructor( + private _host: EngineHost, + protected _workflow?: Workflow | undefined, + ) {} - get workflow() { return this._workflow || null; } - get defaultMergeStrategy() { return this._host.defaultMergeStrategy || MergeStrategy.Default; } + get workflow(): Workflow | null { + return this._workflow || null; + } + get defaultMergeStrategy(): MergeStrategy { + return this._host.defaultMergeStrategy || MergeStrategy.Default; + } - createCollection(name: string): Collection { + createCollection( + name: string, + requester?: Collection, + ): Collection { let collection = this._collectionCache.get(name); if (collection) { return collection; } - const [description, bases] = this._createCollectionDescription(name); + const [description, bases] = this._createCollectionDescription(name, requester?.description); collection = new CollectionImpl(description, this, bases); this._collectionCache.set(name, collection); - this._schematicCache.set(name, new Map()); + this._schematicCache.set(collection, new Map()); return collection; } private _createCollectionDescription( name: string, + requester?: CollectionDescription, parentNames?: Set, ): [CollectionDescription, Array>] { - const description = this._host.createCollectionDescription(name); + const description = this._host.createCollectionDescription(name, requester); if (!description) { throw new UnknownCollectionException(name); } @@ -204,7 +225,11 @@ export class SchematicEngine()).add(description.name); for (const baseName of description.extends) { - const [base, baseBases] = this._createCollectionDescription(baseName, new Set(parentNames)); + const [base, baseBases] = this._createCollectionDescription( + baseName, + description, + new Set(parentNames), + ); bases.unshift(base, ...baseBases); } @@ -231,13 +256,14 @@ export class SchematicEngine = { - debug: parent && parent.debug || false, + debug: (parent && parent.debug) || false, engine: this, - logger: (parent && parent.logger && parent.logger.createChild(schematic.description.name)) - || new logging.NullLogger(), + logger: + (parent && parent.logger && parent.logger.createChild(schematic.description.name)) || + new logging.NullLogger(), schematic, - strategy: (parent && parent.strategy !== undefined) - ? parent.strategy : this.defaultMergeStrategy, + strategy: + parent && parent.strategy !== undefined ? parent.strategy : this.defaultMergeStrategy, interactive, addTask, }; @@ -251,7 +277,7 @@ export class SchematicEngine( + function addTask( task: TaskConfigurationGenerator, dependencies?: Array, ): TaskId { @@ -277,14 +303,9 @@ export class SchematicEngine, allowPrivate = false, ): Schematic { - const collectionImpl = this._collectionCache.get(collection.description.name); - const schematicMap = this._schematicCache.get(collection.description.name); - if (!collectionImpl || !schematicMap || collectionImpl !== collection) { - // This is weird, maybe the collection was created by another engine? - throw new UnknownCollectionException(collection.description.name); - } + const schematicMap = this._schematicCache.get(collection); - let schematic = schematicMap.get(name); + let schematic = schematicMap?.get(name); if (schematic) { return schematic; } @@ -314,17 +335,20 @@ export class SchematicEngine(description, factory, collection, this); - schematicMap.set(name, schematic); + schematicMap?.set(name, schematic); return schematic; } - listSchematicNames(collection: Collection): string[] { - const names = this._host.listSchematicNames(collection.description); + listSchematicNames( + collection: Collection, + includeHidden?: boolean, + ): string[] { + const names = this._host.listSchematicNames(collection.description, includeHidden); if (collection.baseDescriptions) { for (const base of collection.baseDescriptions) { - names.push(...this._host.listSchematicNames(base)); + names.push(...this._host.listSchematicNames(base, includeHidden)); } } @@ -342,40 +366,42 @@ export class SchematicEngine): Source { switch (url.protocol) { - case 'null:': return () => new NullTree(); - case 'empty:': return () => empty(); - default: - const hostSource = this._host.createSourceFromUrl(url, context); - if (!hostSource) { - throw new UnknownUrlSourceProtocol(url.toString()); - } + case 'null:': + return () => new NullTree(); + case 'empty:': + return () => empty(); + } - return hostSource; + const hostSource = this._host.createSourceFromUrl(url, context); + if (!hostSource) { + throw new UnknownUrlSourceProtocol(url.toString()); } + + return hostSource; } executePostTasks(): Observable { const executors = new Map(); - const taskObservable = observableFrom(this._taskSchedulers) - .pipe( - concatMap(scheduler => scheduler.finalize()), - concatMap(task => { - const { name, options } = task.configuration; + const taskObservable = observableFrom(this._taskSchedulers).pipe( + concatMap((scheduler) => scheduler.finalize()), + concatMap((task) => { + const { name, options } = task.configuration; - const executor = executors.get(name); - if (executor) { - return executor(options, task.context); - } + const executor = executors.get(name); + if (executor) { + return executor(options, task.context); + } - return this._host.createTaskExecutor(name) - .pipe(concatMap(executor => { - executors.set(name, executor); + return this._host.createTaskExecutor(name).pipe( + concatMap((executor) => { + executors.set(name, executor); - return executor(options, task.context); - })); - }), - ); + return executor(options, task.context); + }), + ); + }), + ); return taskObservable; } diff --git a/packages/angular_devkit/schematics/src/engine/index.ts b/packages/angular_devkit/schematics/src/engine/index.ts index 9f8b476cc297..3223bbfed070 100644 --- a/packages/angular_devkit/schematics/src/engine/index.ts +++ b/packages/angular_devkit/schematics/src/engine/index.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + export * from './engine'; export * from './interface'; export * from './schematic'; diff --git a/packages/angular_devkit/schematics/src/engine/interface.ts b/packages/angular_devkit/schematics/src/engine/interface.ts index ac2d9d2409a1..ddc574fe25b1 100644 --- a/packages/angular_devkit/schematics/src/engine/interface.ts +++ b/packages/angular_devkit/schematics/src/engine/interface.ts @@ -1,17 +1,17 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { analytics, logging } from '@angular-devkit/core'; + +import { logging } from '@angular-devkit/core'; +import { Url } from 'node:url'; import { Observable } from 'rxjs'; -import { Url } from 'url'; import { FileEntry, MergeStrategy, Tree } from '../tree/interface'; import { Workflow } from '../workflow/interface'; - export interface TaskConfiguration { name: string; dependencies?: Array; @@ -22,8 +22,10 @@ export interface TaskConfigurationGenerator { toConfiguration(): TaskConfiguration; } -export type TaskExecutor - = (options: T | undefined, context: SchematicContext) => Promise | Observable; +export type TaskExecutor = ( + options: T | undefined, + context: SchematicContext, +) => Promise | Observable; export interface TaskExecutorFactory { readonly name: string; @@ -36,7 +38,7 @@ export interface TaskId { export interface TaskInfo { readonly id: number; - readonly priority: number; + readonly priority: number; readonly configuration: TaskConfiguration; readonly context: SchematicContext; } @@ -61,31 +63,39 @@ export type CollectionDescription = Collecti * needs to run. The SchematicMetadataT and CollectionMetadataT type parameters contain additional * metadata that you want to store while remaining type-safe. */ -export type SchematicDescription = SchematicMetadataT & { +export type SchematicDescription< + CollectionMetadataT extends object, + SchematicMetadataT extends object, +> = SchematicMetadataT & { readonly collection: CollectionDescription; readonly name: string; readonly private?: boolean; readonly hidden?: boolean; }; - /** * The Host for the Engine. Specifically, the piece of the tooling responsible for resolving * collections and schematics descriptions. The SchematicMetadataT and CollectionMetadataT type * parameters contain additional metadata that you want to store while remaining type-safe. */ export interface EngineHost { - createCollectionDescription(name: string): CollectionDescription; - listSchematicNames(collection: CollectionDescription): string[]; + createCollectionDescription( + name: string, + requester?: CollectionDescription, + ): CollectionDescription; + listSchematicNames( + collection: CollectionDescription, + includeHidden?: boolean, + ): string[]; createSchematicDescription( - name: string, - collection: CollectionDescription): - SchematicDescription | null; + name: string, + collection: CollectionDescription, + ): SchematicDescription | null; getSchematicRuleFactory( - schematic: SchematicDescription, - collection: CollectionDescription): RuleFactory; + schematic: SchematicDescription, + collection: CollectionDescription, + ): RuleFactory; createSourceFromUrl( url: Url, context: TypedSchematicContext, @@ -104,7 +114,6 @@ export interface EngineHost { - createCollection(name: string): Collection; + createCollection( + name: string, + requester?: Collection, + ): Collection; createContext( schematic: Schematic, parent?: Partial>, executionOptions?: Partial, ): TypedSchematicContext; createSchematic( - name: string, - collection: Collection, + name: string, + collection: Collection, ): Schematic; createSourceFromUrl( url: Url, context: TypedSchematicContext, ): Source; transformOptions( - schematic: Schematic, - options: OptionT, - context?: TypedSchematicContext, + schematic: Schematic, + options: OptionT, + context?: TypedSchematicContext, ): Observable; executePostTasks(): Observable; @@ -141,7 +153,6 @@ export interface Engine; - listSchematicNames(): string[]; + listSchematicNames(includeHidden?: boolean): string[]; } - /** * A Schematic as created by the Engine. This should be used by the tool to execute the main * schematics, or by rules to execute other schematics as well. @@ -174,40 +184,38 @@ export interface Schematic; } - /** * A SchematicContext. Contains information necessary for Schematics to execute some rules, for * example when using another schematics, as we need the engine and collection. */ -export interface TypedSchematicContext { +export interface TypedSchematicContext< + CollectionMetadataT extends object, + SchematicMetadataT extends object, +> { readonly debug: boolean; readonly engine: Engine; readonly logger: logging.LoggerApi; readonly schematic: Schematic; readonly strategy: MergeStrategy; readonly interactive: boolean; - addTask(task: TaskConfigurationGenerator, dependencies?: Array): TaskId; - - // This might be undefined if the feature is unsupported. - readonly analytics?: analytics.Analytics; + addTask( + task: TaskConfigurationGenerator, + dependencies?: Array, + ): TaskId; } - /** * This is used by the Schematics implementations in order to avoid needing to have typing from * the tooling. Schematics are not specific to a tool. */ export type SchematicContext = TypedSchematicContext<{}, {}>; - /** * A rule factory, which is normally the way schematics are implemented. Returned by the tooling * after loading a schematic description. */ export type RuleFactory = (options: T) => Rule; - /** * A FileOperator applies changes synchronously to a FileEntry. An async operator returns * asynchronously. We separate them so that the type system can catch early errors. @@ -215,7 +223,6 @@ export type RuleFactory = (options: T) => Rule; export type FileOperator = (entry: FileEntry) => FileEntry | null; export type AsyncFileOperator = (tree: FileEntry) => Observable; - /** * A source is a function that generates a Tree from a specific context. A rule transforms a tree * into another tree from a specific context. In both cases, an Observable can be returned if @@ -226,5 +233,7 @@ export type AsyncFileOperator = (tree: FileEntry) => Observable Tree | Observable; -export type Rule = (tree: Tree, context: SchematicContext) => - Tree | Observable | Rule | Promise | Promise | void; +export type Rule = ( + tree: Tree, + context: SchematicContext, +) => Tree | Observable | Rule | Promise | void; diff --git a/packages/angular_devkit/schematics/src/engine/schematic.ts b/packages/angular_devkit/schematics/src/engine/schematic.ts index 594bc4a1f151..bf99bbf63493 100644 --- a/packages/angular_devkit/schematics/src/engine/schematic.ts +++ b/packages/angular_devkit/schematics/src/engine/schematic.ts @@ -1,13 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { BaseException } from '@angular-devkit/core'; -import { Observable, of as observableOf } from 'rxjs'; -import { concatMap, first, map } from 'rxjs/operators'; +import { Observable, concatMap, first, map } from 'rxjs'; import { callRule } from '../rules/call'; import { Tree } from '../tree/interface'; import { ScopedTree } from '../tree/scoped'; @@ -21,28 +21,32 @@ import { TypedSchematicContext, } from './interface'; - export class InvalidSchematicsNameException extends BaseException { constructor(name: string) { super(`Schematics has invalid name: "${name}".`); } } - export class SchematicImpl - implements Schematic { - - constructor(private _description: SchematicDescription, - private _factory: RuleFactory<{}>, - private _collection: Collection, - private _engine: Engine) { + implements Schematic +{ + constructor( + private _description: SchematicDescription, + private _factory: RuleFactory<{}>, + private _collection: Collection, + private _engine: Engine, + ) { if (!_description.name.match(/^[-@/_.a-zA-Z0-9]+$/)) { throw new InvalidSchematicsNameException(_description.name); } } - get description() { return this._description; } - get collection() { return this._collection; } + get description(): SchematicDescription { + return this._description; + } + get collection(): Collection { + return this._collection; + } call( options: OptionT, @@ -52,36 +56,37 @@ export class SchematicImpl { const context = this._engine.createContext(this, parentContext, executionOptions); - return host - .pipe( - first(), - concatMap(tree => this._engine.transformOptions(this, options, context).pipe( - map(o => [tree, o]), - )), - concatMap(([tree, transformedOptions]: [Tree, OptionT]) => { - let input: Tree; - let scoped = false; - if (executionOptions && executionOptions.scope) { - scoped = true; - input = new ScopedTree(tree, executionOptions.scope); - } else { - input = tree; - } + return host.pipe( + first(), + concatMap((tree) => + this._engine + .transformOptions(this, options, context) + .pipe(map((o) => [tree, o] as [Tree, OptionT])), + ), + concatMap(([tree, transformedOptions]) => { + let input: Tree; + let scoped = false; + if (executionOptions && executionOptions.scope) { + scoped = true; + input = new ScopedTree(tree, executionOptions.scope); + } else { + input = tree; + } - return callRule(this._factory(transformedOptions), observableOf(input), context).pipe( - map(output => { - if (output === input) { - return tree; - } else if (scoped) { - tree.merge(output); + return callRule(this._factory(transformedOptions), input, context).pipe( + map((output) => { + if (output === input) { + return tree; + } else if (scoped) { + tree.merge(output); - return tree; - } else { - return output; - } - }), - ); - }), - ); + return tree; + } else { + return output; + } + }), + ); + }), + ); } } diff --git a/packages/angular_devkit/schematics/src/engine/schematic_spec.ts b/packages/angular_devkit/schematics/src/engine/schematic_spec.ts index 5f16ed347644..8beb6ad81e9f 100644 --- a/packages/angular_devkit/schematics/src/engine/schematic_spec.ts +++ b/packages/angular_devkit/schematics/src/engine/schematic_spec.ts @@ -1,20 +1,20 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-non-null-assertion + +/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { logging } from '@angular-devkit/core'; -import { of as observableOf } from 'rxjs'; +import { lastValueFrom, of as observableOf } from 'rxjs'; import { chain } from '../rules/base'; import { MergeStrategy, Tree } from '../tree/interface'; import { branch, empty } from '../tree/static'; import { CollectionDescription, Engine, Rule, Schematic, SchematicDescription } from './interface'; import { SchematicImpl } from './schematic'; - type CollectionT = { description: string; }; @@ -40,17 +40,15 @@ const collection = { description: 'description', } as CollectionDescription; - function files(tree: Tree) { const files: string[] = []; - tree.visit(x => files.push(x)); + tree.visit((x) => files.push(x)); return files; } - describe('Schematic', () => { - it('works with a rule', done => { + it('works with a rule', async () => { let inner: Tree | null = null; const desc: SchematicDescription = { collection, @@ -65,17 +63,13 @@ describe('Schematic', () => { }, }; - const schematic = new SchematicImpl(desc, desc.factory, null !, engine); - schematic.call({}, observableOf(empty())) - .toPromise() - .then(x => { - expect(files(inner !)).toEqual([]); - expect(files(x)).toEqual(['/a/b/c']); - }) - .then(done, done.fail); + const schematic = new SchematicImpl(desc, desc.factory, null!, engine); + const x = await lastValueFrom(schematic.call({}, observableOf(empty()))); + expect(files(inner!)).toEqual([]); + expect(files(x)).toEqual(['/a/b/c']); }); - it('works with a rule that returns an observable', done => { + it('works with a rule that returns an observable', async () => { let inner: Tree | null = null; const desc: SchematicDescription = { collection, @@ -89,31 +83,30 @@ describe('Schematic', () => { }, }; - - const schematic = new SchematicImpl(desc, desc.factory, null !, engine); - schematic.call({}, observableOf(empty())) - .toPromise() - .then(x => { - expect(files(inner !)).toEqual([]); - expect(files(x)).toEqual([]); - expect(inner).not.toBe(x); - }) - .then(done, done.fail); + const schematic = new SchematicImpl(desc, desc.factory, null!, engine); + const x = await lastValueFrom(schematic.call({}, observableOf(empty()))); + expect(files(inner!)).toEqual([]); + expect(files(x)).toEqual([]); + expect(inner!).not.toBe(x); }); - it('works with nested chained function rules', done => { + it('works with nested chained function rules', async () => { let chainCount = 0; let oneCount = 0; let twoCount = 0; let threeCount = 0; const one = () => { return chain([ - () => { oneCount++; }, + () => { + oneCount++; + }, ]); }; const two = () => { return chain([ - () => { twoCount++; }, + () => { + twoCount++; + }, ]); }; const three = () => { @@ -127,7 +120,9 @@ describe('Schematic', () => { path: '/a/b/c', factory: () => { return chain([ - () => { chainCount++; }, + () => { + chainCount++; + }, one, two, three, @@ -135,19 +130,15 @@ describe('Schematic', () => { }, }; - const schematic = new SchematicImpl(desc, desc.factory, null !, engine); - schematic.call({}, observableOf(empty())) - .toPromise() - .then(_x => { - expect(chainCount).toBe(1); - expect(oneCount).toBe(1); - expect(twoCount).toBe(1); - expect(threeCount).toBe(1); - }) - .then(done, done.fail); + const schematic = new SchematicImpl(desc, desc.factory, null!, engine); + await lastValueFrom(schematic.call({}, observableOf(empty()))); + expect(chainCount).toBe(1); + expect(oneCount).toBe(1); + expect(twoCount).toBe(1); + expect(threeCount).toBe(1); }); - it('can be called with a scope', done => { + it('can be called with a scope', async () => { const desc: SchematicDescription = { collection, name: 'test', @@ -158,13 +149,8 @@ describe('Schematic', () => { }, }; - const schematic = new SchematicImpl(desc, desc.factory, null !, engine); - schematic.call({}, observableOf(empty()), {}, { scope: 'base' }) - .toPromise() - .then(x => { - expect(files(x)).toEqual(['/base/a/b/c']); - }) - .then(done, done.fail); + const schematic = new SchematicImpl(desc, desc.factory, null!, engine); + const x = await lastValueFrom(schematic.call({}, observableOf(empty()), {}, { scope: 'base' })); + expect(files(x)).toEqual(['/base/a/b/c']); }); - }); diff --git a/packages/angular_devkit/schematics/src/exception/exception.ts b/packages/angular_devkit/schematics/src/exception/exception.ts index f7f419bfc145..7da97b665138 100644 --- a/packages/angular_devkit/schematics/src/exception/exception.ts +++ b/packages/angular_devkit/schematics/src/exception/exception.ts @@ -1,23 +1,26 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { BaseException } from '@angular-devkit/core'; +import { BaseException } from '@angular-devkit/core'; // Used by schematics to throw exceptions. export class SchematicsException extends BaseException {} - // Exceptions export class FileDoesNotExistException extends BaseException { - constructor(path: string) { super(`Path "${path}" does not exist.`); } + constructor(path: string) { + super(`Path "${path}" does not exist.`); + } } export class FileAlreadyExistException extends BaseException { - constructor(path: string) { super(`Path "${path}" already exist.`); } + constructor(path: string) { + super(`Path "${path}" already exist.`); + } } export class ContentHasMutatedException extends BaseException { constructor(path: string) { @@ -25,7 +28,9 @@ export class ContentHasMutatedException extends BaseException { } } export class InvalidUpdateRecordException extends BaseException { - constructor() { super(`Invalid record instance.`); } + constructor() { + super(`Invalid record instance.`); + } } export class MergeConflictException extends BaseException { constructor(path: string) { @@ -40,5 +45,7 @@ export class UnsuccessfulWorkflowExecution extends BaseException { } export class UnimplementedException extends BaseException { - constructor() { super('This function is unimplemented.'); } + constructor() { + super('This function is unimplemented.'); + } } diff --git a/packages/angular_devkit/schematics/src/formats/format-validator.ts b/packages/angular_devkit/schematics/src/formats/format-validator.ts index 863a5b3e214a..7b665c2b7314 100644 --- a/packages/angular_devkit/schematics/src/formats/format-validator.ts +++ b/packages/angular_devkit/schematics/src/formats/format-validator.ts @@ -1,27 +1,25 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { JsonObject, JsonValue, schema } from '@angular-devkit/core'; -import { Observable } from 'rxjs'; -import { mergeMap } from 'rxjs/operators'; +import { JsonObject, JsonValue, schema } from '@angular-devkit/core'; -export function formatValidator( +export async function formatValidator( data: JsonValue, dataSchema: JsonObject, formats: schema.SchemaFormat[], -): Observable { +): Promise { const registry = new schema.CoreSchemaRegistry(); for (const format of formats) { registry.addFormat(format); } - return registry - .compile(dataSchema) - .pipe(mergeMap(validator => validator(data))); + const validator = await registry.compile(dataSchema); + + return validator(data); } diff --git a/packages/angular_devkit/schematics/src/formats/html-selector.ts b/packages/angular_devkit/schematics/src/formats/html-selector.ts index b048482d2eb7..bc3efd019c29 100644 --- a/packages/angular_devkit/schematics/src/formats/html-selector.ts +++ b/packages/angular_devkit/schematics/src/formats/html-selector.ts @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { schema } from '@angular-devkit/core'; // As per https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name @@ -14,18 +15,18 @@ import { schema } from '@angular-devkit/core'; // NOTE: This should eventually be broken out into two formats: full and partial (allows for prefix) const unicodeRanges = [ - [0xC0, 0xD6], - [0xD8, 0xF6], - [0xF8, 0x37D], - [0x37F, 0x1FFF], - [0x200C, 0x200D], - [0x203F, 0x2040], - [0x2070, 0x218F], - [0x2C00, 0x2FEF], - [0x3001, 0xD7FF], - [0xF900, 0xFDCF], - [0xFDF0, 0xFFFD], - [0x10000, 0xEFFFF], + [0xc0, 0xd6], + [0xd8, 0xf6], + [0xf8, 0x37d], + [0x37f, 0x1fff], + [0x200c, 0x200d], + [0x203f, 0x2040], + [0x2070, 0x218f], + [0x2c00, 0x2fef], + [0x3001, 0xd7ff], + [0xf900, 0xfdcf], + [0xfdf0, 0xfffd], + [0x10000, 0xeffff], ]; function isValidElementName(name: string) { @@ -46,6 +47,6 @@ export const htmlSelectorFormat: schema.SchemaFormat = { name: 'html-selector', formatter: { async: false, - validate: name => typeof name === 'string' && isValidElementName(name), + validate: (name: unknown) => typeof name === 'string' && isValidElementName(name), }, }; diff --git a/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts b/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts index 411d1df67df9..4327e32ca8e5 100644 --- a/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts +++ b/packages/angular_devkit/schematics/src/formats/html-selector_spec.ts @@ -1,67 +1,62 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { map } from 'rxjs/operators'; + import { formatValidator } from './format-validator'; import { htmlSelectorFormat } from './html-selector'; describe('Schematics HTML selector format', () => { - it('accepts correct selectors', done => { + it('accepts correct selectors', async () => { const data = { selector: 'my-selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; - formatValidator(data, dataSchema, [htmlSelectorFormat]) - .pipe(map(result => expect(result.success).toBe(true))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); + expect(result.success).toBeTrue(); }); - it('rejects selectors starting with invalid characters', done => { + it('rejects selectors starting with invalid characters', async () => { const data = { selector: 'my-selector$' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; - formatValidator(data, dataSchema, [htmlSelectorFormat]) - .pipe(map(result => expect(result.success).toBe(false))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); + expect(result.success).toBeFalse(); }); - it('rejects selectors starting with number', done => { + it('rejects selectors starting with number', async () => { const data = { selector: '1selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; - formatValidator(data, dataSchema, [htmlSelectorFormat]) - .pipe(map(result => expect(result.success).toBe(false))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); + expect(result.success).toBeFalse(); }); - it('accepts selectors with non-letter after dash', done => { + it('accepts selectors with non-letter after dash', async () => { const data = { selector: 'my-1selector' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; - formatValidator(data, dataSchema, [htmlSelectorFormat]) - .pipe(map(result => expect(result.success).toBe(true))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); + expect(result.success).toBeTrue(); }); - it('accepts selectors with unicode', done => { + it('accepts selectors with unicode', async () => { const data = { selector: 'app-root😀' }; const dataSchema = { properties: { selector: { type: 'string', format: 'html-selector' } }, }; - formatValidator(data, dataSchema, [htmlSelectorFormat]) - .pipe(map(result => expect(result.success).toBe(true))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [htmlSelectorFormat]); + expect(result.success).toBeTrue(); }); }); diff --git a/packages/angular_devkit/schematics/src/formats/index.ts b/packages/angular_devkit/schematics/src/formats/index.ts index 2cfab19db670..dff6a9035003 100644 --- a/packages/angular_devkit/schematics/src/formats/index.ts +++ b/packages/angular_devkit/schematics/src/formats/index.ts @@ -1,18 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ import { schema } from '@angular-devkit/core'; import { htmlSelectorFormat } from './html-selector'; -export { htmlSelectorFormat } from './html-selector'; import { pathFormat } from './path'; + +export { htmlSelectorFormat } from './html-selector'; export { pathFormat } from './path'; -export const standardFormats: schema.SchemaFormat[] = [ - htmlSelectorFormat, - pathFormat, -]; +export const standardFormats: schema.SchemaFormat[] = [htmlSelectorFormat, pathFormat]; diff --git a/packages/angular_devkit/schematics/src/formats/path.ts b/packages/angular_devkit/schematics/src/formats/path.ts index 0c854957f15a..6261e4c67b2b 100644 --- a/packages/angular_devkit/schematics/src/formats/path.ts +++ b/packages/angular_devkit/schematics/src/formats/path.ts @@ -1,14 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ import { normalize, schema } from '@angular-devkit/core'; - export const pathFormat: schema.SchemaFormat = { name: 'path', formatter: { diff --git a/packages/angular_devkit/schematics/src/formats/path_spec.ts b/packages/angular_devkit/schematics/src/formats/path_spec.ts index 24901f08a72f..66ad815288ae 100644 --- a/packages/angular_devkit/schematics/src/formats/path_spec.ts +++ b/packages/angular_devkit/schematics/src/formats/path_spec.ts @@ -1,36 +1,32 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { map } from 'rxjs/operators'; import { formatValidator } from './format-validator'; import { pathFormat } from './path'; - describe('Schematics Path format', () => { - it('accepts correct Paths', done => { + it('accepts correct Paths', async () => { const data = { path: 'a/b/c' }; const dataSchema = { properties: { path: { type: 'string', format: 'path' } }, }; - formatValidator(data, dataSchema, [pathFormat]) - .pipe(map(result => expect(result.success).toBe(true))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [pathFormat]); + expect(result.success).toBeTrue(); }); - it('rejects Paths that are not normalized', done => { + it('rejects Paths that are not normalized', async () => { const data = { path: 'a/b/c/../' }; const dataSchema = { properties: { path: { type: 'string', format: 'path' } }, }; - formatValidator(data, dataSchema, [pathFormat]) - .pipe(map(result => expect(result.success).toBe(false))) - .toPromise().then(done, done.fail); + const result = await formatValidator(data, dataSchema, [pathFormat]); + expect(result.success).toBeFalse(); }); }); diff --git a/packages/angular_devkit/schematics/src/index.ts b/packages/angular_devkit/schematics/src/index.ts index d0951eb363ad..47363d0b9552 100644 --- a/packages/angular_devkit/schematics/src/index.ts +++ b/packages/angular_devkit/schematics/src/index.ts @@ -1,13 +1,17 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + +import { strings } from '@angular-devkit/core'; +import * as formats from './formats/index'; import { FilePredicate, MergeStrategy, Tree as TreeInterface } from './tree/interface'; import { branch, empty, merge, partition } from './tree/static'; +import * as workflow from './workflow/index'; export { SchematicsException } from './exception/exception'; @@ -25,17 +29,12 @@ export * from './rules/url'; export * from './tree/delegate'; export * from './tree/empty'; export * from './tree/host-tree'; -export { UpdateRecorder } from './tree/interface'; +export type { UpdateRecorder } from './tree/interface'; export * from './engine/schematic'; export * from './sink/dryrun'; export * from './sink/host'; export * from './sink/sink'; - -import * as formats from './formats/index'; -export { formats }; - -import * as workflow from './workflow/index'; -export { workflow }; +export { formats, strings, workflow }; export interface TreeConstructor { empty(): TreeInterface; @@ -47,15 +46,23 @@ export interface TreeConstructor { export type Tree = TreeInterface; export const Tree: TreeConstructor = { - empty() { return empty(); }, - branch(tree: TreeInterface) { return branch(tree); }, - merge(tree: TreeInterface, - other: TreeInterface, - strategy: MergeStrategy = MergeStrategy.Default) { + empty() { + return empty(); + }, + branch(tree: TreeInterface) { + return branch(tree); + }, + merge( + tree: TreeInterface, + other: TreeInterface, + strategy: MergeStrategy = MergeStrategy.Default, + ) { return merge(tree, other, strategy); }, partition(tree: TreeInterface, predicate: FilePredicate) { return partition(tree, predicate); }, - optimize(tree: TreeInterface) { return tree; }, + optimize(tree: TreeInterface) { + return tree; + }, }; diff --git a/packages/angular_devkit/schematics/src/rules/base.ts b/packages/angular_devkit/schematics/src/rules/base.ts index 779219d3c321..7c85e5678cbd 100644 --- a/packages/angular_devkit/schematics/src/rules/base.ts +++ b/packages/angular_devkit/schematics/src/rules/base.ts @@ -1,18 +1,19 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { Observable, concat } from 'rxjs'; -import { map, mapTo, toArray } from 'rxjs/operators'; + +import { concat, lastValueFrom, map, mapTo, toArray } from 'rxjs'; import { FileOperator, Rule, Source } from '../engine/interface'; import { SchematicsException } from '../exception/exception'; +import { DelegateTree } from '../tree/delegate'; import { FilterHostTree, HostTree } from '../tree/host-tree'; import { FileEntry, FilePredicate, MergeStrategy, Tree } from '../tree/interface'; import { ScopedTree } from '../tree/scoped'; -import { empty as staticEmpty, partition } from '../tree/static'; +import { partition, empty as staticEmpty } from '../tree/static'; import { callRule, callSource } from './call'; /** @@ -32,12 +33,20 @@ export function empty(): Source { /** * Chain multiple rules into a single rule. */ -export function chain(rules: Rule[]): Rule { - return (tree, context) => { - return rules.reduce( - (acc: Tree | Observable, curr: Rule) => callRule(curr, acc, context), - tree, - ); +export function chain(rules: Iterable | AsyncIterable): Rule { + return async (initialTree, context) => { + let intermediateTree = initialTree; + if (Symbol.asyncIterator in rules) { + for await (const rule of rules) { + intermediateTree = await lastValueFrom(callRule(rule, intermediateTree, context)); + } + } else { + for (const rule of rules) { + intermediateTree = await lastValueFrom(callRule(rule, intermediateTree, context)); + } + } + + return intermediateTree; }; } @@ -45,7 +54,7 @@ export function chain(rules: Rule[]): Rule { * Apply multiple rules to a source, and returns the source transformed. */ export function apply(source: Source, rules: Rule[]): Source { - return context => callRule(chain(rules), callSource(source, context), context); + return (context) => callRule(chain(rules), callSource(source, context), context); } /** @@ -54,7 +63,7 @@ export function apply(source: Source, rules: Rule[]): Source { export function mergeWith(source: Source, strategy: MergeStrategy = MergeStrategy.Default): Rule { return (tree, context) => { return callSource(source, context).pipe( - map(sourceTree => tree.merge(sourceTree, strategy || context.strategy)), + map((sourceTree) => tree.merge(sourceTree, strategy || context.strategy)), mapTo(tree), ); }; @@ -65,23 +74,27 @@ export function noop(): Rule { } export function filter(predicate: FilePredicate): Rule { - return ((tree: Tree) => { + return (tree: Tree) => { + if (tree instanceof DelegateTree) { + tree = tree.branch(); + } + if (HostTree.isHostTree(tree)) { return new FilterHostTree(tree, predicate); } else { throw new SchematicsException('Tree type is not supported.'); } - }); + }; } export function asSource(rule: Rule): Source { - return context => callRule(rule, staticEmpty(), context); + return (context) => callRule(rule, staticEmpty(), context); } -export function branchAndMerge(rule: Rule, strategy = MergeStrategy.Default): Rule { +export function branchAndMerge(rule: Rule, strategy: MergeStrategy = MergeStrategy.Default): Rule { return (tree, context) => { return callRule(rule, tree.branch(), context).pipe( - map(branch => tree.merge(branch, strategy || context.strategy)), + map((branch) => tree.merge(branch, strategy || context.strategy)), mapTo(tree), ); }; @@ -105,10 +118,7 @@ export function partitionApplyMerge( return (tree, context) => { const [yes, no] = partition(tree, predicate); - return concat( - callRule(ruleYes, yes, context), - callRule(ruleNo || noop(), no, context), - ).pipe( + return concat(callRule(ruleYes, yes, context), callRule(ruleNo || noop(), no, context)).pipe( toArray(), map(([yesTree, noTree]) => { yesTree.merge(noTree, context.strategy); @@ -165,7 +175,7 @@ export function applyToSubtree(path: string, rules: Rule[]): Rule { const scoped = new ScopedTree(tree, path); return callRule(chain(rules), scoped, context).pipe( - map(result => { + map((result) => { if (result === scoped) { return tree; } else { diff --git a/packages/angular_devkit/schematics/src/rules/base_spec.ts b/packages/angular_devkit/schematics/src/rules/base_spec.ts index 0b2c3f13a22a..94bbd228ce49 100644 --- a/packages/angular_devkit/schematics/src/rules/base_spec.ts +++ b/packages/angular_devkit/schematics/src/rules/base_spec.ts @@ -1,36 +1,30 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-implicit-dependencies -// tslint:disable:no-non-null-assertion + import { Path, virtualFs } from '@angular-devkit/core'; -import { - HostTree, - MergeStrategy, - partitionApplyMerge, -} from '@angular-devkit/schematics'; -import { of as observableOf } from 'rxjs'; +import { lastValueFrom, of as observableOf } from 'rxjs'; +import { UnitTestTree } from '../../testing'; import { Rule, SchematicContext, Source } from '../engine/interface'; -import { Tree } from '../tree/interface'; +import { HostTree } from '../tree/host-tree'; +import { MergeStrategy, Tree } from '../tree/interface'; import { empty } from '../tree/static'; -import { apply, applyToSubtree, chain } from './base'; +import { apply, applyToSubtree, chain, filter, partitionApplyMerge } from './base'; import { callRule, callSource } from './call'; import { move } from './move'; - const context: SchematicContext = { engine: null, debug: false, strategy: MergeStrategy.Default, } as {} as SchematicContext; - describe('chain', () => { - it('works with simple rules', done => { + it('works with simple rules', async () => { const rulesCalled: Tree[] = []; const tree0 = empty(); @@ -38,23 +32,21 @@ describe('chain', () => { const tree2 = empty(); const tree3 = empty(); - const rule0: Rule = (tree: Tree) => (rulesCalled[0] = tree, tree1); - const rule1: Rule = (tree: Tree) => (rulesCalled[1] = tree, tree2); - const rule2: Rule = (tree: Tree) => (rulesCalled[2] = tree, tree3); - - callRule(chain([ rule0, rule1, rule2 ]), observableOf(tree0), context) - .toPromise() - .then(result => { - expect(result).not.toBe(tree0); - expect(rulesCalled[0]).toBe(tree0); - expect(rulesCalled[1]).toBe(tree1); - expect(rulesCalled[2]).toBe(tree2); - expect(result).toBe(tree3); - }) - .then(done, done.fail); + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + const result = await lastValueFrom( + callRule(chain([rule0, rule1, rule2]), observableOf(tree0), context), + ); + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); }); - it('works with observable rules', done => { + it('works with async rules', async () => { const rulesCalled: Tree[] = []; const tree0 = empty(); @@ -62,79 +54,152 @@ describe('chain', () => { const tree2 = empty(); const tree3 = empty(); - const rule0: Rule = (tree: Tree) => (rulesCalled[0] = tree, observableOf(tree1)); - const rule1: Rule = (tree: Tree) => (rulesCalled[1] = tree, observableOf(tree2)); - const rule2: Rule = (tree: Tree) => (rulesCalled[2] = tree, tree3); - - callRule(chain([ rule0, rule1, rule2 ]), observableOf(tree0), context) - .toPromise() - .then(result => { - expect(result).not.toBe(tree0); - expect(rulesCalled[0]).toBe(tree0); - expect(rulesCalled[1]).toBe(tree1); - expect(rulesCalled[2]).toBe(tree2); - expect(result).toBe(tree3); - }) - .then(done, done.fail); + const rule0: Rule = async (tree: Tree) => ((rulesCalled[0] = tree), tree1); + const rule1: Rule = async (tree: Tree) => ((rulesCalled[1] = tree), tree2); + const rule2: Rule = async (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + const result = await lastValueFrom(callRule(chain([rule0, rule1, rule2]), tree0, context)); + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); }); -}); -describe('apply', () => { - it('works with simple rules', done => { + it('works with a sync generator of rules', async () => { + const rulesCalled: Tree[] = []; + + const tree0 = empty(); + const tree1 = empty(); + const tree2 = empty(); + const tree3 = empty(); + + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + function* generateRules() { + yield rule0; + yield rule1; + yield rule2; + } + + const result = await lastValueFrom(callRule(chain(generateRules()), tree0, context)); + + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); + }); + + it('works with an async generator of rules', async () => { + const rulesCalled: Tree[] = []; + + const tree0 = empty(); + const tree1 = empty(); + const tree2 = empty(); + const tree3 = empty(); + + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + async function* generateRules() { + yield rule0; + yield rule1; + yield rule2; + } + + const result = await lastValueFrom(callRule(chain(generateRules()), tree0, context)); + + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); + }); + + it('works with observable rules', async () => { const rulesCalled: Tree[] = []; - let sourceCalled = false; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); - const source: Source = () => (sourceCalled = true, tree0); - const rule0: Rule = (tree: Tree) => (rulesCalled[0] = tree, tree1); - const rule1: Rule = (tree: Tree) => (rulesCalled[1] = tree, tree2); - const rule2: Rule = (tree: Tree) => (rulesCalled[2] = tree, tree3); - - callSource(apply(source, [ rule0, rule1, rule2 ]), context) - .toPromise() - .then(result => { - expect(result).not.toBe(tree0); - expect(rulesCalled[0]).toBe(tree0); - expect(rulesCalled[1]).toBe(tree1); - expect(rulesCalled[2]).toBe(tree2); - expect(result).toBe(tree3); - }) - .then(done, done.fail); + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), observableOf(tree1)); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), observableOf(tree2)); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + const result = await lastValueFrom( + callRule(chain([rule0, rule1, rule2]), observableOf(tree0), context), + ); + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); + }); + + it('works with a large number of rules', async () => { + const tree0 = empty(); + let callCount = 0; + const rules: Rule[] = Array.from({ length: 20_000 }, () => () => { + callCount++; + }); + + const result = await lastValueFrom(callRule(chain(rules), tree0, context)); + + expect(result).toBe(tree0); + expect(callCount).toBe(20_000); }); +}); - it('works with observable rules', done => { +describe('apply', () => { + it('works with simple rules', async () => { const rulesCalled: Tree[] = []; - let sourceCalled = false; + const tree0 = empty(); + const tree1 = empty(); + const tree2 = empty(); + const tree3 = empty(); + + const source: Source = () => tree0; + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), tree1); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), tree2); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + const result = await lastValueFrom(callSource(apply(source, [rule0, rule1, rule2]), context)); + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); + }); + + it('works with observable rules', async () => { + const rulesCalled: Tree[] = []; const tree0 = empty(); const tree1 = empty(); const tree2 = empty(); const tree3 = empty(); - const source: Source = () => (sourceCalled = true, tree0); - const rule0: Rule = (tree: Tree) => (rulesCalled[0] = tree, observableOf(tree1)); - const rule1: Rule = (tree: Tree) => (rulesCalled[1] = tree, observableOf(tree2)); - const rule2: Rule = (tree: Tree) => (rulesCalled[2] = tree, tree3); - - callSource(apply(source, [ rule0, rule1, rule2 ]), context) - .toPromise() - .then(result => { - expect(result).not.toBe(tree0); - expect(rulesCalled[0]).toBe(tree0); - expect(rulesCalled[1]).toBe(tree1); - expect(rulesCalled[2]).toBe(tree2); - expect(result).toBe(tree3); - }) - .then(done, done.fail); + const source: Source = () => tree0; + const rule0: Rule = (tree: Tree) => ((rulesCalled[0] = tree), observableOf(tree1)); + const rule1: Rule = (tree: Tree) => ((rulesCalled[1] = tree), observableOf(tree2)); + const rule2: Rule = (tree: Tree) => ((rulesCalled[2] = tree), tree3); + + const result = await lastValueFrom(callSource(apply(source, [rule0, rule1, rule2]), context)); + expect(result).not.toBe(tree0); + expect(rulesCalled[0]).toBe(tree0); + expect(rulesCalled[1]).toBe(tree1); + expect(rulesCalled[2]).toBe(tree2); + expect(result).toBe(tree3); }); }); describe('partitionApplyMerge', () => { - it('works with simple rules', done => { + it('works with simple rules', async () => { const host = new virtualFs.test.TestHost({ '/test1': '', '/test2': '', @@ -155,30 +220,86 @@ describe('partitionApplyMerge', () => { return empty(); }; - callRule(partitionApplyMerge(predicate, ruleYes, ruleNo), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('/test1')).toBe(false); - expect(result.exists('/test2')).toBe(false); - }) - .then(done, done.fail); + const result = await lastValueFrom( + callRule(partitionApplyMerge(predicate, ruleYes, ruleNo), observableOf(tree), context), + ); + expect(result.exists('/test1')).toBe(false); + expect(result.exists('/test2')).toBe(false); + }); + + it('works with a UnitTestTree', async () => { + const tree = new HostTree(); + tree.create('/test1', ''); + tree.create('/test2', ''); + const predicate = (path: Path) => path.indexOf('1') != -1; + + const ruleYes: Rule = (tree: Tree) => { + expect(tree.exists('/test1')).toBe(true); + expect(tree.exists('/test2')).toBe(false); + }; + const ruleNo: Rule = (tree: Tree) => { + expect(tree.exists('/test1')).toBe(false); + expect(tree.exists('/test2')).toBe(true); + }; + + const result = await lastValueFrom( + callRule( + partitionApplyMerge(predicate, ruleYes, ruleNo), + observableOf(new UnitTestTree(new UnitTestTree(tree))), + context, + ), + ); + expect(result.exists('/test1')).toBe(true); + expect(result.exists('/test2')).toBe(true); }); }); describe('applyToSubtree', () => { - it('works', done => { + it('works', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(applyToSubtree('a/b', [move('x')]), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('a/b/x/file1')).toBe(true); - expect(result.exists('a/b/x/file2')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom( + callRule(applyToSubtree('a/b', [move('x')]), observableOf(tree), context), + ); + expect(result.exists('a/b/x/file1')).toBe(true); + expect(result.exists('a/b/x/file2')).toBe(true); + expect(result.exists('a/c/file3')).toBe(true); + }); +}); + +describe('filter', () => { + it('works with a HostTree', async () => { + const tree = new HostTree(); + tree.create('/file1.ts', ''); + tree.create('/file2.js', ''); + + const result = await lastValueFrom( + callRule( + filter((path) => path.endsWith('.ts')), + observableOf(tree), + context, + ), + ); + expect(result.exists('/file1.ts')).toBe(true); + expect(result.exists('/file2.js')).toBe(false); + }); + + it('works with a UnitTestTree', async () => { + const tree = new HostTree(); + tree.create('/file1.ts', ''); + tree.create('/file2.js', ''); + + const result = await lastValueFrom( + callRule( + filter((path) => path.endsWith('.ts')), + observableOf(new UnitTestTree(new UnitTestTree(tree))), + context, + ), + ); + expect(result.exists('/file1.ts')).toBe(true); + expect(result.exists('/file2.js')).toBe(false); }); }); diff --git a/packages/angular_devkit/schematics/src/rules/call.ts b/packages/angular_devkit/schematics/src/rules/call.ts index a9f2762e3c96..0bc86ad0c352 100644 --- a/packages/angular_devkit/schematics/src/rules/call.ts +++ b/packages/angular_devkit/schematics/src/rules/call.ts @@ -1,17 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { BaseException, isPromise } from '@angular-devkit/core'; -import { Observable, from, isObservable, of as observableOf, throwError } from 'rxjs'; -import { defaultIfEmpty, last, mergeMap, tap } from 'rxjs/operators'; + +import { BaseException } from '@angular-devkit/core'; +import { Observable, defaultIfEmpty, defer, isObservable, lastValueFrom, mergeMap } from 'rxjs'; import { Rule, SchematicContext, Source } from '../engine/interface'; import { Tree, TreeSymbol } from '../tree/interface'; - function _getTypeOfResult(value?: {}): string { if (value === undefined) { return 'undefined'; @@ -32,7 +31,6 @@ function _getTypeOfResult(value?: {}): string { } } - /** * When a rule or source returns an invalid value. */ @@ -42,75 +40,59 @@ export class InvalidRuleResultException extends BaseException { } } - export class InvalidSourceResultException extends BaseException { constructor(value?: {}) { super(`Invalid source result: ${_getTypeOfResult(value)}.`); } } - export function callSource(source: Source, context: SchematicContext): Observable { - const result = source(context); + return defer(async () => { + let result: Tree | Observable | undefined = source(context); - if (isObservable(result)) { - // Only return the last Tree, and make sure it's a Tree. - return result.pipe( - defaultIfEmpty(), - last(), - tap(inner => { - if (!inner || !(TreeSymbol in inner)) { - throw new InvalidSourceResultException(inner); - } - }), - ); - } else if (result && TreeSymbol in result) { - return observableOf(result); - } else { - return throwError(new InvalidSourceResultException(result)); - } -} + if (isObservable(result)) { + result = await lastValueFrom(result.pipe(defaultIfEmpty(undefined))); + } + if (result && TreeSymbol in result) { + return result; + } + + throw new InvalidSourceResultException(result); + }); +} export function callRule( rule: Rule, input: Tree | Observable, context: SchematicContext, ): Observable { - return (isObservable(input) ? input : observableOf(input)).pipe(mergeMap(inputTree => { - const result = rule(inputTree, context); + if (isObservable(input)) { + return input.pipe(mergeMap((inputTree) => callRuleAsync(rule, inputTree, context))); + } else { + return defer(() => callRuleAsync(rule, input, context)); + } +} - if (!result) { - return observableOf(inputTree); - } else if (typeof result == 'function') { - // This is considered a Rule, chain the rule and return its output. - return callRule(result, inputTree, context); - } else if (isObservable(result)) { - // Only return the last Tree, and make sure it's a Tree. - return result.pipe( - defaultIfEmpty(), - last(), - tap(inner => { - if (!inner || !(TreeSymbol in inner)) { - throw new InvalidRuleResultException(inner); - } - }), - ); - } else if (isPromise(result)) { - return from(result).pipe( - mergeMap(inner => { - if (typeof inner === 'function') { - // This is considered a Rule, chain the rule and return its output. - return callRule(inner, inputTree, context); - } else { - return observableOf(inputTree); - } - }), - ); - } else if (TreeSymbol in result) { - return observableOf(result); - } else { - return throwError(new InvalidRuleResultException(result)); - } - })); +async function callRuleAsync(rule: Rule, tree: Tree, context: SchematicContext): Promise { + let result = await rule(tree, context); + + while (typeof result === 'function') { + // This is considered a Rule, chain the rule and return its output. + result = await result(tree, context); + } + + if (typeof result === 'undefined') { + return tree; + } + + if (isObservable(result)) { + result = await lastValueFrom(result.pipe(defaultIfEmpty(tree))); + } + + if (result && TreeSymbol in result) { + return result; + } + + throw new InvalidRuleResultException(result); } diff --git a/packages/angular_devkit/schematics/src/rules/call_spec.ts b/packages/angular_devkit/schematics/src/rules/call_spec.ts index b4ec2d4b43e5..3d9a7c8ce2ea 100644 --- a/packages/angular_devkit/schematics/src/rules/call_spec.ts +++ b/packages/angular_devkit/schematics/src/rules/call_spec.ts @@ -1,17 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-non-null-assertion -// tslint:disable:no-any -// tslint:disable:no-implicit-dependencies -import { MergeStrategy } from '@angular-devkit/schematics'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ import { of as observableOf } from 'rxjs'; import { Rule, SchematicContext, Source } from '../engine/interface'; -import { Tree } from '../tree/interface'; +import { MergeStrategy, Tree } from '../tree/interface'; import { empty } from '../tree/static'; import { InvalidRuleResultException, @@ -20,131 +18,87 @@ import { callSource, } from './call'; - const context: SchematicContext = { engine: null, debug: false, strategy: MergeStrategy.Default, } as {} as SchematicContext; - describe('callSource', () => { - it('errors if undefined source', done => { + it('errors if undefined source', async () => { const source0: any = () => undefined; - callSource(source0, context) - .toPromise() - .then(() => done.fail(), err => { - expect(err).toEqual(new InvalidSourceResultException()); - }) - .then(done, done.fail); + await expectAsync(callSource(source0, context).toPromise()).toBeRejectedWithError( + InvalidSourceResultException, + ); }); - it('errors if invalid source object', done => { - const source0: Source = () => ({} as Tree); + it('errors if invalid source object', async () => { + const source0: Source = () => ({}) as Tree; - callSource(source0, context) - .toPromise() - .then(() => done.fail(), err => { - expect(err).toEqual(new InvalidSourceResultException({})); - }) - .then(done, done.fail); + await expectAsync(callSource(source0, context).toPromise()).toBeRejectedWithError( + InvalidSourceResultException, + ); }); - it('errors if Observable of invalid source object', done => { + it('errors if Observable of invalid source object', async () => { const source0: Source = () => observableOf({} as Tree); - callSource(source0, context) - .toPromise() - .then(() => done.fail(), err => { - expect(err).toEqual(new InvalidSourceResultException({})); - }) - .then(done, done.fail); + await expectAsync(callSource(source0, context).toPromise()).toBeRejectedWithError( + InvalidSourceResultException, + ); }); - it('works with a Tree', done => { + it('works with a Tree', async () => { const tree0 = empty(); const source0: Source = () => tree0; - - callSource(source0, context) - .toPromise() - .then(tree => { - expect(tree).toBe(tree0); - }) - .then(done, done.fail); + const tree = await callSource(source0, context).toPromise(); + expect(tree).toBe(tree0); }); - it('works with an Observable', done => { + it('works with an Observable', async () => { const tree0 = empty(); const source0: Source = () => observableOf(tree0); - - callSource(source0, context) - .toPromise() - .then(tree => { - expect(tree).toBe(tree0); - }) - .then(done, done.fail); + const tree = await callSource(source0, context).toPromise(); + expect(tree).toBe(tree0); }); }); describe('callRule', () => { - it('errors if invalid source object', done => { - const tree0 = observableOf(empty()); - const rule0: Rule = () => ({} as Tree); - - callRule(rule0, tree0, context) - .toPromise() - .then(() => done.fail(), err => { - expect(err).toEqual(new InvalidRuleResultException({})); - }) - .then(done, done.fail); + it('should throw InvalidRuleResultException when rule result is non-Tree object', async () => { + const rule0: Rule = () => ({}) as Tree; + + await expectAsync(callRule(rule0, empty(), context).toPromise()).toBeRejectedWithError( + InvalidRuleResultException, + ); }); - it('errors if Observable of invalid source object', done => { - const tree0 = observableOf(empty()); - const rule0: Rule = () => observableOf({} as Tree); + it('should throw InvalidRuleResultException when rule result is null', async () => { + const rule0: Rule = () => null as unknown as Tree; - callRule(rule0, tree0, context) - .toPromise() - .then(() => done.fail(), err => { - expect(err).toEqual(new InvalidRuleResultException({})); - }) - .then(done, done.fail); + await expectAsync(callRule(rule0, empty(), context).toPromise()).toBeRejectedWithError( + InvalidRuleResultException, + ); }); - it('works with undefined result', done => { + it('works with undefined result', async () => { const tree0 = empty(); const rule0: Rule = () => undefined; - - callRule(rule0, observableOf(tree0), context) - .toPromise() - .then(tree => { - expect(tree).toBe(tree0); - }) - .then(done, done.fail); + const tree = await callRule(rule0, observableOf(tree0), context).toPromise(); + expect(tree).toBe(tree0); }); - it('works with a Tree', done => { + it('works with a Tree', async () => { const tree0 = empty(); const rule0: Rule = () => tree0; - - callRule(rule0, observableOf(tree0), context) - .toPromise() - .then(tree => { - expect(tree).toBe(tree0); - }) - .then(done, done.fail); + const tree = await callRule(rule0, observableOf(tree0), context).toPromise(); + expect(tree).toBe(tree0); }); - it('works with an Observable', done => { + it('works with an Observable', async () => { const tree0 = empty(); const rule0: Rule = () => observableOf(tree0); - - callRule(rule0, observableOf(tree0), context) - .toPromise() - .then(tree => { - expect(tree).toBe(tree0); - }) - .then(done, done.fail); + const tree = await callRule(rule0, observableOf(tree0), context).toPromise(); + expect(tree).toBe(tree0); }); }); diff --git a/packages/angular_devkit/schematics/src/rules/move.ts b/packages/angular_devkit/schematics/src/rules/move.ts index 211d00f01837..4c6c1e8d2f39 100644 --- a/packages/angular_devkit/schematics/src/rules/move.ts +++ b/packages/angular_devkit/schematics/src/rules/move.ts @@ -1,15 +1,17 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { join, normalize } from '@angular-devkit/core'; import { Rule } from '../engine/interface'; import { noop } from './base'; - +export function move(from: string, to: string): Rule; +export function move(to: string): Rule; export function move(from: string, to?: string): Rule { if (to === undefined) { to = from; @@ -23,14 +25,14 @@ export function move(from: string, to?: string): Rule { return noop; } - return tree => { + return (tree) => { if (tree.exists(fromPath)) { // fromPath is a file tree.rename(fromPath, toPath); } else { // fromPath is a directory - tree.getDir(fromPath).visit(path => { - tree.rename(path, join(toPath, path.substr(fromPath.length))); + tree.getDir(fromPath).visit((path) => { + tree.rename(path, join(toPath, path.slice(fromPath.length))); }); } diff --git a/packages/angular_devkit/schematics/src/rules/move_spec.ts b/packages/angular_devkit/schematics/src/rules/move_spec.ts index 96bfcc896331..10a33c693d43 100644 --- a/packages/angular_devkit/schematics/src/rules/move_spec.ts +++ b/packages/angular_devkit/schematics/src/rules/move_spec.ts @@ -1,101 +1,80 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-non-null-assertion -import { of as observableOf } from 'rxjs'; + +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { lastValueFrom, of as observableOf } from 'rxjs'; import { SchematicContext } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; import { callRule } from './call'; import { move } from './move'; - -const context: SchematicContext = null !; - +const context: SchematicContext = null!; describe('move', () => { - it('works on moving the whole structure', done => { + it('works on moving the whole structure', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(move('sub'), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('sub/a/b/file1')).toBe(true); - expect(result.exists('sub/a/b/file2')).toBe(true); - expect(result.exists('sub/a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom(callRule(move('sub'), observableOf(tree), context)); + expect(result.exists('sub/a/b/file1')).toBe(true); + expect(result.exists('sub/a/b/file2')).toBe(true); + expect(result.exists('sub/a/c/file3')).toBe(true); }); - it('works on moving a subdirectory structure', done => { + it('works on moving a subdirectory structure', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(move('a/b', 'sub'), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('sub/file1')).toBe(true); - expect(result.exists('sub/file2')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom(callRule(move('a/b', 'sub'), observableOf(tree), context)); + expect(result.exists('sub/file1')).toBe(true); + expect(result.exists('sub/file2')).toBe(true); + expect(result.exists('a/c/file3')).toBe(true); }); - it('works on moving a directory into a subdirectory of itself', done => { + it('works on moving a directory into a subdirectory of itself', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(move('a/b', 'a/b/c'), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('a/b/c/file1')).toBe(true); - expect(result.exists('a/b/c/file2')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom(callRule(move('a/b', 'a/b/c'), observableOf(tree), context)); + expect(result.exists('a/b/c/file1')).toBe(true); + expect(result.exists('a/b/c/file2')).toBe(true); + expect(result.exists('a/c/file3')).toBe(true); }); - it('works on moving a directory into a parent of itself', done => { + it('works on moving a directory into a parent of itself', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(move('a/b', 'a'), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('file1')).toBe(false); - expect(result.exists('file2')).toBe(false); - expect(result.exists('a/file1')).toBe(true); - expect(result.exists('a/file2')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom(callRule(move('a/b', 'a'), observableOf(tree), context)); + expect(result.exists('file1')).toBe(false); + expect(result.exists('file2')).toBe(false); + expect(result.exists('a/file1')).toBe(true); + expect(result.exists('a/file2')).toBe(true); + expect(result.exists('a/c/file3')).toBe(true); }); - it('becomes a noop with identical from and to', done => { + it('becomes a noop with identical from and to', async () => { const tree = new HostTree(); tree.create('a/b/file1', 'hello world'); tree.create('a/b/file2', 'hello world'); tree.create('a/c/file3', 'hello world'); - callRule(move(''), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('a/b/file1')).toBe(true); - expect(result.exists('a/b/file2')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); + const result = await lastValueFrom(callRule(move(''), observableOf(tree), context)); + expect(result.exists('a/b/file1')).toBe(true); + expect(result.exists('a/b/file2')).toBe(true); + expect(result.exists('a/c/file3')).toBe(true); }); }); diff --git a/packages/angular_devkit/schematics/src/rules/random.ts b/packages/angular_devkit/schematics/src/rules/random.ts index a2575f57a5b0..68b0bde82286 100644 --- a/packages/angular_devkit/schematics/src/rules/random.ts +++ b/packages/angular_devkit/schematics/src/rules/random.ts @@ -1,41 +1,44 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { Source } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; - function generateStringOfLength(l: number) { - return new Array(l).fill(0).map(_x => { - return 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)]; - }).join(''); + return new Array(l) + .fill(0) + .map((_x) => { + return 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)]; + }) + .join(''); } - function random(from: number, to: number) { return Math.floor(Math.random() * (to - from)) + from; } - export interface RandomOptions { root?: string; multi?: boolean | number; multiFiles?: boolean | number; } - -export default function(options: RandomOptions): Source { +export default function (options: RandomOptions): Source { return () => { - const root = ('root' in options) ? options.root : '/'; + const root = 'root' in options ? options.root : '/'; const map = new HostTree(); - const nbFiles = ('multiFiles' in options) - ? (typeof options.multiFiles == 'number' ? options.multiFiles : random(2, 12)) - : 1; + const nbFiles = + 'multiFiles' in options + ? typeof options.multiFiles == 'number' + ? options.multiFiles + : random(2, 12) + : 1; for (let i = 0; i < nbFiles; i++) { const path = 'a/b/c/d/e/f'.slice(Math.random() * 10); diff --git a/packages/angular_devkit/schematics/src/rules/rename.ts b/packages/angular_devkit/schematics/src/rules/rename.ts deleted file mode 100644 index 2405d5302273..000000000000 --- a/packages/angular_devkit/schematics/src/rules/rename.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { normalize } from '@angular-devkit/core'; -import { Rule } from '../engine/interface'; -import { FilePredicate } from '../tree/interface'; -import { forEach } from './base'; - - -export function rename(match: FilePredicate, to: FilePredicate): Rule { - return forEach(entry => { - if (match(entry.path, entry)) { - return { - content: entry.content, - path: normalize(to(entry.path, entry)), - }; - } else { - return entry; - } - }); -} diff --git a/packages/angular_devkit/schematics/src/rules/rename_spec.ts b/packages/angular_devkit/schematics/src/rules/rename_spec.ts deleted file mode 100644 index c9fdda3cdd4a..000000000000 --- a/packages/angular_devkit/schematics/src/rules/rename_spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -// tslint:disable:no-non-null-assertion -import { of as observableOf } from 'rxjs'; -import { SchematicContext } from '../engine/interface'; -import { HostTree } from '../tree/host-tree'; -import { callRule } from './call'; -import { rename } from './rename'; - - -const context: SchematicContext = null !; - - -describe('rename', () => { - it('works', done => { - const tree = new HostTree(); - tree.create('a/b/file1', 'hello world'); - tree.create('a/b/file2', 'hello world'); - tree.create('a/c/file3', 'hello world'); - - let i = 0; - - // Rename all files that contain 'b' to 'hello'. - callRule(rename(x => !!x.match(/b/), () => 'hello' + (i++)), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('a/b/file1')).toBe(false); - expect(result.exists('a/b/file2')).toBe(false); - expect(result.exists('hello0')).toBe(true); - expect(result.exists('hello1')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); - }); - - it('works (2)', done => { - const tree = new HostTree(); - tree.create('a/b/file1', 'hello world'); - tree.create('a/b/file2', 'hello world'); - tree.create('a/c/file3', 'hello world'); - - let i = 0; - - // Rename all files that contain 'b' to 'hello'. - callRule(rename(x => !!x.match(/b/), x => x + (i++)), observableOf(tree), context) - .toPromise() - .then(result => { - expect(result.exists('a/b/file1')).toBe(false); - expect(result.exists('a/b/file2')).toBe(false); - expect(result.exists('a/b/file10')).toBe(true); - expect(result.exists('a/b/file21')).toBe(true); - expect(result.exists('a/c/file3')).toBe(true); - }) - .then(done, done.fail); - }); -}); diff --git a/packages/angular_devkit/schematics/src/rules/schematic.ts b/packages/angular_devkit/schematics/src/rules/schematic.ts index 6885ad9bacb6..ffa313246539 100644 --- a/packages/angular_devkit/schematics/src/rules/schematic.ts +++ b/packages/angular_devkit/schematics/src/rules/schematic.ts @@ -1,17 +1,16 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -import { of as observableOf } from 'rxjs'; -import { last, map } from 'rxjs/operators'; + +import { last, map, of as observableOf } from 'rxjs'; import { ExecutionOptions, Rule, SchematicContext } from '../engine/interface'; import { MergeStrategy, Tree } from '../tree/interface'; import { branch } from '../tree/static'; - /** * Run a schematic from a separate collection. * @@ -26,14 +25,23 @@ export function externalSchematic( executionOptions?: Partial, ): Rule { return (input: Tree, context: SchematicContext) => { - const collection = context.engine.createCollection(collectionName); + const collection = context.engine.createCollection( + collectionName, + context.schematic.collection, + ); const schematic = collection.createSchematic(schematicName); - return schematic.call(options, observableOf(branch(input)), context, executionOptions); + return schematic.call(options, observableOf(branch(input)), context, executionOptions).pipe( + last(), + map((x) => { + input.merge(x, MergeStrategy.AllowOverwriteConflict); + + return input; + }), + ); }; } - /** * Run a schematic from the same collection. * @@ -51,7 +59,7 @@ export function schematic( return schematic.call(options, observableOf(branch(input)), context, executionOptions).pipe( last(), - map(x => { + map((x) => { // We allow overwrite conflict here because they're the only merge conflict we particularly // don't want to deal with; the input tree might have an OVERWRITE which the sub input.merge(x, MergeStrategy.AllowOverwriteConflict); diff --git a/packages/angular_devkit/schematics/src/rules/template.ts b/packages/angular_devkit/schematics/src/rules/template.ts index 3e5d34e9241b..1c8417a336b2 100644 --- a/packages/angular_devkit/schematics/src/rules/template.ts +++ b/packages/angular_devkit/schematics/src/rules/template.ts @@ -1,43 +1,43 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + import { BaseException, normalize, template as templateImpl } from '@angular-devkit/core'; +import { EOL } from 'node:os'; import { FileOperator, Rule } from '../engine/interface'; import { FileEntry } from '../tree/interface'; import { chain, composeFileOperators, forEach, when } from './base'; -import { rename } from './rename'; -import { isBinary } from './utils/is-binary'; - - -export const TEMPLATE_FILENAME_RE = /\.template$/; +export const TEMPLATE_FILENAME_RE: RegExp = /\.template$/; export class OptionIsNotDefinedException extends BaseException { - constructor(name: string) { super(`Option "${name}" is not defined.`); } + constructor(name: string) { + super(`Option "${name}" is not defined.`); + } } - export class UnknownPipeException extends BaseException { - constructor(name: string) { super(`Pipe "${name}" is not defined.`); } + constructor(name: string) { + super(`Pipe "${name}" is not defined.`); + } } - export class InvalidPipeException extends BaseException { - constructor(name: string) { super(`Pipe "${name}" is invalid.`); } + constructor(name: string) { + super(`Pipe "${name}" is invalid.`); + } } - export type PathTemplateValue = boolean | string | number | undefined; export type PathTemplatePipeFunction = (x: string) => PathTemplateValue; export type PathTemplateData = { - [key: string]: PathTemplateValue | PathTemplateData | PathTemplatePipeFunction, + [key: string]: PathTemplateValue | PathTemplateData | PathTemplatePipeFunction; }; - export interface PathTemplateOptions { // Interpolation start and end strings. interpolationStart: string; @@ -48,27 +48,46 @@ export interface PathTemplateOptions { pipeSeparator?: string; } +const decoder = new TextDecoder('utf-8', { fatal: true }); export function applyContentTemplate(options: T): FileOperator { return (entry: FileEntry) => { - const {path, content} = entry; - if (isBinary(content)) { - return entry; + const { path, content } = entry; + + let decodedContent: string; + try { + decodedContent = decoder.decode(content); + } catch (e) { + // The second part should not be needed. But Jest does not support instanceof correctly. + // See: https://github.com/jestjs/jest/issues/2549 + if ( + e instanceof TypeError || + (e as NodeJS.ErrnoException).code === 'ERR_ENCODING_INVALID_ENCODED_DATA' + ) { + return entry; + } + + throw e; } + decodedContent = decodedContent.replace(/\r?\n/g, EOL); + + try { + return { + path, + content: Buffer.from(templateImpl(decodedContent, {})(options)), + }; + } catch (e) { + const message = e instanceof Error ? e.message : String(e); - return { - path: path, - content: Buffer.from(templateImpl(content.toString('utf-8'), {})(options)), - }; + throw new Error(`Failed to apply content template to "${path}": ${message}`, { cause: e }); + } }; } - export function contentTemplate(options: T): Rule { return forEach(applyContentTemplate(options)); } - export function applyPathTemplate( data: T, options: PathTemplateOptions = { @@ -122,12 +141,13 @@ export function applyPathTemplate( if (!(pipe in data)) { throw new UnknownPipeException(pipe); } - if (typeof data[pipe] != 'function') { + const pipeFn = data[pipe]; + if (typeof pipeFn != 'function') { throw new InvalidPipeException(pipe); } // Coerce to string. - return '' + (data[pipe] as PathTemplatePipeFunction)(acc); + return '' + pipeFn(acc); }, '' + replacement); } @@ -142,24 +162,27 @@ export function applyPathTemplate( }; } - export function pathTemplate(options: T): Rule { return forEach(applyPathTemplate(options)); } - /** * Remove every `.template` suffix from file names. */ export function renameTemplateFiles(): Rule { - return rename( - path => !!path.match(TEMPLATE_FILENAME_RE), - path => path.replace(TEMPLATE_FILENAME_RE, ''), - ); + return forEach((entry) => { + if (entry.path.match(TEMPLATE_FILENAME_RE)) { + return { + content: entry.content, + path: normalize(entry.path.replace(TEMPLATE_FILENAME_RE, '')), + }; + } else { + return entry; + } + }); } - -export function template(options: T): Rule { +export function template(options: T): Rule { return chain([ contentTemplate(options), // Force cast to PathTemplateData. We need the type for the actual pathTemplate() call, @@ -169,16 +192,15 @@ export function template(options: T): Rule { ]); } - -export function applyTemplates(options: T): Rule { +export function applyTemplates(options: T): Rule { return forEach( when( - path => path.endsWith('.template'), + (path) => path.endsWith('.template'), composeFileOperators([ applyContentTemplate(options), // See above for this weird cast. applyPathTemplate(options as {} as PathTemplateData), - entry => { + (entry) => { return { content: entry.content, path: entry.path.replace(TEMPLATE_FILENAME_RE, ''), diff --git a/packages/angular_devkit/schematics/src/rules/template_spec.ts b/packages/angular_devkit/schematics/src/rules/template_spec.ts index 56e99f9a90dd..e46d523ea032 100644 --- a/packages/angular_devkit/schematics/src/rules/template_spec.ts +++ b/packages/angular_devkit/schematics/src/rules/template_spec.ts @@ -1,14 +1,15 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -// tslint:disable:no-implicit-dependencies + +/* eslint-disable import/no-extraneous-dependencies */ import { normalize } from '@angular-devkit/core'; -import { UnitTestTree } from '@angular-devkit/schematics/testing'; -import { of as observableOf } from 'rxjs'; +import { lastValueFrom, of as observableOf } from 'rxjs'; +import { UnitTestTree } from '../../testing'; import { SchematicContext } from '../engine/interface'; import { HostTree } from '../tree/host-tree'; import { FileEntry, MergeStrategy } from '../tree/interface'; @@ -22,7 +23,6 @@ import { applyTemplates, } from './template'; - function _entry(path?: string, content?: string): FileEntry { if (!path) { path = 'a/b/c'; @@ -37,7 +37,6 @@ function _entry(path?: string, content?: string): FileEntry { }; } - describe('applyPathTemplate', () => { function _applyPathTemplate(path: string, options: {}): string | null { const newEntry = applyPathTemplate(options)(_entry(path)); @@ -61,26 +60,29 @@ describe('applyPathTemplate', () => { }); it('works with complex _________...', () => { - expect(_applyPathTemplate( - '/_____' + 'a' + '___a__' + '_/' + '__a___/__b___', - { _a: 0, a: 1, b: 2, _: '.' }, - )).toBe('/.a0_/1_/2_'); - - expect(_applyPathTemplate( - '_____' + '_____' + '_____' + '___', - { _: '.' }, - )).toBe('...___'); + expect( + _applyPathTemplate('/_____' + 'a' + '___a__' + '_/' + '__a___/__b___', { + _a: 0, + a: 1, + b: 2, + _: '.', + }), + ).toBe('/.a0_/1_/2_'); + + expect(_applyPathTemplate('_____' + '_____' + '_____' + '___', { _: '.' })).toBe('...___'); }); it('works with functions', () => { let arg = ''; - expect(_applyPathTemplate('/a__c__b', { - c: (x: string) => { - arg = x; - - return 'hello'; - }, - })).toBe('/ahellob'); + expect( + _applyPathTemplate('/a__c__b', { + c: (x: string) => { + arg = x; + + return 'hello'; + }, + }), + ).toBe('/ahellob'); expect(arg).toBe('/a__c__b'); }); @@ -88,17 +90,21 @@ describe('applyPathTemplate', () => { let called = ''; let called2 = ''; - expect(_applyPathTemplate('/a__c@d__b', { - c: 1, - d: (x: string) => (called = x, 2), - })).toBe('/a2b'); + expect( + _applyPathTemplate('/a__c@d__b', { + c: 1, + d: (x: string) => ((called = x), 2), + }), + ).toBe('/a2b'); expect(called).toBe('1'); - expect(_applyPathTemplate('/a__c@d@e__b', { - c: 10, - d: (x: string) => (called = x, 20), - e: (x: string) => (called2 = x, 30), - })).toBe('/a30b'); + expect( + _applyPathTemplate('/a__c@d@e__b', { + c: 10, + d: (x: string) => ((called = x), 20), + e: (x: string) => ((called2 = x), 30), + }), + ).toBe('/a30b'); expect(called).toBe('10'); expect(called2).toBe('20'); }); @@ -109,12 +115,12 @@ describe('applyPathTemplate', () => { it('errors out on undefined or invalid pipes', () => { expect(() => _applyPathTemplate('/a__b@d__c', { b: 1 })).toThrow(new UnknownPipeException('d')); - expect(() => _applyPathTemplate('/a__b@d__c', { b: 1, d: 1 })) - .toThrow(new InvalidPipeException('d')); + expect(() => _applyPathTemplate('/a__b@d__c', { b: 1, d: 1 })).toThrow( + new InvalidPipeException('d'), + ); }); }); - describe('contentTemplate', () => { function _applyContentTemplate(content: string, options: {}) { const newEntry = applyContentTemplate(options)(_entry('', content)); @@ -130,38 +136,74 @@ describe('contentTemplate', () => { }); it('works with if', () => { - expect(_applyContentTemplate('a<% if (a) { %>b<% } %>c', { - value: 123, - a: true, - })).toBe('abc'); - expect(_applyContentTemplate('a<% if (a) { %>b<% } %>c', { - value: 123, - a: false, - })).toBe('ac'); + expect( + _applyContentTemplate('a<% if (a) { %>b<% } %>c', { + value: 123, + a: true, + }), + ).toBe('abc'); + expect( + _applyContentTemplate('a<% if (a) { %>b<% } %>c', { + value: 123, + a: false, + }), + ).toBe('ac'); }); it('works with for', () => { - expect(_applyContentTemplate('a<% for (let i = 0; i < value; i++) { %>1<% } %>b', { - value: 5, - })).toBe('a11111b'); + expect( + _applyContentTemplate('a<% for (let i = 0; i < value; i++) { %>1<% } %>b', { + value: 5, + }), + ).toBe('a11111b'); }); it('escapes HTML', () => { - expect(_applyContentTemplate('a<%- html %>b', { - html: '', + '', + '', + ].join(''), + ); + } else { + await expectFileToMatch( + 'dist/test-project/browser/index.html', + [ + '', + '', + '', + '', + '', + ].join(''), + ); + } +} diff --git a/tests/e2e/tests/basic/serve.ts b/tests/e2e/tests/basic/serve.ts new file mode 100644 index 000000000000..eac4823a3126 --- /dev/null +++ b/tests/e2e/tests/basic/serve.ts @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import { killAllProcesses } from '../../utils/process'; +import { ngServe } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + // Serve works without HMR + const noHmrPort = await ngServe('--no-hmr'); + await verifyResponse(noHmrPort); + await killAllProcesses(); + + // Serve works with HMR + const hmrPort = await ngServe('--hmr'); + await verifyResponse(hmrPort); + + await executeBrowserTest({ baseUrl: `http://localhost:${hmrPort}/` }); +} + +async function verifyResponse(port: number): Promise { + const indexResponse = await fetch(`http://localhost:${port}/`); + assert.match(await indexResponse.text(), /<\/app-root>/); + + const assetResponse = await fetch(`http://localhost:${port}/favicon.ico`); + assert(assetResponse.ok, 'Expected favicon asset to be available.'); +} diff --git a/tests/e2e/tests/basic/styles-array.ts b/tests/e2e/tests/basic/styles-array.ts new file mode 100644 index 000000000000..cc4d6d56f506 --- /dev/null +++ b/tests/e2e/tests/basic/styles-array.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + await writeMultipleFiles({ + 'src/string-style.css': '.string-style { color: red }', + 'src/input-style.css': '.input-style { color: red }', + 'src/lazy-style.css': '.lazy-style { color: red }', + 'src/pre-rename-style.css': '.pre-rename-style { color: red }', + 'src/pre-rename-lazy-style.css': '.pre-rename-lazy-style { color: red }', + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [ + { input: 'src/string-style.css' }, + { input: 'src/input-style.css' }, + { input: 'src/lazy-style.css', inject: false }, + { input: 'src/pre-rename-style.css', bundleName: 'renamed-style' }, + { + input: 'src/pre-rename-lazy-style.css', + bundleName: 'renamed-lazy-style', + inject: false, + }, + ]; + }); + + const { stdout } = await ng('build', '--configuration=development'); + + await expectFileToMatch('dist/test-project/browser/styles.css', '.string-style'); + await expectFileToMatch('dist/test-project/browser/styles.css', '.input-style'); + await expectFileToMatch('dist/test-project/browser/lazy-style.css', '.lazy-style'); + await expectFileToMatch('dist/test-project/browser/renamed-style.css', '.pre-rename-style'); + await expectFileToMatch( + 'dist/test-project/browser/renamed-lazy-style.css', + '.pre-rename-lazy-style', + ); + await expectFileToMatch( + 'dist/test-project/browser/index.html', + '', + ); + + // Non injected styles should be listed under lazy chunk files + assert.match(stdout, /Lazy chunk files[\s\S]+renamed-lazy-style\.css/m); +} diff --git a/tests/e2e/tests/basic/test.ts b/tests/e2e/tests/basic/test.ts new file mode 100644 index 000000000000..50580581d442 --- /dev/null +++ b/tests/e2e/tests/basic/test.ts @@ -0,0 +1,59 @@ +import { ng } from '../../utils/process'; +import { writeMultipleFiles } from '../../utils/fs'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + // make sure both --watch=false work + await ng('test', '--watch=false'); + + // Works with custom config + await writeMultipleFiles({ + './karma.conf.bis.js': ` + // Karma configuration file, see link for more information + // https://karma-runner.github.io/1.0/config/configuration-file.html + module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage'), + require('@angular-devkit/build-angular/plugins/karma') + ], + client: { + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['ChromeHeadlessNoSandbox'], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: [ + '--no-sandbox', + '--headless', + '--disable-gpu', + '--disable-dev-shm-usage', + ], + } + }, + singleRun: false, + restartOnFileChange: true + }); + }; + `, + }); + + const isWebpack = !getGlobalVariable('argv')['esbuild']; + + if (isWebpack) { + await ng('test', '--watch=false', '--karma-config=karma.conf.bis.js'); + } else { + await ng('test', '--watch=false', '--runner-config=karma.conf.bis.js'); + } +} diff --git a/tests/e2e/tests/build/app-shell/app-shell-ngmodule.ts b/tests/e2e/tests/build/app-shell/app-shell-ngmodule.ts new file mode 100644 index 000000000000..b1b6cfab499d --- /dev/null +++ b/tests/e2e/tests/build/app-shell/app-shell-ngmodule.ts @@ -0,0 +1,35 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToMatch } from '../../../utils/fs'; +import { installPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +const snapshots = require('../../../ng-snapshot/package.json'); + +export default async function () { + await ng('generate', 'app', 'test-project-two', '--routing', '--no-standalone', '--skip-install'); + await ng('generate', 'app-shell', '--project', 'test-project-two'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + const packagesToInstall: string[] = []; + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries( + snapshots.dependencies as { [p: string]: string }, + )) { + if (name in dependencies && dependencies[name] !== version) { + packagesToInstall.push(version); + } + } + }); + + for (const pkg of packagesToInstall) { + await installPackage(pkg); + } + } + + await ng('build', 'test-project-two'); + await expectFileToMatch('dist/test-project-two/browser/index.html', 'app-shell works!'); +} diff --git a/tests/e2e/tests/build/app-shell/app-shell-with-schematic.ts b/tests/e2e/tests/build/app-shell/app-shell-with-schematic.ts new file mode 100644 index 000000000000..65f6fdb23c48 --- /dev/null +++ b/tests/e2e/tests/build/app-shell/app-shell-with-schematic.ts @@ -0,0 +1,34 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { appendToFile, expectFileToMatch } from '../../../utils/fs'; +import { installPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +const snapshots = require('../../../ng-snapshot/package.json'); + +export default async function () { + await appendToFile('src/app/app.html', ''); + await ng('generate', 'app-shell', '--project', 'test-project'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + const packagesToInstall: string[] = []; + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries( + snapshots.dependencies as { [p: string]: string }, + )) { + if (name in dependencies && dependencies[name] !== version) { + packagesToInstall.push(version); + } + } + }); + + for (const pkg of packagesToInstall) { + await installPackage(pkg); + } + } + await ng('build'); + await expectFileToMatch('dist/test-project/browser/index.html', 'app-shell works!'); +} diff --git a/tests/e2e/tests/build/app-shell/app-shell-with-service-worker.ts b/tests/e2e/tests/build/app-shell/app-shell-with-service-worker.ts new file mode 100644 index 000000000000..0841754ad1b2 --- /dev/null +++ b/tests/e2e/tests/build/app-shell/app-shell-with-service-worker.ts @@ -0,0 +1,65 @@ +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../../utils/env'; +import { appendToFile, expectFileToMatch } from '../../../utils/fs'; +import { installPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +const snapshots = require('../../../ng-snapshot/package.json'); + +export default async function () { + await appendToFile('src/app/app.html', ''); + await ng('generate', 'service-worker', '--project', 'test-project'); + await ng('generate', 'app-shell', '--project', 'test-project'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + const packagesToInstall: string[] = []; + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries( + snapshots.dependencies as { [p: string]: string }, + )) { + if (name in dependencies && dependencies[name] !== version) { + packagesToInstall.push(version); + } + } + }); + + for (const pkg of packagesToInstall) { + await installPackage(pkg); + } + } + + await ng('build'); + await expectFileToMatch('dist/test-project/browser/index.html', /app-shell works!/); + + await executeBrowserTest({ + configuration: 'production', + checkFn: async (page) => { + // Wait for service worker to load. + await setTimeout(2000); + + const baseUrl = page.url(); + await page.goto(new URL('/ngsw/state', baseUrl).href); + + // Should have updated, and be in normal state. + const preText = await page.$eval('pre', (el) => el.textContent); + if (preText?.includes('Last update check: never')) { + throw new Error(`Expected service worker to have checked for updates, but got: ${preText}`); + } + + // TODO: Investigate why the last condition fails with vite-based setup. + // Temporarily disabled to support protractor migration. + if (getGlobalVariable('argv')['esbuild']) { + return; + } + + if (!preText?.includes('Driver state: NORMAL')) { + throw new Error(`Expected service worker driver state to be NORMAL, but got: ${preText}`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/assets.ts b/tests/e2e/tests/build/assets.ts new file mode 100644 index 000000000000..4a8fa7548d35 --- /dev/null +++ b/tests/e2e/tests/build/assets.ts @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict'; +import { writeFile, stat, mkdir, symlink, utimes, rm } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { expectFileToExist, expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + // Update the atime and mtime of the original file. + // Note: Node.js has different time precision, which may cause mtime-based tests to fail. + // Ensure both values are rounded to the same precision for consistency. + // Example: + // Original: '1742973507738.0234' + // Node.js CP: '1742973507737.999' + const { atime, mtime } = await stat('public/favicon.ico'); + await utimes('public/favicon.ico', atime, mtime); + + await writeFile('public/.file', ''); + await writeFile('public/test.abc', 'hello world'); + + await ng('build', '--configuration=development'); + await expectFileToExist('dist/test-project/browser/favicon.ico'); + await expectFileToExist('dist/test-project/browser/.file'); + await expectFileToMatch('dist/test-project/browser/test.abc', 'hello world'); + await expectToFail(() => expectFileToExist('dist/test-project/browser/.gitkeep')); + + // Timestamp preservation only supported with application build system on Node.js v22+ + if (getGlobalVariable('argv')['esbuild']) { + const [originalStats, outputStats] = await Promise.all([ + stat('public/favicon.ico'), + stat('dist/test-project/browser/favicon.ico'), + ]); + + assert.equal( + originalStats.mtimeMs, + outputStats.mtimeMs, + 'Asset file modified timestamp should be preserved.', + ); + } + + // Ensure `followSymlinks` option follows symlinks + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect['build'].options.assets = [ + { glob: '**/*', input: 'public', followSymlinks: true }, + ]; + }); + + await mkdir('dirToSymlink/subdir1', { recursive: true }); + await mkdir('dirToSymlink/subdir2/subsubdir1', { recursive: true }); + await symlink(process.cwd() + '/dirToSymlink', 'public/symlinkDir'); + + await Promise.all([ + writeFile('dirToSymlink/a.txt', ''), + writeFile('dirToSymlink/subdir1/b.txt', ''), + writeFile('dirToSymlink/subdir2/c.txt', ''), + writeFile('dirToSymlink/subdir2/subsubdir1/d.txt', ''), + ]); + + await ng('build', '--configuration=development'); + + await expectFileToExist('dist/test-project/browser/symlinkDir/a.txt'); + await expectFileToExist('dist/test-project/browser/symlinkDir/subdir1/b.txt'); + await expectFileToExist('dist/test-project/browser/symlinkDir/subdir2/c.txt'); + await expectFileToExist('dist/test-project/browser/symlinkDir/subdir2/subsubdir1/d.txt'); + + // Ensure symlinks pointing outside workspace root (monorepo setups) are followed + const outsideAssetsDir = resolve(process.cwd(), '../outside-monorepo-assets'); + await mkdir(`${outsideAssetsDir}/nested`, { recursive: true }); + try { + await symlink(outsideAssetsDir, 'public/outsideAssets'); + await Promise.all([ + writeFile(`${outsideAssetsDir}/outside.txt`, 'outside asset'), + writeFile(`${outsideAssetsDir}/nested/nested.txt`, 'nested outside asset'), + ]); + + await ng('build', '--configuration=development'); + + await expectFileToExist('dist/test-project/browser/outsideAssets/outside.txt'); + await expectFileToExist('dist/test-project/browser/outsideAssets/nested/nested.txt'); + await expectFileToMatch('dist/test-project/browser/outsideAssets/outside.txt', 'outside asset'); + await expectFileToMatch( + 'dist/test-project/browser/outsideAssets/nested/nested.txt', + 'nested outside asset', + ); + } finally { + await Promise.all([ + rm(outsideAssetsDir, { force: true, recursive: true }), + rm('public/outsideAssets', { force: true }), + ]); + } +} diff --git a/tests/e2e/tests/build/auto-csp.ts b/tests/e2e/tests/build/auto-csp.ts new file mode 100644 index 000000000000..aa4ed0e53f18 --- /dev/null +++ b/tests/e2e/tests/build/auto-csp.ts @@ -0,0 +1,138 @@ +import assert from 'node:assert/strict'; +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch, writeFile, writeMultipleFiles } from '../../utils/fs'; +import { findFreePort } from '../../utils/network'; +import { execAndWaitForOutputToMatch, ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +const CSP_META_TAG = / { + const build = json['projects']['test-project']['architect']['build']; + build.options = { + ...build.options, + security: { autoCsp: true }, + }; + }); + + await writeMultipleFiles({ + 'serve.js': ` + const express = require('express'); + const path = require('path'); + + const app = express(); + const PORT = process.env.PORT || 3000; + + app.use(express.static(path.join(__dirname, 'dist/test-project/browser'))); + + app.listen(PORT, () => { + console.log('Node Express server listening on ' + PORT); + }); + `, + 'public/script1.js': ` + const externalScriptCreated = 1337; + console.warn('First External Script: ' + inlineScriptBodyCreated); + `, + 'public/script2.js': `console.warn('Second External Script: ' + externalScriptCreated);`, + 'src/index.html': ` + + + + + + + + + + + + + + + + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + + await execAndWaitForOutputToMatch('node', ['serve.js'], /Node Express server listening on/, { + ...process.env, + 'PORT': String(port), + }); + + return port; + } + + await ng('build'); + + // Make sure the output files have auto-CSP as a result of `ng build` + await expectFileToMatch('dist/test-project/browser/index.html', CSP_META_TAG); + + // Make sure if contains the critical CSS inlining CSP code. + await expectFileToMatch('dist/test-project/browser/index.html', 'data-beasties-media'); + + // Make sure that our e2e tests run to confirm that our angular project runs. + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + const warnMessages: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warn') { + warnMessages.push(msg.text()); + } + }); + + // Reload to ensure we capture messages from the start if needed, + // although executeBrowserTest already navigated. + await page.reload(); + + // Wait for the expected number of warnings + let retries = 50; + while (warnMessages.length < 4 && retries > 0) { + await setTimeout(100); + retries--; + } + + assert.strictEqual( + warnMessages.length, + 4, + `Expected 4 console warnings, but got ${warnMessages.length}:\n${warnMessages.join('\n')}`, + ); + + const expectedMessages = [ + 'Inline Script Head', + 'Inline Script Body: 1339', + 'First External Script: 1338', + 'Second External Script: 1337', + ]; + + for (let i = 0; i < expectedMessages.length; i++) { + if (!warnMessages[i].includes(expectedMessages[i])) { + assert.fail( + `Expected warning ${i} to include '${expectedMessages[i]}', but got '${warnMessages[i]}'`, + ); + } + } + }, + }); +} diff --git a/tests/e2e/tests/build/bundle-budgets.ts b/tests/e2e/tests/build/bundle-budgets.ts new file mode 100644 index 000000000000..1401d8d3c6e3 --- /dev/null +++ b/tests/e2e/tests/build/bundle-budgets.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ +import assert from 'node:assert/strict'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + // Error + await updateJsonFile('angular.json', (json) => { + json.projects['test-project'].architect.build.configurations.production.budgets = [ + { type: 'all', maximumError: '100b' }, + ]; + }); + + const { message: errorMessage } = await expectToFail(() => ng('build')); + assert.match(errorMessage, /Error.+budget/i, 'Budget error: all, max error.'); + + // Warning + await updateJsonFile('angular.json', (json) => { + json.projects['test-project'].architect.build.configurations.production.budgets = [ + { type: 'all', minimumWarning: '100mb' }, + ]; + }); + + const { stderr } = await ng('build'); + assert.match(stderr, /Warning.+budget/i, 'Budget warning: all, min warning'); + + // Pass + await updateJsonFile('angular.json', (json) => { + json.projects['test-project'].architect.build.configurations.production.budgets = [ + { type: 'allScript', maximumError: '100mb' }, + ]; + }); + + const { stderr: stderr2 } = await ng('build'); + assert.doesNotMatch(stderr2, /(Warning|Error)/i, 'BIG max for all, should not error'); +} diff --git a/tests/e2e/tests/build/chunk-optimizer-animations.ts b/tests/e2e/tests/build/chunk-optimizer-animations.ts new file mode 100644 index 000000000000..2a4e46adc676 --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer-animations.ts @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { readFile, writeFile } from '../../utils/fs'; +import { installPackage } from '../../utils/packages'; +import { execWithEnv } from '../../utils/process'; +import { readNgVersion } from '../../utils/version'; + +export default async function () { + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + let animationsSpecifier: string; + if (isSnapshotBuild) { + const snapshots = require('../../ng-snapshot/package.json'); + animationsSpecifier = snapshots.dependencies['@angular/animations']; + } else { + const coreVersion = readNgVersion(); + animationsSpecifier = `@angular/animations@${coreVersion}`; + } + + // Install @angular/animations package + await installPackage(animationsSpecifier); + + // Configure app.config.ts with provideAnimationsAsync + const originalConfig = await readFile('src/app/app.config.ts'); + await writeFile( + 'src/app/app.config.ts', + ` + import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; + ${originalConfig.replace(/providers:\s*\[/, 'providers: [provideAnimationsAsync(),')} + `, + ); + + const updatedConfig = await readFile('src/app/app.config.ts'); + assert.ok( + updatedConfig.includes('provideAnimationsAsync()'), + 'Expected src/app/app.config.ts to include provideAnimationsAsync().', + ); + + // Build with chunk optimization + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: '1', + }); + const optimizedFiles = await readdir('dist/test-project/browser'); + const optimizedJsFiles = optimizedFiles.filter((f) => f.endsWith('.js')); + + // Read the optimized main.js file + const mainCode = await readFile('dist/test-project/browser/main.js'); + + // Check that optimized chunks still contain more than 1 javascript file + assert.ok( + optimizedJsFiles.length > 1, + `Expected more than one chunk, but found ${optimizedJsFiles.length}.`, + ); + + // Check that one of the lazy loaded chunks contains the animations package code + let foundAnimationsChunk = false; + for (const file of optimizedJsFiles) { + if (file === 'main.js') { + continue; + } + const code = await readFile(`dist/test-project/browser/${file}`); + if (code.includes('AnimationEngine')) { + foundAnimationsChunk = true; + break; + } + } + + assert.ok( + foundAnimationsChunk, + 'Expected to find AnimationEngine in one of the optimized lazy chunks.', + ); + + // The animations engine should not be bundled in main.js + assert.ok( + !mainCode.includes('AnimationEngine'), + 'Expected main.js not to contain AnimationEngine from @angular/animations/browser.', + ); +} diff --git a/tests/e2e/tests/build/chunk-optimizer-env.ts b/tests/e2e/tests/build/chunk-optimizer-env.ts new file mode 100644 index 000000000000..e5221811664e --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer-env.ts @@ -0,0 +1,105 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { replaceInFile } from '../../utils/fs'; +import { execWithEnv, ng } from '../../utils/process'; +import { installPackage, uninstallPackage } from '../../utils/packages'; + +export default async function () { + // Case 1: Force on with true/1 with 1 lazy chunk + await ng('generate', 'component', 'lazy-a'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [ + { + path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + }, + ];`, + ); + + // Build with forced optimization + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'true', + }); + + // Build with forced off + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'false', + }); + + // We just verify it runs without error. + // With 1 chunk it might not be able to optimize further, so counts might be equal. + + // Case 2: Force off with false/0 with 3 lazy chunks + await ng('generate', 'component', 'lazy-b'); + await ng('generate', 'component', 'lazy-c'); + await replaceInFile( + 'src/app/app.routes.ts', + `path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + },`, + `path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + }, + { + path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + }, + { + path: 'lazy-c', + loadComponent: () => import('./lazy-c/lazy-c').then(m => m.LazyC), + },`, + ); + + // Build with forced off + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'false', + }); + const files3Unopt = await readdir('dist/test-project/browser'); + const jsFiles3Unopt = files3Unopt.filter((f) => f.endsWith('.js')); + + // Build with default (should optimize because 3 chunks) + await ng('build', '--output-hashing=none'); + const files3Default = await readdir('dist/test-project/browser'); + const jsFiles3Default = files3Default.filter((f) => f.endsWith('.js')); + + assert.ok( + jsFiles3Default.length < jsFiles3Unopt.length, + `Expected default build (3 chunks) to be optimized compared to forced off. Default: ${jsFiles3Default.length}, Forced Off: ${jsFiles3Unopt.length}`, + ); + + // Case 3: Custom threshold + // Set threshold to 4 with 3 chunks -> should NOT optimize! + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: '4', + }); + const files3Thresh4 = await readdir('dist/test-project/browser'); + const jsFiles3Thresh4 = files3Thresh4.filter((f) => f.endsWith('.js')); + + assert.ok( + jsFiles3Thresh4.length >= jsFiles3Unopt.length, + `Expected build with threshold 4 and 3 chunks to NOT be optimized. Thresh 4: ${jsFiles3Thresh4.length}, Unoptimized: ${jsFiles3Unopt.length}`, + ); + + // Case 4: Opt back into Rollup (requires manual install since it's an optional peer dependency) + await installPackage('rollup@4.62.0'); + try { + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_CHUNKS_ROLLDOWN: 'false', + NG_BUILD_OPTIMIZE_CHUNKS: 'true', + }); + const filesRollup = await readdir('dist/test-project/browser'); + const jsFilesRollup = filesRollup.filter((f) => f.endsWith('.js')); + + assert.ok(jsFilesRollup.length > 0, 'Expected Rollup build to produce output files.'); + } finally { + // Clean up + await uninstallPackage('rollup'); + } +} diff --git a/tests/e2e/tests/build/chunk-optimizer-heuristic.ts b/tests/e2e/tests/build/chunk-optimizer-heuristic.ts new file mode 100644 index 000000000000..f8db4220699a --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer-heuristic.ts @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { replaceInFile } from '../../utils/fs'; +import { execWithEnv, ng } from '../../utils/process'; + +export default async function () { + // Case 1: 2 lazy chunks (below threshold of 3) -> should NOT optimize by default + await ng('generate', 'component', 'lazy-a'); + await ng('generate', 'component', 'lazy-b'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [ + { + path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + }, + { + path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + }, + ];`, + ); + + // Build without explicit flag (should use default threshold of 3) + await ng('build', '--output-hashing=none'); + const files2 = await readdir('dist/test-project/browser'); + const jsFiles2 = files2.filter((f) => f.endsWith('.js')); + + // Build with forced optimization to see if it COULD reduce chunks + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'true', + }); + const files2Opt = await readdir('dist/test-project/browser'); + const jsFiles2Opt = files2Opt.filter((f) => f.endsWith('.js')); + + // If forced optimization reduces chunks, then default should have MORE chunks (since it didn't run). + // If forced optimization doesn't reduce chunks, they will be equal. + // So we assert that default is NOT fewer than forced. + assert.ok( + jsFiles2.length >= jsFiles2Opt.length, + `Expected default build with 2 lazy chunks to NOT be optimized. Default: ${jsFiles2.length}, Forced: ${jsFiles2Opt.length}`, + ); + + // Case 2: 3 lazy chunks (at threshold of 3) -> should optimize by default + await ng('generate', 'component', 'lazy-c'); + await replaceInFile( + 'src/app/app.routes.ts', + `path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + },`, + `path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + }, + { + path: 'lazy-c', + loadComponent: () => import('./lazy-c/lazy-c').then(m => m.LazyC), + },`, + ); + + // Build without explicit flag (should use default threshold of 3) + await ng('build', '--output-hashing=none'); + const files3 = await readdir('dist/test-project/browser'); + const jsFiles3 = files3.filter((f) => f.endsWith('.js')); + + // Build with explicit disable + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'false', + }); + const files3Unopt = await readdir('dist/test-project/browser'); + const jsFiles3Unopt = files3Unopt.filter((f) => f.endsWith('.js')); + + // Expect default build to be optimized (fewer chunks than explicitly disabled) + assert.ok( + jsFiles3.length < jsFiles3Unopt.length, + `Expected default build with 3 lazy chunks to be optimized. Default: ${jsFiles3.length}, Unoptimized: ${jsFiles3Unopt.length}`, + ); +} diff --git a/tests/e2e/tests/build/chunk-optimizer-lazy.ts b/tests/e2e/tests/build/chunk-optimizer-lazy.ts new file mode 100644 index 000000000000..9b51c74d0898 --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer-lazy.ts @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { replaceInFile } from '../../utils/fs'; +import { execWithEnv, ng } from '../../utils/process'; + +export default async function () { + // Add lazy routes. + await ng('generate', 'component', 'lazy-a'); + await ng('generate', 'component', 'lazy-b'); + await ng('generate', 'component', 'lazy-c'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [ + { + path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + }, + { + path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + }, + { + path: 'lazy-c', + loadComponent: () => import('./lazy-c/lazy-c').then(m => m.LazyC), + }, + ];`, + ); + + // Build without chunk optimization + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'false', + }); + const unoptimizedFiles = await readdir('dist/test-project/browser'); + const unoptimizedJsFiles = unoptimizedFiles.filter((f) => f.endsWith('.js')); + + // Build with chunk optimization + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: '1', + }); + const optimizedFiles = await readdir('dist/test-project/browser'); + const optimizedJsFiles = optimizedFiles.filter((f) => f.endsWith('.js')); + + // Check that the number of chunks is reduced but not all combined + assert.ok( + optimizedJsFiles.length < unoptimizedJsFiles.length, + `Expected chunk count to be less than ${unoptimizedJsFiles.length}, but was ${optimizedJsFiles.length}.`, + ); + assert.ok( + optimizedJsFiles.length > 1, + `Expected more than one chunk, but found ${optimizedJsFiles.length}.`, + ); +} diff --git a/tests/e2e/tests/build/chunk-optimizer.ts b/tests/e2e/tests/build/chunk-optimizer.ts new file mode 100644 index 000000000000..fff428b47263 --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer.ts @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { execWithEnv } from '../../utils/process'; + +/** + * AOT builds with chunk optimizer should contain generated component definitions. + * This is currently testing that the generated code is propagating through the + * chunk optimization step. + */ +export default async function () { + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: '1', + NG_BUILD_MANGLE: '0', + }); + + const content = await readFile('dist/test-project/browser/main.js', 'utf-8'); + assert.match(content, /(ɵɵ|\\u0275\\u0275)defineComponent/u); +} diff --git a/tests/e2e/tests/build/config-file-fallback.ts b/tests/e2e/tests/build/config-file-fallback.ts new file mode 100644 index 000000000000..53298b573e12 --- /dev/null +++ b/tests/e2e/tests/build/config-file-fallback.ts @@ -0,0 +1,9 @@ +import { ng } from '../../utils/process'; +import { moveFile } from '../../utils/fs'; + +export default function () { + return Promise.resolve() + .then(() => ng('build')) + .then(() => moveFile('angular.json', '.angular.json')) + .then(() => ng('build')); +} diff --git a/tests/e2e/tests/build/css-urls.ts b/tests/e2e/tests/build/css-urls.ts new file mode 100644 index 000000000000..839ecf58f567 --- /dev/null +++ b/tests/e2e/tests/build/css-urls.ts @@ -0,0 +1,225 @@ +import { ng } from '../../utils/process'; +import { + expectFileToMatch, + expectFileToExist, + expectFileMatchToExist, + writeMultipleFiles, +} from '../../utils/fs'; +import { copyProjectAsset } from '../../utils/assets'; +import { expectToFail } from '../../utils/utils'; +import { getGlobalVariable } from '../../utils/env'; +import { mkdir } from 'node:fs/promises'; + +const imgSvg = ` + + + +`; + +export default async function () { + const usingWebpack = !getGlobalVariable('argv')['esbuild']; + + const mediaPath = usingWebpack + ? './dist/test-project/browser' + : './dist/test-project/browser/media'; + + await mkdir('public/assets/', { recursive: true }); + + await Promise.resolve() + // Verify absolute/relative paths in global/component css. + .then(() => + writeMultipleFiles({ + 'src/styles.css': ` + h1 { background: url('/assets/global-img-absolute.svg'); } + h2 { background: url('./assets/global-img-relative.png'); } + `, + 'src/app/app.css': ` + h3 { background: url('/assets/component-img-absolute.svg'); } + h4 { background: url('../assets/component-img-relative.png'); } + `, + 'public/assets/global-img-absolute.svg': imgSvg, + 'public/assets/component-img-absolute.svg': imgSvg, + }), + ) + .then(() => copyProjectAsset('images/spectrum.png', './src/assets/global-img-relative.png')) + .then(() => copyProjectAsset('images/spectrum.png', './src/assets/component-img-relative.png')) + .then(() => ng('build', '--aot', '--configuration=development')) + // Check paths are correctly generated. + .then(() => + expectFileToMatch('dist/test-project/browser/styles.css', 'assets/global-img-absolute.svg'), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /url\((['"]?)\/assets\/global-img-absolute\.svg\1\)/, + ), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/styles.css', /global-img-relative\.png/), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/main.js', '/assets/component-img-absolute.svg'), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/main.js', /component-img-relative\.png/), + ) + // Check files are correctly created. + .then(() => expectToFail(() => expectFileToExist(`${mediaPath}/global-img-absolute.svg`))) + .then(() => expectToFail(() => expectFileToExist(`${mediaPath}/component-img-absolute.svg`))) + .then(() => expectFileMatchToExist(mediaPath, /global-img-relative\.png/)) + .then(() => expectFileMatchToExist(mediaPath, /component-img-relative\.png/)); + + // Early exit before deploy url tests + if (!usingWebpack) { + return; + } + + // Check urls with deploy-url scheme are used as is. + return ( + Promise.resolve() + .then(() => + ng( + 'build', + '--base-href=/base/', + '--deploy-url=http://deploy.url/', + '--configuration=development', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /url\(\'\/assets\/global-img-absolute\.svg\'\)/, + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /url\(\'\/assets\/component-img-absolute\.svg\'\)/, + ), + ) + // Check urls with base-href scheme are used as is (with deploy-url). + .then(() => + ng( + 'build', + '--base-href=http://base.url/', + '--deploy-url=deploy/', + '--configuration=development', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /url\(\'\/assets\/global-img-absolute\.svg\'\)/, + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /url\(\'\/assets\/component-img-absolute\.svg\'\)/, + ), + ) + // Check urls with deploy-url and base-href scheme only use deploy-url. + .then(() => + ng( + 'build', + '--base-href=http://base.url/', + '--deploy-url=http://deploy.url/', + '--configuration=development', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /url\(\'\/assets\/global-img-absolute\.svg\'\)/, + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /url\(\'\/assets\/component-img-absolute\.svg\'\)/, + ), + ) + // Check with base-href and deploy-url flags. + .then(() => + ng( + 'build', + '--base-href=/base/', + '--deploy-url=deploy/', + '--aot', + '--configuration=development', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + '/assets/global-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/styles.css', /global-img-relative\.png/), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + '/assets/component-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /deploy\/component-img-relative\.png/, + ), + ) + // Check with identical base-href and deploy-url flags. + .then(() => + ng( + 'build', + '--base-href=/base/', + '--deploy-url=/base/', + '--aot', + '--configuration=development', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + '/assets/global-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/styles.css', /global-img-relative\.png/), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + '/assets/component-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /\/base\/component-img-relative\.png/, + ), + ) + // Check with only base-href flag. + .then(() => ng('build', '--base-href=/base/', '--aot', '--configuration=development')) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + '/assets/global-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/styles.css', /global-img-relative\.png/), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + '/assets/component-img-absolute.svg', + ), + ) + .then(() => + expectFileToMatch('dist/test-project/browser/main.js', /component-img-relative\.png/), + ) + ); +} diff --git a/tests/e2e/tests/build/disk-cache-purge.ts b/tests/e2e/tests/build/disk-cache-purge.ts new file mode 100644 index 000000000000..52edd4845038 --- /dev/null +++ b/tests/e2e/tests/build/disk-cache-purge.ts @@ -0,0 +1,30 @@ +import { join } from 'node:path'; +import { createDir, expectFileNotToExist, expectFileToExist, writeFile } from '../../utils/fs'; +import { silentNg } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + const cachePath = '.angular/cache'; + const staleCachePath = join(cachePath, 'v1.0.0'); + + // No need to include all applications code to verify disk cache existence. + await writeFile('src/main.ts', 'console.log(1);'); + + // Enable cache for all environments + await updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.cache = { + environment: 'all', + enabled: true, + path: cachePath, + }; + }); + + // Create a dummy stale disk cache directory. + await createDir(staleCachePath); + await expectFileToExist(staleCachePath); + + await silentNg('build'); + await expectFileToExist(cachePath); + await expectFileNotToExist(staleCachePath); +} diff --git a/tests/e2e/tests/build/disk-cache.ts b/tests/e2e/tests/build/disk-cache.ts new file mode 100644 index 000000000000..1873905646ca --- /dev/null +++ b/tests/e2e/tests/build/disk-cache.ts @@ -0,0 +1,56 @@ +import { expectFileNotToExist, expectFileToExist, rimraf, writeFile } from '../../utils/fs'; +import { silentNg } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +const defaultCachePath = '.angular/cache'; +const overriddenCachePath = '.cache/angular-cli'; + +export default async function () { + const originalCIValue = process.env['CI']; + + // No need to include all applications code to verify disk cache existence. + await writeFile('src/main.ts', 'console.log(1);'); + + try { + // Should be enabled by default. + process.env['CI'] = '0'; + await configureAndRunTest(); + + // Should not write cache when it's disabled + await configureAndRunTest({ enabled: false }); + await expectFileNotToExist(defaultCachePath); + + // Should not write cache by default when in CI. + process.env['CI'] = '1'; + await configureAndRunTest(); + await expectFileNotToExist(defaultCachePath); + + // Should write cache when it's enabled and 'environment' is set to 'all' or 'ci'. + await configureAndRunTest({ environment: 'all' }); + await expectFileToExist(defaultCachePath); + + // Should write cache to custom path when configured. + await configureAndRunTest({ environment: 'ci', path: overriddenCachePath }); + await expectFileNotToExist(defaultCachePath); + await expectFileToExist(overriddenCachePath); + } finally { + process.env['CI'] = originalCIValue; + } +} + +async function configureAndRunTest(cacheOptions?: { + environment?: 'ci' | 'local' | 'all'; + enabled?: boolean; + path?: string; +}): Promise { + await Promise.all([ + rimraf(overriddenCachePath), + rimraf(defaultCachePath), + updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.cache = cacheOptions; + }), + ]); + + await silentNg('build'); +} diff --git a/tests/e2e/tests/build/extract-licenses.ts b/tests/e2e/tests/build/extract-licenses.ts new file mode 100644 index 000000000000..04ab08f5d49e --- /dev/null +++ b/tests/e2e/tests/build/extract-licenses.ts @@ -0,0 +1,29 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist, expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + const usingWebpack = !getGlobalVariable('argv')['esbuild']; + + // Licenses should be left intact if extraction is disabled + await ng('build', '--extract-licenses=false', '--output-hashing=none'); + + if (usingWebpack) { + await expectToFail(() => expectFileToExist('dist/test-project/browser/3rdpartylicenses.txt')); + } else { + // Application builder puts the licenses at the output path root + await expectToFail(() => expectFileToExist('dist/test-project/3rdpartylicenses.txt')); + } + await expectFileToMatch('dist/test-project/browser/main.js', '@license'); + + // Licenses should be removed if extraction is enabled + await ng('build', '--extract-licenses', '--output-hashing=none'); + + if (usingWebpack) { + await expectFileToExist('dist/test-project/browser/3rdpartylicenses.txt'); + } else { + await expectFileToExist('dist/test-project/3rdpartylicenses.txt'); + } + await expectToFail(() => expectFileToMatch('dist/test-project/browser/main.js', '@license')); +} diff --git a/tests/e2e/tests/build/incremental-watch.ts b/tests/e2e/tests/build/incremental-watch.ts new file mode 100644 index 000000000000..68f281c8bab5 --- /dev/null +++ b/tests/e2e/tests/build/incremental-watch.ts @@ -0,0 +1,92 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, readFile, writeFile } from '../../utils/fs'; +import { execAndWaitForOutputToMatch, waitForAnyProcessOutputToMatch } from '../../utils/process'; + +const buildReadyRegEx = /Application bundle generation complete\./; + +async function getOutputChunks( + dir: string, + predicate: (chunks: string[]) => boolean, + timeout = 10_000, +): Promise { + const start = Date.now(); + while (Date.now() - start < timeout) { + try { + const chunks = (await readdir(dir)).filter((file) => file.endsWith('.js')); + if (predicate(chunks)) { + return chunks; + } + } catch (err: any) { + if (err?.code !== 'ENOENT') { + throw err; + } + } + await setTimeout(50); + } + + const chunks = (await readdir(dir)).filter((file) => file.endsWith('.js')); + assert(predicate(chunks), `Condition not met for chunks in ${dir}: ${JSON.stringify(chunks)}`); + + return chunks; +} + +export default async function () { + const usingApplicationBuilder = getGlobalVariable('argv')['esbuild']; + assert( + usingApplicationBuilder, + 'Incremental watch E2E test should not be executed with Webpack.', + ); + + // Perform an initial build in watch mode + await execAndWaitForOutputToMatch( + 'ng', + ['build', '--watch', '--configuration=development'], + buildReadyRegEx, + ); + const initialOutputChunks = await getOutputChunks( + 'dist/test-project/browser', + (chunks) => chunks.length > 0, + ); + + const originalMain = await readFile('src/main.ts'); + + // Add a dynamic import to create an additional output chunk + await Promise.all([ + waitForAnyProcessOutputToMatch(buildReadyRegEx), + writeFile( + 'src/a.ts', + ` + export function sayHi() { + console.log('hi'); + } + `, + ), + appendToFile('src/main.ts', `\nimport('./a').then((m) => m.sayHi());`), + ]); + const intermediateOutputChunks = await getOutputChunks( + 'dist/test-project/browser', + (chunks) => chunks.length > initialOutputChunks.length, + ); + assert( + initialOutputChunks.length < intermediateOutputChunks.length, + 'Additional chunks should be present', + ); + + // Remove usage of dynamic import which should remove the additional output chunk + await Promise.all([ + waitForAnyProcessOutputToMatch(buildReadyRegEx), + writeFile('src/main.ts', originalMain), + ]); + const finalOutputChunks = await getOutputChunks( + 'dist/test-project/browser', + (chunks) => chunks.length === initialOutputChunks.length, + ); + assert.equal( + initialOutputChunks.length, + finalOutputChunks.length, + 'Final chunk count should be equal to initial chunk count.', + ); +} diff --git a/tests/e2e/tests/build/jit-ngmodule.ts b/tests/e2e/tests/build/jit-ngmodule.ts new file mode 100644 index 000000000000..aa6b3fda86bb --- /dev/null +++ b/tests/e2e/tests/build/jit-ngmodule.ts @@ -0,0 +1,48 @@ +import { getGlobalVariable } from '../../utils/env'; +import { ng } from '../../utils/process'; +import { updateJsonFile, useCIDefaults } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); + await useCIDefaults('test-project-two'); + + // Make prod use JIT. + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + // Setup webpack builder if esbuild is not requested on the commandline + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project-two']['architect']['build']; + if (useWebpackBuilder) { + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + buildOptimizer: false, + outputPath: 'dist/test-project-two', + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + }; + } + + // Remove bundle budgets due to the increased size from JIT + build.configurations.production = { + ...build.configurations.production, + budgets: undefined, + }; + + build.options.aot = false; + + const serve = json['projects']['test-project-two']['architect']['serve']; + serve.builder = '@angular-devkit/build-angular:dev-server'; + }); + // Test it works + await executeBrowserTest({ project: 'test-project-two', configuration: 'production' }); + await executeBrowserTest({ project: 'test-project-two', configuration: 'development' }); +} diff --git a/tests/e2e/tests/build/jit-prod.ts b/tests/e2e/tests/build/jit-prod.ts new file mode 100644 index 000000000000..b2dc9d0bdddc --- /dev/null +++ b/tests/e2e/tests/build/jit-prod.ts @@ -0,0 +1,22 @@ +import { getGlobalVariable } from '../../utils/env'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + // Make prod use JIT. + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + appArchitect.build.configurations['production'].aot = false; + + // JIT applications have significantly larger sizes + appArchitect.build.configurations['production'].budgets = []; + + if (!getGlobalVariable('argv')['esbuild']) { + // The build optimizer option does not exist with the application build system + appArchitect.build.configurations['production'].buildOptimizer = false; + } + }); + + // Test it works + await executeBrowserTest({ configuration: 'production' }); +} diff --git a/tests/e2e/tests/build/lazy-load-syntax.ts b/tests/e2e/tests/build/lazy-load-syntax.ts new file mode 100644 index 000000000000..bc0a375673dc --- /dev/null +++ b/tests/e2e/tests/build/lazy-load-syntax.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { replaceInFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + // Add lazy route. + await ng('generate', 'component', 'lazy-comp'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [{ + path: 'lazy', + loadComponent: () => import('./lazy-comp/lazy-comp').then(c => c.LazyComp), + }];`, + ); + + // Convert the default config to use JIT and prod to just do AOT. + // This way we can use `ng e2e` to test JIT and `ng e2e --configuration=production` to test AOT. + await updateJsonFile('angular.json', (json) => { + const buildTarget = json['projects']['test-project']['architect']['build']; + buildTarget['options']['aot'] = true; + buildTarget['configurations']['development']['aot'] = false; + }); + + const checkFn = async (page: any) => { + await page.goto(page.url() + 'lazy'); + await page.waitForFunction( + () => + !!(globalThis as any).document + .querySelector('app-lazy-comp p') + ?.textContent?.includes('lazy-comp works!'), + { timeout: 10000 }, + ); + }; + + await executeBrowserTest({ checkFn }); + await executeBrowserTest({ configuration: 'production', checkFn }); +} diff --git a/tests/e2e/tests/build/library-with-demo-app.ts b/tests/e2e/tests/build/library-with-demo-app.ts new file mode 100644 index 000000000000..0158e41d42d5 --- /dev/null +++ b/tests/e2e/tests/build/library-with-demo-app.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { appendToFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + await ng('generate', 'library', 'mylib'); + await ng('generate', 'entry-point', 'secondary', '--project', 'mylib'); + await ng('generate', 'entry-point', 'another', '--project', 'mylib'); + + await appendToFile( + 'src/app/app.config.ts', + ` + import * as secondary from 'mylib/secondary'; + import * as another from 'mylib/another'; + + console.log({ + secondary, + another + }); + `, + ); + + // Scenario #1 where we use wildcard path mappings as generated by the schematics. + await ng('build', 'mylib'); + await ng('build'); + + // Scenario #2 where we don't use wildcard path mappings. + await updateJsonFile('tsconfig.json', (json) => { + json.compilerOptions.paths = { + 'mylib': ['./dist/mylib'], + 'mylib/secondary': ['./dist/mylib/secondary'], + 'mylib/another': ['./dist/mylib/another'], + }; + }); + + await ng('build'); +} diff --git a/tests/e2e/tests/build/library/lib-consumption-full-aot.ts b/tests/e2e/tests/build/library/lib-consumption-full-aot.ts new file mode 100644 index 000000000000..08d114f1de4a --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-full-aot.ts @@ -0,0 +1,14 @@ +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in full mode (development) + await ng('build', 'my-lib', '--configuration=development'); + + // Check that the e2e succeeds prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); +} diff --git a/tests/e2e/tests/build/library/lib-consumption-full-jit.ts b/tests/e2e/tests/build/library/lib-consumption-full-jit.ts new file mode 100644 index 000000000000..906a920dba44 --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-full-jit.ts @@ -0,0 +1,34 @@ +import { updateJsonFile } from '../../../utils/project'; +import { expectFileToMatch } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; +import { getGlobalVariable } from '../../../utils/env'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in full mode (development) + await ng('build', 'my-lib', '--configuration=development'); + + // JIT linking + await updateJsonFile('angular.json', (config) => { + const build = config.projects['test-project'].architect.build; + build.options.aot = false; + build.configurations.production.budgets = undefined; + if (!getGlobalVariable('argv')['esbuild']) { + build.configurations.production.buildOptimizer = false; + } + }); + + // Ensure app works in prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); + + // Validate that sourcemaps for the library exists. + await ng('build', '--configuration=development'); + await expectFileToMatch( + 'dist/test-project/browser/main.js.map', + 'projects/my-lib/src/lib/my-lib.ts', + ); +} diff --git a/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts b/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts new file mode 100644 index 000000000000..f906be54b0e6 --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts @@ -0,0 +1,14 @@ +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in partial mode (production) + await ng('build', 'my-lib', '--configuration=production'); + + // Check that the e2e succeeds prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); +} diff --git a/tests/e2e/tests/build/library/lib-consumption-partial-jit.ts b/tests/e2e/tests/build/library/lib-consumption-partial-jit.ts new file mode 100644 index 000000000000..503c09e525e9 --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-partial-jit.ts @@ -0,0 +1,27 @@ +import { updateJsonFile } from '../../../utils/project'; +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; +import { getGlobalVariable } from '../../../utils/env'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in partial mode (production) + await ng('build', 'my-lib', '--configuration=production'); + + // JIT linking + await updateJsonFile('angular.json', (config) => { + const build = config.projects['test-project'].architect.build; + build.options.aot = false; + build.configurations.production.budgets = undefined; + + if (!getGlobalVariable('argv')['esbuild']) { + build.configurations.production.buildOptimizer = false; + } + }); + + // Check that the e2e succeeds prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); +} diff --git a/tests/e2e/tests/build/library/lib-consumption-sourcemaps.ts b/tests/e2e/tests/build/library/lib-consumption-sourcemaps.ts new file mode 100644 index 000000000000..c0b7a5e78a73 --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-sourcemaps.ts @@ -0,0 +1,17 @@ +import { expectFileToMatch } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { libraryConsumptionSetup } from './setup'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in full mode (development) + await ng('build', 'my-lib', '--configuration=development'); + + // Validate that sourcemaps for the library exists. + await ng('build', '--configuration=development'); + await expectFileToMatch( + 'dist/test-project/browser/main.js.map', + 'projects/my-lib/src/lib/my-lib.ts', + ); +} diff --git a/tests/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts b/tests/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts new file mode 100644 index 000000000000..33b221a32efe --- /dev/null +++ b/tests/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts @@ -0,0 +1,49 @@ +import assert from 'node:assert'; +import { appendToFile, expectFileToExist, expectFileToMatch, readFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { libraryConsumptionSetup } from './setup'; +import { updateJsonFile } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + await ng('cache', 'off'); + await libraryConsumptionSetup(); + + // Add an unused class as part of the public api. + await appendToFile( + 'projects/my-lib/src/lib/my-lib.ts', + ` + function something() { + return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { + console.log("someDecorator"); + }; + } + + export class ExampleClass { + @something() + method() {} + } + `, + ); + + // build the lib + await ng('build', 'my-lib', '--configuration=production'); + const packageJson = JSON.parse(await readFile('dist/my-lib/package.json')); + assert.equal(packageJson.sideEffects, false); + + // build the app + await ng('build', 'test-project', '--configuration=production', '--output-hashing=none'); + // Output should not contain `ExampleClass` as the library is marked as side-effect free. + await expectFileToExist('dist/test-project/browser/main.js'); + await expectToFail(() => expectFileToMatch('dist/test-project/browser/main.js', 'someDecorator')); + + // Mark library as side-effectful. + await updateJsonFile('dist/my-lib/package.json', (packageJson) => { + packageJson.sideEffects = true; + }); + + // build the app + await ng('build', 'test-project', '--configuration=production', '--output-hashing=none'); + // Output should contain `ExampleClass` as the library is marked as side-effectful. + await expectFileToMatch('dist/test-project/browser/main.js', 'someDecorator'); +} diff --git a/tests/e2e/tests/build/library/setup.ts b/tests/e2e/tests/build/library/setup.ts new file mode 100644 index 000000000000..621b740cf4bc --- /dev/null +++ b/tests/e2e/tests/build/library/setup.ts @@ -0,0 +1,45 @@ +import type { Page } from 'puppeteer'; +import { writeMultipleFiles } from '../../../utils/fs'; +import { silentNg } from '../../../utils/process'; + +export async function libraryConsumptionSetup(): Promise { + await silentNg('generate', 'library', 'my-lib'); + + // Force an external template + await writeMultipleFiles({ + 'projects/my-lib/src/lib/my-lib.html': `

my-lib works!

`, + 'projects/my-lib/src/lib/my-lib.ts': `import { Component } from '@angular/core'; + + @Component({ + selector: 'lib-my-lib', + templateUrl: './my-lib.html', + }) + export class MyLibComponent {}`, + './src/app/app.ts': ` + import { Component } from '@angular/core'; + import { MyLibComponent } from 'my-lib'; + + @Component({ + selector: 'app-root', + template: '', + imports: [MyLibComponent], + }) + export class App { + title = 'test-project'; + + constructor() { + } + } + `, + }); +} + +export async function browserCheck(page: Page): Promise { + await page.waitForFunction( + () => + !!(globalThis as any).document + .querySelector('lib-my-lib p') + ?.textContent?.includes('my-lib works!'), + { timeout: 10000 }, + ); +} diff --git a/tests/e2e/tests/build/material.ts b/tests/e2e/tests/build/material.ts new file mode 100644 index 000000000000..bc4862f735fc --- /dev/null +++ b/tests/e2e/tests/build/material.ts @@ -0,0 +1,89 @@ +import { appendFile } from 'node:fs/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { readFile, replaceInFile } from '../../utils/fs'; +import { + getActivePackageManager, + installPackage, + installWorkspacePackages, +} from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +const snapshots = require('../../ng-snapshot/package.json'); + +export default async function () { + const isPrerelease = await isPrereleaseCli(); + let tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + await ng('add', `@angular/material${tag}`, '--skip-confirmation'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Angular material adds dependencies on other Angular packages + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries(snapshots.dependencies)) { + if (name in dependencies) { + dependencies[name] = version; + } + } + + dependencies['@angular/material-moment-adapter'] = + snapshots.dependencies['@angular/material-moment-adapter']; + }); + await installWorkspacePackages(); + } else { + if (!tag) { + const installedMaterialVersion = JSON.parse(await readFile('package.json'))['dependencies'][ + '@angular/material' + ]; + tag = `@${installedMaterialVersion}`; + } + await installPackage(`@angular/material-moment-adapter${tag}`); + } + + await installPackage('moment'); + + await ng('build'); + + // Ensure moment adapter works (uses unique importing mechanism for moment) + // Issue: https://github.com/angular/angular-cli/issues/17320 + await replaceInFile( + 'src/app/app.config.ts', + `from '@angular/core';`, + ` + from '@angular/core'; + import { + MomentDateAdapter, + MAT_MOMENT_DATE_FORMATS + } from '@angular/material-moment-adapter'; + import { + DateAdapter, + MAT_DATE_LOCALE, + MAT_DATE_FORMATS + } from '@angular/material/core'; + `, + ); + + await replaceInFile( + 'src/app/app.config.ts', + `provideRouter(routes)`, + `provideRouter(routes), + { + provide: DateAdapter, + useClass: MomentDateAdapter, + deps: [MAT_DATE_LOCALE] + }, + { + provide: MAT_DATE_FORMATS, + useValue: MAT_MOMENT_DATE_FORMATS + }`, + ); + + await executeBrowserTest({ configuration: 'production' }); +} diff --git a/tests/e2e/tests/build/multiple-configs.ts b/tests/e2e/tests/build/multiple-configs.ts new file mode 100644 index 000000000000..dbbeba4658e3 --- /dev/null +++ b/tests/e2e/tests/build/multiple-configs.ts @@ -0,0 +1,63 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + // TODO: Restructure to support application builder option + // This only needs to be tested once since it is really testing the CLI itself and not the builders + if (getGlobalVariable('argv')['esbuild']) { + return; + } + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + // These are the default options, that we'll overwrite in subsequent configs. + // sourceMap defaults to true + appArchitect['build'] = { + ...appArchitect['build'], + defaultConfiguration: undefined, + options: { + ...appArchitect['build'].options, + optimization: false, + sourceMap: true, + outputHashing: 'none', + vendorChunk: true, + styles: ['src/styles.css'], + scripts: [], + budgets: [], + }, + configurations: { + development: { + sourceMap: true, + }, + one: { + assets: [], + }, + two: { + sourceMap: false, + }, + }, + }; + + return workspaceJson; + }); + + // Test the base configuration. + await ng('build', '--configuration=development'); + await expectFileToExist('dist/test-project/browser/favicon.ico'); + await expectFileToExist('dist/test-project/browser/main.js.map'); + await expectFileToExist('dist/test-project/browser/vendor.js'); + await ng('build'); + await expectFileToExist('dist/test-project/browser/styles.css'); + // Use two configurations. + await ng('build', '--configuration=one,two', '--vendor-chunk=false'); + await expectToFail(() => expectFileToExist('dist/test-project/browser/favicon.ico')); + await expectToFail(() => expectFileToExist('dist/test-project/browser/main.js.map')); + // Use two configurations and two overrides, one of which overrides a config. + await ng('build', '--configuration=one,two', '--vendor-chunk=false', '--source-map=true'); + await expectToFail(() => expectFileToExist('dist/test-project/browser/favicon.ico')); + await expectFileToExist('dist/test-project/browser/main.js.map'); + await expectToFail(() => expectFileToExist('dist/test-project/browser/vendor.js')); +} diff --git a/tests/e2e/tests/build/output-dir.ts b/tests/e2e/tests/build/output-dir.ts new file mode 100644 index 000000000000..0a93ebae67b4 --- /dev/null +++ b/tests/e2e/tests/build/output-dir.ts @@ -0,0 +1,29 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist } from '../../utils/fs'; +import { expectGitToBeClean } from '../../utils/git'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default function () { + // TODO(architect): Delete this test. It is now in devkit/build-angular. + + const usingWebpack = !getGlobalVariable('argv')['esbuild']; + + return ng('build', '--output-path', 'build-output', '--configuration=development') + .then(() => expectFileToExist(`./build-output/${usingWebpack ? '' : 'browser/'}index.html`)) + .then(() => expectFileToExist(`./build-output/${usingWebpack ? '' : 'browser/'}main.js`)) + .then(() => expectToFail(expectGitToBeClean)) + .then(() => + updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.outputPath = 'config-build-output'; + }), + ) + .then(() => ng('build', '--configuration=development')) + .then(() => + expectFileToExist(`./config-build-output/${usingWebpack ? '' : 'browser/'}index.html`), + ) + .then(() => expectFileToExist(`./config-build-output/${usingWebpack ? '' : 'browser/'}main.js`)) + .then(() => expectToFail(expectGitToBeClean)); +} diff --git a/tests/e2e/tests/build/poll.ts b/tests/e2e/tests/build/poll.ts new file mode 100644 index 000000000000..3b72b7c2d4e6 --- /dev/null +++ b/tests/e2e/tests/build/poll.ts @@ -0,0 +1,29 @@ +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile } from '../../utils/fs'; +import { waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { ngServe } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +const webpackGoodRegEx = getGlobalVariable('argv')['esbuild'] + ? /Application bundle generation complete\./ + : / Compiled successfully\./; + +export default async function () { + await ngServe('--poll=10000'); + + // Wait before editing a file. + // Editing too soon seems to trigger a rebuild and throw polling out of whack. + await setTimeout(3000); + await appendToFile('src/main.ts', 'console.log(1);'); + + // We have to wait poll time + rebuild build time for the regex match. + await waitForAnyProcessOutputToMatch(webpackGoodRegEx, 14000); + + // No rebuilds should occur for a while + await appendToFile('src/main.ts', 'console.log(1);'); + await expectToFail(() => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 7000)); + + // But a rebuild should happen roughly within the 10 second window. + await waitForAnyProcessOutputToMatch(webpackGoodRegEx, 7000); +} diff --git a/tests/e2e/tests/build/prerender/discover-routes-ngmodule.ts b/tests/e2e/tests/build/prerender/discover-routes-ngmodule.ts new file mode 100644 index 000000000000..9d4843e00f7d --- /dev/null +++ b/tests/e2e/tests/build/prerender/discover-routes-ngmodule.ts @@ -0,0 +1,150 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile, useSha } from '../../../utils/project'; + +export default async function () { + const projectName = 'test-project-two'; + await ng('generate', 'application', projectName, '--no-standalone', '--skip-install'); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // Setup webpack builder if esbuild is not requested on the commandline + await updateJsonFile('angular.json', (json) => { + const build = json['projects'][projectName]['architect']['build']; + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + buildOptimizer: false, + }; + }); + } + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng( + 'add', + '@angular/ssr', + '--project', + projectName, + '--skip-confirmation', + '--skip-install', + ); + + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + `projects/${projectName}/src/app/app-routing-module.ts`, + ` + import { NgModule } from '@angular/core'; + import { RouterModule, Routes } from '@angular/router'; + import { One} from './one/one'; + import { TwoChildOne } from './two-child-one/two-child-one'; + import { TwoChildTwo } from './two-child-two/two-child-two'; + + const routes: Routes = [ + { + path: '', + component: One, + }, + { + path: 'two', + children: [ + { + path: 'two-child-one', + component: TwoChildOne, + }, + { + path: 'two-child-two', + component: TwoChildTwo, + }, + ], + }, + ]; + + @NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule], + }) + export class AppRoutingModule {} + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['one', 'two-child-one', 'two-child-two']; + + for (const componentName of componentNames) { + await ng('generate', 'component', componentName, '--project', projectName); + } + + // Generate lazy routes + const lazyModules: [route: string, moduleName: string][] = [ + ['lazy-one', 'app-module'], + ['lazy-one-child', 'lazy-one/lazy-one-module'], + ['lazy-two', 'app-module'], + ]; + + for (const [route, moduleName] of lazyModules) { + await ng( + 'generate', + 'module', + route, + '--route', + route, + '--module', + moduleName, + '--project', + projectName, + ); + } + + // Prerender pages + if (useWebpackBuilder) { + await ng('run', `${projectName}:prerender:production`); + await runExpects(); + + return; + } + + await ng('build', projectName, '--configuration=production'); + await runExpects(); + + // Test also JIT mode. + await ng('build', projectName, '--configuration=development', '--no-aot'); + + await runExpects(); + + async function runExpects(): Promise { + const expects: Record = { + 'index.html': 'one works!', + 'two/index.html': 'router-outlet', + 'two/two-child-one/index.html': 'two-child-one works!', + 'two/two-child-two/index.html': 'two-child-two works!', + 'lazy-one/index.html': 'lazy-one works!', + 'lazy-one/lazy-one-child/index.html': 'lazy-one-child works!', + 'lazy-two/index.html': 'lazy-two works!', + }; + + if (!useWebpackBuilder) { + expects['index.csr.html'] = ''; + } + + const distPath = 'dist/' + projectName + '/browser'; + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join(distPath, filePath), fileMatch); + } + } +} diff --git a/tests/e2e/tests/build/prerender/discover-routes-standalone.ts b/tests/e2e/tests/build/prerender/discover-routes-standalone.ts new file mode 100644 index 000000000000..71a3ba2fb15d --- /dev/null +++ b/tests/e2e/tests/build/prerender/discover-routes-standalone.ts @@ -0,0 +1,126 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToMatch, readFile, writeFile } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useSha } from '../../../utils/project'; +import { deepStrictEqual } from 'node:assert'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { One } from './one/one'; + import { TwoChildOne } from './two-child-one/two-child-one'; + import { TwoChildTwo } from './two-child-two/two-child-two'; + + export const routes: Routes = [ + { + path: '', + component: One, + }, + { + path: 'two', + children: [ + { + path: 'two-child-one', + component: TwoChildOne, + }, + { + path: 'two-child-two', + component: TwoChildTwo, + }, + ], + }, + { + path: 'lazy-one', + children: [ + { + path: '', + loadComponent: () => import('./lazy-one/lazy-one').then(c => c.LazyOne), + }, + { + path: 'lazy-one-child', + loadComponent: () => import('./lazy-one-child/lazy-one-child').then(c => c.LazyOneChild), + }, + ], + }, + { + path: 'lazy-two', + loadComponent: () => import('./lazy-two/lazy-two').then(c => c.LazyTwo), + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = [ + 'one', + 'two-child-one', + 'two-child-two', + 'lazy-one', + 'lazy-one-child', + 'lazy-two', + ]; + + for (const componentName of componentNames) { + await ng('generate', 'component', componentName); + } + + // Prerender pages + if (useWebpackBuilder) { + await ng('run', 'test-project:prerender:production'); + await runExpects(); + + return; + } + + await ng('build', '--configuration=production', '--prerender'); + await runExpects(); + + // Test also JIT mode. + await ng('build', '--configuration=development', '--prerender', '--no-aot'); + await runExpects(); + + async function runExpects(): Promise { + const expects: Record = { + 'index.html': 'one works!', + 'two/index.html': 'router-outlet', + 'two/two-child-one/index.html': 'two-child-one works!', + 'two/two-child-two/index.html': 'two-child-two works!', + 'lazy-one/index.html': 'lazy-one works!', + 'lazy-one/lazy-one-child/index.html': 'lazy-one-child works!', + 'lazy-two/index.html': 'lazy-two works!', + }; + + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); + } + + if (!useWebpackBuilder) { + // prerendered-routes.json file is only generated when using esbuild. + const generatedRoutesStats = await readFile('dist/test-project/prerendered-routes.json'); + deepStrictEqual(JSON.parse(generatedRoutesStats), { + routes: { + '/': {}, + '/lazy-one': {}, + '/lazy-one/lazy-one-child': {}, + '/lazy-two': {}, + '/two': {}, + '/two/two-child-one': {}, + '/two/two-child-two': {}, + }, + }); + } + } +} diff --git a/tests/e2e/tests/build/prerender/error-component-render.ts b/tests/e2e/tests/build/prerender/error-component-render.ts new file mode 100644 index 000000000000..07c048c71c39 --- /dev/null +++ b/tests/e2e/tests/build/prerender/error-component-render.ts @@ -0,0 +1,72 @@ +import { existsSync } from 'node:fs'; +import assert, { match } from 'node:assert'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileNotToExist, readFile, rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useSha } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + return; + } + + // Forcibly remove in case another test doesn't clean itself up. + await rimraf('node_modules/@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Component } from '@angular/core'; + + @Component({ + selector: 'app-home', + standalone: true, + template: '

home works!

', + }) + export class HomeRoute {} + + @Component({ + selector: 'app-second', + standalone: true, + template: '

second works!

', + }) + export class SecondRoute { + constructor() { + throw new Error('render failure'); + } + } + + export const routes: Routes = [ + { path: '', component: HomeRoute }, + { path: 'second', component: SecondRoute }, + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: 'second', renderMode: RenderMode.Prerender }, + { path: '**', renderMode: RenderMode.Prerender }, + ]; + `, + }); + + const { message } = await expectToFail(() => ng('build', '--output-mode=server')); + + match(message, /An error occurred while prerendering route '\/second'\./); + + await expectFileNotToExist('dist/test-project/browser/second/index.html'); + + // prerendered-routes.json should only contain successfully prerendered routes if emitted + const statsPath = 'dist/test-project/prerendered-routes.json'; + if (existsSync(statsPath)) { + const stats = JSON.parse(await readFile(statsPath)); + assert.strictEqual(stats.routes['/second'], undefined); + } +} diff --git a/tests/e2e/tests/build/prerender/error-with-sourcemaps.ts b/tests/e2e/tests/build/prerender/error-with-sourcemaps.ts new file mode 100644 index 000000000000..875638877fbd --- /dev/null +++ b/tests/e2e/tests/build/prerender/error-with-sourcemaps.ts @@ -0,0 +1,52 @@ +import { ng } from '../../../utils/process'; +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { match } from 'node:assert'; +import { expectToFail } from '../../../utils/utils'; +import { useSha } from '../../../utils/project'; +import { installWorkspacePackages } from '../../../utils/packages'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + return; + } + + // Forcibly remove in case another test doesn't clean itself up. + await rimraf('node_modules/@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + 'src/app/app.ts': ` + import { Component, signal } from '@angular/core'; + import { CommonModule } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + + @Component({ + selector: 'app-root', + imports: [CommonModule, RouterOutlet], + templateUrl: './app.html', + styleUrls: ['./app.css'] + }) + export class App { + protected readonly title = signal('test-ssr'); + + constructor() { + console.log(window) + } + } + `, + }); + + const { message } = await expectToFail(() => + ng('build', '--configuration', 'development', '--prerender'), + ); + match( + message, + // When babel is used it will add names to the sourcemap and `constructor` will be used in the stack trace. + // This will currently only happen if AOT and script optimizations are set which enables advanced optimizations. + /window is not defined[.\s\S]*(?:constructor|_App) \(.*app\.ts\:\d+:\d+\)/, + ); +} diff --git a/tests/e2e/tests/build/prerender/http-requests-assets.ts b/tests/e2e/tests/build/prerender/http-requests-assets.ts new file mode 100644 index 000000000000..71288b3c242e --- /dev/null +++ b/tests/e2e/tests/build/prerender/http-requests-assets.ts @@ -0,0 +1,92 @@ +import { ng } from '../../../utils/process'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // Not supported by the webpack based builder. + return; + } + + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Add http client and route + 'src/app/app.config.ts': ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import {Home} from './home/home'; + import { provideClientHydration } from '@angular/platform-browser'; + import { provideHttpClient, withFetch } from '@angular/common/http'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter([{ + path: '', + component: Home, + }]), + provideClientHydration(), + provideHttpClient(withFetch()), + ], + }; + `, + + // Add asset + 'public/media.json': JSON.stringify({ dataFromAssets: true }), + 'public/media with-space.json': JSON.stringify({ dataFromAssetsWithSpace: true }), + + // Update component to do an HTTP call to asset. + 'src/app/app.ts': ` + import { ChangeDetectorRef, Component, inject } from '@angular/core'; + import { CommonModule } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + import { HttpClient } from '@angular/common/http'; + + @Component({ + selector: 'app-root', + imports: [CommonModule, RouterOutlet], + template: \` +

{{ data | json }}

+

{{ dataWithSpace | json }}

+ + \`, + }) + export class App { + data: any; + dataWithSpace: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); + + constructor() { + const http = inject(HttpClient); + http.get('/media.json').subscribe((d) => { + this.data = d; + this.cdr.markForCheck(); + }); + + http.get('/media%20with-space.json').subscribe((d) => { + this.dataWithSpace = d; + this.cdr.markForCheck(); + }); + } + } + `, + }); + + await ng('generate', 'component', 'home'); + await ng('build', '--configuration=production', '--prerender'); + await expectFileToMatch( + 'dist/test-project/browser/index.html', + /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/, + ); + await expectFileToMatch( + 'dist/test-project/browser/index.html', + /

{[\S\s]*"dataFromAssetsWithSpace":[\s\S]*true[\S\s]*}<\/p>/, + ); +} diff --git a/tests/e2e/tests/build/prod-build.ts b/tests/e2e/tests/build/prod-build.ts new file mode 100644 index 000000000000..dee45876e379 --- /dev/null +++ b/tests/e2e/tests/build/prod-build.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import { statSync } from 'node:fs'; +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist, expectFileToMatch, readFile } from '../../utils/fs'; +import { noSilentNg } from '../../utils/process'; + +function verifySize(bundle: string, baselineBytes: number) { + const size = statSync(`dist/test-project/browser/${bundle}`).size; + const percentageBaseline = (baselineBytes * 10) / 100; + const maxSize = baselineBytes + percentageBaseline; + const minSize = baselineBytes - percentageBaseline; + + assert( + size < maxSize, + `Expected ${bundle} size to be less than ${maxSize / 1024}Kb but it was ${size / 1024}Kb.`, + ); + + assert( + size > minSize, + `Expected ${bundle} size to be greater than ${minSize / 1024}Kb but it was ${size / 1024}Kb.`, + ); +} + +export default async function () { + await noSilentNg('build'); + await expectFileToExist(join(process.cwd(), 'dist')); + // Check for cache busting hash script src + if (getGlobalVariable('argv')['esbuild']) { + // esbuild uses an 8 character hash and a dash as separator + await expectFileToMatch('dist/test-project/browser/index.html', /main-[0-9a-zA-Z]{8}\.js/); + await expectFileToMatch('dist/test-project/browser/index.html', /styles-[0-9a-zA-Z]{8}\.css/); + await expectFileToMatch('dist/test-project/3rdpartylicenses.txt', /MIT/); + } else { + await expectFileToMatch('dist/test-project/browser/index.html', /main\.[0-9a-zA-Z]{16}\.js/); + await expectFileToMatch('dist/test-project/browser/index.html', /styles\.[0-9a-zA-Z]{16}\.css/); + await expectFileToMatch('dist/test-project/browser/3rdpartylicenses.txt', /MIT/); + } + + const indexContent = await readFile('dist/test-project/browser/index.html'); + const mainSrcRegExp = getGlobalVariable('argv')['esbuild'] + ? /src="(main-[0-9a-zA-Z]{8}\.js)"/ + : /src="(main\.[0-9a-zA-Z]{16}\.js)"/; + const mainPath = indexContent.match(mainSrcRegExp)![1]; + + // Size checks in bytes + verifySize(mainPath, 210000); +} diff --git a/tests/e2e/tests/build/progress-and-stats.ts b/tests/e2e/tests/build/progress-and-stats.ts new file mode 100644 index 000000000000..940179df052e --- /dev/null +++ b/tests/e2e/tests/build/progress-and-stats.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { getGlobalVariable } from '../../utils/env'; +import { ng } from '../../utils/process'; + +export default async function () { + const { stderr: stderrProgress, stdout } = await ng('build', '--progress'); + assert.match(stdout, /Initial total/); + assert.match(stdout, /Estimated transfer size/); + + let logs; + if (getGlobalVariable('argv')['esbuild']) { + assert.match(stdout, /Building\.\.\./); + + return; + } else { + logs = [ + 'Browser application bundle generation complete', + 'Copying assets complete', + 'Index html generation complete', + ]; + } + + for (const log of logs) { + assert.match(stderrProgress, new RegExp(log)); + } + + const { stderr: stderrNoProgress } = await ng('build', '--no-progress'); + for (const log of logs) { + assert.doesNotMatch(stderrNoProgress, new RegExp(log)); + } +} diff --git a/tests/e2e/tests/build/project-name.ts b/tests/e2e/tests/build/project-name.ts new file mode 100644 index 000000000000..309ba4d8e897 --- /dev/null +++ b/tests/e2e/tests/build/project-name.ts @@ -0,0 +1,8 @@ +import { silentNg } from '../../utils/process'; + +export default async function () { + // Named Development build + await silentNg('build', 'test-project', '--configuration=development'); + await silentNg('build', '--configuration=development', 'test-project', '--no-progress'); + await silentNg('build', '--configuration=development', '--no-progress', 'test-project'); +} diff --git a/tests/e2e/tests/build/rebuild-deps-type-check.ts b/tests/e2e/tests/build/rebuild-deps-type-check.ts new file mode 100644 index 000000000000..1f4964f6689b --- /dev/null +++ b/tests/e2e/tests/build/rebuild-deps-type-check.ts @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, prependToFile, writeFile } from '../../utils/fs'; +import { execAndWaitForOutputToMatch, waitForAnyProcessOutputToMatch } from '../../utils/process'; + +const doneRe = getGlobalVariable('argv')['esbuild'] + ? /Application bundle generation complete\./ + : / Compiled successfully\.|: Failed to compile\./; +const errorRe = /Error/i; + +export default function () { + // TODO(architect): Delete this test. It is now in devkit/build-angular. + + if (process.platform.startsWith('win')) { + return Promise.resolve(); + } + + return ( + Promise.resolve() + // Create and import files. + .then(() => + writeFile( + 'src/funky2.ts', + ` + export function funky2(value: string): string { + return value + 'hello'; + } + `, + ), + ) + .then(() => + writeFile( + 'src/funky.ts', + ` + export * from './funky2'; + `, + ), + ) + .then(() => + prependToFile( + 'src/main.ts', + ` + import { funky2 } from './funky'; + `, + ), + ) + .then(() => + appendToFile( + 'src/main.ts', + ` + console.log(funky2('town')); + `, + ), + ) + // Should trigger a rebuild, no error expected. + .then(() => execAndWaitForOutputToMatch('ng', ['serve'], doneRe)) + // Make an invalid version of the file. + // Should trigger a rebuild, this time an error is expected. + .then(() => + Promise.all([ + waitForAnyProcessOutputToMatch(errorRe, 20000), + writeFile( + 'src/funky2.ts', + ` + export function funky2(value: number): number { + return value + 1; + } + `, + ), + ]), + ) + .then((results) => { + const { stderr } = results[0]; + assert.match( + stderr, + /Argument of type 'string' is not assignable to parameter of type 'number'/, + ); + }) + // Change an UNRELATED file and the error should still happen. + // Should trigger a rebuild, this time an error is also expected. + .then(() => + Promise.all([ + waitForAnyProcessOutputToMatch(errorRe, 20000), + appendToFile( + 'src/app/app.config.ts', + ` + function anything(): number { return 1; } + `, + ), + ]), + ) + .then((results) => { + const { stderr } = results[0]; + assert.match( + stderr, + /Argument of type 'string' is not assignable to parameter of type 'number'/, + ); + }) + // Fix the error! + .then(() => + Promise.all([ + waitForAnyProcessOutputToMatch(doneRe, 20000), + writeFile( + 'src/funky2.ts', + ` + export function funky2(value: string): string { + return value + 'hello'; + } + `, + ), + ]), + ) + .then((results) => { + const { stderr } = results[0]; + assert.doesNotMatch( + stderr, + /Argument of type 'string' is not assignable to parameter of type 'number'/, + ); + }) + ); +} diff --git a/tests/e2e/tests/build/rebuild-dot-dirname.ts b/tests/e2e/tests/build/rebuild-dot-dirname.ts new file mode 100644 index 000000000000..ed5f12ed94c1 --- /dev/null +++ b/tests/e2e/tests/build/rebuild-dot-dirname.ts @@ -0,0 +1,63 @@ +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, createDir, rimraf } from '../../utils/fs'; +import { installWorkspacePackages } from '../../utils/packages'; +import { killAllProcesses, ng, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { ngServe, updateJsonFile, useSha } from '../../utils/project'; + +const goodRegEx = getGlobalVariable('argv')['esbuild'] + ? /Application bundle generation complete\./ + : / Compiled successfully\./; + +export default async function () { + const originalCwd = process.cwd(); + // Delete angular.json so that we can create a new app. + await rimraf('angular.json'); + await createDir('./.subdirectory'); + + try { + process.chdir('./.subdirectory'); + + await ng('new', 'subdirectory-test-project', '--skip-install'); + process.chdir('./subdirectory-test-project'); + + await useSha(); + await installWorkspacePackages(); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['subdirectory-test-project']['architect']['build']; + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + outputPath: 'dist/subdirectory-test-project', + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + buildOptimizer: false, + }; + + const serve = json['projects']['subdirectory-test-project']['architect']['serve']; + serve.builder = '@angular-devkit/build-angular:dev-server'; + }); + } + + await ngServe(); + + // Wait before editing a file. + await setTimeout(1000); + await appendToFile('src/main.ts', 'console.log(1);'); + await waitForAnyProcessOutputToMatch(goodRegEx); + } finally { + process.chdir(originalCwd); + await killAllProcesses(); + await setTimeout(100); + } +} diff --git a/tests/e2e/tests/build/rebuild-symlink.ts b/tests/e2e/tests/build/rebuild-symlink.ts new file mode 100644 index 000000000000..d06c1e559a5f --- /dev/null +++ b/tests/e2e/tests/build/rebuild-symlink.ts @@ -0,0 +1,42 @@ +import { symlink } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { setTimeout } from 'node:timers/promises'; +import { appendToFile, expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; +import { execAndWaitForOutputToMatch, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +const buildReadyRegEx = getGlobalVariable('argv')['esbuild'] + ? /Application bundle generation complete\./ + : /Build at: /; + +export default async function () { + await updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].architect.build.options.preserveSymlinks = true; + }); + + await writeMultipleFiles({ + 'src/link-source.ts': '// empty file', + 'src/main.ts': `import './link-dest';`, + }); + + await symlink(resolve('src/link-source.ts'), resolve('src/link-dest.ts')); + + await execAndWaitForOutputToMatch( + 'ng', + ['build', '--watch', '--configuration=development'], + buildReadyRegEx, + ); + + await setTimeout(200); + + // Trigger a rebuild + await Promise.all([ + waitForAnyProcessOutputToMatch(buildReadyRegEx), + appendToFile('src/link-source.ts', `\nconsole.log('foo-bar');`), + ]); + + await setTimeout(200); + + await expectFileToMatch('dist/test-project/browser/main.js', /console\.log\(["']foo-bar["']\);/); +} diff --git a/tests/e2e/tests/build/relative-sourcemap.ts b/tests/e2e/tests/build/relative-sourcemap.ts new file mode 100644 index 000000000000..209e29aabd76 --- /dev/null +++ b/tests/e2e/tests/build/relative-sourcemap.ts @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import { isAbsolute } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + // General secondary application project + await ng('generate', 'application', 'secondary-project', '--skip-install'); + // Setup webpack builder if esbuild is not requested on the commandline + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['secondary-project']['architect']['build']; + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + outputPath: 'dist/secondary-project', + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + buildOptimizer: false, + }; + }); + } + + await ng('build', 'secondary-project', '--configuration=development'); + await ng('build', '--output-hashing=none', '--source-map', '--configuration=development'); + + const sourceMapPath = getGlobalVariable('argv')['esbuild'] + ? './dist/secondary-project/browser/main.js.map' + : './dist/secondary-project/main.js.map'; + const content = fs.readFileSync(sourceMapPath, 'utf8'); + const { sources } = JSON.parse(content) as { sources: string[] }; + let mainFileFound = false; + for (const source of sources) { + assert(!isAbsolute(source), `Expected ${source} to be relative.`); + + if (source.endsWith('main.ts')) { + mainFileFound = true; + assert( + source === 'projects/secondary-project/src/main.ts' || + source === './projects/secondary-project/src/main.ts', + `Expected main file ${source} to be relative to the workspace root.`, + ); + } + } + + assert(mainFileFound, 'Could not find the main file in the application sourcemap sources array.'); +} diff --git a/tests/e2e/tests/build/scripts-output-hashing.ts b/tests/e2e/tests/build/scripts-output-hashing.ts new file mode 100644 index 000000000000..8b34662c485e --- /dev/null +++ b/tests/e2e/tests/build/scripts-output-hashing.ts @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import { getGlobalVariable } from '../../utils/env'; +import { + expectFileMatchToExist, + expectFileToMatch, + writeFile, + writeMultipleFiles, +} from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +function getScriptsFilename(): Promise { + if (getGlobalVariable('argv')['esbuild']) { + return expectFileMatchToExist('dist/test-project/browser/', /external-module-[0-9A-Z]{8}\.js/); + } else { + return expectFileMatchToExist( + 'dist/test-project/browser/', + /external-module\.[0-9a-f]{16}\.js/, + ); + } +} + +export default async function () { + // verify content hash is based on code after optimizations + await writeMultipleFiles({ + 'src/script.js': 'try { console.log(); } catch {}', + }); + await updateJsonFile('angular.json', (configJson) => { + const build = configJson.projects['test-project'].architect.build; + build.options['scripts'] = [ + { + input: 'src/script.js', + inject: true, + bundleName: 'external-module', + }, + ]; + build.configurations['production'].outputHashing = 'all'; + configJson['cli'] = { cache: { enabled: 'false' } }; + }); + + // Chrome 65 does not support optional catch in try/catch blocks. + await writeFile('.browserslistrc', 'Chrome 65'); + + await ng('build', '--configuration=production'); + const filenameBuild1 = await getScriptsFilename(); + await expectFileToMatch( + `dist/test-project/browser/${filenameBuild1}`, + 'try{console.log()}catch(c){}', + ); + + await writeFile('.browserslistrc', 'last 1 Chrome version'); + + await ng('build', '--configuration=production'); + const filenameBuild2 = await getScriptsFilename(); + await expectFileToMatch( + `dist/test-project/browser/${filenameBuild2}`, + 'try{console.log()}catch{}', + ); + + assert.notEqual( + filenameBuild1, + filenameBuild2, + 'Contents of the built file changed between builds, but the content hash stayed the same!', + ); +} diff --git a/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts b/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts new file mode 100644 index 000000000000..ad10738c759f --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts @@ -0,0 +1,117 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + if (!useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project']['architect']['build']; + build.options.outputMode = undefined; + build.configurations.production.prerender = false; + }); + + await updateServerFileForEsbuild('src/server.ts'); + } + + await writeMultipleFiles({ + 'src/app/app.css': `div { color: #000 }`, + 'src/styles.css': `* { color: #000 }`, + 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; + import { App } from './app/app'; + import { appConfig } from './app/app.config'; + + (window as any)['doBootstrap'] = () => { + bootstrapApplication(App, appConfig).catch((err) => console.error(err)); + }; + `, + 'src/index.html': ` + + + + + + + + + + + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + + const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; + } + + await ng('build'); + + if (useWebpackBuilder) { + // Build server code + await ng('run', 'test-project:server'); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + () => !!(globalThis as any).document.querySelector('style[ng-app-id="ng"]'), + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // style tags all have a nonce attribute + const nonces = await page.$$eval('style', (styles) => + styles.map((s) => s.getAttribute('nonce')), + ); + for (const nonce of nonces) { + if (nonce !== '{% nonce %}') { + throw new Error(`Expected nonce to be '{% nonce %}', but got '${nonce}'`); + } + } + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts b/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts new file mode 100644 index 000000000000..8b718c14b162 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts @@ -0,0 +1,130 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + + await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + + if (useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project-two']['architect']['build']; + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + buildOptimizer: false, + }; + }); + } + + await ng( + 'add', + '@angular/ssr', + '--skip-confirmation', + '--skip-install', + '--project=test-project-two', + ); + + await useSha(); + await installWorkspacePackages(); + + if (!useWebpackBuilder) { + // Disable prerendering + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project-two']['architect']['build']; + build.configurations.production.prerender = false; + build.options.outputMode = undefined; + }); + + await updateServerFileForEsbuild('projects/test-project-two/src/server.ts'); + } + + await writeMultipleFiles({ + 'projects/test-project-two/src/app/app.css': `div { color: #000 }`, + 'projects/test-project-two/src/styles.css': `* { color: #000 }`, + 'projects/test-project-two/src/main.ts': ` + import { platformBrowser } from '@angular/platform-browser'; + import { AppModule } from './app/app-module'; + + (window as any)['doBootstrap'] = () => { + platformBrowser() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); + }; + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + + const runCommand = useWebpackBuilder ? 'serve:ssr' : `serve:ssr:test-project-two`; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; + } + + await ng('build', 'test-project-two'); + + if (useWebpackBuilder) { + // Build server code + await ng('run', `test-project-two:server`); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + `!!document.querySelector('style[ng-app-id="ng"]')`, + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts b/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts new file mode 100644 index 000000000000..ce141c862c30 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts @@ -0,0 +1,96 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + + if (!useWebpackBuilder) { + // Disable prerendering + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project']['architect']['build']; + build.options.outputMode = undefined; + }); + + await updateServerFileForEsbuild('src/server.ts'); + } + + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + 'src/app/app.css': `div { color: #000 }`, + 'src/styles.css': `* { color: #000 }`, + 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; + import { App } from './app/app'; + import { appConfig } from './app/app.config'; + + (window as any)['doBootstrap'] = () => { + bootstrapApplication(App, appConfig).catch((err) => console.error(err)); + }; + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; + } + + await ng('build'); + if (useWebpackBuilder) { + // Build server code + await ng('run', `test-project:server`); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + `!!document.querySelector('style[ng-app-id="ng"]')`, + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts new file mode 100644 index 000000000000..52ceafa7b05f --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert'; +import { ng } from '../../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { updateJsonFile, useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project']['architect']['build']; + build.options.externalDependencies = [ + '@angular/platform-browser', + '@angular/core', + '@angular/router', + '@angular/common', + '@angular/common/http', + '@angular/platform-browser/animations', + ]; + }); + + await ng('build'); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts new file mode 100644 index 000000000000..aa6f7e3426ee --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts @@ -0,0 +1,119 @@ +import { join } from 'node:path'; +import assert from 'node:assert'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; +import { langTranslations, setupI18nConfig } from '../../i18n/setup'; +import { findFreePort } from '../../../utils/network'; +import { getGlobalVariable } from '../../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Setup project + await setupI18nConfig(); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Ssr } from './ssr/ssr'; + import { Ssg } from './ssg/ssg'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: 'ssr', + component: Ssr, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: '', + renderMode: RenderMode.Prerender, + }, + { + path: 'ssg', + renderMode: RenderMode.Prerender, + }, + { + path: '**', + renderMode: RenderMode.Server, + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg', 'csr', 'ssr']; + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + await noSilentNg('build', '--output-mode=server', '--base-href=/base/'); + + for (const { lang, outputPath } of langTranslations) { + await expectFileToMatch(join(outputPath, 'index.html'), `

${lang}

`); + await expectFileToMatch(join(outputPath, 'ssg/index.html'), `

${lang}

`); + } + + // Tests responses + const port = await spawnServer(); + const pathnamesToVerify = ['/ssr', '/ssg']; + for (const { lang } of langTranslations) { + for (const pathname of pathnamesToVerify) { + const res = await fetch(`http://localhost:${port}/base/${lang}${pathname}`); + const text = await res.text(); + + assert.match( + text, + new RegExp(`

${lang}

`), + `Response for '${lang}${pathname}': '

${lang}

' was not matched in content.`, + ); + } + } +} + +async function spawnServer(): Promise { + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npm', + ['run', 'serve:ssr:test-project'], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts new file mode 100644 index 000000000000..7bc323311b4f --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts @@ -0,0 +1,154 @@ +import { join } from 'node:path'; +import assert from 'node:assert'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; +import { langTranslations, setupI18nConfig } from '../../i18n/setup'; +import { findFreePort } from '../../../utils/network'; +import { getGlobalVariable } from '../../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { updateJsonFile, useSha } from '../../../utils/project'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Setup project + await setupI18nConfig(); + + // Update angular.json + const URL_SUB_PATH: Record = { + 'en-US': '', + 'fr': 'fr', + 'de': 'deutsche', + }; + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const i18n: Record = appProject.i18n; + i18n.sourceLocale = { + subPath: URL_SUB_PATH['en-US'], + }; + + i18n.locales['fr'] = { + translation: i18n.locales['fr'], + subPath: URL_SUB_PATH['fr'], + }; + + i18n.locales['de'] = { + translation: i18n.locales['de'], + subPath: URL_SUB_PATH['de'], + }; + }); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Ssr } from './ssr/ssr'; + import { Ssg } from './ssg/ssg'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: 'ssr', + component: Ssr, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: '', + renderMode: RenderMode.Prerender, + }, + { + path: 'ssg', + renderMode: RenderMode.Prerender, + }, + { + path: '**', + renderMode: RenderMode.Server, + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg', 'ssr']; + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + await noSilentNg('build', '--output-mode=server', '--base-href=/base/'); + + const pathToVerify = ['/index.html', '/ssg/index.html']; + for (const { lang } of langTranslations) { + const subPath = URL_SUB_PATH[lang]; + const outputPath = join('dist/test-project/browser', subPath); + + for (const path of pathToVerify) { + await expectFileToMatch(join(outputPath, path), `

${lang}

`); + const baseHref = `/base/${subPath ? `${subPath}/` : ''}`; + await expectFileToMatch(join(outputPath, path), ``); + } + } + + // Tests responses + const port = await spawnServer(); + const pathnamesToVerify = ['/ssr', '/ssg']; + + for (const { lang } of langTranslations) { + for (const pathname of pathnamesToVerify) { + const subPath = URL_SUB_PATH[lang]; + const urlPathname = `/base${subPath ? `/${subPath}` : ''}${pathname}`; + const res = await fetch(`http://localhost:${port}${urlPathname}`); + const text = await res.text(); + + assert.match( + text, + new RegExp(`

${lang}

`), + `Response for '${urlPathname}': '

${lang}

' was not matched in content.`, + ); + } + } +} + +async function spawnServer(): Promise { + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npm', + ['run', 'serve:ssr:test-project'], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts new file mode 100644 index 000000000000..efbff9871bbc --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts @@ -0,0 +1,130 @@ +import { join } from 'node:path'; +import assert from 'node:assert'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; +import { langTranslations, setupI18nConfig } from '../../i18n/setup'; +import { findFreePort } from '../../../utils/network'; +import { getGlobalVariable } from '../../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Setup project + await setupI18nConfig(); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Ssr } from './ssr/ssr'; + import { Ssg } from './ssg/ssg'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: 'ssr', + component: Ssr, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: '', + renderMode: RenderMode.Prerender, + }, + { + path: 'ssg', + renderMode: RenderMode.Prerender, + }, + { + path: '**', + renderMode: RenderMode.Server, + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg', 'ssr']; + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + await noSilentNg('build', '--output-mode=server'); + + const expects: Record = { + 'index.html': 'home works!', + 'ssg/index.html': 'ssg works!', + }; + + for (const { lang, outputPath } of langTranslations) { + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join(outputPath, filePath), `

${lang}

`); + await expectFileToMatch(join(outputPath, filePath), fileMatch); + } + } + + // Tests responses + const port = await spawnServer(); + const pathname = '/ssr'; + + // We run the tests twice to ensure that the locale ID is set correctly. + for (const iteration of [1, 2]) { + for (const { lang, translation } of langTranslations) { + const res = await fetch(`http://localhost:${port}/${lang}${pathname}`); + const text = await res.text(); + + for (const match of [`

${translation.date}

`, `

${lang}

`]) { + assert.match( + text, + new RegExp(match), + `Response for '${lang}${pathname}': '${match}' was not matched in content. Iteration: ${iteration}.`, + ); + } + } + } +} + +async function spawnServer(): Promise { + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npm', + ['run', 'serve:ssr:test-project'], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts new file mode 100644 index 000000000000..dff15d055943 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts @@ -0,0 +1,133 @@ +import { join } from 'node:path'; +import { existsSync } from 'node:fs'; +import assert from 'node:assert'; +import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; +import { + installPackage, + installWorkspacePackages, + uninstallPackage, +} from '../../../utils/packages'; +import { updateJsonFile, useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; +import { findFreePort } from '../../../utils/network'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await installPackage('h3@1'); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Ssr } from './ssr/ssr'; + import { SsgWithParams } from './ssg-with-params/ssg-with-params'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssr', + component: Ssr, + }, + { + path: 'ssg/:id', + component: SsgWithParams, + }, + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: 'ssg/:id', + renderMode: RenderMode.Prerender, + getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}], + }, + { + path: 'ssr', + renderMode: RenderMode.Server, + }, + { + path: '**', + renderMode: RenderMode.Prerender, + }, + ]; + `, + 'src/server.ts': ` + import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; + import { createApp, createRouter, toWebHandler, defineEventHandler, toWebRequest } from 'h3'; + + export const app = createApp(); + const router = createRouter(); + const angularAppEngine = new AngularAppEngine(); + + router.use( + '/**', + defineEventHandler((event) => angularAppEngine.handle(toWebRequest(event))), + ); + + app.use(router); + export const reqHandler = createRequestHandler(toWebHandler(app)); + `, + }); + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssr', 'ssg-with-params']; + + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + await updateJsonFile('angular.json', (json) => { + const buildTarget = json['projects']['test-project']['architect']['build']; + const options = buildTarget['options']; + options['ssr']['platform'] = 'neutral'; + options['outputMode'] = 'server'; + options['security'] ??= {}; + options['security']['allowedHosts'] = ['localhost']; + }); + + await noSilentNg('build'); + + // Valid SSG pages work + const expects: Record = { + 'index.html': 'home works!', + 'ssg/one/index.html': 'ssg-with-params works!', + 'ssg/two/index.html': 'ssg-with-params works!', + }; + + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); + } + + const filesDoNotExist: string[] = ['csr/index.html', 'ssr/index.html', 'redirect/index.html']; + for (const filePath of filesDoNotExist) { + const file = join('dist/test-project/browser', filePath); + assert.equal(existsSync(file), false, `Expected '${file}' to not exist.`); + } + + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npx', + ['-y', 'listhen@1', './dist/test-project/server/server.mjs', `--port=${port}`], + /Server initialized/, + ); + + const res = await fetch(`http://localhost:${port}/ssr`); + const text = await res.text(); + assert.match(text, new RegExp('ssr works!')); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts new file mode 100644 index 000000000000..a922d9e142e7 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts @@ -0,0 +1,215 @@ +import { join } from 'node:path'; +import { existsSync } from 'node:fs'; +import assert from 'node:assert'; +import { expectFileToMatch, readFile, replaceInFile, writeFile } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; +import { findFreePort } from '../../../utils/network'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Test scenario to verify that the content length, including \r\n, is accurate + await replaceInFile('src/app/app.ts', "title = signal('", "title = signal('Title\\r\\n"); + + // Ensure text has been updated. + assert.match(await readFile('src/app/app.ts'), /title = signal\('Title/); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Csr } from './csr/csr'; + import { Ssr } from './ssr/ssr'; + import { Ssg } from './ssg/ssg'; + import { SsgWithParams } from './ssg-with-params/ssg-with-params'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: 'ssr', + component: Ssr, + }, + { + path: 'csr', + component: Csr, + }, + { + path: 'redirect', + redirectTo: 'ssg' + }, + { + path: 'ssg/:id', + component: SsgWithParams, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: 'ssg/:id', + renderMode: RenderMode.Prerender, + headers: { 'x-custom': 'ssg-with-params' }, + getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}, {id: "customer's-choice"}], + }, + { + path: 'ssr', + renderMode: RenderMode.Server, + headers: { 'x-custom': 'ssr' }, + }, + { + path: 'csr', + renderMode: RenderMode.Client, + headers: { 'x-custom': 'csr' }, + }, + { + path: '**', + renderMode: RenderMode.Prerender, + headers: { 'x-custom': 'ssg' }, + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg', 'ssg-with-params', 'csr', 'ssr']; + + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + // Generate app-shell + await ng('g', 'app-shell'); + + await noSilentNg('build', '--output-mode=server'); + + const expects: Record = { + 'index.html': 'home works!', + 'ssg/index.html': 'ssg works!', + 'ssg/one/index.html': 'ssg-with-params works!', + 'ssg/two/index.html': 'ssg-with-params works!', + "ssg/customer's-choice/index.html": 'ssg-with-params works!', + }; + + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); + } + + const filesDoNotExist: string[] = ['csr/index.html', 'ssr/index.html', 'redirect/index.html']; + for (const filePath of filesDoNotExist) { + const file = join('dist/test-project/browser', filePath); + assert.equal(existsSync(file), false, `Expected '${file}' to not exist.`); + } + + // Tests responses + const responseExpects: Record< + string, + { headers: Record; content: string; serverContext: string } + > = { + '/': { + content: 'home works', + serverContext: 'ng-server-context="ssg"', + headers: { + 'x-custom': 'ssg', + }, + }, + '/ssg': { + content: 'ssg works!', + serverContext: 'ng-server-context="ssg"', + headers: { + 'x-custom': 'ssg', + }, + }, + '/ssr': { + content: 'ssr works!', + serverContext: 'ng-server-context="ssr"', + headers: { + 'x-custom': 'ssr', + }, + }, + '/csr': { + content: 'app-shell works', + serverContext: 'ng-server-context="ssg"', + headers: { + 'x-custom': 'csr', + }, + }, + '/redirect': { + content: 'ssg works!', + serverContext: 'ng-server-context="ssg"', + headers: { + 'x-custom': 'ssg', + }, + }, + }; + + const port = await spawnServer(); + for (const [pathname, { content, headers, serverContext }] of Object.entries(responseExpects)) { + // NOTE: A global 'UND_ERR_SOCKET' may occur due to an incorrect Content-Length header value. + const res = await fetch(`http://localhost:${port}${pathname}`); + const text = await res.text(); + + assert.match( + text, + new RegExp(content), + `Response for '${pathname}': ${content} was not matched in content.`, + ); + + assert.match( + text, + new RegExp(serverContext), + `Response for '${pathname}': ${serverContext} was not matched in content.`, + ); + + for (const [name, value] of Object.entries(headers)) { + assert.equal( + res.headers.get(name), + value, + `Response for '${pathname}': ${name} header value did not match expected.`, + ); + } + } +} + +async function spawnServer(): Promise { + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npm', + ['run', 'serve:ssr:test-project'], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts new file mode 100644 index 000000000000..b565144b37bf --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts @@ -0,0 +1,130 @@ +import assert, { match } from 'node:assert'; +import { readFile, writeMultipleFiles } from '../../../utils/fs'; +import { ng, noSilentNg, silentNg } from '../../../utils/process'; +import { getGlobalVariable } from '../../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Add asset + 'public/media.json': JSON.stringify({ dataFromAssets: true }), + // Update component to do an HTTP call to asset and API. + 'src/app/app.ts': ` + import { ChangeDetectorRef, Component, inject } from '@angular/core'; + import { JsonPipe } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + import { HttpClient } from '@angular/common/http'; + + @Component({ + selector: 'app-root', + imports: [JsonPipe, RouterOutlet], + template: \` +

{{ assetsData | json }}

+

{{ apiData | json }}

+ + \`, + }) + export class App { + assetsData: any; + apiData: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); + + constructor() { + const http = inject(HttpClient); + + http.get('/media.json').toPromise().then((d) => { + this.assetsData = d; + this.cdr.markForCheck(); + }); + + http.get('/api').toPromise().then((d) => { + this.apiData = d; + this.cdr.markForCheck(); + }); + } + } + `, + // Add http client and route + 'src/app/app.config.ts': ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import { Home } from './home/home'; + import { provideClientHydration } from '@angular/platform-browser'; + import { provideHttpClient, withFetch } from '@angular/common/http'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter([{ + path: 'home', + component: Home, + }]), + provideClientHydration(), + provideHttpClient(withFetch()), + ], + }; + `, + 'src/server.ts': ` + import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node'; + import express from 'express'; + import { join } from 'node:path'; + + export function app(): express.Express { + const server = express(); + const browserDistFolder = join(import.meta.dirname, '../browser'); + const angularNodeAppEngine = new AngularNodeAppEngine(); + + server.get('/api', (req, res) => { + res.json({ dataFromAPI: true }) + }); + + server.use(express.static(browserDistFolder, { + maxAge: '1y', + index: 'index.html' + })); + + server.use((req, res, next) => { + angularNodeAppEngine.handle(req) + .then((response) => response ? writeResponseToNodeResponse(response, res) : next()) + .catch(next); + }); + return server; + } + + const server = app(); + + if (isMainModule(import.meta.url)) { + const port = process.env['PORT'] || 4000; + server.listen(port, (error) => { + if (error) { + throw error; + } + console.log(\`Node Express server listening on http://localhost:\${port}\`); + }); + } + + export const reqHandler = createNodeRequestHandler(server); + `, + }); + + await silentNg('generate', 'component', 'home'); + + await noSilentNg('build', '--output-mode=static'); + + const contents = await readFile('dist/test-project/browser/home/index.html'); + match(contents, /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/); + match(contents, /

{[\S\s]*"dataFromAPI":[\s\S]*true[\S\s]*}<\/p>/); + match(contents, /home works!/); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n-http-calls.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n-http-calls.ts new file mode 100644 index 000000000000..964c7827c23e --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n-http-calls.ts @@ -0,0 +1,137 @@ +import assert, { match } from 'node:assert'; +import { join } from 'node:path'; +import { readFile, writeMultipleFiles } from '../../../utils/fs'; +import { ng, noSilentNg, silentNg } from '../../../utils/process'; +import { getGlobalVariable } from '../../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; +import { langTranslations, setupI18nConfig } from '../../i18n/setup'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Setup project + await setupI18nConfig(); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Add asset + 'public/media.json': JSON.stringify({ dataFromAssets: true }), + // Update component to do an HTTP call to asset and API. + 'src/app/app.ts': ` + import { ChangeDetectorRef, Component, inject } from '@angular/core'; + import { JsonPipe } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + import { HttpClient } from '@angular/common/http'; + + @Component({ + selector: 'app-root', + imports: [JsonPipe, RouterOutlet], + template: \` +

{{ assetsData | json }}

+

{{ apiData | json }}

+ + \`, + }) + export class App { + assetsData: any; + apiData: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); + + constructor() { + const http = inject(HttpClient); + + http.get('media.json').toPromise().then((d) => { + this.assetsData = d; + this.cdr.markForCheck(); + }); + + http.get('/api').toPromise().then((d) => { + this.apiData = d; + this.cdr.markForCheck(); + }); + } + } + `, + // Add http client and route + 'src/app/app.config.ts': ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import { Home } from './home/home'; + import { provideClientHydration } from '@angular/platform-browser'; + import { provideHttpClient, withFetch } from '@angular/common/http'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter([{ + path: 'home', + component: Home, + }]), + provideClientHydration(), + provideHttpClient(withFetch()), + ], + }; + `, + 'src/server.ts': ` + import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node'; + import express from 'express'; + import { join } from 'node:path'; + + export function app(): express.Express { + const server = express(); + const browserDistFolder = join(import.meta.dirname, '../browser'); + const angularNodeAppEngine = new AngularNodeAppEngine(); + + server.get('/api', (req, res) => { + res.json({ dataFromAPI: true }) + }); + + server.use(express.static(browserDistFolder, { + maxAge: '1y', + index: 'index.html' + })); + + server.use((req, res, next) => { + angularNodeAppEngine.handle(req) + .then((response) => response ? writeResponseToNodeResponse(response, res) : next()) + .catch(next); + }); + return server; + } + + const server = app(); + + if (isMainModule(import.meta.url)) { + const port = process.env['PORT'] || 4000; + server.listen(port, (error) => { + if (error) { + throw error; + } + console.log(\`Node Express server listening on http://localhost:\${port}\`); + }); + } + + export const reqHandler = createNodeRequestHandler(server); + `, + }); + + await silentNg('generate', 'component', 'home'); + + await noSilentNg('build', '--output-mode=static'); + + for (const { lang, outputPath } of langTranslations) { + const contents = await readFile(join(outputPath, 'home/index.html')); + match(contents, /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/); + match(contents, /

{[\S\s]*"dataFromAPI":[\s\S]*true[\S\s]*}<\/p>/); + match(contents, new RegExp(``)); + } +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts new file mode 100644 index 000000000000..245375101946 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts @@ -0,0 +1,105 @@ +import { join } from 'node:path'; +import { existsSync } from 'node:fs'; +import assert from 'node:assert'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { ng, noSilentNg, silentNg } from '../../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; +import { langTranslations, setupI18nConfig } from '../../i18n/setup'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Setup project + await setupI18nConfig(); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + import { Ssg } from './ssg/ssg'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: '**', + component: Home, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: '**', + renderMode: RenderMode.Prerender, + }, + ]; + `, + ); + + await writeFile( + 'src/app/app.config.ts', + ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import { routes } from './app.routes'; + import { provideClientHydration } from '@angular/platform-browser'; + import { APP_BASE_HREF } from '@angular/common'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter(routes), + provideClientHydration(), + { + provide: APP_BASE_HREF, + useValue: '/', + }, + ], + }; + `, + ); + + // Generate components for the above routes + await silentNg('generate', 'component', 'home'); + await silentNg('generate', 'component', 'ssg'); + + await noSilentNg('build', '--output-mode=static'); + + for (const { lang, outputPath } of langTranslations) { + await expectFileToMatch(join(outputPath, 'index.html'), `

${lang}

`); + await expectFileToMatch(join(outputPath, 'ssg/index.html'), `

${lang}

`); + } + + // Check that server directory does not exist + assert( + !existsSync('dist/test-project/server'), + 'Server directory should not exist when output-mode is static', + ); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts new file mode 100644 index 000000000000..362cdc97e09e --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts @@ -0,0 +1,146 @@ +import { join } from 'node:path'; +import { existsSync } from 'node:fs'; +import assert from 'node:assert'; +import { + expectFileNotToExist, + expectFileToMatch, + replaceInFile, + writeFile, +} from '../../../utils/fs'; +import { ng, noSilentNg, silentNg } from '../../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Add routes + await writeFile( + 'src/app/app.routes.ts', + ` + import { inject } from '@angular/core'; + import { Routes, Router } from '@angular/router'; + import { Home } from './home/home'; + import { Ssg } from './ssg/ssg'; + import { SsgWithParams } from './ssg-with-params/ssg-with-params'; + + export const routes: Routes = [ + { + path: '', + component: Home, + }, + { + path: 'ssg', + component: Ssg, + }, + { + path: 'ssg-redirect', + redirectTo: 'ssg' + }, + { + path: 'ssg-redirect-external', + component: Ssg, + }, + { + path: 'ssg-redirect-via-guard', + canActivate: [() => { + return inject(Router).createUrlTree(['ssg'], { queryParams: { foo: 'bar' }}) + }], + }, + { + path: 'ssg/:id', + component: SsgWithParams, + }, + { + path: '**', + component: Home, + }, + ]; + `, + ); + + // Add server routing + await writeFile( + 'src/app/app.routes.server.ts', + ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: 'ssg-redirect-external', + renderMode: RenderMode.Prerender, + headers: { Location: 'https://example.com/docs?from=ssg&next=/ssg' }, + }, + { + path: 'ssg/:id', + renderMode: RenderMode.Prerender, + getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}], + }, + { + path: '**', + renderMode: RenderMode.Server, + }, + ]; + `, + ); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg', 'ssg-with-params']; + + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + // Should error as above we set `RenderMode.Server` + const { message: errorMessage } = await expectToFail(() => + noSilentNg('build', '--output-mode=static'), + ); + assert.match( + errorMessage, + new RegExp( + `Route '/' is configured with server render mode, but the build 'outputMode' is set to 'static'.`, + ), + ); + + // Fix the error + await replaceInFile('src/app/app.routes.server.ts', 'RenderMode.Server', 'RenderMode.Prerender'); + await noSilentNg('build', '--output-mode=static'); + + const expects: Record = { + 'index.html': /ng-server-context="ssg".+home works!/, + 'ssg/index.html': /ng-server-context="ssg".+ssg works!/, + 'ssg/one/index.html': /ng-server-context="ssg".+ssg-with-params works!/, + 'ssg/two/index.html': /ng-server-context="ssg".+ssg-with-params works!/, + // When static redirects are generated as meta tags. + 'ssg-redirect/index.html': '', + // The target of a 'Location' header is HTML escaped before it is written to the page. + 'ssg-redirect-external/index.html': + '', + 'ssg-redirect-via-guard/index.html': + '', + }; + + for (const [filePath, fileMatch] of Object.entries(expects)) { + await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); + } + + // Check that server directory does not exist + assert( + !existsSync('dist/test-project/server'), + 'Server directory should not exist when output-mode is static', + ); + + // Should not prerender the catch all + await expectFileNotToExist(join('dist/test-project/browser/**/index.html')); +} diff --git a/tests/e2e/tests/build/server-rendering/server-routes-preload-links.ts b/tests/e2e/tests/build/server-rendering/server-routes-preload-links.ts new file mode 100644 index 000000000000..697f2234fbf7 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/server-routes-preload-links.ts @@ -0,0 +1,225 @@ +import assert from 'node:assert'; +import { replaceInFile, writeMultipleFiles } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch, execWithEnv, ng, silentNg } from '../../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ngServe, updateJsonFile, useSha } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; +import { findFreePort } from '../../../utils/network'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + appProject.architect['build'].options.namedChunks = true; + }); + + // Add routes + await writeMultipleFiles({ + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + + export const routes: Routes = [ + { + path: '', + loadComponent: () => import('./home/home').then(c => c.Home), + }, + { + path: 'ssg', + loadChildren: () => import('./ssg.routes').then(m => m.routes), + }, + { + path: 'ssr', + loadComponent: () => import('./ssr/ssr').then(c => c.Ssr), + }, + { + path: 'csr', + loadComponent: () => import('./csr/csr').then(c => c.Csr), + }, + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { + path: 'ssr', + renderMode: RenderMode.Server, + }, + { + path: 'csr', + renderMode: RenderMode.Client, + }, + { + path: '**', + renderMode: RenderMode.Prerender, + }, + ]; + `, + 'src/app/cross-dep.ts': `export const foo = 'foo';`, + 'src/app/ssg.routes.ts': ` + import { Routes } from '@angular/router'; + + export const routes: Routes = [ + { + path: '', + loadComponent: () => import('./ssg-component/ssg-component').then(c => c.SsgComponent), + }, + { + path: 'one', + loadComponent: () => import('./ssg-one/ssg-one').then(c => c.SsgOne), + }, + { + path: 'two', + loadComponent: () => import('./ssg-two/ssg-two').then(c => c.SsgTwo), + }, + ];`, + }); + + // Generate components for the above routes + const componentNames: string[] = ['home', 'ssg-component', 'csr', 'ssr', 'ssg-one', 'ssg-two']; + + for (const componentName of componentNames) { + await silentNg('generate', 'component', componentName); + } + + // Add a cross-dependency + await Promise.all([ + replaceInFile( + 'src/app/ssg-one/ssg-one.ts', + `One {`, + `One { + async ngOnInit() { + await import('../cross-dep'); + } + `, + ), + replaceInFile( + 'src/app/ssg-two/ssg-two.ts', + `Two {`, + `Two { + async ngOnInit() { + await import('../cross-dep'); + } + `, + ), + ]); + + // Test both vite and `ng build` + await runTests(await ngServe()); + + // Test with chunk optimization explicitly disabled + await execWithEnv('ng', ['build', '--output-mode=server'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: 'false', + }); + await runTests(await spawnServer()); + + // Test with default build behavior (chunk optimization enabled) + await ng('build', '--output-mode=server'); + await runTests(await spawnServer()); +} + +const RESPONSE_EXPECTS: Record< + string, + { + matches: RegExp[]; + notMatches: RegExp[]; + } +> = { + '/': { + matches: [//], + notMatches: [/ssg\-component/, /ssr/, /csr/, /cross-dep-/], + }, + '/ssg': { + matches: [ + //, + //, + ], + notMatches: [/home/, /ssr/, /csr/, /ssg-one/, /ssg-two/, /cross-dep-/], + }, + '/ssg/one': { + matches: [ + //, + //, + ], + notMatches: [/home/, /ssr/, /csr/, /ssg-two/, /ssg\-component/, /cross-dep-/], + }, + '/ssg/two': { + matches: [ + //, + //, + ], + notMatches: [/home/, /ssr/, /csr/, /ssg-one/, /ssg\-component/, /cross-dep-/], + }, + '/ssr': { + matches: [//], + notMatches: [/home/, /ssg\-component/, /csr/], + }, + '/csr': { + matches: [//], + notMatches: [/home/, /ssg\-component/, /ssr/, /cross-dep-/], + }, +}; + +async function runTests(port: number): Promise { + for (const [pathname, { matches, notMatches }] of Object.entries(RESPONSE_EXPECTS)) { + const res = await fetch(`http://localhost:${port}${pathname}`); + const text = await res.text(); + + for (const match of matches) { + assert.match(text, match, `Response for '${pathname}': ${match} was not matched in content.`); + } + + for (const match of notMatches) { + assert.doesNotMatch( + text, + match, + `Response for '${pathname}': ${match} was matched in content.`, + ); + } + + // Every emitted preload link must resolve successfully. + const preloadLinks = [...text.matchAll(//g)].map( + (match) => match[1], + ); + assert.ok( + preloadLinks.length > 0, + `Response for '${pathname}' should contain at least one modulepreload link.`, + ); + + for (const link of preloadLinks) { + const preloadRes = await fetch(new URL(link, `http://localhost:${port}/`)); + assert.equal( + preloadRes.status, + 200, + `Preload link '${link}' for '${pathname}' should resolve.`, + ); + } + } +} + +async function spawnServer(): Promise { + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'npm', + ['run', 'serve:ssr:test-project'], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + 'NG_ALLOWED_HOSTS': 'localhost', + }, + ); + + return port; +} diff --git a/tests/e2e/tests/build/sourcemap.ts b/tests/e2e/tests/build/sourcemap.ts new file mode 100644 index 000000000000..2e153e637f30 --- /dev/null +++ b/tests/e2e/tests/build/sourcemap.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + + // The below is needed to cache bundles and verify that sourcemaps are generated + // corretly when output-hashing is disabled. + await ng('build', '--output-hashing=bundles', '--source-map', '--configuration=development'); + + await ng('build', '--output-hashing=none', '--source-map'); + await testForSourceMaps(useWebpackBuilder ? 2 : 1); + + await ng('build', '--output-hashing=none', '--source-map', '--configuration=development'); + await testForSourceMaps(useWebpackBuilder ? 3 : 1); +} + +async function testForSourceMaps(expectedNumberOfFiles: number): Promise { + await expectFileToExist('dist/test-project/browser/main.js.map'); + + const files = fs.readdirSync('./dist/test-project/browser'); + + let count = 0; + for (const file of files) { + if (!file.endsWith('.js')) { + continue; + } + + ++count; + + assert(files.includes(file + '.map'), 'Sourcemap not generated for ' + file); + + const content = fs.readFileSync('./dist/test-project/browser/' + file, 'utf8'); + let lastLineIndex = content.lastIndexOf('\n'); + if (lastLineIndex === content.length - 1) { + // Skip empty last line + lastLineIndex = content.lastIndexOf('\n', lastLineIndex - 1); + } + const comment = lastLineIndex !== -1 && content.slice(lastLineIndex).trim(); + assert.equal( + comment, + `//# sourceMappingURL=${file}.map`, + 'Sourcemap comment not generated for ' + file, + ); + } + + assert( + count >= expectedNumberOfFiles, + `Javascript file count is low. Expected ${expectedNumberOfFiles} but found ${count}`, + ); +} diff --git a/tests/e2e/tests/build/styles/bootstrap.ts b/tests/e2e/tests/build/styles/bootstrap.ts new file mode 100644 index 000000000000..ec8c9f7936be --- /dev/null +++ b/tests/e2e/tests/build/styles/bootstrap.ts @@ -0,0 +1,22 @@ +import { writeMultipleFiles } from '../../../utils/fs'; +import { installPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + // Install bootstrap + await installPackage('bootstrap@5'); + + await writeMultipleFiles({ + 'src/styles.scss': ` + @import 'bootstrap/scss/bootstrap'; + `, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; + }); + + await ng('build'); +} diff --git a/tests/e2e/tests/build/styles/include-paths.ts b/tests/e2e/tests/build/styles/include-paths.ts new file mode 100644 index 000000000000..fb1a0326ed9f --- /dev/null +++ b/tests/e2e/tests/build/styles/include-paths.ts @@ -0,0 +1,60 @@ +import { writeMultipleFiles, expectFileToMatch, replaceInFile, createDir } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + await createDir('src/style-paths'); + await writeMultipleFiles({ + 'src/style-paths/_variables.scss': '$primary-color: red;', + 'src/styles.scss': ` + @import 'variables'; + h1 { color: $primary-color; } + `, + 'src/app/app.scss': ` + @import 'variables'; + h2 { color: $primary-color; } + `, + 'src/style-paths/variables.less': '@primary-color: #ADDADD;', + 'src/styles.less': ` + @import 'variables'; + h5 { color: @primary-color; } + `, + 'src/app/app.less': ` + @import 'variables'; + h6 { color: @primary-color; } + `, + }); + + await replaceInFile( + 'src/app/app.ts', + `styleUrl: './app.css\'`, + `styleUrls: ['./app.scss', './app.less']`, + ); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [ + { input: 'src/styles.scss' }, + { input: 'src/styles.less' }, + ]; + appArchitect.build.options.stylePreprocessorOptions = { + includePaths: ['src/style-paths'], + }; + }); + + await ng('build', '--configuration=development'); + await expectFileToMatch('dist/test-project/browser/styles.css', /h1\s*{\s*color: red;\s*}/); + await expectFileToMatch('dist/test-project/browser/main.js', /h2.*{.*color: red;.*}/); + // These checks are for the less files + await expectFileToMatch('dist/test-project/browser/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/); + await expectFileToMatch('dist/test-project/browser/main.js', /h6.*{.*color: #ADDADD;.*}/); + + await ng('build', '--no-aot', '--configuration=development'); + await expectFileToMatch('dist/test-project/browser/styles.css', /h1\s*{\s*color: red;\s*}/); + await expectFileToMatch('dist/test-project/browser/main.js', /h2.*{[\S\s]*color: red;[\S\s]*}/); + await expectFileToMatch('dist/test-project/browser/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /h6.*{[\S\s]*color: #ADDADD;[\S\s]*}/, + ); +} diff --git a/tests/e2e/tests/build/styles/less.ts b/tests/e2e/tests/build/styles/less.ts new file mode 100644 index 000000000000..c5d58d2d3b08 --- /dev/null +++ b/tests/e2e/tests/build/styles/less.ts @@ -0,0 +1,60 @@ +import { + writeMultipleFiles, + deleteFile, + expectFileToMatch, + replaceInFile, +} from '../../../utils/fs'; +import { expectToFail } from '../../../utils/utils'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default function () { + // TODO(architect): Delete this test. It is now in devkit/build-angular. + + return writeMultipleFiles({ + 'src/styles.less': ` + @import './imported-styles.less'; + body { background-color: blue; } + `, + 'src/imported-styles.less': 'p { background-color: red; }', + 'src/app/app.less': ` + .outer { + .inner { + background: #fff; + } + } + `, + }) + .then(() => deleteFile('src/app/app.css')) + .then(() => + updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [{ input: 'src/styles.less' }]; + }), + ) + .then(() => replaceInFile('src/app/app.ts', './app.css', './app.less')) + .then(() => ng('build', '--source-map', '--configuration=development')) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /body\s*{\s*background-color: blue;\s*}/, + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /p\s*{\s*background-color: red;\s*}/, + ), + ) + .then(() => + expectToFail(() => + expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), + ), + ) + .then(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /.outer.*.inner.*background:\s*#[fF]+/, + ), + ); +} diff --git a/tests/e2e/tests/build/styles/loaders.ts b/tests/e2e/tests/build/styles/loaders.ts new file mode 100644 index 000000000000..cbb602ece07b --- /dev/null +++ b/tests/e2e/tests/build/styles/loaders.ts @@ -0,0 +1,43 @@ +import { + writeMultipleFiles, + deleteFile, + expectFileToMatch, + replaceInFile, +} from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + await writeMultipleFiles({ + 'src/styles.scss': ` + @import './imported-styles.scss'; + body { background-color: blue; } + `, + 'src/imported-styles.scss': 'p { background-color: red; }', + 'src/app/app.scss': ` + .outer { + .inner { + background: #fff; + } + } + `, + }); + + await deleteFile('src/app/app.css'); + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; + }); + await replaceInFile('src/app/app.ts', './app.css', './app.scss'); + + await ng('build', '--configuration=development'); + + await expectToFail(() => expectFileToMatch('dist/test-project/browser/styles.css', /exports/)); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /".*module\.exports.*\.outer.*background:/, + ), + ); +} diff --git a/tests/e2e/tests/build/styles/sass-pkg-importer.ts b/tests/e2e/tests/build/styles/sass-pkg-importer.ts new file mode 100644 index 000000000000..8fbb6e74310f --- /dev/null +++ b/tests/e2e/tests/build/styles/sass-pkg-importer.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert'; +import { writeFile } from '../../../utils/fs'; +import { getActivePackageManager, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { isPrereleaseCli, updateJsonFile } from '../../../utils/project'; +import { appendFile } from 'node:fs/promises'; +import { getGlobalVariable } from '../../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // forcibly remove in case another test doesn't clean itself up + await uninstallPackage('@angular/material'); + + const isPrerelease = await isPrereleaseCli(); + const tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + await ng('add', `@angular/material${tag}`, '--skip-confirmation'); + await Promise.all([ + updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = ['src/styles.scss']; + }), + writeFile('src/styles.scss', `@use 'pkg:@angular/material' as mat;`), + ]); + + await ng('build'); +} diff --git a/tests/e2e/tests/build/styles/sass.ts b/tests/e2e/tests/build/styles/sass.ts new file mode 100644 index 000000000000..45fd969b4c7b --- /dev/null +++ b/tests/e2e/tests/build/styles/sass.ts @@ -0,0 +1,54 @@ +import { + writeMultipleFiles, + deleteFile, + expectFileToMatch, + replaceInFile, +} from '../../../utils/fs'; +import { expectToFail } from '../../../utils/utils'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + await writeMultipleFiles({ + 'src/styles.sass': ` +@import './imported-styles.sass' +body + background-color: blue +`, + 'src/imported-styles.sass': ` +p + background-color: red +`, + 'src/app/app.sass': ` +.outer + .inner + background: #fff +`, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [{ input: 'src/styles.sass' }]; + }); + + await deleteFile('src/app/app.css'); + await replaceInFile('src/app/app.ts', './app.css', './app.sass'); + + await ng('build', '--source-map', '--configuration=development'); + + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /body\s*{\s*background-color: blue;\s*}/, + ); + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /p\s*{\s*background-color: red;\s*}/, + ); + await expectToFail(() => + expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /.outer.*.inner.*background:\s*#[fF]+/, + ); +} diff --git a/tests/e2e/tests/build/styles/scss-partial-resolution.ts b/tests/e2e/tests/build/styles/scss-partial-resolution.ts new file mode 100644 index 000000000000..1a555b26e23b --- /dev/null +++ b/tests/e2e/tests/build/styles/scss-partial-resolution.ts @@ -0,0 +1,35 @@ +import { installPackage } from '../../../utils/packages'; +import { writeMultipleFiles, deleteFile, replaceInFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + // Supports resolving node_modules with are pointing to partial files partial files. + // @material/button/button below points to @material/button/_button.scss + // https://unpkg.com/browse/@material/button@14.0.0/_button.scss + + await installPackage('@material/button@14.0.0'); + + await writeMultipleFiles({ + 'src/styles.scss': ` + @use '@material/button/button'; + + @include button.core-styles; + `, + 'src/app/app.scss': ` + @use '@material/button/button'; + + @include button.core-styles; + `, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = ['src/styles.scss']; + }); + + await deleteFile('src/app/app.css'); + await replaceInFile('src/app/app.ts', './app.css', './app.scss'); + + await ng('build', '--configuration=development'); +} diff --git a/tests/e2e/tests/build/styles/scss.ts b/tests/e2e/tests/build/styles/scss.ts new file mode 100644 index 000000000000..69fcc1c0f060 --- /dev/null +++ b/tests/e2e/tests/build/styles/scss.ts @@ -0,0 +1,52 @@ +import { + writeMultipleFiles, + deleteFile, + expectFileToMatch, + replaceInFile, +} from '../../../utils/fs'; +import { expectToFail } from '../../../utils/utils'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + await writeMultipleFiles({ + 'src/styles.scss': ` + @import './imported-styles.scss'; + body { background-color: blue; } + `, + 'src/imported-styles.scss': 'p { background-color: red; }', + 'src/app/app.scss': ` + .outer { + .inner { + background: #fff; + } + } + `, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; + }); + + await deleteFile('src/app/app.css'); + await replaceInFile('src/app/app.ts', './app.css', './app.scss'); + + await ng('build', '--source-map', '--configuration=development'); + + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /body\s*{\s*background-color: blue;\s*}/, + ); + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /p\s*{\s*background-color: red;\s*}/, + ); + await expectToFail(() => + expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /.outer.*.inner.*background:\s*#[fF]+/, + ); +} diff --git a/tests/e2e/tests/build/styles/symlinked-global.ts b/tests/e2e/tests/build/styles/symlinked-global.ts new file mode 100644 index 000000000000..b38663b321e9 --- /dev/null +++ b/tests/e2e/tests/build/styles/symlinked-global.ts @@ -0,0 +1,27 @@ +import { symlinkSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + await writeMultipleFiles({ + 'src/styles.scss': `p { color: red }`, + 'src/styles-for-link.scss': `p { color: blue }`, + }); + + symlinkSync(resolve('src/styles-for-link.scss'), resolve('src/styles-linked.scss')); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.options.styles = ['src/styles.scss', 'src/styles-linked.scss']; + }); + + await ng('build', '--configuration=development'); + await expectFileToMatch('dist/test-project/browser/styles.css', 'red'); + await expectFileToMatch('dist/test-project/browser/styles.css', 'blue'); + + await ng('build', '--preserve-symlinks', '--configuration=development'); + await expectFileToMatch('dist/test-project/browser/styles.css', 'red'); + await expectFileToMatch('dist/test-project/browser/styles.css', 'blue'); +} diff --git a/tests/e2e/tests/build/styles/tailwind-v2.ts b/tests/e2e/tests/build/styles/tailwind-v2.ts new file mode 100644 index 000000000000..f081e040dcb5 --- /dev/null +++ b/tests/e2e/tests/build/styles/tailwind-v2.ts @@ -0,0 +1,74 @@ +import { deleteFile, expectFileToMatch, writeFile } from '../../../utils/fs'; +import { installPackage, uninstallPackage } from '../../../utils/packages'; +import { ng, silentExec } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + // Temporarily turn off caching until the build cache accounts for the presence of tailwind + // and its configuration file. Otherwise cached builds without tailwind will cause test failures. + await ng('cache', 'off'); + + // Create configuration file + await silentExec('npx', 'tailwindcss@2', 'init'); + + // Add Tailwind directives to a component style + await writeFile('src/app/app.css', '@tailwind base; @tailwind components;'); + + // Add Tailwind directives to a global style + await writeFile('src/styles.css', '@tailwind base; @tailwind components;'); + + // Ensure installation warning is present + const { stderr } = await ng('build', '--configuration=development'); + if (!stderr.includes("To enable Tailwind CSS, please install the 'tailwindcss' package.")) { + throw new Error(`Expected tailwind installation warning. STDERR:\n${stderr}`); + } + + // Tailwind directives should be unprocessed with missing package + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ); + + // Install Tailwind + await installPackage('tailwindcss@2'); + + // Build should succeed and process Tailwind directives + await ng('build', '--configuration=development'); + + // Check for Tailwind output + await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); + await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ), + ); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ), + ); + + // Remove configuration file + await deleteFile('tailwind.config.js'); + + // Ensure Tailwind is disabled when no configuration file is present + await ng('build', '--configuration=development'); + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ); + + // Uninstall Tailwind + await uninstallPackage('tailwindcss'); +} diff --git a/tests/e2e/tests/build/styles/tailwind-v3-cjs.ts b/tests/e2e/tests/build/styles/tailwind-v3-cjs.ts new file mode 100644 index 000000000000..c69f56aa7af4 --- /dev/null +++ b/tests/e2e/tests/build/styles/tailwind-v3-cjs.ts @@ -0,0 +1,40 @@ +import { expectFileToMatch, writeFile } from '../../../utils/fs'; +import { installPackage, uninstallPackage } from '../../../utils/packages'; +import { ng, silentExec } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + // Temporarily turn off caching until the build cache accounts for the presence of tailwind + // and its configuration file. Otherwise cached builds without tailwind will cause test failures. + await ng('cache', 'off'); + + // Add type module in package.json. + await updateJsonFile('package.json', (json) => { + json['type'] = 'module'; + }); + + // Install Tailwind + await installPackage('tailwindcss@3'); + + // Create configuration file + await silentExec('npx', 'tailwindcss', 'init'); + + // Add Tailwind directives to a global style + await writeFile('src/styles.css', '@tailwind base; @tailwind components;'); + + // Build should succeed and process Tailwind directives + await ng('build', '--configuration=development'); + + // Check for Tailwind output + await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ), + ); + + // Uninstall Tailwind + await uninstallPackage('tailwindcss'); +} diff --git a/tests/e2e/tests/build/styles/tailwind-v3.ts b/tests/e2e/tests/build/styles/tailwind-v3.ts new file mode 100644 index 000000000000..97700a4c4b3e --- /dev/null +++ b/tests/e2e/tests/build/styles/tailwind-v3.ts @@ -0,0 +1,108 @@ +import { deleteFile, expectFileToMatch, rimraf, writeFile } from '../../../utils/fs'; +import { installPackage, uninstallPackage } from '../../../utils/packages'; +import { ng, silentExec } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + // Temporarily turn off caching until the build cache accounts for the presence of tailwind + // and its configuration file. Otherwise cached builds without tailwind will cause test failures. + await ng('cache', 'off'); + + // In case a previous test installed tailwindcss, clear it. + // (we don't clear node module directories between tests) + await rimraf('node_modules/tailwindcss'); + + // Create configuration file + await silentExec('npx', 'tailwindcss@3', 'init'); + + // Add Tailwind directives to a component style + await writeFile('src/app/app.css', '@tailwind base; @tailwind components;'); + + // Add Tailwind directives to a global style + await writeFile( + 'src/styles.css', + ` + @import url(https://fonts.googleapis.com/css?family=Roboto:400); + @tailwind base; + @tailwind components; + `, + ); + + // Ensure installation warning is present + const { stderr } = await ng('build', '--configuration=development'); + if (!stderr.includes("To enable Tailwind CSS, please install the 'tailwindcss' package.")) { + throw new Error('Expected tailwind installation warning'); + } + + // Tailwind directives should be unprocessed with missing package + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ); + + // Install Tailwind + await installPackage('tailwindcss@3'); + + // Build should succeed and process Tailwind directives + await ng('build', '--configuration=development'); + + // Check for Tailwind output + await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); + await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ), + ); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ), + ); + + // Add Tailwind directives to an imported global style + await writeFile('src/tailwind.scss', '@tailwind base; @tailwind components;'); + await writeFile('src/styles.css', '@import "./tailwind.scss";'); + + // Build should succeed and process Tailwind directives + await ng('build', '--configuration=development'); + + // Check for Tailwind output + await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); + await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ), + ); + await expectToFail(() => + expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ), + ); + + // Remove configuration file + await deleteFile('tailwind.config.js'); + + // Ensure Tailwind is disabled when no configuration file is present + await ng('build', '--configuration=development'); + await expectFileToMatch( + 'dist/test-project/browser/styles.css', + /@tailwind base;\s+@tailwind components;/, + ); + await expectFileToMatch( + 'dist/test-project/browser/main.js', + /@tailwind base;(?:\\n|\s*)@tailwind components;/, + ); + + // Uninstall Tailwind + await uninstallPackage('tailwindcss'); +} diff --git a/tests/e2e/tests/build/ts-paths.ts b/tests/e2e/tests/build/ts-paths.ts new file mode 100644 index 000000000000..1461aaef2636 --- /dev/null +++ b/tests/e2e/tests/build/ts-paths.ts @@ -0,0 +1,53 @@ +import { appendToFile, createDir, replaceInFile, rimraf, writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateTsConfig } from '../../utils/project'; + +export default async function () { + await updateTsConfig((json) => { + json['compilerOptions']['paths'] = { + '@shared': ['./src/app/shared'], + '@shared/*': ['./src/app/shared/*'], + '@root/*': ['./src/*'], + 'src/*': ['./src/*'], + }; + }); + + await createDir('src/app/shared'); + await writeMultipleFiles({ + 'src/meaning-too.ts': 'export var meaning = 42;', + 'src/app/shared/meaning.ts': 'export var meaning = 42;', + 'src/app/shared/index.ts': `export * from './meaning'`, + }); + + await replaceInFile('src/main.ts', './app/app', '@root/app/app'); + await ng('build', '--configuration=development'); + + await updateTsConfig((json) => { + json['compilerOptions']['paths']['*'] = ['./*', './src/app/shared/*']; + }); + + await appendToFile( + 'src/app/app.ts', + ` + import { meaning } from 'src/app/shared/meaning'; + import { meaning as meaning2 } from '@shared'; + import { meaning as meaning3 } from '@shared/meaning'; + import { meaning as meaning4 } from 'meaning'; + import { meaning as meaning5 } from 'src/meaning-too'; + + // need to use imports otherwise they are ignored and + // no error is outputted, even if baseUrl/paths don't work + console.log(meaning) + console.log(meaning2) + console.log(meaning3) + console.log(meaning4) + console.log(meaning5) + `, + ); + + await ng('build', '--configuration=development'); + + // Simulate no package.json file which causes Webpack to have an undefined 'descriptionFileData'. + await rimraf('package.json'); + await ng('build', '--configuration=development'); +} diff --git a/tests/e2e/tests/build/ts-standard-decorators.ts b/tests/e2e/tests/build/ts-standard-decorators.ts new file mode 100644 index 000000000000..05d056675d3b --- /dev/null +++ b/tests/e2e/tests/build/ts-standard-decorators.ts @@ -0,0 +1,37 @@ +import { getGlobalVariable } from '../../utils/env'; +import { ng } from '../../utils/process'; +import { updateJsonFile, updateTsConfig } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + // Update project to disable experimental decorators + await updateTsConfig((json) => { + json['compilerOptions']['experimentalDecorators'] = false; + }); + + // Default production build + await ng('build'); + + // Production build with JIT + await updateJsonFile('angular.json', (json) => { + // Remove bundle budgets to avoid a build error due to the expected increased output size + // of a JIT production build. + json.projects['test-project'].architect.build.configurations.production.budgets = []; + }); + + if (!getGlobalVariable('argv')['esbuild']) { + await ng('build', '--no-aot', '--no-build-optimizer'); + } + + // Default development build + await ng('build', '--configuration=development'); + + // Development build with JIT + await ng('build', '--configuration=development', '--no-aot'); + + // Unit tests (JIT only) + await ng('test', '--no-watch'); + + // Ensure application functions in a browser + await executeBrowserTest(); +} diff --git a/tests/e2e/tests/build/type-check-disabled-emit.ts b/tests/e2e/tests/build/type-check-disabled-emit.ts new file mode 100644 index 000000000000..e2b831e1360e --- /dev/null +++ b/tests/e2e/tests/build/type-check-disabled-emit.ts @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { readFile, writeFile } from '../../utils/fs'; +import { execWithEnv, ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +const OUTPUT_DIR = 'dist/test-project/browser'; + +async function readEmittedJs(): Promise> { + const contents = new Map(); + for (const file of (await readdir(OUTPUT_DIR)).sort()) { + if (file.endsWith('.js')) { + contents.set(file, await readFile(`${OUTPUT_DIR}/${file}`)); + } + } + + return contents; +} + +/** + * Verifies that disabling type checking (`NG_BUILD_TYPE_CHECK=0`) does not change the + * emitted JavaScript. When type checking is disabled, the AOT compilation skips the + * semantic "affected files" walk in the isolatedModules fast path (its only remaining + * consumers are diagnostics, which are already suppressed). The emitted output must remain + * byte-for-byte identical to a type-checked build. + */ +export default async function () { + // Disable the persistent disk cache so both builds are cold and independent, keeping the + // comparison free of incremental state carried over between the two runs. + await updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.cache = { enabled: false }; + }); + + // A type-only cross-file dependency. The interface is used solely as a type (and in the + // template via `user.name`), so it is fully erased from the emitted JS. This is exactly the + // kind of cross-file type relationship that the affected-file walk would type-check. + await writeFile( + 'src/app/user.model.ts', + 'export interface User {\n id: number;\n name: string;\n}\n', + ); + + // Root component with both a template and the type-only dependency above. + await writeFile( + 'src/app/app.ts', + [ + `import { Component, signal } from '@angular/core';`, + `import { RouterOutlet } from '@angular/router';`, + `import type { User } from './user.model';`, + ``, + `@Component({`, + ` selector: 'app-root',`, + ` imports: [RouterOutlet],`, + ` template: '

Hello, {{ user.name }}

',`, + `})`, + `export class App {`, + ` protected readonly title = signal('test-project');`, + ` protected readonly user: User = { id: 1, name: 'Angular' };`, + `}`, + ``, + ].join('\n'), + ); + + // Baseline: type checking enabled (default). The affected-file walk runs. + await ng('build', '--configuration=development', '--output-hashing=none'); + const withTypeChecking = await readEmittedJs(); + + // Sanity check that the component (and therefore real emit) is present in the baseline, + // so an all-empty comparison cannot pass trivially. + assert.ok( + [...withTypeChecking.values()].some((contents) => contents.includes('Angular')), + 'Expected the baseline build to emit the component.', + ); + + // Type checking disabled: the affected-file walk is skipped in the isolatedModules fast + // path. The emitted output must be byte-for-byte identical to the baseline. + await execWithEnv('ng', ['build', '--configuration=development', '--output-hashing=none'], { + ...process.env, + NG_BUILD_TYPE_CHECK: '0', + }); + const withoutTypeChecking = await readEmittedJs(); + + assert.deepStrictEqual( + [...withoutTypeChecking.keys()], + [...withTypeChecking.keys()], + 'Disabling type checking must not change the set of emitted JS files.', + ); + + for (const [file, baseline] of withTypeChecking) { + assert.strictEqual( + withoutTypeChecking.get(file), + baseline, + `Emitted output for "${file}" changed when type checking was disabled.`, + ); + } +} diff --git a/tests/e2e/tests/build/unix-esbuild-unsupported.ts b/tests/e2e/tests/build/unix-esbuild-unsupported.ts new file mode 100644 index 000000000000..a7e491aebb02 --- /dev/null +++ b/tests/e2e/tests/build/unix-esbuild-unsupported.ts @@ -0,0 +1,16 @@ +import { join } from 'node:path'; +import { execWithEnv } from '../../utils/process'; + +export default async function () { + // TODO(bazel): fails with bazel on windows + if (process.platform.startsWith('win')) { + return; + } + + // Set the esbuild native binary path to a non-existent file to simulate a spawn error. + // The build should still succeed by falling back to the WASM variant of esbuild. + await execWithEnv('ng', ['build'], { + ...process.env, + 'ESBUILD_BINARY_PATH': join(__dirname, 'esbuild-bin-no-exist-xyz'), + }); +} diff --git a/tests/e2e/tests/build/unix-rebuild-replacements.ts b/tests/e2e/tests/build/unix-rebuild-replacements.ts new file mode 100644 index 000000000000..8f2286ae36b7 --- /dev/null +++ b/tests/e2e/tests/build/unix-rebuild-replacements.ts @@ -0,0 +1,41 @@ +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, createDir, writeMultipleFiles } from '../../utils/fs'; +import { waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { ngServe, updateJsonFile } from '../../utils/project'; + +const webpackGoodRegEx = getGlobalVariable('argv')['esbuild'] + ? /Application bundle generation complete\./ + : / Compiled successfully./; + +export default async function () { + if (process.platform.startsWith('win')) { + return; + } + + await createDir('src/environments'); + + await writeMultipleFiles({ + 'src/environments/environment.ts': `export const env = 'dev';`, + 'src/environments/environment.prod.ts': `export const env = 'prod';`, + 'src/main.ts': ` + import { env } from './environments/environment'; + console.log(env); + `, + }); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect.build.configurations.production.fileReplacements = [ + { + replace: 'src/environments/environment.ts', + with: 'src/environments/environment.prod.ts', + }, + ]; + }); + + await ngServe('--configuration=production'); + + // Should trigger a rebuild. + await appendToFile('src/environments/environment.prod.ts', `console.log('PROD');`); + await waitForAnyProcessOutputToMatch(webpackGoodRegEx); +} diff --git a/tests/e2e/tests/build/wasm-esm.ts b/tests/e2e/tests/build/wasm-esm.ts new file mode 100644 index 000000000000..70633a1021c1 --- /dev/null +++ b/tests/e2e/tests/build/wasm-esm.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ +import { readFile, writeFile } from 'node:fs/promises'; +import assert from 'node:assert/strict'; +import { ng } from '../../utils/process'; +import { prependToFile, replaceInFile } from '../../utils/fs'; +import { updateJsonFile, useSha } from '../../utils/project'; +import { installWorkspacePackages } from '../../utils/packages'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +/** + * Compiled and base64 encoded WASM file for the following WAT: + * ``` + * (module + * (import "./values" "getValue" (func $getvalue (result i32))) + * (export "multiply" (func $multiply)) + * (export "subtract1" (func $subtract)) + * (func $multiply (param i32 i32) (result i32) + * local.get 0 + * local.get 1 + * i32.mul + * ) + * (func $subtract (param i32) (result i32) + * call $getvalue + * local.get 0 + * i32.sub + * ) + * ) + * ``` + */ +const importWasmBase64 = + 'AGFzbQEAAAABEANgAAF/YAJ/fwF/YAF/AX8CFQEILi92YWx1ZXMIZ2V0VmFsdWUAAAMDAgECBxgCCG11bHRpcGx5AAEJc3VidHJhY3QxAAIKEQIHACAAIAFsCwcAEAAgAGsLAC8EbmFtZQEfAwAIZ2V0dmFsdWUBCG11bHRpcGx5AghzdWJ0cmFjdAIHAwAAAQACAA=='; +const importWasmBytes = Buffer.from(importWasmBase64, 'base64'); + +export default async function () { + // Add WASM file to project + await writeFile('src/app/multiply.wasm', importWasmBytes); + await writeFile( + 'src/app/multiply.wasm.d.ts', + 'export declare function multiply(a: number, b: number): number; export declare function subtract1(a: number): number;', + ); + + // Add requested WASM import file + await writeFile('src/app/values.js', 'export function getValue() { return 100; }'); + + // Use WASM file in project + await prependToFile( + 'src/app/app.ts', + ` + import { multiply, subtract1 } from './multiply.wasm'; + `, + ); + await replaceInFile('src/app/app.ts', "'test-project'", 'multiply(4, 5) + subtract1(88)'); + + // Remove Zone.js from polyfills and make zoneless + await updateJsonFile('angular.json', (json) => { + // Remove bundle budgets to avoid a build error due to the expected increased output size + // of a JIT production build. + json.projects['test-project'].architect.build.options.polyfills = []; + }); + + await ng('build'); + + // Update E2E test to check for WASM execution + await executeBrowserTest({ expectedTitleText: 'Hello, 32' }); + + // Setup prerendering and build to test Node.js functionality + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await ng('build', '--configuration', 'development', '--prerender'); + const content = await readFile('dist/test-project/browser/index.html', 'utf-8'); + assert.match(content, /Hello, 32/); +} diff --git a/tests/e2e/tests/build/worker.ts b/tests/e2e/tests/build/worker.ts new file mode 100644 index 000000000000..be81aae7dfd4 --- /dev/null +++ b/tests/e2e/tests/build/worker.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { setTimeout } from 'node:timers/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist, expectFileToMatch, replaceInFile, writeFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + + const workerPath = 'src/app/app.worker.ts'; + const snippetPath = 'src/app/app.ts'; + const projectTsConfig = 'tsconfig.json'; + const workerTsConfig = 'tsconfig.worker.json'; + + await ng('generate', 'web-worker', 'app'); + await expectFileToExist(workerPath); + await expectFileToExist(projectTsConfig); + await expectFileToExist(workerTsConfig); + await expectFileToMatch(snippetPath, `new Worker(new URL('./app.worker', import.meta.url)`); + + await ng('build', '--configuration=development'); + if (useWebpackBuilder) { + await expectFileToExist('dist/test-project/browser/src_app_app_worker_ts.js'); + await expectFileToMatch('dist/test-project/browser/main.js', 'src_app_app_worker_ts'); + } else { + const workerOutputFile = await getWorkerOutputFile(false); + await expectFileToExist(`dist/test-project/browser/${workerOutputFile}`); + await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile); + await expectToFail(() => + expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile + '.map'), + ); + } + + await ng('build', '--output-hashing=none'); + + const workerOutputFile = await getWorkerOutputFile(useWebpackBuilder); + await expectFileToExist(`dist/test-project/browser/${workerOutputFile}`); + if (useWebpackBuilder) { + // Check Webpack builds for the numeric chunk identifier + await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile.substring(0, 3)); + } else { + await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile); + } + + // console.warn has to be used because chrome only captures warnings and errors by default + // https://github.com/angular/protractor/issues/2207 + await replaceInFile('src/app/app.ts', 'console.log', 'console.warn'); + + await executeBrowserTest({ + checkFn: async (page) => { + const messages: string[] = []; + page.on('console', (msg) => { + messages.push(msg.text()); + }); + + // Reload to ensure we capture messages from the start if needed, + // although executeBrowserTest already navigated. + await page.reload(); + + // Wait for the worker message + let retries = 50; + while ( + !messages.some((m) => m.includes('page got message: worker response to hello')) && + retries > 0 + ) { + await setTimeout(100); + retries--; + } + + if (!messages.some((m) => m.includes('page got message: worker response to hello'))) { + assert.fail(`Expected worker message not found in console. Got:\n${messages.join('\n')}`); + } + }, + }); +} + +async function getWorkerOutputFile(useWebpackBuilder: boolean): Promise { + const files = await readdir('dist/test-project/browser'); + let fileName; + if (useWebpackBuilder) { + fileName = files.find((f) => /^\d{3}\.js$/.test(f)); + } else { + fileName = files.find((f) => /worker-[\dA-Z]{8}\.js/.test(f)); + } + + assert(fileName, 'Cannot determine worker output file name.'); + + return fileName; +} diff --git a/tests/e2e/tests/commands/add/add-material.ts b/tests/e2e/tests/commands/add/add-material.ts new file mode 100644 index 000000000000..a7453f035a6f --- /dev/null +++ b/tests/e2e/tests/commands/add/add-material.ts @@ -0,0 +1,46 @@ +import { assertIsError } from '../../../utils/utils'; +import { readFile, rimraf } from '../../../utils/fs'; +import { getActivePackageManager, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { isPrereleaseCli } from '../../../utils/project'; +import { appendFile } from 'node:fs/promises'; +import assert from 'node:assert'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/material'); + + const isPrerelease = await isPrereleaseCli(); + const tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + try { + await ng('add', `@angular/material${tag}`, '--unknown', '--skip-confirmation'); + } catch (error) { + assertIsError(error); + if (!(error as Error).message.includes(`Unknown option: '--unknown'`)) { + throw error; + } + } + + await ng( + 'add', + `@angular/material${tag}`, + '--theme', + 'azure-blue', + '--verbose', + '--skip-confirmation', + ); + + const { dependencies } = JSON.parse(await readFile('package.json')); + assert.ok( + dependencies['@angular/material'], + '`@angular/material` was not found added to dependencies', + ); + + // Clean up existing cdk package + // Not doing so can cause adding material to fail if an incompatible cdk is present + await uninstallPackage('@angular/cdk'); +} diff --git a/tests/e2e/tests/commands/add/add-pwa.ts b/tests/e2e/tests/commands/add/add-pwa.ts new file mode 100644 index 000000000000..c01cc185c84b --- /dev/null +++ b/tests/e2e/tests/commands/add/add-pwa.ts @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToExist, readFile, rimraf } from '../../../utils/fs'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +const snapshots = require('../../../ng-snapshot/package.json'); + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/pwa'); + await ng('add', '@angular/pwa', '--skip-confirmation'); + await expectFileToExist('public/manifest.webmanifest'); + + // Angular PWA doesn't install as a dependency + const { dependencies, devDependencies } = JSON.parse(await readFile('package.json')); + const hasPWADep = Object.keys({ ...dependencies, ...devDependencies }).some( + (d) => d === '@angular/pwa', + ); + assert.ok(!hasPWADep, `Expected 'package.json' not to contain a dependency on '@angular/pwa'.`); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + let needInstall = false; + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries(snapshots.dependencies)) { + if (name in dependencies && dependencies[name] !== version) { + dependencies[name] = version; + needInstall = true; + } + } + }); + + if (needInstall) { + await installWorkspacePackages(); + } + } + + // It should generate a SW configuration file (`ngsw.json`). + const ngswPath = 'dist/test-project/browser/ngsw.json'; + + await ng('build'); + await expectFileToExist(ngswPath); + + // It should correctly generate assetGroups and include at least one URL in each group. + const ngswJson = JSON.parse(await readFile(ngswPath)); + // @ts-ignore + const assetGroups: any[] = ngswJson.assetGroups.map(({ name, urls }) => ({ + name, + urlCount: urls.length, + })); + const emptyAssetGroups = assetGroups.filter(({ urlCount }) => urlCount === 0); + + assert.ok(assetGroups.length > 0, "Expected 'ngsw.json' to contain at least one asset-group."); + assert.ok( + emptyAssetGroups.length === 0, + 'Expected all asset-groups to contain at least one URL, but the following groups are empty: ' + + emptyAssetGroups.map(({ name }) => name).join(', '), + ); +} diff --git a/tests/e2e/tests/commands/add/add-registry-stripped-schematics.ts b/tests/e2e/tests/commands/add/add-registry-stripped-schematics.ts new file mode 100644 index 000000000000..c6356dc8d92c --- /dev/null +++ b/tests/e2e/tests/commands/add/add-registry-stripped-schematics.ts @@ -0,0 +1,121 @@ +import { join } from 'node:path'; +import { promises as fs } from 'node:fs'; +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToExist, expectFileNotToExist, rimraf } from '../../../utils/fs'; +import { getActivePackageManager } from '../../../utils/packages'; +import { ng, silentNpm } from '../../../utils/process'; +import { mktempd } from '../../../utils/utils'; + +export default async function () { + const testRegistry = getGlobalVariable('package-registry'); + const tmpRoot = getGlobalVariable('tmp-root'); + + // 1. Create a temp directory for the custom package + const pkgDir = await mktempd('registry-stripped-pkg-', tmpRoot); + + try { + // 2. Write the package files + const packageJson = { + name: '@angular-devkit/ng-add-registry-stripped', + version: '1.0.0', + schematics: './collection.json', + 'ng-add': { + save: false, + }, + }; + + const collectionJson = { + schematics: { + 'ng-add': { + factory: './index.js', + description: 'Add test empty file to your application.', + }, + }, + }; + + const indexJs = ` + exports.default = function() { + return function(tree) { + tree.create('schematic-executed-successfully.txt', 'Registry Stripped schematic works!'); + return tree; + }; + }; + `; + + await fs.writeFile(join(pkgDir, 'package.json'), JSON.stringify(packageJson, null, 2)); + await fs.writeFile(join(pkgDir, 'collection.json'), JSON.stringify(collectionJson, null, 2)); + await fs.writeFile(join(pkgDir, 'index.js'), indexJs); + + // Write a temporary .npmrc with a fake authentication token so that npm publish succeeds + // without needing real credentials or throwing ENEEDAUTH. + const npmrcContent = ` +${testRegistry.replace(/^https?:/, '')}/:_authToken=fake-secret +registry=${testRegistry} +`; + await fs.writeFile(join(pkgDir, '.npmrc'), npmrcContent); + + // 3. Pack the package + const packResult = await silentNpm(['pack'], { cwd: pkgDir }); + const tarballName = packResult.stdout.trim().split('\n').pop() || ''; + + // 4. Publish the package to the local verdaccio registry + // Verdaccio has publish: $all for @angular-devkit/* so this will succeed + await silentNpm(['publish'], { cwd: pkgDir }); + + // 5. Strip "schematics" and "ng-add" from Verdaccio's metadata on disk + const verdaccioDbPath = join( + tmpRoot, + 'registry', + 'storage', + '@angular-devkit', + 'ng-add-registry-stripped', + 'package.json', + ); + + const verdaccioDb = JSON.parse(await fs.readFile(verdaccioDbPath, 'utf-8')); + + // Strip from the top-level versions list + if (verdaccioDb.versions) { + for (const versionKey of Object.keys(verdaccioDb.versions)) { + delete verdaccioDb.versions[versionKey].schematics; + delete verdaccioDb.versions[versionKey]['ng-add']; + } + } + + // Write back the modified metadata + await fs.writeFile(verdaccioDbPath, JSON.stringify(verdaccioDb, null, 2), 'utf-8'); + + // 6. Execute `ng add` on the registry-stripped package + // Ensure file doesn't already exist + await expectFileNotToExist('schematic-executed-successfully.txt'); + + await ng('add', '@angular-devkit/ng-add-registry-stripped', '--skip-confirmation'); + + // 7. Assertions + // A. The schematic executed successfully + await expectFileToExist('schematic-executed-successfully.txt'); + + // B. The dependency was pruned from package.json since save: false + const rootPackageJson = JSON.parse(await fs.readFile('package.json', 'utf-8')); + const hasDep = + (rootPackageJson.dependencies && + rootPackageJson.dependencies['@angular-devkit/ng-add-registry-stripped']) || + (rootPackageJson.devDependencies && + rootPackageJson.devDependencies['@angular-devkit/ng-add-registry-stripped']); + + if (hasDep) { + throw new Error( + 'Package @angular-devkit/ng-add-registry-stripped was not cleaned up from package.json dependencies!', + ); + } + + // C. The dependency was pruned from node_modules physical folder + // Bun intentionally does not prune unreferenced packages from node_modules automatically. + if (getActivePackageManager() !== 'bun') { + await expectFileNotToExist('node_modules/@angular-devkit/ng-add-registry-stripped'); + } + } finally { + // Cleanup temp package source folder + await rimraf(pkgDir); + } +} diff --git a/tests/e2e/tests/commands/add/add-tailwindcss.ts b/tests/e2e/tests/commands/add/add-tailwindcss.ts new file mode 100644 index 000000000000..fa42815d2fdf --- /dev/null +++ b/tests/e2e/tests/commands/add/add-tailwindcss.ts @@ -0,0 +1,39 @@ +import assert from 'node:assert'; +import { expectFileToExist, expectFileToMatch, readFile, rimraf } from '../../../utils/fs'; +import { getActivePackageManager, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; + +export default async function () { + // In case a previous test installed tailwindcss, clear it. + // (we don't clear node module directories between tests) + // npm does not appear to fully uninstall sometimes + if (getActivePackageManager() === 'npm') { + await rimraf('node_modules/tailwindcss'); + } + + try { + await ng('add', 'tailwindcss', '--skip-confirmation'); + await expectFileToExist('.postcssrc.json'); + await expectFileToMatch('src/styles.css', /@import 'tailwindcss';/); + + const { dependencies, devDependencies } = JSON.parse(await readFile('package.json')); + assert.strictEqual( + dependencies?.tailwindcss, + undefined, + 'tailwindcss should not be added to dependencies.', + ); + assert.ok(devDependencies?.tailwindcss, 'tailwindcss should be added to devDependencies.'); + assert.ok( + devDependencies?.['@tailwindcss/postcss'], + '@tailwindcss/postcss should be added to devDependencies.', + ); + assert.ok(devDependencies?.postcss, 'postcss should be added to devDependencies.'); + + // Ensure the project builds + await ng('build', '--configuration=development'); + } finally { + await uninstallPackage('tailwindcss'); + await uninstallPackage('@tailwindcss/postcss'); + await uninstallPackage('postcss'); + } +} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-version.ts b/tests/e2e/tests/commands/add/add-version.ts similarity index 79% rename from tests/legacy-cli/e2e/tests/commands/add/add-version.ts rename to tests/e2e/tests/commands/add/add-version.ts index 0fcdbc0c1fa3..02d63eb66e0b 100644 --- a/tests/legacy-cli/e2e/tests/commands/add/add-version.ts +++ b/tests/e2e/tests/commands/add/add-version.ts @@ -1,9 +1,8 @@ import { expectFileToExist, expectFileToMatch, rimraf } from '../../../utils/fs'; import { ng } from '../../../utils/process'; - export default async function () { - await ng('add', '@angular-devkit-tests/ng-add-simple@^1.0.0'); + await ng('add', '@angular-devkit-tests/ng-add-simple@^1.0.0', '--skip-confirmation'); await expectFileToMatch('package.json', /\/ng-add-simple.*\^1\.0\.0/); await expectFileToExist('ng-add-test'); await rimraf('node_modules/@angular-devkit-tests/ng-add-simple'); diff --git a/tests/e2e/tests/commands/add/add-vitest-browser.ts b/tests/e2e/tests/commands/add/add-vitest-browser.ts new file mode 100644 index 000000000000..7a2b780c0d8f --- /dev/null +++ b/tests/e2e/tests/commands/add/add-vitest-browser.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert'; +import { expectFileToMatch, readFile } from '../../../utils/fs'; +import { uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { applyVitestBuilder } from '../../../utils/vitest'; + +export default async function () { + await applyVitestBuilder(); + + try { + await ng('add', '@vitest/browser-playwright', '--skip-confirmation'); + + const { dependencies, devDependencies } = JSON.parse(await readFile('package.json')); + assert.strictEqual( + dependencies?.['@vitest/browser-playwright'], + undefined, + '@vitest/browser-playwright should not be added to dependencies.', + ); + assert.ok( + devDependencies?.['@vitest/browser-playwright'], + '@vitest/browser-playwright should be added to devDependencies.', + ); + assert.ok(devDependencies?.playwright, 'playwright should be added to devDependencies.'); + + await expectFileToMatch('tsconfig.spec.json', /"vitest\/globals"/); + await expectFileToMatch('tsconfig.spec.json', /"@vitest\/browser-playwright"/); + } finally { + await uninstallPackage('@vitest/browser-playwright'); + await uninstallPackage('playwright'); + } +} diff --git a/tests/e2e/tests/commands/add/add.ts b/tests/e2e/tests/commands/add/add.ts new file mode 100644 index 000000000000..6d9827013dc4 --- /dev/null +++ b/tests/e2e/tests/commands/add/add.ts @@ -0,0 +1,9 @@ +import { expectFileToExist, expectFileToMatch, rimraf } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + await ng('add', '@angular-devkit-tests/ng-add-simple', '--skip-confirmation'); + await expectFileToMatch('package.json', /@angular-devkit-tests\/ng-add-simple/); + await expectFileToExist('ng-add-test'); + await rimraf('node_modules/@angular-devkit-tests/ng-add-simple'); +} diff --git a/tests/e2e/tests/commands/add/base.ts b/tests/e2e/tests/commands/add/base.ts new file mode 100644 index 000000000000..d31210c6c242 --- /dev/null +++ b/tests/e2e/tests/commands/add/base.ts @@ -0,0 +1,19 @@ +import { assetDir } from '../../../utils/assets'; +import { deleteFile, expectFileToExist, symlinkFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + await symlinkFile(assetDir('add-collection-dir'), `./node_modules/add-collection`, 'dir'); + + await ng('add', 'add-collection'); + await expectFileToExist('empty-file'); + + await ng('add', 'add-collection', '--name=blah'); + await expectFileToExist('blah'); + + await expectToFail(() => ng('add', 'add-collection')); // File already exists. + + // Cleanup the package + await deleteFile('node_modules/add-collection'); +} diff --git a/tests/e2e/tests/commands/add/dir.ts b/tests/e2e/tests/commands/add/dir.ts new file mode 100644 index 000000000000..7cb00704cc8e --- /dev/null +++ b/tests/e2e/tests/commands/add/dir.ts @@ -0,0 +1,19 @@ +import { cp } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { assetDir } from '../../../utils/assets'; +import { expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + const collectionName = 'add-collection-dir'; + const dirCollectionPath = resolve(collectionName); + + // Copy locally as bun doesn't install the dependency correctly if it has symlinks. + await cp(assetDir(collectionName), dirCollectionPath, { + recursive: true, + dereference: true, + }); + + await ng('add', dirCollectionPath, '--name=blah', '--skip-confirmation'); + await expectFileToExist('blah'); +} diff --git a/tests/e2e/tests/commands/add/file.ts b/tests/e2e/tests/commands/add/file.ts new file mode 100644 index 000000000000..5b22b4211ceb --- /dev/null +++ b/tests/e2e/tests/commands/add/file.ts @@ -0,0 +1,13 @@ +import { copyFile } from 'node:fs/promises'; +import { assetDir } from '../../../utils/assets'; +import { expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + // Avoids ERR_PNPM_ENAMETOOLONG errors. + const tarball = './add-collection.tgz'; + await copyFile(assetDir(tarball), tarball); + + await ng('add', tarball, '--name=blah', '--skip-confirmation'); + await expectFileToExist('blah'); +} diff --git a/tests/e2e/tests/commands/add/npm-config.ts b/tests/e2e/tests/commands/add/npm-config.ts new file mode 100644 index 000000000000..6f7599e8c00c --- /dev/null +++ b/tests/e2e/tests/commands/add/npm-config.ts @@ -0,0 +1,8 @@ +import { writeFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + // Works with before option + await writeFile('.npmrc', `before=${new Date().toISOString()}`); + await ng('add', '@angular/pwa', '--skip-confirmation'); +} diff --git a/tests/e2e/tests/commands/add/peer.ts b/tests/e2e/tests/commands/add/peer.ts new file mode 100644 index 000000000000..143542e4533c --- /dev/null +++ b/tests/e2e/tests/commands/add/peer.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { resolve } from 'node:path'; +import { cp } from 'node:fs/promises'; +import { assetDir } from '../../../utils/assets'; +import { ng } from '../../../utils/process'; + +export default async function (): Promise { + const warning = /Adding the package may not succeed/; + + const stdout1 = await runNgAdd('add-collection-peer-bad'); + assert.match( + stdout1, + warning, + `Peer warning should be shown for add-collection-peer-bad but was not.`, + ); + + const stdout2 = await runNgAdd('add-collection-dir'); + assert.doesNotMatch( + stdout2, + warning, + `Peer warning should NOT be shown for add-collection-dir but was.`, + ); + + const stdout3 = await runNgAdd('add-collection-peer-good'); + assert.doesNotMatch( + stdout3, + warning, + `Peer warning should NOT be shown for add-collection-peer-good but was.`, + ); +} + +async function runNgAdd(collectionName: string): Promise { + const collectionPath = resolve(collectionName); + + // Copy locally as bun doesn't install the dependency correctly if it has symlinks. + await cp(assetDir(collectionName), collectionPath, { + recursive: true, + dereference: true, + }); + + const { stdout } = await ng('add', collectionPath, '--skip-confirmation'); + + return stdout; +} diff --git a/tests/e2e/tests/commands/add/registry-option.ts b/tests/e2e/tests/commands/add/registry-option.ts new file mode 100644 index 000000000000..1343cebf4dd1 --- /dev/null +++ b/tests/e2e/tests/commands/add/registry-option.ts @@ -0,0 +1,42 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { expectFileToExist } from '../../../utils/fs'; +import { execAndCaptureError, ng } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + const testRegistry = getGlobalVariable('package-registry'); + + // Validate that a non-URL registry string fails with a validation error + const error = await execAndCaptureError('ng', [ + 'add', + '--registry=not-a-valid-url', + '@angular/pwa', + '--skip-confirmation', + ]); + if (!error.message.includes('Option --registry must be a valid URL.')) { + throw new Error( + `Expected registry validation error, but got different error: ${error.message}`, + ); + } + + // Validate that an empty registry string fails with a validation error + const errorEmpty = await execAndCaptureError('ng', [ + 'add', + '--registry=', + '@angular/pwa', + '--skip-confirmation', + ]); + if (!errorEmpty.message.includes('Option --registry must be a valid URL.')) { + throw new Error( + `Expected registry validation error for empty string, but got: ${errorEmpty.message}`, + ); + } + + // Set an invalid registry + process.env['NPM_CONFIG_REGISTRY'] = 'http://127.0.0.1:9999'; + + await expectToFail(() => ng('add', '@angular/pwa', '--skip-confirmation')); + + await ng('add', `--registry=${testRegistry}`, '@angular/pwa', '--skip-confirmation'); + await expectFileToExist('public/manifest.webmanifest'); +} diff --git a/tests/e2e/tests/commands/add/secure-registry.ts b/tests/e2e/tests/commands/add/secure-registry.ts new file mode 100644 index 000000000000..e585444b02e4 --- /dev/null +++ b/tests/e2e/tests/commands/add/secure-registry.ts @@ -0,0 +1,30 @@ +import { expectFileNotToExist, expectFileToExist } from '../../../utils/fs'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { git, ng } from '../../../utils/process'; +import { createNpmConfigForAuthentication } from '../../../utils/registry'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + const originalNpmConfigRegistry = process.env['NPM_CONFIG_REGISTRY']; + try { + // The environment variable has priority over the .npmrc + delete process.env['NPM_CONFIG_REGISTRY']; + const command = ['add', '@angular/pwa', '--skip-confirmation']; + + // Works with scoped registry authentication details + await expectFileNotToExist('public/manifest.webmanifest'); + + await createNpmConfigForAuthentication(); + await ng(...command); + await expectFileToExist('public/manifest.webmanifest'); + await git('clean', '-dxf'); + + // Invalid authentication token + await createNpmConfigForAuthentication(true, true); + await expectToFail(() => ng(...command)); + } finally { + process.env['NPM_CONFIG_REGISTRY'] = originalNpmConfigRegistry; + await git('clean', '-dxf'); + await installWorkspacePackages(); + } +} diff --git a/tests/e2e/tests/commands/add/version-specifier.ts b/tests/e2e/tests/commands/add/version-specifier.ts new file mode 100644 index 000000000000..f88d60a51ec9 --- /dev/null +++ b/tests/e2e/tests/commands/add/version-specifier.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict'; +import { appendFile } from 'node:fs/promises'; +import { expectFileToMatch } from '../../../utils/fs'; +import { getActivePackageManager, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { isPrereleaseCli } from '../../../utils/project'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/localize'); + + // If using npm, enable the legacy-peer-deps option to allow testing the output behavior of the + // `ng add` command itself and not the behavior of npm which may otherwise fail depending + // on the npm version in use and the version specifier supplied in each test. + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true\n'); + } + + const tag = isPrereleaseCli() ? '@next' : ''; + + await ng('add', `@angular/localize${tag}`, '--skip-confirmation'); + await expectFileToMatch('package.json', /@angular\/localize/); + + const output1 = await ng('add', '@angular/localize', '--skip-confirmation'); + assert.match( + output1.stdout, + /Skipping installation: Package already installed/, + 'Installation was not skipped', + ); + + const output2 = await ng('add', '@angular/localize@latest', '--skip-confirmation'); + assert.doesNotMatch( + output2.stdout, + /Skipping installation: Package already installed/, + 'Installation should not have been skipped', + ); + + const output3 = await ng('add', '@angular/localize@19.1.0', '--skip-confirmation'); + assert.doesNotMatch( + output3.stdout, + /Skipping installation: Package already installed/, + 'Installation should not have been skipped', + ); + + const output4 = await ng('add', '@angular/localize@19', '--skip-confirmation'); + assert.match( + output4.stdout, + /Skipping installation: Package already installed/, + 'Installation was not skipped', + ); + + await uninstallPackage('@angular/localize'); +} diff --git a/tests/e2e/tests/commands/add/yarn-env-vars.ts b/tests/e2e/tests/commands/add/yarn-env-vars.ts new file mode 100644 index 000000000000..103a99c04056 --- /dev/null +++ b/tests/e2e/tests/commands/add/yarn-env-vars.ts @@ -0,0 +1,29 @@ +import { expectFileNotToExist, expectFileToExist } from '../../../utils/fs'; +import { getActivePackageManager } from '../../../utils/packages'; +import { git, ng } from '../../../utils/process'; +import { + createNpmConfigForAuthentication, + setNpmEnvVarsForAuthentication, +} from '../../../utils/registry'; + +export default async function () { + // Yarn specific test that tests YARN_ env variables. + // https://classic.yarnpkg.com/en/docs/envvars/ + if (getActivePackageManager() !== 'yarn') { + return; + } + const command = ['add', '@angular/pwa', '--skip-confirmation']; + + // Environment variables only + await expectFileNotToExist('public/manifest.webmanifest'); + setNpmEnvVarsForAuthentication(false, true); + await ng(...command); + await expectFileToExist('public/manifest.webmanifest'); + await git('clean', '-dxf'); + + // Mix of config file and env vars works + await expectFileNotToExist('public/manifest.webmanifest'); + await createNpmConfigForAuthentication(false, true); + await ng(...command); + await expectFileToExist('public/manifest.webmanifest'); +} diff --git a/tests/e2e/tests/commands/additional-properties.ts b/tests/e2e/tests/commands/additional-properties.ts new file mode 100644 index 000000000000..a53006853fca --- /dev/null +++ b/tests/e2e/tests/commands/additional-properties.ts @@ -0,0 +1,31 @@ +import { createDir, rimraf, writeMultipleFiles } from '../../utils/fs'; +import { execAndWaitForOutputToMatch } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + await createDir('example-builder'); + await writeMultipleFiles({ + 'example-builder/package.json': '{ "builders": "./builders.json" }', + 'example-builder/schema.json': + '{ "$schema": "http://json-schema.org/draft-07/schema", "type": "object", "additionalProperties": true }', + 'example-builder/builders.json': + '{ "$schema": "@angular-devkit/architect/src/builders-schema.json", "builders": { "example": { "implementation": "./example", "schema": "./schema.json" } } }', + 'example-builder/example.js': + 'module.exports.default = require("@angular-devkit/architect").createBuilder((options) => { console.log(options); return { success: true }; });', + }); + + await updateJsonFile('angular.json', (json) => { + const appArchitect = json.projects['test-project'].architect; + appArchitect.example = { + builder: './example-builder:example', + }; + }); + + await execAndWaitForOutputToMatch( + 'ng', + ['run', 'test-project:example', '--additional', 'property'], + /Unknown argument: additional/, + ); + + await rimraf('example-builder'); +} diff --git a/tests/e2e/tests/commands/analytics/analytics-enable-disable.ts b/tests/e2e/tests/commands/analytics/analytics-enable-disable.ts new file mode 100644 index 000000000000..94bd8f95edb2 --- /dev/null +++ b/tests/e2e/tests/commands/analytics/analytics-enable-disable.ts @@ -0,0 +1,11 @@ +import assert from 'node:assert'; +import { readFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + await ng('analytics', 'enable'); + assert.ok(JSON.parse(await readFile('angular.json')).cli.analytics); + + await ng('analytics', 'disable'); + assert.strictEqual(JSON.parse(await readFile('angular.json')).cli.analytics, false); +} diff --git a/tests/e2e/tests/commands/analytics/analytics-info.ts b/tests/e2e/tests/commands/analytics/analytics-info.ts new file mode 100644 index 000000000000..d92dfd2ffde6 --- /dev/null +++ b/tests/e2e/tests/commands/analytics/analytics-info.ts @@ -0,0 +1,30 @@ +import { execAndWaitForOutputToMatch } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +export default async function () { + // Should be disabled by default. + await configureTest(undefined /** analytics */); + await execAndWaitForOutputToMatch('ng', ['analytics', 'info'], /Effective status: disabled/, { + ...process.env, + NG_FORCE_TTY: '0', // Disable prompts + }); + + await configureTest('1dba0835-38a3-4957-bf34-9974e2df0df3' /** analytics */); + await execAndWaitForOutputToMatch('ng', ['analytics', 'info'], /Effective status: enabled/, { + ...process.env, + NG_FORCE_TTY: '0', // Disable prompts + }); + + await configureTest(false /** analytics */); + await execAndWaitForOutputToMatch('ng', ['analytics', 'info'], /Effective status: disabled/, { + ...process.env, + NG_FORCE_TTY: '0', // Disable prompts + }); +} + +async function configureTest(analytics: false | string | undefined): Promise { + await updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.analytics = analytics; + }); +} diff --git a/tests/e2e/tests/commands/analytics/ask-analytics-command.ts b/tests/e2e/tests/commands/analytics/ask-analytics-command.ts new file mode 100644 index 000000000000..ae20bb21f2fa --- /dev/null +++ b/tests/e2e/tests/commands/analytics/ask-analytics-command.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import { execWithEnv } from '../../../utils/process'; +import { mockHome } from '../../../utils/utils'; + +const ANALYTICS_PROMPT = /Would you like to share pseudonymous usage data/; + +export default async function () { + // CLI should prompt for analytics permissions. + await mockHome(async () => { + const { stdout } = await execWithEnv( + 'ng', + ['config'], + { + ...process.env, + NG_FORCE_TTY: '1', + NG_FORCE_AUTOCOMPLETE: 'false', + }, + 'n\n' /* stdin */, + ); + + assert.match(stdout, ANALYTICS_PROMPT, 'CLI did not prompt for analytics permission.'); + }); + + // CLI should skip analytics prompt with `NG_CLI_ANALYTICS=false`. + await mockHome(async () => { + const { stdout } = await execWithEnv('ng', ['config'], { + ...process.env, + NG_FORCE_TTY: '1', + NG_CLI_ANALYTICS: 'false', + NG_FORCE_AUTOCOMPLETE: 'false', + }); + + assert.doesNotMatch( + stdout, + ANALYTICS_PROMPT, + 'CLI prompted for analytics permission when it should be forced off.', + ); + }); + + // CLI should skip analytics prompt during `ng update`. + await mockHome(async () => { + const { stdout } = await execWithEnv('ng', ['update', '--help'], { + ...process.env, + NG_FORCE_TTY: '1', + NG_FORCE_AUTOCOMPLETE: 'false', + }); + + assert.doesNotMatch( + stdout, + ANALYTICS_PROMPT, + 'CLI prompted for analytics permission during an update where it should not have.', + ); + }); +} diff --git a/tests/e2e/tests/commands/builder-not-found.ts b/tests/e2e/tests/commands/builder-not-found.ts new file mode 100644 index 000000000000..ec0002ef65d3 --- /dev/null +++ b/tests/e2e/tests/commands/builder-not-found.ts @@ -0,0 +1,45 @@ +import { moveFile } from '../../utils/fs'; +import { getActivePackageManager, installPackage, uninstallPackage } from '../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + try { + await uninstallPackage('@angular-devkit/build-angular'); + + await expectToFail(() => ng('build')); + await execAndWaitForOutputToMatch( + 'ng', + ['build'], + /Could not find the '@angular-devkit\/build-angular:browser' builder's node package\./, + ); + await expectToFail(() => + execAndWaitForOutputToMatch( + 'ng', + ['build'], + new RegExp( + `Node packages may not be installed\\. Try installing with '${getActivePackageManager()} install'\\.`, + ), + ), + ); + + await moveFile('node_modules', 'temp_node_modules'); + + await expectToFail(() => ng('build')); + await execAndWaitForOutputToMatch( + 'ng', + ['build'], + /Could not find the '@angular-devkit\/build-angular:browser' builder's node package\./, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['build'], + new RegExp( + `Node packages may not be installed\\. Try installing with '${getActivePackageManager()} install'\\.`, + ), + ); + } finally { + await moveFile('temp_node_modules', 'node_modules'); + await installPackage('@angular-devkit/build-angular'); + } +} diff --git a/tests/e2e/tests/commands/builder-project-by-cwd.ts b/tests/e2e/tests/commands/builder-project-by-cwd.ts new file mode 100644 index 000000000000..6033f4542391 --- /dev/null +++ b/tests/e2e/tests/commands/builder-project-by-cwd.ts @@ -0,0 +1,21 @@ +import { join } from 'node:path'; +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + await ng('generate', 'app', 'second-app', '--skip-install'); + await ng('generate', 'app', 'third-app', '--skip-install'); + const startCwd = process.cwd(); + + try { + // When no project is provided it should favor the project that is located in the current working directory. + process.chdir(join(startCwd, 'projects/second-app')); + await ng('build', '--configuration=development'); + + process.chdir(startCwd); + await expectFileToExist('dist/second-app'); + } finally { + // restore path + process.chdir(startCwd); + } +} diff --git a/tests/e2e/tests/commands/cache/cache-clean.ts b/tests/e2e/tests/commands/cache/cache-clean.ts new file mode 100644 index 000000000000..004c5a069dfc --- /dev/null +++ b/tests/e2e/tests/commands/cache/cache-clean.ts @@ -0,0 +1,11 @@ +import { createDir, expectFileNotToExist, expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + const cachePath = '.angular/cache'; + await createDir(cachePath); + await expectFileToExist(cachePath); + + await ng('cache', 'clean'); + await expectFileNotToExist(cachePath); +} diff --git a/tests/e2e/tests/commands/cache/cache-enable-disable.ts b/tests/e2e/tests/commands/cache/cache-enable-disable.ts new file mode 100644 index 000000000000..1cfbf705787e --- /dev/null +++ b/tests/e2e/tests/commands/cache/cache-enable-disable.ts @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { readFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + await ng('cache', 'enable'); + assert.strictEqual( + JSON.parse(await readFile('angular.json')).cli.cache.enabled, + true, + `Expected 'cli.cache.enable' to be true.`, + ); + + await ng('cache', 'disable'); + assert.strictEqual( + JSON.parse(await readFile('angular.json')).cli.cache.enabled, + false, + `Expected 'cli.cache.enable' to be false.`, + ); +} diff --git a/tests/e2e/tests/commands/cache/cache-info.ts b/tests/e2e/tests/commands/cache/cache-info.ts new file mode 100644 index 000000000000..bad2df6c3bdc --- /dev/null +++ b/tests/e2e/tests/commands/cache/cache-info.ts @@ -0,0 +1,78 @@ +import { execAndWaitForOutputToMatch } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; + +const ENV_NO_COLOR = { + 'NO_COLOR': '1', +}; + +export default async function () { + const originalCIValue = process.env['CI']; + + try { + // Should be enabled by default for local builds. + await configureTest('0' /** envCI */); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Should be disabled by default for CI builds. + await configureTest('1' /** envCI */, { enabled: true }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Should be enabled by when environment is local and env is not CI. + await configureTest('0' /** envCI */, { environment: 'local' }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Should be disabled by when environment is local and env is CI. + await configureTest('1' /** envCI */, { environment: 'local' }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Effective status should be enabled when 'environment' is set to 'all' or 'ci'. + await configureTest('1' /** envCI */, { environment: 'all' }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Effective status should be enabled when 'environment' is set to 'ci' and run is in ci + await configureTest('1' /** envCI */, { environment: 'ci' }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + + // Effective status should be disabled when 'enabled' is set to false + await configureTest('1' /** envCI */, { environment: 'all', enabled: false }); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); + } finally { + process.env['CI'] = originalCIValue; + } +} + +async function configureTest( + envCI: '1' | '0', + cacheOptions?: { + environment?: 'ci' | 'local' | 'all'; + enabled?: boolean; + }, +): Promise { + process.env['CI'] = envCI; + + await updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.cache = cacheOptions; + }); +} diff --git a/tests/e2e/tests/commands/completion/completion-prompt.ts b/tests/e2e/tests/commands/completion/completion-prompt.ts new file mode 100644 index 000000000000..424b373e47a6 --- /dev/null +++ b/tests/e2e/tests/commands/completion/completion-prompt.ts @@ -0,0 +1,470 @@ +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { env } from 'node:process'; +import { getGlobalVariable } from '../../../utils/env'; +import { mockHome } from '../../../utils/utils'; +import assert from 'node:assert/strict'; + +import { + execAndCaptureError, + execAndWaitForOutputToMatch, + execWithEnv, + silentNpm, +} from '../../../utils/process'; + +const AUTOCOMPLETION_PROMPT = /Would you like to enable autocompletion\?/; +const DEFAULT_ENV = Object.freeze({ + ...env, + // Shell should be mocked for each test that cares about it. + SHELL: '/bin/bash', + // Even if the actual test process is run on CI, we're testing user flows which aren't on CI. + CI: undefined, + // Tests run on CI technically don't have a TTY, but the autocompletion prompt requires it, so we + // force a TTY by default. + NG_FORCE_TTY: '1', + // Analytics wants to prompt for a first command as well, but we don't care about that here. + NG_CLI_ANALYTICS: 'false', +}); + +const testRegistry = getGlobalVariable('package-registry'); + +export default async function () { + // Windows Cmd and Powershell do not support autocompletion. Run a different set of tests to + // confirm autocompletion skips the prompt appropriately. + if (process.platform === 'win32') { + await windowsTests(); + return; + } + + // Sets up autocompletion after user accepts a prompt from any command. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, `# Other content...`); + + const { stdout } = await execWithEnv( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'y\n' /* stdin: accept prompt */, + ); + + assert.match( + stdout, + AUTOCOMPLETION_PROMPT, + 'CLI execution did not prompt for autocompletion setup when it should have.', + ); + + const bashrcContents = await fs.readFile(bashrc, 'utf-8'); + assert.match( + bashrcContents, + /source <\(ng completion script\)/, + 'Autocompletion was *not* added to `~/.bashrc` after accepting the setup prompt.', + ); + + assert.match( + stdout, + /Appended `source <\(ng completion script\)`/, + 'CLI did not print that it successfully set up autocompletion.', + ); + }); + + // Does nothing if the user rejects the autocompletion prompt. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, `# Other content...`); + + const { stdout } = await execWithEnv( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'n\n' /* stdin: reject prompt */, + ); + + assert.match( + stdout, + AUTOCOMPLETION_PROMPT, + 'CLI execution did not prompt for autocompletion setup when it should have.', + ); + + const bashrcContents = await fs.readFile(bashrc, 'utf-8'); + assert.doesNotMatch( + bashrcContents, + /ng completion/, + 'Autocompletion was incorrectly added to `~/.bashrc` after refusing the setup prompt.', + ); + + assert.doesNotMatch( + stdout, + /Appended `source <\(ng completion script\)`/, + "CLI printed that it successfully set up autocompletion when it actually didn't.", + ); + + assert.match( + stdout, + /Ok, you won't be prompted again\./, + 'CLI did not inform the user they will not be prompted again.', + ); + }); + + // Does *not* prompt if the user already accepted (even if they delete the completion config). + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, '# Other commands...'); + + const { stdout: stdout1 } = await execWithEnv( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'y\n' /* stdin: accept prompt */, + ); + + assert.match( + stdout1, + AUTOCOMPLETION_PROMPT, + 'First execution did not prompt for autocompletion setup.', + ); + + const bashrcContents1 = await fs.readFile(bashrc, 'utf-8'); + assert.match( + bashrcContents1, + /source <\(ng completion script\)/, + '`~/.bashrc` file was not updated after the user accepted the autocompletion' + + ` prompt. Contents:\n${bashrcContents1}`, + ); + + // User modifies their configuration and removes `ng completion`. + await fs.writeFile(bashrc, '# Some new commands...'); + + const { stdout: stdout2 } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }); + + assert.doesNotMatch( + stdout2, + AUTOCOMPLETION_PROMPT, + 'Subsequent execution after rejecting autocompletion setup prompted again' + + ' when it should not have.', + ); + + const bashrcContents2 = await fs.readFile(bashrc, 'utf-8'); + assert.strictEqual( + bashrcContents2, + '# Some new commands...', + '`~/.bashrc` file was incorrectly modified when using a modified `~/.bashrc`' + + ` after previously accepting the autocompletion prompt. Contents:\n${bashrcContents2}`, + ); + }); + + // Does *not* prompt if the user already rejected. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, '# Other commands...'); + + const { stdout: stdout1 } = await execWithEnv( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'n\n' /* stdin: reject prompt */, + ); + + assert.match( + stdout1, + AUTOCOMPLETION_PROMPT, + 'First execution did not prompt for autocompletion setup.', + ); + + const { stdout: stdout2 } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }); + + assert.doesNotMatch( + stdout2, + AUTOCOMPLETION_PROMPT, + 'Subsequent execution after rejecting autocompletion setup prompted again' + + ' when it should not have.', + ); + + const bashrcContents = await fs.readFile(bashrc, 'utf-8'); + assert.strictEqual( + bashrcContents, + '# Other commands...', + '`~/.bashrc` file was incorrectly modified when the user never accepted the' + + ` autocompletion prompt. Contents:\n${bashrcContents}`, + ); + }); + + // Prompts user again on subsequent execution after accepting prompt but failing to setup. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, '# Other commands...'); + + // Make `~/.bashrc` readonly. This is enough for the CLI to verify that the file exists and + // `ng completion` is not in it, but will fail when actually trying to modify the file. + await fs.chmod(bashrc, 0o444); + + const err = await execAndCaptureError( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'y\n' /* stdin: accept prompt */, + ); + + assert.match( + err.message, + /Failed to append autocompletion setup/, + `Failed first execution did not print the expected error message. Actual:\n${err.message}`, + ); + + // User corrects file permissions between executions. + await fs.chmod(bashrc, 0o777); + + const { stdout: stdout2 } = await execWithEnv( + 'ng', + ['config'], + { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }, + 'y\n' /* stdin: accept prompt */, + ); + + assert.match( + stdout2, + AUTOCOMPLETION_PROMPT, + 'Subsequent execution after failed autocompletion setup did not prompt again when it should' + + ' have.', + ); + + const bashrcContents = await fs.readFile(bashrc, 'utf-8'); + assert.match( + bashrcContents, + /ng completion script/, + '`~/.bashrc` file does not include `ng completion` after the user never accepted the' + + ` autocompletion prompt a second time. Contents:\n${bashrcContents}`, + ); + }); + + // Does *not* prompt for `ng update` commands. + await mockHome(async (home) => { + // Use `ng update --help` so it's actually a no-op and we don't need to setup a project. + const { stdout } = await execWithEnv('ng', ['update', '--help'], { + ...DEFAULT_ENV, + HOME: home, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + '`ng update` command incorrectly prompted for autocompletion setup.', + ); + }); + + // Does *not* prompt for `ng completion` commands. + await mockHome(async (home) => { + const { stdout } = await execWithEnv('ng', ['completion'], { + ...DEFAULT_ENV, + HOME: home, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + '`ng completion` command incorrectly prompted for autocompletion setup.', + ); + }); + + // Does *not* prompt user for CI executions. + { + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + CI: 'true', + NG_FORCE_TTY: undefined, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'CI execution prompted for autocompletion setup but should not have.', + ); + } + + // Does *not* prompt user for non-TTY executions. + { + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + NG_FORCE_TTY: 'false', + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Non-TTY execution prompted for autocompletion setup but should not have.', + ); + } + + // Does *not* prompt user for executions without a `$HOME`. + { + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + HOME: undefined, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Execution without a `$HOME` value prompted for autocompletion setup but' + + ' should not have.', + ); + } + + // Does *not* prompt user for executions without a `$SHELL`. + { + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + SHELL: undefined, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Execution without a `$SHELL` value prompted for autocompletion setup but' + + ' should not have.', + ); + } + + // Does *not* prompt user for executions from unknown shells. + { + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + SHELL: '/usr/bin/unknown', + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Execution with an unknown `$SHELL` value prompted for autocompletion setup' + + ' but should not have.', + ); + } + + // Does *not* prompt user when an RC file already uses `ng completion`. + await mockHome(async (home) => { + await fs.writeFile( + path.join(home, '.bashrc'), + ` +# Some stuff... + +source <(ng completion script) + +# Some other stuff... + `.trim(), + ); + + const { stdout } = await execWithEnv('ng', ['config'], { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + "Execution with an existing `ng completion` line in the user's RC file" + + ' prompted for autocompletion setup but should not have.', + ); + }); + + // Prompts when a global CLI install is present on the system. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, `# Other content...`); + + await execAndWaitForOutputToMatch('ng', ['config'], AUTOCOMPLETION_PROMPT, { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + }); + }); + + // Does *not* prompt when a global CLI install is missing from the system. + await mockHome(async (home) => { + try { + // Temporarily uninstall the global CLI binary from the system. + await silentNpm(['uninstall', '--global', '@angular/cli', `--registry=${testRegistry}`]); + + // Setup a fake project directory with a local install of the CLI. + const projectDir = path.join(home, 'project'); + await fs.mkdir(projectDir); + await silentNpm(['init', '-y', `--registry=${testRegistry}`], { cwd: projectDir }); + await silentNpm(['install', '@angular/cli', `--registry=${testRegistry}`], { + cwd: projectDir, + }); + + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, `# Other content...`); + + const localCliDir = path.join(projectDir, 'node_modules', '.bin'); + const localCliBinary = path.join(localCliDir, 'ng'); + const pathDirs = process.env['PATH']!.split(':'); + const pathEnvVar = [...pathDirs, localCliDir].join(':'); + const { stdout } = await execWithEnv(localCliBinary, ['config'], { + ...DEFAULT_ENV, + SHELL: '/bin/bash', + HOME: home, + PATH: pathEnvVar, + }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Execution without a global CLI install prompted for autocompletion setup but should' + + ' not have.', + ); + } finally { + // Reinstall global CLI for remainder of the tests. + await silentNpm(['install', '--global', '@angular/cli', `--registry=${testRegistry}`]); + } + }); +} + +async function windowsTests(): Promise { + // Should *not* prompt on Windows, autocompletion isn't supported. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, `# Other content...`); + + const { stdout } = await execWithEnv('ng', ['config'], { ...env }); + + assert.doesNotMatch( + stdout, + AUTOCOMPLETION_PROMPT, + 'Execution prompted to set up autocompletion on Windows despite not actually being' + + ' supported.', + ); + }); +} diff --git a/tests/e2e/tests/commands/completion/completion-script.ts b/tests/e2e/tests/commands/completion/completion-script.ts new file mode 100644 index 000000000000..421763478950 --- /dev/null +++ b/tests/e2e/tests/commands/completion/completion-script.ts @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import { exec, execAndWaitForOutputToMatch } from '../../../utils/process'; + +export default async function () { + // ng build + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'b', ''], + /test-project/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'build', ''], + /test-project/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'build', '--a'], + /--aot/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'build', '--configuration'], + /production/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'b', '--configuration'], + /production/, + ); + + // ng run + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'run', ''], + /test-project\\:build\\:development/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'run', ''], + /test-project\\:build/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'run', ''], + /test-project\\:test/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'run', 'test-project:build'], + /test-project\\:build\\:development/, + ); + await execAndWaitForOutputToMatch( + 'ng', + ['--get-yargs-completions', 'ng', 'run', 'test-project:'], + /test-project\\:test/, + ); + + const { stdout: noServeStdout } = await exec( + 'ng', + '--get-yargs-completions', + 'ng', + 'run', + 'test-project:build', + ); + assert.doesNotMatch( + noServeStdout, + /:serve/, + `':serve' should not have been listed as a completion option.\nSTDOUT:\n${noServeStdout}`, + ); +} diff --git a/tests/e2e/tests/commands/completion/completion.ts b/tests/e2e/tests/commands/completion/completion.ts new file mode 100644 index 000000000000..5b81490c8400 --- /dev/null +++ b/tests/e2e/tests/commands/completion/completion.ts @@ -0,0 +1,350 @@ +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { getGlobalVariable } from '../../../utils/env'; +import { mockHome } from '../../../utils/utils'; +import { + execAndCaptureError, + execAndWaitForOutputToMatch, + execWithEnv, + silentNpm, +} from '../../../utils/process'; + +const testRegistry = getGlobalVariable('package-registry'); + +const AUTOCOMPLETION_SNIPPET = ` +# Load Angular CLI autocompletion for interactive shells. +if [[ $- == *i* ]]; then + source <(ng completion script) +fi +`.trim(); + +export default async function () { + // Windows Cmd and Powershell do not support autocompletion. Run a different set of tests to + // confirm autocompletion fails gracefully. + if (process.platform === 'win32') { + await windowsTests(); + + return; + } + + // Generates new `.bashrc` file. + await mockHome(async (home) => { + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/bin/bash', + }, + ); + + const rcContents = await fs.readFile(path.join(home, '.bashrc'), 'utf-8'); + if (!rcContents.includes(AUTOCOMPLETION_SNIPPET)) { + throw new Error(`~/.bashrc does not contain autocompletion script. Contents:\n${rcContents}`); + } + }); + + // Generates new `.zshrc` file. + await mockHome(async (home) => { + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }, + ); + + const rcContents = await fs.readFile(path.join(home, '.zshrc'), 'utf-8'); + if (!rcContents.includes(AUTOCOMPLETION_SNIPPET)) { + throw new Error(`~/.zshrc does not contain autocompletion script. Contents:\n${rcContents}`); + } + }); + + // Appends to existing `.bashrc` file. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/bin/bash', + }, + ); + + const rcContents = await fs.readFile(bashrc, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.bashrc does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Appends to existing `.bash_profile` file. + await mockHome(async (home) => { + const bashProfile = path.join(home, '.bash_profile'); + await fs.writeFile(bashProfile, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/bin/bash', + }, + ); + + const rcContents = await fs.readFile(bashProfile, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.bash_profile does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Appends to existing `.profile` file (using Bash). + await mockHome(async (home) => { + const profile = path.join(home, '.profile'); + await fs.writeFile(profile, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/bin/bash', + }, + ); + + const rcContents = await fs.readFile(profile, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.profile does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Bash shell prefers `.bashrc`. + await mockHome(async (home) => { + const bashrc = path.join(home, '.bashrc'); + await fs.writeFile(bashrc, '# `.bashrc` commands...'); + const bashProfile = path.join(home, '.bash_profile'); + await fs.writeFile(bashProfile, '# `.bash_profile` commands...'); + const profile = path.join(home, '.profile'); + await fs.writeFile(profile, '# `.profile` commands...'); + + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/bin/bash', + }, + ); + + const bashrcContents = await fs.readFile(bashrc, 'utf-8'); + const bashrcExpected = `# \`.bashrc\` commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (bashrcContents !== bashrcExpected) { + throw new Error(`~/.bashrc does not match expectation. Contents:\n${bashrcContents}`); + } + const bashProfileContents = await fs.readFile(bashProfile, 'utf-8'); + if (bashProfileContents !== '# `.bash_profile` commands...') { + throw new Error( + `~/.bash_profile does not match expectation. Contents:\n${bashProfileContents}`, + ); + } + const profileContents = await fs.readFile(profile, 'utf-8'); + if (profileContents !== '# `.profile` commands...') { + throw new Error(`~/.profile does not match expectation. Contents:\n${profileContents}`); + } + }); + + // Appends to existing `.zshrc` file. + await mockHome(async (home) => { + const zshrc = path.join(home, '.zshrc'); + await fs.writeFile(zshrc, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }, + ); + + const rcContents = await fs.readFile(zshrc, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.zshrc does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Appends to existing `.zsh_profile` file. + await mockHome(async (home) => { + const zshProfile = path.join(home, '.zsh_profile'); + await fs.writeFile(zshProfile, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }, + ); + + const rcContents = await fs.readFile(zshProfile, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.zsh_profile does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Appends to existing `.profile` file (using Zsh). + await mockHome(async (home) => { + const profile = path.join(home, '.profile'); + await fs.writeFile(profile, '# Other commands...'); + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }, + ); + + const rcContents = await fs.readFile(profile, 'utf-8'); + const expected = `# Other commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (rcContents !== expected) { + throw new Error(`~/.profile does not match expectation. Contents:\n${rcContents}`); + } + }); + + // Zsh prefers `.zshrc`. + await mockHome(async (home) => { + const zshrc = path.join(home, '.zshrc'); + await fs.writeFile(zshrc, '# `.zshrc` commands...'); + const zshProfile = path.join(home, '.zsh_profile'); + await fs.writeFile(zshProfile, '# `.zsh_profile` commands...'); + const profile = path.join(home, '.profile'); + await fs.writeFile(profile, '# `.profile` commands...'); + + await execAndWaitForOutputToMatch( + 'ng', + ['completion'], + /Appended `source <\(ng completion script\)`/, + { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }, + ); + + const zshrcContents = await fs.readFile(zshrc, 'utf-8'); + const zshrcExpected = `# \`.zshrc\` commands...\n\n${AUTOCOMPLETION_SNIPPET}\n`; + if (zshrcContents !== zshrcExpected) { + throw new Error(`~/.zshrc does not match expectation. Contents:\n${zshrcContents}`); + } + + const zshProfileContents = await fs.readFile(zshProfile, 'utf-8'); + if (zshProfileContents !== '# `.zsh_profile` commands...') { + throw new Error( + `~/.zsh_profile does not match expectation. Contents:\n${zshProfileContents}`, + ); + } + const profileContents = await fs.readFile(profile, 'utf-8'); + if (profileContents !== '# `.profile` commands...') { + throw new Error(`~/.profile does not match expectation. Contents:\n${profileContents}`); + } + }); + + // Fails for no `$HOME` directory. + { + const err = await execAndCaptureError('ng', ['completion'], { + ...process.env, + SHELL: '/bin/bash', + HOME: undefined, + }); + if (!err.message.includes('`$HOME` environment variable not set.')) { + throw new Error(`Expected unset \`$HOME\` error message, but got:\n\n${err.message}`); + } + } + + // Fails for no `$SHELL`. + await mockHome(async (home) => { + const err = await execAndCaptureError('ng', ['completion'], { + ...process.env, + SHELL: undefined, + }); + if (!err.message.includes('`$SHELL` environment variable not set.')) { + throw new Error(`Expected unset \`$SHELL\` error message, but got:\n\n${err.message}`); + } + }); + + // Fails for unknown `$SHELL`. + await mockHome(async (home) => { + const err = await execAndCaptureError('ng', ['completion'], { + ...process.env, + SHELL: '/usr/bin/unknown', + }); + if (!err.message.includes('Unknown `$SHELL` environment variable')) { + throw new Error(`Expected unknown \`$SHELL\` error message, but got:\n\n${err.message}`); + } + }); + + // Does *not* warn when a global CLI install is present on the system. + await mockHome(async (home) => { + const { stdout } = await execWithEnv('ng', ['completion'], { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }); + + if (stdout.includes('there does not seem to be a global install of the Angular CLI')) { + throw new Error(`CLI warned about missing global install, but one should exist.`); + } + }); + + // Warns when a global CLI install is *not* present on the system. + await mockHome(async (home) => { + try { + // Temporarily uninstall the global CLI binary from the system. + await silentNpm(['uninstall', '--global', '@angular/cli', `--registry=${testRegistry}`]); + + // Setup a fake project directory with a local install of the CLI. + const projectDir = path.join(home, 'project'); + await fs.mkdir(projectDir); + await silentNpm(['init', '-y', `--registry=${testRegistry}`], { cwd: projectDir }); + await silentNpm(['install', '@angular/cli', `--registry=${testRegistry}`], { + cwd: projectDir, + }); + + // Invoke the local CLI binary. + const localCliBinary = path.join(projectDir, 'node_modules', '.bin', 'ng'); + const { stdout } = await execWithEnv(localCliBinary, ['completion'], { + ...process.env, + 'SHELL': '/usr/bin/zsh', + }); + + if (stdout.includes('there does not seem to be a global install of the Angular CLI')) { + throw new Error(`CLI warned about missing global install, but one should exist.`); + } + } finally { + // Reinstall global CLI for remainder of the tests. + await silentNpm(['install', '--global', '@angular/cli', `--registry=${testRegistry}`]); + } + }); +} + +async function windowsTests(): Promise { + // Should fail with a clear error message. + const err = await execAndCaptureError('ng', ['completion']); + if (!err.message.includes("Cmd and Powershell don't support command autocompletion")) { + throw new Error( + `Expected Windows autocompletion to fail with custom error, but got:\n\n${err.message}`, + ); + } +} diff --git a/tests/e2e/tests/commands/config/config-get.ts b/tests/e2e/tests/commands/config/config-get.ts new file mode 100644 index 000000000000..d64e0a630af0 --- /dev/null +++ b/tests/e2e/tests/commands/config/config-get.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { ng } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + await expectToFail(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle')); + await ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'false'); + const { stdout } = await ng('config', 'schematics.@schematics/angular.component.inlineStyle'); + assert.match(stdout, /false\n?/); + + await ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'true'); + const { stdout: stdout1 } = await ng( + 'config', + 'schematics.@schematics/angular.component.inlineStyle', + ); + assert.match(stdout1, /true\n?/); + + await ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'false'); + const { stdout: stdout2 } = await ng( + 'config', + `projects.test-project.architect.build.options.assets[0]`, + ); + assert.ok(stdout2.includes('"input": "public"')); + + const { stdout: stdout3 } = await ng( + 'config', + `projects["test-project"].architect.build.options.assets[0]`, + ); + assert.ok(stdout3.includes('"input": "public"')); + + // should print all config when no positional args are provided. + const { stdout: stdout4 } = await ng('config'); + assert.ok(stdout4.includes('$schema')); +} diff --git a/tests/e2e/tests/commands/config/config-global-validation.ts b/tests/e2e/tests/commands/config/config-global-validation.ts new file mode 100644 index 000000000000..85be4d5b9f6c --- /dev/null +++ b/tests/e2e/tests/commands/config/config-global-validation.ts @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { deleteFile, expectFileToExist } from '../../../utils/fs'; +import { ng, silentNg } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + let ngError: Error; + + ngError = await expectToFail(() => silentNg('config', 'cli.completion.prompted', 'true')); + assert.match(ngError.message, /Unknown option "completion" at "\/cli"\./); + + ngError = await expectToFail(() => + silentNg('config', '--global', 'cli.completion.invalid', 'true'), + ); + assert.match(ngError.message, /Unknown option "invalid" at "\/cli\/completion"\./); + + ngError = await expectToFail(() => silentNg('config', '--global', 'cli.cache.enabled', 'true')); + assert.match(ngError.message, /Unknown option "cache" at "\/cli"\./); + + ngError = await expectToFail(() => silentNg('config', 'cli.completion.prompted')); + assert.match(ngError.message, /Value cannot be found\./); + + const globalConfigPath = join(homedir(), '.angular-config.json'); + try { + await ng('config', '--global', 'cli.completion.prompted', 'true'); + const { stdout } = await silentNg('config', '--global', 'cli.completion.prompted'); + assert.match(stdout, /true/); + + await expectFileToExist(globalConfigPath); + } finally { + await deleteFile(globalConfigPath).catch(() => {}); + } +} diff --git a/tests/e2e/tests/commands/config/config-global.ts b/tests/e2e/tests/commands/config/config-global.ts new file mode 100644 index 000000000000..c12c195de3fa --- /dev/null +++ b/tests/e2e/tests/commands/config/config-global.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { deleteFile, expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + const globalConfigPath = join(homedir(), '.angular-config.json'); + + try { + await expectToFail(() => + ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle'), + ); + + await ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle', 'false'); + let output = await ng( + 'config', + '--global', + 'schematics.@schematics/angular.component.inlineStyle', + ); + assert.match(output.stdout, /false\n?/); + + const cwd = process.cwd(); + process.chdir('/'); + try { + await ng( + 'config', + '--global', + 'schematics.@schematics/angular.component.inlineStyle', + 'true', + ); + } finally { + process.chdir(cwd); + } + + output = await ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle'); + assert.match(output.stdout, /true\n?/); + + await expectToFail(() => ng('config', '--global', 'cli.warnings.notreal', 'true')); + + await ng('config', '--global', 'cli.warnings.versionMismatch', 'false'); + await expectFileToExist(globalConfigPath); + } finally { + await deleteFile(globalConfigPath).catch(() => {}); + } +} diff --git a/tests/e2e/tests/commands/config/config-set-enum-check.ts b/tests/e2e/tests/commands/config/config-set-enum-check.ts new file mode 100644 index 000000000000..571dc74cdd14 --- /dev/null +++ b/tests/e2e/tests/commands/config/config-set-enum-check.ts @@ -0,0 +1,15 @@ +import { ng } from '../../../utils/process'; + +export default async function () { + // These tests require schema querying capabilities + // .then(() => expectToFail( + // () => ng('config', 'schematics.@schematics/angular.component.aaa', 'bbb')), + // ) + // .then(() => expectToFail(() => ng( + // 'config', + // 'schematics.@schematics/angular.component.viewEncapsulation', + // 'bbb', + // ))) + + await ng('config', 'schematics.@schematics/angular.component.viewEncapsulation', 'Emulated'); +} diff --git a/tests/e2e/tests/commands/config/config-set-prefix.ts b/tests/e2e/tests/commands/config/config-set-prefix.ts new file mode 100644 index 000000000000..40f22699baed --- /dev/null +++ b/tests/e2e/tests/commands/config/config-set-prefix.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict'; +import { ng } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default function () { + return Promise.resolve() + .then(() => expectToFail(() => ng('config', 'schematics.@schematics/angular.component.prefix'))) + .then(() => ng('config', 'schematics.@schematics/angular.component.prefix', 'new-prefix')) + .then(() => ng('config', 'schematics.@schematics/angular.component.prefix')) + .then(({ stdout }) => { + assert.match(stdout, /new-prefix/); + }); +} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-serve-port.ts b/tests/e2e/tests/commands/config/config-set-serve-port.ts similarity index 90% rename from tests/legacy-cli/e2e/tests/commands/config/config-set-serve-port.ts rename to tests/e2e/tests/commands/config/config-set-serve-port.ts index 7557c6f534c9..125d21d7e66f 100644 --- a/tests/legacy-cli/e2e/tests/commands/config/config-set-serve-port.ts +++ b/tests/e2e/tests/commands/config/config-set-serve-port.ts @@ -1,7 +1,7 @@ import { expectFileToMatch } from '../../../utils/fs'; import { ng } from '../../../utils/process'; -export default function() { +export default function () { return Promise.resolve() .then(() => ng('config', 'projects.test-project.architect.serve.options.port', '1234')) .then(() => expectFileToMatch('angular.json', /"port": 1234/)); diff --git a/tests/e2e/tests/commands/config/config-set.ts b/tests/e2e/tests/commands/config/config-set.ts new file mode 100644 index 000000000000..05fa364bcb37 --- /dev/null +++ b/tests/e2e/tests/commands/config/config-set.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { ng, silentNg } from '../../../utils/process'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + let ngError: Error; + + ngError = await expectToFail(() => silentNg('config', 'cli.warnings.zzzz', 'true')); + assert.match(ngError.message, /Unknown option "zzzz" at "\/cli\/warnings"\./); + + ngError = await expectToFail(() => silentNg('config', 'cli.warnings.zzzz')); + assert.match(ngError.message, /Value cannot be found\./); + + await ng('config', 'cli.warnings.versionMismatch', 'false'); + const { stdout } = await ng('config', 'cli.warnings.versionMismatch'); + assert.match(stdout, /false/); + + await ng('config', 'cli.packageManager', 'yarn'); + const { stdout: stdout2 } = await ng('config', 'cli.packageManager'); + assert.match(stdout2, /yarn/); + + await ng('config', 'schematics', '{"@schematics/angular:component":{"style": "scss"}}'); + const { stdout: stdout3 } = await ng('config', 'schematics.@schematics/angular:component.style'); + assert.match(stdout3, /scss/); + + await ng('config', 'schematics'); + await ng('config', 'schematics', 'undefined'); + await expectToFail(() => ng('config', 'schematics')); +} diff --git a/tests/e2e/tests/commands/help/help-hidden.ts b/tests/e2e/tests/commands/help/help-hidden.ts new file mode 100644 index 000000000000..bd972d26a942 --- /dev/null +++ b/tests/e2e/tests/commands/help/help-hidden.ts @@ -0,0 +1,14 @@ +import assert from 'node:assert/strict'; +import { silentNg } from '../../../utils/process'; + +export default async function () { + const { stdout: stdoutNew } = await silentNg('--help'); + assert.doesNotMatch( + stdoutNew, + /(easter-egg)|(ng make-this-awesome)|(ng init)/, + 'Expected to not match "(easter-egg)|(ng make-this-awesome)|(ng init)" in help output.', + ); + + const { stdout: ngGenerate } = await silentNg('--help', 'generate', 'component'); + assert.doesNotMatch(ngGenerate, /--path/, 'Expected to not match "--path" in help output.'); +} diff --git a/tests/e2e/tests/commands/help/help-json.ts b/tests/e2e/tests/commands/help/help-json.ts new file mode 100644 index 000000000000..6f1b8e89db49 --- /dev/null +++ b/tests/e2e/tests/commands/help/help-json.ts @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { silentNg } from '../../../utils/process'; + +export default async function () { + // This test is use as a sanity check. + const addHelpOutputSnapshot = JSON.stringify({ + 'name': 'config', + 'command': 'ng config [json-path] [value]', + 'shortDescription': + 'Retrieves or sets Angular configuration values in the angular.json file for the workspace.', + 'longDescriptionRelativePath': '@angular/cli/src/commands/config/long-description.md', + 'longDescription': + 'A workspace has a single CLI configuration file, `angular.json`, at the top level.\nThe `projects` object contains a configuration object for each project in the workspace.\n\nYou can edit the configuration directly in a code editor,\nor indirectly on the command line using this command.\n\nThe configurable property names match command option names,\nexcept that in the configuration file, all names must use camelCase,\nwhile on the command line options can be given dash-case.\n\nFor further details, see [Workspace Configuration](reference/configs/workspace-config).\n\nFor configuration of CLI usage analytics, see [ng analytics](cli/analytics).\n', + 'options': [ + { + 'name': 'global', + 'type': 'boolean', + 'aliases': ['g'], + 'default': false, + 'description': "Access the global configuration in the caller's home directory.", + }, + { + 'name': 'help', + 'type': 'boolean', + 'description': 'Shows a help message for this command in the console.', + }, + { + 'name': 'json-path', + 'type': 'string', + 'description': + 'The configuration key to set or query, in JSON path format. For example: "a[3].foo.bar[2]". If no new value is provided, returns the current value of this key.', + 'positional': 0, + }, + { + 'name': 'value', + 'type': 'string', + 'description': 'If provided, a new value for the given configuration key.', + 'positional': 1, + }, + ], + }); + + const { stdout } = await silentNg('config', '--help', '--json-help'); + const output = JSON.stringify(JSON.parse(stdout.trim())); + + assert.strictEqual( + output, + addHelpOutputSnapshot, + `ng config JSON help output didn\'t match snapshot.`, + ); + + const { stdout: stdout2 } = await silentNg('--help', '--json-help'); + assert.doesNotThrow( + () => JSON.parse(stdout2.trim()), + `'ng --help ---json-help' failed to return JSON.`, + ); + + const { stdout: stdout3 } = await silentNg('generate', '--help', '--json-help'); + assert.doesNotThrow( + () => JSON.parse(stdout3.trim()), + `'ng generate --help ---json-help' failed to return JSON.`, + ); +} diff --git a/tests/e2e/tests/commands/ng-new-collection.ts b/tests/e2e/tests/commands/ng-new-collection.ts new file mode 100644 index 000000000000..e55c75ee69b4 --- /dev/null +++ b/tests/e2e/tests/commands/ng-new-collection.ts @@ -0,0 +1,19 @@ +import { execAndWaitForOutputToMatch } from '../../utils/process'; + +export default async function () { + const currentDirectory = process.cwd(); + + try { + process.chdir('..'); + + // The below is a way to validate that the `--collection` option is being considered. + await execAndWaitForOutputToMatch( + 'ng', + ['new', '--collection', 'invalid-schematic'], + /Collection "invalid-schematic" cannot be resolved/, + ); + } finally { + // Change directory back + process.chdir(currentDirectory); + } +} diff --git a/tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts b/tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts new file mode 100644 index 000000000000..f0eaf7633482 --- /dev/null +++ b/tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { execAndCaptureError, execAndWaitForOutputToMatch, ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + const errorMessage = + 'Cannot determine project for command.\n' + + 'This is a multi-project workspace and more than one project supports this command.'; + + // Delete root project + await updateJsonFile('angular.json', (workspaceJson) => { + delete workspaceJson.projects['test-project']; + }); + + await ng('generate', 'app', 'second-app', '--skip-install'); + await ng('generate', 'app', 'third-app', '--skip-install'); + + const startCwd = process.cwd(); + + try { + const { message } = await expectToFail(() => ng('build')); + assert.match(message, new RegExp(errorMessage)); + + // Schematics that require a project should explain how to select one + const { message: generateMessage } = await expectToFail(() => + ng('generate', 'component', 'foo'), + ); + assert.match(generateMessage, new RegExp(errorMessage)); + assert.match(generateMessage, /Use the "--project" option to specify a project/); + assert.match(generateMessage, /Available projects are:\n- second-app\n- third-app/); + + // The project is checked before prompting for other options + const { message: interactiveMessage } = await execAndCaptureError( + 'ng', + ['generate', 'component'], + { + ...process.env, + NG_FORCE_TTY: '1', + NG_CLI_ANALYTICS: 'false', + NG_FORCE_AUTOCOMPLETE: 'false', + }, + 'foo\n', + ); + assert.match(interactiveMessage, /Use the "--project" option to specify a project/); + assert.doesNotMatch(interactiveMessage, /What name would you like to use for the component/); + + // Help should still work + await execAndWaitForOutputToMatch('ng', ['build', '--help'], /--configuration/); + + // Yargs allows positional args to be passed as flags. Verify that in this case the project can be determined. + await ng('build', '--project=third-app', '--configuration=development'); + + process.chdir(join(startCwd, 'projects/second-app')); + await ng('build', '--configuration=development'); + await ng('generate', 'component', 'foo', '--dry-run'); + } finally { + // Restore path + process.chdir(startCwd); + } + + // A project from the workspace schematic options is used and other validation errors are kept + await updateJsonFile('angular.json', (workspaceJson) => { + workspaceJson.schematics ??= {}; + workspaceJson.schematics['@schematics/angular:component'] = { project: 'second-app' }; + }); + const { message: selectorMessage } = await expectToFail(() => + ng('generate', 'component', 'foo', '--selector=1foo'), + ); + assert.match(selectorMessage, /must match format "html-selector"/); + assert.doesNotMatch(selectorMessage, /Cannot determine project/); + await ng('generate', 'component', 'foo', '--dry-run'); +} diff --git a/tests/e2e/tests/commands/run-configuration-option.ts b/tests/e2e/tests/commands/run-configuration-option.ts new file mode 100644 index 000000000000..ab2761dce531 --- /dev/null +++ b/tests/e2e/tests/commands/run-configuration-option.ts @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict'; +import { silentNg } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + const errorMatch = `Provide the configuration as part of the target 'ng run test-project:build:production`; + + { + const { message } = await expectToFail(() => + silentNg('run', 'test-project:build:development', '--configuration=production'), + ); + + assert.ok(message.includes(errorMatch)); + } + + { + const { message } = await expectToFail(() => + silentNg('run', 'test-project:build', '--configuration=production'), + ); + + assert.ok(message.includes(errorMatch)); + } +} diff --git a/tests/e2e/tests/commands/serve/assets.ts b/tests/e2e/tests/commands/serve/assets.ts new file mode 100644 index 000000000000..dba1abea37cb --- /dev/null +++ b/tests/e2e/tests/commands/serve/assets.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert'; +import { ngServe } from '../../../utils/project'; +import { getGlobalVariable } from '../../../utils/env'; + +export default async function () { + const port = await ngServe(); + + let response = await fetch(`http://localhost:${port}/favicon.ico`); + assert.strictEqual(response.status, 200, 'favicon.ico response should be ok'); + + // A non-existent HTML file request with accept header should fallback to the index HTML + response = await fetch(`http://localhost:${port}/does-not-exist.html`, { + headers: { accept: 'text/html' }, + }); + assert.strictEqual(response.status, 200, 'non-existent file response should fallback and be ok'); + assert.match( + await response.text(), + / { + const result = await fetch(url, { method: 'HEAD' }); + const content = await result.blob(); + + assert.strictEqual(content.size, 0, `Expected "size" to be "0" but got "${content.size}".`); + assert.strictEqual( + result.status, + 200, + `Expected "status" to be "200" but got "${result.status}".`, + ); +} diff --git a/tests/e2e/tests/commands/serve/preflight-request.ts b/tests/e2e/tests/commands/serve/preflight-request.ts new file mode 100644 index 000000000000..02a763dce197 --- /dev/null +++ b/tests/e2e/tests/commands/serve/preflight-request.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { ngServe } from '../../../utils/project'; + +export default async function () { + const port = await ngServe(); + const result = await fetch(`http://localhost:${port}/main.js`, { method: 'OPTIONS' }); + const content = await result.blob(); + + assert.strictEqual(content.size, 0, `Expected "size" to be "0" but got "${content.size}".`); + assert.strictEqual( + result.status, + 204, + `Expected "status" to be "204" but got "${result.status}".`, + ); +} diff --git a/tests/e2e/tests/commands/serve/reload-shims.ts b/tests/e2e/tests/commands/serve/reload-shims.ts new file mode 100644 index 000000000000..345979da5cc2 --- /dev/null +++ b/tests/e2e/tests/commands/serve/reload-shims.ts @@ -0,0 +1,21 @@ +import { prependToFile, writeFile } from '../../../utils/fs'; +import { execAndWaitForOutputToMatch } from '../../../utils/process'; + +export default async function () { + // Simulate a JS library using a Node.js specific module + await writeFile('src/node-usage.js', `const path = require('path');\n`); + await prependToFile('src/main.ts', `import './node-usage';\n`); + + // Make sure serve is consistent with build + await execAndWaitForOutputToMatch( + 'ng', + ['build'], + /Module not found: Error: Can't resolve 'path'/, + ); + // The Node.js specific module should not be found + await execAndWaitForOutputToMatch( + 'ng', + ['serve', '--port=0'], + /Module not found: Error: Can't resolve 'path'/, + ); +} diff --git a/tests/e2e/tests/commands/serve/serve-path.ts b/tests/e2e/tests/commands/serve/serve-path.ts new file mode 100644 index 000000000000..397a6c2f973f --- /dev/null +++ b/tests/e2e/tests/commands/serve/serve-path.ts @@ -0,0 +1,20 @@ +import * as assert from 'node:assert'; +import { ngServe } from '../../../utils/project'; + +export default async function () { + // TODO(architect): Delete this test. It is now in devkit/build-angular. + + const port = await ngServe('--serve-path', 'test/'); + + return Promise.resolve() + .then(() => fetch(`http://localhost:${port}/test`, { headers: { 'Accept': 'text/html' } })) + .then(async (response) => { + assert.strictEqual(response.status, 200); + assert.match(await response.text(), /<\/app-root>/); + }) + .then(() => fetch(`http://localhost:${port}/test/abc`, { headers: { 'Accept': 'text/html' } })) + .then(async (response) => { + assert.strictEqual(response.status, 200); + assert.match(await response.text(), /<\/app-root>/); + }); +} diff --git a/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts b/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts new file mode 100644 index 000000000000..6946788c758f --- /dev/null +++ b/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts @@ -0,0 +1,125 @@ +import assert from 'node:assert'; +import { Agent, fetch } from 'undici'; +import { killAllProcesses, ng } from '../../../utils/process'; +import { writeMultipleFiles } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ngServe, useSha } from '../../../utils/project'; + +export default async function () { + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Add http client and route + 'src/app/app.config.ts': ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import { Home } from './home/home'; + import { provideClientHydration } from '@angular/platform-browser'; + import { provideHttpClient, withFetch } from '@angular/common/http'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter([{ + path: '', + component: Home, + }]), + provideClientHydration(), + provideHttpClient(withFetch()), + ], + }; + `, + // Add asset + 'public/media.json': JSON.stringify({ dataFromAssets: true }), + // Update component to do an HTTP call to asset. + 'src/app/app.ts': ` + import { ChangeDetectorRef, Component, inject } from '@angular/core'; + import { CommonModule } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + import { HttpClient } from '@angular/common/http'; + + @Component({ + selector: 'app-root', + imports: [CommonModule, RouterOutlet], + template: \` +

{{ data | json }}

+ + \`, + }) + export class App { + data: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); + + constructor() { + const http = inject(HttpClient); + http.get('/media.json').toPromise().then((d) => { + this.data = d; + this.cdr.markForCheck(); + }); + } + } + `, + }); + + await ng('generate', 'component', 'home'); + const match = /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/; + const port = await ngServe('--no-ssl'); + assert.match(await (await fetch(`http://localhost:${port}/`)).text(), match); + + await killAllProcesses(); + + const sslPort = await ngServe('--ssl'); + assert.match( + await ( + await fetch(`https://localhost:${sslPort}/`, { + dispatcher: new Agent({ + connect: { + rejectUnauthorized: false, + }, + }), + }) + ).text(), + match, + ); + + await killAllProcesses(); + + // With OpenSSl cert+key + await writeMultipleFiles({ + 'server.key': `-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgEpythQjrJo9bm8GM +LFacGutCqc/XxDZ3dDkSMYZYZ2ehRANCAARvwtZ3OwP1uLhrcLp7nemvaWqkA+FN +NDjOA3OZKhyVHYog1jNTawJJjwk66upbXGFL8622yU1INWbZFxvrSANl +-----END PRIVATE KEY----- +`, + 'server.crt': `-----BEGIN CERTIFICATE----- +MIIBfzCCASWgAwIBAgIUUoRhwzxAE3y5nrOW8de+cJEIVvQwCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTAxOTA4NTUyNVoYDzIxMjYwOTI1 +MDg1NTI1WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO +PQMBBwNCAARvwtZ3OwP1uLhrcLp7nemvaWqkA+FNNDjOA3OZKhyVHYog1jNTawJJ +jwk66upbXGFL8622yU1INWbZFxvrSANlo1MwUTAdBgNVHQ4EFgQUWyqB1QeFcs6L +LL7Utsybm6+XFvIwHwYDVR0jBBgwFoAUWyqB1QeFcs6LLL7Utsybm6+XFvIwDwYD +VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBazry25W+Qewb/WzadhmdY +YDGdshNZCk0g0DI3ctNjlgIhAKm2X8pmqdkM38Yh8QDN0cHBsAcDfRYffDnjJ3tP +dpnU +-----END CERTIFICATE----- +`, + }); + + const sslPortForCerts = await ngServe('--ssl', '--ssl-cert=server.crt', '--ssl-key="server.key"'); + assert.match( + await ( + await fetch(`https://localhost:${sslPortForCerts}/`, { + dispatcher: new Agent({ + connect: { + rejectUnauthorized: false, + }, + }), + }) + ).text(), + match, + ); +} diff --git a/tests/e2e/tests/commands/unknown-configuration.ts b/tests/e2e/tests/commands/unknown-configuration.ts new file mode 100644 index 000000000000..c74d6547de59 --- /dev/null +++ b/tests/e2e/tests/commands/unknown-configuration.ts @@ -0,0 +1,11 @@ +import assert from 'node:assert'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + const error = await expectToFail(() => ng('build', '--configuration', 'invalid')); + assert.match( + error.message, + /Configuration 'invalid' for target 'build' in project 'test-project' is not set in the workspace/, + ); +} diff --git a/tests/e2e/tests/commands/unknown-option.ts b/tests/e2e/tests/commands/unknown-option.ts new file mode 100644 index 000000000000..f0f4cde0693f --- /dev/null +++ b/tests/e2e/tests/commands/unknown-option.ts @@ -0,0 +1,17 @@ +import { execAndWaitForOutputToMatch, ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + await expectToFail(() => ng('build', '--notanoption')); + + await execAndWaitForOutputToMatch( + 'ng', + ['build', '--notanoption'], + /Unknown argument: notanoption/, + ); + + const ngGenerateArgs = ['generate', 'component', 'component-name', '--notanoption']; + await expectToFail(() => ng(...ngGenerateArgs)); + + await execAndWaitForOutputToMatch('ng', ngGenerateArgs, /Unknown argument: notanoption/); +} diff --git a/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts b/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts new file mode 100644 index 000000000000..b475ed03b3a7 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts @@ -0,0 +1,16 @@ +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + try { + await ng('generate', 'app', 'ngmodules', '--no-standalone', '--skip-install', '--no-zoneless'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('ngmodules', 'projects/ngmodules'); + await ng('test', 'ngmodules', '--watch=false'); + await ng('build', 'ngmodules'); + } finally { + await uninstallPackage('zone.js'); + } +} diff --git a/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts b/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts new file mode 100644 index 000000000000..065957f9fe11 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts @@ -0,0 +1,16 @@ +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + try { + await ng('generate', 'app', 'standalone', '--standalone', '--skip-install', '--no-zoneless'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('standalone', 'projects/standalone'); + await ng('test', 'standalone', '--watch=false'); + await ng('build', 'standalone'); + } finally { + await uninstallPackage('zone.js'); + } +} diff --git a/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts b/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts new file mode 100644 index 000000000000..5ad207a2fa76 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts @@ -0,0 +1,12 @@ +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'app', 'ngmodules', '--no-standalone', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('ngmodules', 'projects/ngmodules'); + await ng('test', 'ngmodules', '--watch=false'); + await ng('build', 'ngmodules'); +} diff --git a/tests/e2e/tests/generate/application/application-zoneless-standalone.ts b/tests/e2e/tests/generate/application/application-zoneless-standalone.ts new file mode 100644 index 000000000000..b203ed4a28d0 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-zoneless-standalone.ts @@ -0,0 +1,12 @@ +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'app', 'standalone', '--standalone', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('standalone', 'projects/standalone'); + await ng('test', 'standalone', '--watch=false'); + await ng('build', 'standalone'); +} diff --git a/tests/e2e/tests/generate/component/component-basic.ts b/tests/e2e/tests/generate/component/component-basic.ts new file mode 100644 index 000000000000..06d4e093553d --- /dev/null +++ b/tests/e2e/tests/generate/component/component-basic.ts @@ -0,0 +1,21 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; + +export default async function () { + const componentDir = 'src/app/test-component'; + + await ng('generate', 'component', 'test-component'); + await expectFileToExist(componentDir); + await expectFileToExist(join(componentDir, 'test-component.ts')); + await expectFileToExist(join(componentDir, 'test-component.spec.ts')); + await expectFileToExist(join(componentDir, 'test-component.html')); + await expectFileToExist(join(componentDir, 'test-component.css')); + + // Try to run the unit tests. + await ng('test', '--watch=false'); + + // Should generate component that is named "help". + await ng('generate', 'component', 'help'); + await expectFileToExist('src/app/help/help.ts'); +} diff --git a/tests/e2e/tests/generate/component/component-child-dir.ts b/tests/e2e/tests/generate/component/component-child-dir.ts new file mode 100644 index 000000000000..e6ce6577a07a --- /dev/null +++ b/tests/e2e/tests/generate/component/component-child-dir.ts @@ -0,0 +1,35 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { createDir, expectFileToExist, rimraf } from '../../../utils/fs'; + +export default async function () { + const currentDirectory = process.cwd(); + const childDirectory = join('src', 'app', 'sub-dir'); + + try { + // Create and enter a child directory inside the project + await createDir(childDirectory); + process.chdir(childDirectory); + + // Generate a component inside the child directory + await ng('generate', 'component', 'test-component'); + + // Move back to the root of the workspace + process.chdir(currentDirectory); + + // Ensure component is created in the correct location relative to the workspace root + const componentDirectory = join(childDirectory, 'test-component'); + await expectFileToExist(join(componentDirectory, 'test-component.ts')); + await expectFileToExist(join(componentDirectory, 'test-component.spec.ts')); + await expectFileToExist(join(componentDirectory, 'test-component.html')); + await expectFileToExist(join(componentDirectory, 'test-component.css')); + + // Ensure unit test execute and pass + await ng('test', '--watch=false'); + } finally { + process.chdir(currentDirectory); + // Windows CI may fail to clean up the created directory + // Resolves: "Error: Running "cmd.exe /c git clean -df" returned error code 1" + await rimraf(childDirectory); + } +} diff --git a/tests/e2e/tests/generate/component/component-flat.ts b/tests/e2e/tests/generate/component/component-flat.ts new file mode 100644 index 000000000000..4bdb101391fa --- /dev/null +++ b/tests/e2e/tests/generate/component/component-flat.ts @@ -0,0 +1,27 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; +import { updateJsonFile } from '../../../utils/project'; + +export default function () { + const appDir = join('src', 'app'); + return ( + Promise.resolve() + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].schematics = { + '@schematics/angular:component': { flat: true }, + }; + }), + ) + .then(() => ng('generate', 'component', 'test-component')) + .then(() => expectFileToExist(appDir)) + .then(() => expectFileToExist(join(appDir, 'test-component.ts'))) + .then(() => expectFileToExist(join(appDir, 'test-component.spec.ts'))) + .then(() => expectFileToExist(join(appDir, 'test-component.html'))) + .then(() => expectFileToExist(join(appDir, 'test-component.css'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/component/component-inline-template.ts b/tests/e2e/tests/generate/component/component-inline-template.ts new file mode 100644 index 000000000000..135b97c43fcb --- /dev/null +++ b/tests/e2e/tests/generate/component/component-inline-template.ts @@ -0,0 +1,29 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; +import { updateJsonFile } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +// tslint:disable:max-line-length +export default function () { + const componentDir = join('src', 'app', 'test-component'); + return ( + Promise.resolve() + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].schematics = { + '@schematics/angular:component': { inlineTemplate: true }, + }; + }), + ) + .then(() => ng('generate', 'component', 'test-component')) + .then(() => expectFileToExist(componentDir)) + .then(() => expectFileToExist(join(componentDir, 'test-component.ts'))) + .then(() => expectFileToExist(join(componentDir, 'test-component.spec.ts'))) + .then(() => expectToFail(() => expectFileToExist(join(componentDir, 'test-component.html')))) + .then(() => expectFileToExist(join(componentDir, 'test-component.css'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/component/component-not-flat.ts b/tests/e2e/tests/generate/component/component-not-flat.ts new file mode 100644 index 000000000000..eedc3926da89 --- /dev/null +++ b/tests/e2e/tests/generate/component/component-not-flat.ts @@ -0,0 +1,28 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; +import { updateJsonFile } from '../../../utils/project'; + +export default function () { + const componentDir = join('src', 'app', 'test-component'); + + return ( + Promise.resolve() + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].schematics = { + '@schematics/angular:component': { flat: false }, + }; + }), + ) + .then(() => ng('generate', 'component', 'test-component')) + .then(() => expectFileToExist(componentDir)) + .then(() => expectFileToExist(join(componentDir, 'test-component.ts'))) + .then(() => expectFileToExist(join(componentDir, 'test-component.spec.ts'))) + .then(() => expectFileToExist(join(componentDir, 'test-component.html'))) + .then(() => expectFileToExist(join(componentDir, 'test-component.css'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/component/component-path-case.ts b/tests/e2e/tests/generate/component/component-path-case.ts new file mode 100644 index 000000000000..63d08af7099d --- /dev/null +++ b/tests/e2e/tests/generate/component/component-path-case.ts @@ -0,0 +1,38 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist, rimraf } from '../../../utils/fs'; + +export default async function () { + const upperDirs = join('non', 'existing', 'dir'); + const rootDir = join('src', 'app', upperDirs); + + const componentDirectory = join(rootDir, 'test-component'); + const componentTwoDirectory = join(rootDir, 'test-component-two'); + + try { + // Generate a component + await ng('generate', 'component', `${upperDirs}/test-component`); + + // Ensure component is created in the correct location relative to the workspace root + await expectFileToExist(join(componentDirectory, 'test-component.ts')); + await expectFileToExist(join(componentDirectory, 'test-component.spec.ts')); + await expectFileToExist(join(componentDirectory, 'test-component.html')); + await expectFileToExist(join(componentDirectory, 'test-component.css')); + + // Generate another component + await ng('generate', 'component', `${upperDirs}/Test-Component-Two`); + + // Ensure component is created in the correct location relative to the workspace root + await expectFileToExist(join(componentTwoDirectory, 'test-component-two.ts')); + await expectFileToExist(join(componentTwoDirectory, 'test-component-two.spec.ts')); + await expectFileToExist(join(componentTwoDirectory, 'test-component-two.html')); + await expectFileToExist(join(componentTwoDirectory, 'test-component-two.css')); + + // Ensure unit test execute and pass + await ng('test', '--watch=false'); + } finally { + // Windows CI may fail to clean up the created directory + // Resolves: "Error: Running "cmd.exe /c git clean -df" returned error code 1" + await rimraf(rootDir); + } +} diff --git a/tests/e2e/tests/generate/component/component-prefix.ts b/tests/e2e/tests/generate/component/component-prefix.ts new file mode 100644 index 000000000000..befa96939b00 --- /dev/null +++ b/tests/e2e/tests/generate/component/component-prefix.ts @@ -0,0 +1,27 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToMatch } from '../../../utils/fs'; +import { updateJsonFile } from '../../../utils/project'; + +export default function () { + const testCompDir = join('src', 'app', 'test-component'); + const aliasCompDir = join('src', 'app', 'alias'); + + return ( + Promise.resolve() + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].schematics = { + '@schematics/angular:component': { prefix: 'pre' }, + }; + }), + ) + .then(() => ng('generate', 'component', 'test-component')) + .then(() => expectFileToMatch(join(testCompDir, 'test-component.ts'), /selector: 'pre-/)) + .then(() => ng('g', 'c', 'alias')) + .then(() => expectFileToMatch(join(aliasCompDir, 'alias.ts'), /selector: 'pre-/)) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/config/type-browserslist.ts b/tests/e2e/tests/generate/config/type-browserslist.ts new file mode 100644 index 000000000000..b9717852a4f1 --- /dev/null +++ b/tests/e2e/tests/generate/config/type-browserslist.ts @@ -0,0 +1,6 @@ +import { ng } from '../../../utils/process'; + +export default async function () { + await ng('generate', 'config', 'browserslist'); + await ng('build'); +} diff --git a/tests/e2e/tests/generate/config/type-karma.ts b/tests/e2e/tests/generate/config/type-karma.ts new file mode 100644 index 000000000000..c81b7d6b1abf --- /dev/null +++ b/tests/e2e/tests/generate/config/type-karma.ts @@ -0,0 +1,8 @@ +import { ng } from '../../../utils/process'; +import { useCIChrome } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'config', 'karma'); + await useCIChrome('test-project'); + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/generate/directive/directive-basic.ts b/tests/e2e/tests/generate/directive/directive-basic.ts new file mode 100644 index 000000000000..9ad00dfa22a3 --- /dev/null +++ b/tests/e2e/tests/generate/directive/directive-basic.ts @@ -0,0 +1,15 @@ +import { ng } from '../../../utils/process'; +import { join } from 'node:path'; +import { expectFileToExist } from '../../../utils/fs'; + +export default function () { + const directiveDir = join('src', 'app'); + return ( + ng('generate', 'directive', 'test-directive') + .then(() => expectFileToExist(join(directiveDir, 'test-directive.ts'))) + .then(() => expectFileToExist(join(directiveDir, 'test-directive.spec.ts'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/directive/directive-prefix.ts b/tests/e2e/tests/generate/directive/directive-prefix.ts new file mode 100644 index 000000000000..a8b5981b34a3 --- /dev/null +++ b/tests/e2e/tests/generate/directive/directive-prefix.ts @@ -0,0 +1,46 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToMatch } from '../../../utils/fs'; +import { updateJsonFile, useCIChrome, useCIDefaults } from '../../../utils/project'; + +export default function () { + const directiveDir = join('src', 'app'); + + return ( + Promise.resolve() + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.schematics = { + '@schematics/angular:directive': { prefix: 'preW' }, + }; + }), + ) + .then(() => ng('generate', 'directive', 'test2-directive')) + .then(() => expectFileToMatch(join(directiveDir, 'test2-directive.ts'), /selector: '\[preW/)) + .then(() => + ng('generate', 'application', 'app-two', '--skip-install', '--test-runner', 'karma'), + ) + .then(() => useCIDefaults('app-two')) + .then(() => useCIChrome('app-two', './projects/app-two')) + .then(() => + updateJsonFile('angular.json', (configJson) => { + configJson.projects['test-project'].schematics = { + '@schematics/angular:directive': { prefix: 'preP' }, + }; + }), + ) + .then(() => process.chdir('projects/app-two')) + .then(() => ng('generate', 'directive', '--skip-import', 'test3-directive')) + .then(() => process.chdir('../..')) + .then(() => + expectFileToMatch(join('projects', 'app-two', 'test3-directive.ts'), /selector: '\[preW/), + ) + .then(() => process.chdir('src/app')) + .then(() => ng('generate', 'directive', 'test-directive')) + .then(() => process.chdir('../..')) + .then(() => expectFileToMatch(join(directiveDir, 'test-directive.ts'), /selector: '\[preP/)) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/formatting.ts b/tests/e2e/tests/generate/formatting.ts new file mode 100644 index 000000000000..9efcaaadd3c5 --- /dev/null +++ b/tests/e2e/tests/generate/formatting.ts @@ -0,0 +1,28 @@ +import { expectFileToMatch, writeFile } from '../../utils/fs'; +import { installPackage, uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; + +export default async function () { + try { + await writeFile('.prettierrc', JSON.stringify({ singleQuote: true, semi: false })); + await ng('generate', 'service', 'prettier-only', '--skip-tests'); + await expectFileToMatch('src/app/prettier-only.ts', "from '@angular/core'"); + + // Distinct configurations make the selected formatter observable when both are installed. + await installPackage('oxfmt'); + await writeFile('.oxfmtrc.json', JSON.stringify({ singleQuote: false, semi: false })); + await ng('generate', 'service', 'both-formatters', '--skip-tests'); + await expectFileToMatch('src/app/both-formatters.ts', "from '@angular/core'"); + + await uninstallPackage('prettier'); + await ng('generate', 'service', 'oxfmt-only', '--skip-tests'); + await expectFileToMatch('src/app/oxfmt-only.ts', 'from "@angular/core"'); + + await uninstallPackage('oxfmt'); + await ng('generate', 'service', 'no-formatter', '--skip-tests'); + await expectFileToMatch('src/app/no-formatter.ts', "from '@angular/core';"); + } finally { + await uninstallPackage('oxfmt'); + await installPackage('prettier'); + } +} diff --git a/tests/e2e/tests/generate/generate-error.ts b/tests/e2e/tests/generate/generate-error.ts new file mode 100644 index 000000000000..cee6d7998239 --- /dev/null +++ b/tests/e2e/tests/generate/generate-error.ts @@ -0,0 +1,9 @@ +import { ng } from '../../utils/process'; +import { deleteFile } from '../../utils/fs'; +import { expectToFail } from '../../utils/utils'; + +export default function () { + return deleteFile('angular.json').then(() => + expectToFail(() => ng('generate', 'class', 'hello')), + ); +} diff --git a/tests/e2e/tests/generate/generate-name-check.ts b/tests/e2e/tests/generate/generate-name-check.ts new file mode 100644 index 000000000000..6fe89a58face --- /dev/null +++ b/tests/e2e/tests/generate/generate-name-check.ts @@ -0,0 +1,27 @@ +import { join } from 'node:path'; +import { ng } from '../../utils/process'; +import { expectFileToExist } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; + +export default function () { + const compDir = join('src', 'app', 'test-component'); + + return ( + Promise.resolve() + .then(() => + updateJsonFile('package.json', (configJson) => { + delete configJson.name; + return configJson; + }), + ) + .then(() => ng('generate', 'component', 'test-component')) + .then(() => expectFileToExist(compDir)) + .then(() => expectFileToExist(join(compDir, 'test-component.ts'))) + .then(() => expectFileToExist(join(compDir, 'test-component.spec.ts'))) + .then(() => expectFileToExist(join(compDir, 'test-component.html'))) + .then(() => expectFileToExist(join(compDir, 'test-component.css'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/guard/guard-basic.ts b/tests/e2e/tests/generate/guard/guard-basic.ts new file mode 100644 index 000000000000..ca4e9a547ff6 --- /dev/null +++ b/tests/e2e/tests/generate/guard/guard-basic.ts @@ -0,0 +1,15 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist, expectFileToMatch } from '../../../utils/fs'; + +export default async function () { + // Does not create a sub directory. + const guardDir = join('src', 'app'); + + await ng('generate', 'guard', 'test'); + await expectFileToExist(guardDir); + await expectFileToExist(join(guardDir, 'test-guard.ts')); + await expectFileToMatch(join(guardDir, 'test-guard.ts'), /export const testGuard: CanActivateFn/); + await expectFileToExist(join(guardDir, 'test-guard.spec.ts')); + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/generate/guard/guard-implements.ts b/tests/e2e/tests/generate/guard/guard-implements.ts new file mode 100644 index 000000000000..ca7c35f754a4 --- /dev/null +++ b/tests/e2e/tests/generate/guard/guard-implements.ts @@ -0,0 +1,15 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist, expectFileToMatch } from '../../../utils/fs'; + +export default async function () { + // Does not create a sub directory. + const guardDir = join('src', 'app'); + + await ng('generate', 'guard', 'match', '--implements=CanMatch'); + await expectFileToExist(guardDir); + await expectFileToExist(join(guardDir, 'match-guard.ts')); + await expectFileToMatch(join(guardDir, 'match-guard.ts'), /export const matchGuard: CanMatch/); + await expectFileToExist(join(guardDir, 'match-guard.spec.ts')); + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/generate/guard/guard-multiple-implements.ts b/tests/e2e/tests/generate/guard/guard-multiple-implements.ts new file mode 100644 index 000000000000..4359eaaf9f59 --- /dev/null +++ b/tests/e2e/tests/generate/guard/guard-multiple-implements.ts @@ -0,0 +1,26 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist, expectFileToMatch } from '../../../utils/fs'; + +export default async function () { + // Does not create a sub directory. + const guardDir = join('src', 'app'); + + // multiple implements are only supported in (deprecated) class-based guards + await ng( + 'generate', + 'guard', + 'multiple', + '--implements=CanActivate', + '--implements=CanDeactivate', + '--no-functional', + ); + await expectFileToExist(guardDir); + await expectFileToExist(join(guardDir, 'multiple-guard.ts')); + await expectFileToMatch( + join(guardDir, 'multiple-guard.ts'), + /implements CanActivate, CanDeactivate/, + ); + await expectFileToExist(join(guardDir, 'multiple-guard.spec.ts')); + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/generate/help-output-no-duplicates.ts b/tests/e2e/tests/generate/help-output-no-duplicates.ts new file mode 100644 index 000000000000..0be6ea93ea48 --- /dev/null +++ b/tests/e2e/tests/generate/help-output-no-duplicates.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { ng } from '../../utils/process'; + +export default async function () { + // Verify that there are no duplicate options + const { stdout } = await ng('generate', 'component', '--help'); + const firstIndex = stdout.indexOf('--prefix'); + + assert.ok(firstIndex >= 0, '--prefix was not part of the help output.'); + assert.strictEqual( + firstIndex, + stdout.lastIndexOf('--prefix'), + '--prefix first and last index were different. Possible duplicate output!', + ); +} diff --git a/tests/e2e/tests/generate/help-output.ts b/tests/e2e/tests/generate/help-output.ts new file mode 100644 index 000000000000..bd5c71a7d9d1 --- /dev/null +++ b/tests/e2e/tests/generate/help-output.ts @@ -0,0 +1,122 @@ +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { createDir, writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default function () { + // setup temp collection + const genRoot = join('node_modules/fake-schematics/'); + + return ( + Promise.resolve() + .then(() => createDir(genRoot)) + .then(() => + writeMultipleFiles({ + [join(genRoot, 'package.json')]: ` + { + "schematics": "./collection.json" + }`, + [join(genRoot, 'collection.json')]: ` + { + "schematics": { + "fake": { + "factory": "./fake", + "description": "Fake schematic", + "schema": "./fake-schema.json" + }, + } + }`, + [join(genRoot, 'fake-schema.json')]: ` + { + "$id": "FakeSchema", + "title": "Fake Schema", + "type": "object", + "required": ["b"], + "properties": { + "b": { + "type": "string", + "description": "b.", + "$default": { + "$source": "argv", + "index": 0 + } + }, + "a": { + "type": "string", + "description": "a.", + "$default": { + "$source": "argv", + "index": 1 + } + }, + "optC": { + "type": "string", + "description": "optC" + }, + "optA": { + "type": "string", + "description": "optA" + }, + "optB": { + "type": "string", + "description": "optB" + } + } + }`, + [join(genRoot, 'fake.js')]: ` + function def(options) { + return (host, context) => { + return host; + }; + } + exports.default = def; + `, + }), + ) + .then(() => ng('generate', 'fake-schematics:fake', '--help')) + .then(({ stdout }) => { + assert.match(stdout, /ng generate fake-schematics:fake \[a\]/); + assert.match(stdout, /opt-a[\s\S]*opt-b[\s\S]*opt-c/); + }) + // set up default collection. + .then(() => + updateJsonFile('angular.json', (json) => { + json.cli = json.cli || ({} as any); + json.cli.schematicCollections = ['fake-schematics']; + }), + ) + .then(() => ng('generate', 'fake', '--help')) + // verify same output + .then(({ stdout }) => { + assert.match(stdout, /ng generate fake \[a\]/); + assert.match(stdout, /opt-a[\s\S]*opt-b[\s\S]*opt-c/); + }) + + // should print all the available schematics in a collection + // when a collection has more than 1 schematic + .then(() => + writeMultipleFiles({ + [join(genRoot, 'collection.json')]: ` + { + "schematics": { + "fake": { + "factory": "./fake", + "description": "Fake schematic", + "schema": "./fake-schema.json" + }, + "fake-two": { + "factory": "./fake", + "description": "Fake schematic", + "schema": "./fake-schema.json" + }, + } + }`, + }), + ) + .then(() => ng('generate', '--help')) + .then(({ stdout }) => { + assert.match(stdout, /fake[\s\S]*fake-two/); + }) + ); +} diff --git a/tests/e2e/tests/generate/install-allow-scripts.ts b/tests/e2e/tests/generate/install-allow-scripts.ts new file mode 100644 index 000000000000..f41a49935d80 --- /dev/null +++ b/tests/e2e/tests/generate/install-allow-scripts.ts @@ -0,0 +1,31 @@ +import { copyAssets } from '../../utils/assets'; +import { expectFileNotToExist, expectFileToExist, rimraf } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + // Copy test schematic into test project to ensure schematic dependencies are available + await copyAssets('schematic-allow-scripts', 'schematic-allow-scripts'); + + // By default should not run the postinstall from the added package.json in the schematic + await ng('generate', './schematic-allow-scripts:test'); + await expectFileToExist('install-test/package.json'); + await expectFileNotToExist('install-test/post-script-ran'); + + // Cleanup for next test case + await rimraf('install-test'); + + // Should run the postinstall if the allowScripts task option is enabled + // For testing purposes, this schematic exposes the task option via a schematic option + await ng('generate', './schematic-allow-scripts:test', '--allow-scripts'); + await expectFileToExist('install-test/package.json'); + await expectFileToExist('install-test/post-script-ran'); + + // Cleanup for next test case + await rimraf('install-test'); + + // Package manager configuration should take priority + // The `ignoreScripts` schematic option sets the value of the `ignore-scripts` option in a test project `.npmrc` + await ng('generate', './schematic-allow-scripts:test', '--allow-scripts', '--ignore-scripts'); + await expectFileToExist('install-test/package.json'); + await expectFileNotToExist('install-test/post-script-ran'); +} diff --git a/tests/e2e/tests/generate/interceptor/interceptor-basic.ts b/tests/e2e/tests/generate/interceptor/interceptor-basic.ts new file mode 100755 index 000000000000..7dd0b48c439b --- /dev/null +++ b/tests/e2e/tests/generate/interceptor/interceptor-basic.ts @@ -0,0 +1,18 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; + +export default function () { + // Does not create a sub directory. + const interceptorDir = join('src', 'app'); + + return ( + ng('generate', 'interceptor', 'test') + .then(() => expectFileToExist(interceptorDir)) + .then(() => expectFileToExist(join(interceptorDir, 'test-interceptor.ts'))) + .then(() => expectFileToExist(join(interceptorDir, 'test-interceptor.spec.ts'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/library/library-basic.ts b/tests/e2e/tests/generate/library/library-basic.ts new file mode 100644 index 000000000000..efc74694ea00 --- /dev/null +++ b/tests/e2e/tests/generate/library/library-basic.ts @@ -0,0 +1,9 @@ +import { ng } from '../../../utils/process'; +import { useCIChrome } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'library', 'lib-ngmodule', '--no-standalone'); + await useCIChrome('lib-ngmodule', 'projects/lib-ngmodule'); + await ng('test', 'lib-ngmodule', '--no-watch'); + await ng('build', 'lib-ngmodule'); +} diff --git a/tests/e2e/tests/generate/library/library-standalone.ts b/tests/e2e/tests/generate/library/library-standalone.ts new file mode 100644 index 000000000000..0b9754644bf5 --- /dev/null +++ b/tests/e2e/tests/generate/library/library-standalone.ts @@ -0,0 +1,9 @@ +import { ng } from '../../../utils/process'; +import { useCIChrome } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'library', 'lib-standalone', '--standalone'); + await useCIChrome('lib-standalone', 'projects/lib-standalone'); + await ng('test', 'lib-standalone', '--no-watch'); + await ng('build', 'lib-standalone'); +} diff --git a/tests/e2e/tests/generate/module/module-basic.ts b/tests/e2e/tests/generate/module/module-basic.ts new file mode 100644 index 000000000000..18e1a05fedde --- /dev/null +++ b/tests/e2e/tests/generate/module/module-basic.ts @@ -0,0 +1,23 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist, expectFileToMatch } from '../../../utils/fs'; +import { expectToFail } from '../../../utils/utils'; +import { useCIChrome, useCIDefaults } from '../../../utils/project'; + +export default async function () { + const projectName = 'test-project-two'; + const moduleDir = `projects/${projectName}/src/app/test`; + await ng('generate', 'application', projectName, '--no-standalone', '--skip-install'); + await useCIDefaults(projectName); + await useCIChrome(projectName, 'projects/test-project-two'); + + await ng('generate', 'module', 'test', '--project', projectName); + await expectFileToExist(moduleDir); + await expectFileToExist(join(moduleDir, 'test-module.ts')); + await expectToFail(() => expectFileToExist(join(moduleDir, 'test-routing-module.ts'))); + await expectToFail(() => expectFileToExist(join(moduleDir, 'test.spec.ts'))); + await expectFileToMatch(join(moduleDir, 'test-module.ts'), 'TestModule'); + + // Try to run the unit tests. + await ng('test', projectName, '--watch=false'); +} diff --git a/tests/e2e/tests/generate/module/module-import.ts b/tests/e2e/tests/generate/module/module-import.ts new file mode 100644 index 000000000000..533b3d19efe7 --- /dev/null +++ b/tests/e2e/tests/generate/module/module-import.ts @@ -0,0 +1,59 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToMatch } from '../../../utils/fs'; + +export default async function () { + const projectName = 'test-project-two'; + await ng('generate', 'application', projectName, '--no-standalone', '--skip-install'); + await ng('generate', 'module', 'sub', '--project', projectName); + await ng('generate', 'module', 'sub/deep', '--project', projectName); + + const projectAppDir = `projects/${projectName}/src/app`; + const modulePath = join(projectAppDir, 'app-module.ts'); + const subModulePath = join(projectAppDir, 'sub/sub-module.ts'); + const deepSubModulePath = join(projectAppDir, 'sub/deep/deep-module.ts'); + + await ng('generate', 'module', 'test1', '--module', 'app-module.ts', '--project', projectName); + await expectFileToMatch(modulePath, `import { Test1Module } from './test1/test1-module'`); + await expectFileToMatch(modulePath, /imports: \[.*?Test1Module.*?\]/s); + + await ng('generate', 'module', 'test2', '--module', 'app-module', '--project', projectName); + await expectFileToMatch(modulePath, `import { Test2Module } from './test2/test2-module'`); + await expectFileToMatch(modulePath, /imports: \[.*?Test2Module.*?\]/s); + + await ng('generate', 'module', 'test3', '--module', 'app', '--project', projectName); + await expectFileToMatch(modulePath, `import { Test3Module } from './test3/test3-module'`); + await expectFileToMatch(modulePath, /imports: \[.*?Test3Module.*?\]/s); + + await ng('generate', 'module', 'test4', '--routing', '--module', 'app', '--project', projectName); + await expectFileToMatch(modulePath, /imports: \[.*?Test4Module.*?\]/s); + await expectFileToMatch( + join(projectAppDir, 'test4/test4-module.ts'), + `import { Test4RoutingModule } from './test4-routing-module'`, + ); + await expectFileToMatch( + join(projectAppDir, 'test4/test4-module.ts'), + /imports: \[.*?Test4RoutingModule.*?\]/s, + ); + + await ng('generate', 'module', 'test5', '--module', 'sub', '--project', projectName); + await expectFileToMatch(subModulePath, `import { Test5Module } from '../test5/test5-module'`); + + await expectFileToMatch(subModulePath, /imports: \[.*?Test5Module.*?\]/s); + + await ng('generate', 'module', 'test6', '--module', 'sub/deep', '--project', projectName); + + await expectFileToMatch( + deepSubModulePath, + `import { Test6Module } from '../../test6/test6-module'`, + ); + await expectFileToMatch(deepSubModulePath, /imports: \[.*?Test6Module.*?\]/s); + + // E2E_DISABLE: temporarily disable pending investigation + // await process.chdir(join(root, 'src', 'app'))) + // await ng('generate', 'module', 'test7', '--module', 'app-module.ts')) + // await process.chdir('..')) + // await expectFileToMatch(modulePath, + // /import { Test7Module } from '.\/test7\/test7-module'/)) + // await expectFileToMatch(modulePath, /imports: \[(.|\s)*Test7Module(.|\s)*\]/m)); +} diff --git a/tests/e2e/tests/generate/module/module-routing-child-folder.ts b/tests/e2e/tests/generate/module/module-routing-child-folder.ts new file mode 100644 index 000000000000..f2ba0e3396f7 --- /dev/null +++ b/tests/e2e/tests/generate/module/module-routing-child-folder.ts @@ -0,0 +1,24 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; +import { expectToFail } from '../../../utils/utils'; +import { useCIChrome, useCIDefaults } from '../../../utils/project'; + +export default async function () { + const projectName = 'test-project-two'; + await ng('generate', 'application', projectName, '--no-standalone', '--skip-install'); + await useCIDefaults(projectName); + await useCIChrome(projectName, 'projects/test-project-two'); + + const testPath = join(process.cwd(), `projects/${projectName}/src/app`); + process.chdir(testPath); + + await ng('generate', 'module', 'sub-dir/child', '--routing'); + await expectFileToExist(join(testPath, 'sub-dir/child')); + await expectFileToExist(join(testPath, 'sub-dir/child', 'child-module.ts')); + await expectFileToExist(join(testPath, 'sub-dir/child', 'child-routing-module.ts')); + await expectToFail(() => expectFileToExist(join(testPath, 'sub-dir/child', 'child.spec.ts'))); + + // Try to run the unit tests. + await ng('test', projectName, '--watch=false'); +} diff --git a/tests/e2e/tests/generate/pipe/pipe-basic.ts b/tests/e2e/tests/generate/pipe/pipe-basic.ts new file mode 100644 index 000000000000..2ddb3ff4225f --- /dev/null +++ b/tests/e2e/tests/generate/pipe/pipe-basic.ts @@ -0,0 +1,19 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; + +import { expectFileToExist } from '../../../utils/fs'; + +export default function () { + // Create the pipe in the same directory. + const pipeDir = join('src', 'app'); + + return ( + ng('generate', 'pipe', 'test') + .then(() => expectFileToExist(pipeDir)) + .then(() => expectFileToExist(join(pipeDir, 'test-pipe.ts'))) + .then(() => expectFileToExist(join(pipeDir, 'test-pipe.spec.ts'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/generate/schematic-aliases.ts b/tests/e2e/tests/generate/schematic-aliases.ts new file mode 100644 index 000000000000..926c96d7aacc --- /dev/null +++ b/tests/e2e/tests/generate/schematic-aliases.ts @@ -0,0 +1,14 @@ +import { ng } from '../../utils/process'; + +export default async function () { + const schematicNameVariation = [ + 'component', + 'c', + '@schematics/angular:component', + '@schematics/angular:c', + ]; + + for (const schematic of schematicNameVariation) { + await ng('generate', schematic, 'comp-name', '--display-block', '--dry-run'); + } +} diff --git a/tests/e2e/tests/generate/schematic-defaults.ts b/tests/e2e/tests/generate/schematic-defaults.ts new file mode 100644 index 000000000000..a6fc32a8c52e --- /dev/null +++ b/tests/e2e/tests/generate/schematic-defaults.ts @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + await updateJsonFile('angular.json', (config) => { + config.projects['test-project'].schematics = { + '@schematics/angular:component': { + style: 'scss', + }, + }; + }); + + // Generate component in application to verify that it's minimal + const { stdout } = await ng('generate', 'component', 'foo'); + assert.match(stdout, /foo\.scss/); + + // Generate another project with different settings + await ng('generate', 'application', 'test-project-two', '--no-minimal'); + + await updateJsonFile('angular.json', (config) => { + config.projects['test-project-two'].schematics = { + '@schematics/angular:component': { + style: 'less', + type: 'Component', + }, + }; + }); + + const { stdout: stdout2 } = await ng( + 'generate', + 'component', + 'foo', + '--project', + 'test-project-two', + ); + assert.match(stdout2, /foo\.component\.less/); +} diff --git a/tests/e2e/tests/generate/schematic-force-override.ts b/tests/e2e/tests/generate/schematic-force-override.ts new file mode 100644 index 000000000000..d3e9e1b7d947 --- /dev/null +++ b/tests/e2e/tests/generate/schematic-force-override.ts @@ -0,0 +1,51 @@ +import { appendFile } from 'node:fs/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { getActivePackageManager, installWorkspacePackages } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +const snapshots = require('../../ng-snapshot/package.json'); + +export default async function () { + const isPrerelease = await isPrereleaseCli(); + let tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + await ng('add', `@angular/material${tag}`, '--skip-confirmation'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Angular material adds dependencies on other Angular packages + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries(snapshots.dependencies)) { + if (name in dependencies) { + dependencies[name] = version; + } + } + }); + await installWorkspacePackages(); + } + + const args: string[] = [ + 'generate', + '@angular/material:theme-color', + '--primary-color=#0641e6', + '--tertiary-color=#994aff', + '--neutral-color=#313138', + '--error-color=#eb5757', + '--secondary-color=#009096', + '--neutral-variant-color=#b2b2b8', + ]; + + await ng(...args); + + // Should fail as file exists + await expectToFail(() => ng(...args)); + + await ng(...args, '--force'); +} diff --git a/tests/e2e/tests/generate/schematics-collections-relative.ts b/tests/e2e/tests/generate/schematics-collections-relative.ts new file mode 100644 index 000000000000..f6f583bf0e72 --- /dev/null +++ b/tests/e2e/tests/generate/schematics-collections-relative.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert'; +import { join } from 'node:path'; +import { ng } from '../../utils/process'; +import { writeMultipleFiles, createDir } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + // setup temp collection + await createDir('./fake-schematics'); + await writeMultipleFiles({ + './fake-schematics/package.json': JSON.stringify({ + 'schematics': './collection.json', + }), + './fake-schematics/collection.json': JSON.stringify({ + 'schematics': { + 'fake': { + 'description': 'Fake schematic', + 'schema': './fake-schema.json', + 'factory': './fake', + }, + }, + }), + './fake-schematics/fake-schema.json': JSON.stringify({ + '$id': 'FakeSchema', + 'title': 'Fake Schema', + 'type': 'object', + }), + './fake-schematics/fake.js': ` + exports.default = () => (host, context) => context.logger.info('fake schematic run.'); + `, + }); + + await updateJsonFile('angular.json', (json) => { + json.cli ??= {}; + json.cli.schematicCollections = ['./fake-schematics']; + }); + + const { stdout: stdout1 } = await ng('generate', '--help'); + assert.match(stdout1, /Fake schematic/); + + const { stdout: stdout2 } = await ng('generate', 'fake'); + assert.match(stdout2, /fake schematic run/); + + // change cwd to a nested directory to validate the relative schematic is resolved correctly + const originalCwd = process.cwd(); + try { + process.chdir(join(originalCwd, 'src/app')); + const { stdout: stdout3 } = await ng('generate', 'fake'); + assert.match(stdout3, /fake schematic run/); + } finally { + process.chdir(originalCwd); + } +} diff --git a/tests/e2e/tests/generate/schematics-collections.ts b/tests/e2e/tests/generate/schematics-collections.ts new file mode 100644 index 000000000000..6c009bf91e5d --- /dev/null +++ b/tests/e2e/tests/generate/schematics-collections.ts @@ -0,0 +1,83 @@ +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { createDir, expectFileToExist, writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + // setup temp collection + const genRoot = join('node_modules/fake-schematics/'); + const fakeComponentSchematicDesc = 'Fake component schematic'; + + await createDir(genRoot); + await writeMultipleFiles({ + [join(genRoot, 'package.json')]: JSON.stringify({ + 'schematics': './collection.json', + }), + [join(genRoot, 'collection.json')]: JSON.stringify({ + 'schematics': { + 'fake': { + 'description': 'Fake schematic', + 'schema': './fake-schema.json', + 'factory': './fake', + }, + 'component': { + 'description': fakeComponentSchematicDesc, + 'schema': './fake-schema.json', + 'factory': './fake-component', + }, + }, + }), + [join(genRoot, 'fake-schema.json')]: JSON.stringify({ + '$id': 'FakeSchema', + 'title': 'Fake Schema', + 'type': 'object', + }), + [join(genRoot, 'fake.js')]: ` + exports.default = function (options) { + return (host, context) => { + console.log('fake schematic run.'); + }; + } + `, + [join(genRoot, 'fake-component.js')]: ` + exports.default = function (options) { + return (host, context) => { + console.log('fake component schematic run.'); + }; + } + `, + }); + + await updateJsonFile('angular.json', (json) => { + json.cli ??= {}; + json.cli.schematicCollections = ['fake-schematics', '@schematics/angular']; + }); + + // should display schematics for all schematics + const { stdout: stdout1 } = await ng('generate', '--help'); + assert.match(stdout1, /ng generate component/); + assert.match(stdout1, /ng generate fake/); + + // check registration order. Both schematics contain a component schematic verify that the first one wins. + assert.match(stdout1, new RegExp(fakeComponentSchematicDesc)); + + // Verify execution based on ordering + const { stdout: stdout2 } = await ng('generate', 'component'); + assert.match(stdout2, /fake component schematic run/); + + await updateJsonFile('angular.json', (json) => { + json.cli ??= {}; + json.cli.schematicCollections = ['@schematics/angular', 'fake-schematics']; + }); + + const { stdout: stdout3 } = await ng('generate', '--help'); + assert.match(stdout3, /ng generate component \[name\]/); + assert.doesNotMatch(stdout3, new RegExp(fakeComponentSchematicDesc)); + + // Verify execution based on ordering + const projectDir = join('src', 'app'); + const componentDir = join(projectDir, 'test-component'); + await ng('generate', 'component', 'test-component'); + await expectFileToExist(componentDir); +} diff --git a/tests/e2e/tests/generate/service/service-basic.ts b/tests/e2e/tests/generate/service/service-basic.ts new file mode 100644 index 000000000000..a7ddb3cb8310 --- /dev/null +++ b/tests/e2e/tests/generate/service/service-basic.ts @@ -0,0 +1,18 @@ +import { join } from 'node:path'; +import { ng } from '../../../utils/process'; +import { expectFileToExist } from '../../../utils/fs'; + +export default function () { + // Does not create a sub directory. + const serviceDir = join('src', 'app'); + + return ( + ng('generate', 'service', 'test-service') + .then(() => expectFileToExist(serviceDir)) + .then(() => expectFileToExist(join(serviceDir, 'test-service.ts'))) + .then(() => expectFileToExist(join(serviceDir, 'test-service.spec.ts'))) + + // Try to run the unit tests. + .then(() => ng('test', '--watch=false')) + ); +} diff --git a/tests/e2e/tests/i18n/extract-ivy-disk-cache.ts b/tests/e2e/tests/i18n/extract-ivy-disk-cache.ts new file mode 100644 index 000000000000..562a481086d5 --- /dev/null +++ b/tests/e2e/tests/i18n/extract-ivy-disk-cache.ts @@ -0,0 +1,51 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch, rimraf, writeFile } from '../../utils/fs'; +import { installPackage, uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { readNgVersion } from '../../utils/version'; + +export default async function () { + // Enable disk cache + await updateJsonFile('angular.json', (config) => { + config.cli ??= {}; + config.cli.cache = { environment: 'all' }; + }); + + // Setup an i18n enabled component + await ng('generate', 'component', 'i18n-test'); + await writeFile(join('src/app/i18n-test', 'i18n-test.html'), '

Hello world

'); + + await writeFile( + 'src/app/app.ts', + ` + import { Component } from '@angular/core'; + import { I18nTest } from './i18n-test/i18n-test'; + + @Component({ + selector: 'app-root', + imports: [I18nTest], + template: '' + }) + export class App {} + `, + ); + + // Install correct version + let localizeVersion = '@angular/localize@' + readNgVersion(); + if (getGlobalVariable('argv')['ng-snapshots']) { + localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; + } + + await installPackage(localizeVersion); + + for (let i = 0; i < 2; i++) { + // Run the extraction twice and make sure the second time round works with cache. + await rimraf('messages.xlf'); + await ng('extract-i18n'); + await expectFileToMatch('messages.xlf', 'Hello world'); + } + + await uninstallPackage('@angular/localize'); +} diff --git a/tests/e2e/tests/i18n/extract-ivy-libraries.ts b/tests/e2e/tests/i18n/extract-ivy-libraries.ts new file mode 100644 index 000000000000..a577a8c5e6a6 --- /dev/null +++ b/tests/e2e/tests/i18n/extract-ivy-libraries.ts @@ -0,0 +1,42 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch, prependToFile, replaceInFile, writeFile } from '../../utils/fs'; +import { installPackage, uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { readNgVersion } from '../../utils/version'; + +export default async function () { + // Setup a library + await ng('generate', 'library', 'i18n-lib-test'); + await replaceInFile('projects/i18n-lib-test/src/lib/i18n-lib-test.ts', '

', '

'); + + // Build library + await ng('build', 'i18n-lib-test', '--configuration=development'); + + // Consume library in application + await replaceInFile('src/app/app.ts', 'imports: [', 'imports: [I18nLibTest,'); + await prependToFile('src/app/app.ts', `import { I18nLibTest } from 'i18n-lib-test';`); + + await writeFile( + 'src/app/app.html', + ` +

Hello world

+ + `, + ); + + // Install correct version + let localizeVersion = '@angular/localize@' + readNgVersion(); + if (getGlobalVariable('argv')['ng-snapshots']) { + localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; + } + await installPackage(localizeVersion); + + // Extract messages + await ng('extract-i18n'); + await expectFileToMatch('messages.xlf', 'Hello world'); + await expectFileToMatch('messages.xlf', 'i18n-lib-test works!'); + await expectFileToMatch('messages.xlf', 'src/app/app.html'); + await expectFileToMatch('messages.xlf', 'projects/i18n-lib-test/src/lib/i18n-lib-test.ts'); + + await uninstallPackage('@angular/localize'); +} diff --git a/tests/e2e/tests/i18n/extract-ivy.ts b/tests/e2e/tests/i18n/extract-ivy.ts new file mode 100644 index 000000000000..cf0d23da08e3 --- /dev/null +++ b/tests/e2e/tests/i18n/extract-ivy.ts @@ -0,0 +1,65 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { deleteFile, expectFileToMatch, writeFile } from '../../utils/fs'; +import { uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; +import { readNgVersion } from '../../utils/version'; + +export default async function () { + // Setup an i18n enabled component + await ng('generate', 'component', 'i18n-test'); + await writeFile(join('src/app/i18n-test', 'i18n-test.html'), '

Hello world

'); + // Actually use the generated component to ensure it is present in the application output + await writeFile( + 'src/app/app.ts', + ` + import { Component } from '@angular/core'; + import { I18nTest } from './i18n-test/i18n-test'; + + @Component({ + selector: 'app-root', + imports: [I18nTest], + template: '' + }) + export class App {} + `, + ); + + // Ensure localize package is not present initially + await uninstallPackage('@angular/localize'); + + // Should fail if `@angular/localize` is missing + const { message: message1 } = await expectToFail(() => ng('extract-i18n')); + if (!message1.includes(`i18n extraction requires the '@angular/localize' package.`)) { + throw new Error('Expected localize package error message when missing'); + } + + // Install correct version + let localizeVersion = '@angular/localize@' + readNgVersion(); + if (getGlobalVariable('argv')['ng-snapshots']) { + // The snapshots job won't work correctly because 'ng add' doesn't support github URLs + // localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; + return; + } + await ng('add', localizeVersion, '--skip-confirmation'); + + // Should not show any warnings when extracting + const { stderr: message5 } = await ng('extract-i18n'); + if (message5.includes('WARNING')) { + throw new Error('Expected no warnings to be shown. STDERR:\n' + message5); + } + + await expectFileToMatch('messages.xlf', 'Hello world'); + + // Template messages should also be extracted when the build target disables AOT + await updateJsonFile('angular.json', (workspaceJson) => { + workspaceJson.projects['test-project'].architect.build.options.aot = false; + }); + await deleteFile('messages.xlf'); + await ng('extract-i18n'); + await expectFileToMatch('messages.xlf', 'Hello world'); + + await uninstallPackage('@angular/localize'); +} diff --git a/tests/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts b/tests/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts new file mode 100644 index 000000000000..b1568be95939 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts @@ -0,0 +1,85 @@ +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, createDir, expectFileToMatch, writeFile } from '../../utils/fs'; +import { installWorkspacePackages } from '../../utils/packages'; +import { ng, silentNg } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { readNgVersion } from '../../utils/version'; + +const snapshots = require('../../ng-snapshot/package.json'); + +export default async function () { + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + dependencies['@angular/localize'] = isSnapshotBuild + ? snapshots.dependencies['@angular/localize'] + : readNgVersion(); + }); + + await appendToFile('src/app/app.html', ''); + + // Add app-shell and service-worker + await silentNg('generate', 'app-shell'); + await silentNg('generate', 'service-worker'); + + if (isSnapshotBuild) { + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; + dependencies['@angular/service-worker'] = snapshots.dependencies['@angular/service-worker']; + dependencies['@angular/router'] = snapshots.dependencies['@angular/router']; + }); + } + + await installWorkspacePackages(); + + // Set configurations for each locale. + const langTranslations = [ + { lang: 'en-US', translation: 'Hello i18n!' }, + { lang: 'fr', translation: 'Bonjour i18n!' }, + ]; + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const appArchitect = appProject.architect; + const buildOptions = appArchitect['build'].options; + + // Enable localization for all locales + buildOptions.localize = true; + + // Add locale definitions to the project + const i18n: Record = (appProject.i18n = { locales: {} }); + for (const { lang } of langTranslations) { + if (lang == 'en-US') { + i18n.sourceLocale = lang; + } else { + i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; + } + } + }); + + await createDir('src/locale'); + + for (const { lang } of langTranslations) { + // dummy translation file. + await writeFile( + `src/locale/messages.${lang}.xlf`, + ` + + + + `, + ); + } + + // Build each locale and verify the SW output. + await ng('build', '--output-hashing=none'); + + for (const { lang } of langTranslations) { + await Promise.all([ + expectFileToMatch(`dist/test-project/browser/${lang}/ngsw.json`, `/${lang}/main.js`), + expectFileToMatch(`dist/test-project/browser/${lang}/ngsw.json`, `/${lang}/index.html`), + ]); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-app-shell.ts b/tests/e2e/tests/i18n/ivy-localize-app-shell.ts new file mode 100644 index 000000000000..cbabbae17140 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-app-shell.ts @@ -0,0 +1,108 @@ +import { getGlobalVariable } from '../../utils/env'; +import { + appendToFile, + copyFile, + expectFileToMatch, + replaceInFile, + writeFile, +} from '../../utils/fs'; +import { installWorkspacePackages } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { readNgVersion } from '../../utils/version'; + +const snapshots = require('../../ng-snapshot/package.json'); + +export default async function () { + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + dependencies['@angular/localize'] = isSnapshotBuild + ? snapshots.dependencies['@angular/localize'] + : readNgVersion(); + }); + + await appendToFile('src/app/app.html', ''); + await ng('generate', 'app-shell', '--project', 'test-project'); + + if (isSnapshotBuild) { + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; + dependencies['@angular/router'] = snapshots.dependencies['@angular/router']; + }); + } + + await installWorkspacePackages(); + + // Set configurations for each locale. + const langTranslations = [ + { lang: 'en-US', translation: 'Hello i18n!' }, + { lang: 'fr', translation: 'Bonjour i18n!' }, + ]; + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const appArchitect = appProject.architect || appProject.targets; + const buildOptions = appArchitect['build'].options; + + // Enable localization for all locales + buildOptions.localize = true; + + // Add locale definitions to the project + const i18n: Record = (appProject.i18n = { locales: {} }); + for (const { lang } of langTranslations) { + if (lang == 'en-US') { + i18n.sourceLocale = lang; + } else { + i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; + } + } + }); + + await writeFile( + 'src/app/app-shell/app-shell.html', + '

Hello i18n!

', + ); + + // Add a translatable element + // Extraction of i18n only works on browser targets. + // Let's add the same translation that there is in the app-shell + await writeFile( + 'src/app/app.html', + '

Hello i18n!

', + ); + + // Extract the translation messages and copy them for each language. + await ng('extract-i18n', '--output-path=src/locale'); + await expectFileToMatch('src/locale/messages.xlf', `source-language="en-US"`); + await expectFileToMatch('src/locale/messages.xlf', `An introduction header for this sample`); + + // Clean up app.ng.html so that we can easily + // find the translation text + await writeFile('src/app/app.html', ''); + + for (const { lang, translation } of langTranslations) { + if (lang != 'en-US') { + await copyFile('src/locale/messages.xlf', `src/locale/messages.${lang}.xlf`); + await replaceInFile( + `src/locale/messages.${lang}.xlf`, + 'source-language="en-US"', + `source-language="en-US" target-language="${lang}"`, + ); + await replaceInFile( + `src/locale/messages.${lang}.xlf`, + 'Hello i18n!', + `Hello i18n!\n${translation}`, + ); + } + } + + // Build each locale and verify the output. + await ng('build', '--output-mode=static'); + + for (const { lang, translation } of langTranslations) { + await expectFileToMatch(`dist/test-project/browser/${lang}/index.html`, translation); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-basehref-absolute.ts b/tests/e2e/tests/i18n/ivy-localize-basehref-absolute.ts new file mode 100644 index 000000000000..db59853ff759 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-basehref-absolute.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { langTranslations, setupI18nConfig } from './setup'; + +const baseHrefs: { [l: string]: string } = { + 'en-US': '/en/', + fr: '/fr-FR/', + de: '', +}; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = { + baseHref: baseHrefs['en-US'], + }; + + i18n.locales['fr'] = { + translation: i18n.locales['fr'], + baseHref: baseHrefs['fr'], + }; + + i18n.locales['de'] = { + translation: i18n.locales['de'], + baseHref: baseHrefs['de'], + }; + }); + + // Test absolute base href. + await ng('build', '--base-href', 'http://www.example.com/', '--configuration=development'); + for (const { lang, outputPath } of langTranslations) { + // Verify the HTML base HREF attribute is present + await expectFileToMatch( + `${outputPath}/index.html`, + `href="http://www.example.com${baseHrefs[lang] || '/'}"`, + ); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-basehref.ts b/tests/e2e/tests/i18n/ivy-localize-basehref.ts new file mode 100644 index 000000000000..4bbd7dece3ee --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-basehref.ts @@ -0,0 +1,95 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { + baseHrefs, + browserCheck, + externalServer, + langTranslations, + setupI18nConfig, +} from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = { + baseHref: baseHrefs['en-US'], + }; + + i18n.locales['fr'] = { + translation: i18n.locales['fr'], + baseHref: baseHrefs['fr'], + }; + + i18n.locales['de'] = { + translation: i18n.locales['de'], + baseHref: baseHrefs['de'], + }; + }); + + // Build each locale and verify the output. + await ng('build'); + for (const { lang, outputPath } of langTranslations) { + if (baseHrefs[lang] === undefined) { + throw new Error('Invalid E2E test setup: unexpected locale ' + lang); + } + + // Verify the HTML lang attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); + + // Verify the HTML base HREF attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `href="${baseHrefs[lang] || '/'}"`); + + // Execute Application E2E tests for a production build without dev server + const { server, url } = await externalServer(outputPath, (baseHrefs[lang] as string) || '/'); + try { + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); + } finally { + server.close(); + } + } + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + + appArchitect['build'].options.baseHref = '/test/'; + }); + + // Build each locale and verify the output. + await ng('build', '--configuration=development'); + for (const { lang, outputPath } of langTranslations) { + // Verify the HTML base HREF attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `href="/test${baseHrefs[lang] || '/'}"`); + + // Execute Application E2E tests for a production build without dev server + const { server, url } = await externalServer(outputPath, '/test' + (baseHrefs[lang] || '/')); + try { + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); + } finally { + server.close(); + } + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts b/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts new file mode 100644 index 000000000000..d1f7ac8e28b8 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts @@ -0,0 +1,14 @@ +import { executeBrowserTest } from '../../utils/puppeteer'; +import { browserCheck, langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + for (const { lang } of langTranslations) { + await executeBrowserTest({ + configuration: lang, + checkFn: (page) => browserCheck(page, lang), + }); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-es2015.ts b/tests/e2e/tests/i18n/ivy-localize-es2015.ts new file mode 100644 index 000000000000..cea87a75f2b8 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-es2015.ts @@ -0,0 +1,46 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { expectToFail } from '../../utils/utils'; +import { browserCheck, externalServer, langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + const { stderr } = await ng('build'); + if (/Locale data for .+ cannot be found/.test(stderr)) { + throw new Error( + `A warning for a locale not found was shown. This should not happen.\n\nSTDERR:\n${stderr}\n`, + ); + } + + for (const { lang, outputPath, translation } of langTranslations) { + await expectFileToMatch(`${outputPath}/main.js`, translation.helloPartial); + await expectToFail(() => expectFileToMatch(`${outputPath}/main.js`, '$localize`')); + + // Ensure locale is inlined (@angular/localize plugin inlines `$localize.locale` references) + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // The only reference in a new application with Webpack is in @angular/core + await expectFileToMatch(`${outputPath}/vendor.js`, lang); + } else { + await expectFileToMatch(`${outputPath}/polyfills.js`, lang); + } + + // Verify the HTML lang attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); + + // Execute Application E2E tests for a production build without dev server + const { server, url } = await externalServer(outputPath, `/${lang}/`); + try { + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); + } finally { + server.close(); + } + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-hashes.ts b/tests/e2e/tests/i18n/ivy-localize-hashes.ts new file mode 100644 index 000000000000..2f682ca76988 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-hashes.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 'node:fs'; +import { appendToFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { langTranslations, setupI18nConfig } from './setup'; + +const OUTPUT_RE = /^(?(?:main|vendor|\d+))(?:\.|-)(?[a-z0-9]+)\.js$/i; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Build each locale and record output file hashes + const hashes = new Map(); + await ng('build', '--output-hashing=all', '--configuration=development'); + for (const { lang, outputPath } of langTranslations) { + for (const entry of fs.readdirSync(outputPath)) { + const match = entry.match(OUTPUT_RE); + if (!match?.groups) { + continue; + } + + hashes.set(`${lang}/${match.groups.name}`, match.groups.hash); + } + } + + // Ensure hashes for output files were recorded + if (hashes.size === 0) { + throw new Error('No output entries found.'); + } + + // Alter content of a used translation file + await appendToFile('src/locale/messages.fr.xlf', '\n'); + + // Build each locale and ensure hashes are different + await ng('build', '--output-hashing=all', '--configuration=development'); + for (const { lang, outputPath } of langTranslations) { + for (const entry of fs.readdirSync(outputPath)) { + const match = entry.match(OUTPUT_RE); + if (!match?.groups) { + continue; + } + + const id = `${lang}/${match.groups.name}`; + const hash = hashes.get(id); + if (!hash) { + throw new Error('Unexpected output entry: ' + id); + } + if (hash === match.groups!.hash) { + throw new Error('Hash value did not change for entry: ' + id); + } + + hashes.delete(id); + } + } + + // Check for missing entries in second build + if (hashes.size > 0) { + throw new Error('Missing output entries: ' + JSON.stringify(Array.from(hashes.values()))); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts b/tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts new file mode 100644 index 000000000000..b4c0ae72ced4 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts @@ -0,0 +1,63 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch, prependToFile, readFile, writeFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { browserCheck, langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json to only localize one locale + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + appProject.architect['build'].options.localize = ['fr']; + }); + + // Augment the locale data and import into the main application file + const localeData = await readFile('node_modules/@angular/common/locales/global/fr.js'); + await writeFile('src/fr-changed.js', localeData.replace('janvier', 'changed-janvier')); + await prependToFile('src/main.ts', "import './fr-changed.js';\n"); + + // Run a build and test + await ng('build'); + for (const { lang, outputPath } of langTranslations) { + // Only the fr locale was built for this test + if (lang !== 'fr') { + continue; + } + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // The only reference in a new application with Webpack is in @angular/core + await expectFileToMatch(`${outputPath}/vendor.js`, lang); + } else { + await expectFileToMatch(`${outputPath}/polyfills.js`, lang); + } + + // Execute Application E2E tests with dev server + await executeBrowserTest({ + configuration: lang, + checkFn: async (page) => { + // Run standard checks but expect failure on date + try { + await browserCheck(page, lang); + throw new Error('Expected browserCheck to fail due to modified locale data'); + } catch (e) { + if (!(e instanceof Error) || !e.message.includes("Expected 'date' to be")) { + throw e; + } + } + + // Verify the modified date + const getParagraph = async (id: string) => + page.$eval(`p#${id}`, (el) => el.textContent?.trim()); + const date = await getParagraph('date'); + if (date !== 'changed-janvier') { + throw new Error(`Expected 'date' to be 'changed-janvier', but got '${date}'.`); + } + }, + }); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-locale-data.ts b/tests/e2e/tests/i18n/ivy-localize-locale-data.ts new file mode 100644 index 000000000000..d378ba5c56a9 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-locale-data.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = 'fr-Abcd'; + appProject.architect['build'].options.localize = ['fr-Abcd']; + }); + + const { stderr: err1 } = await ng('build'); + if (!err1.includes(`Locale data for 'fr-Abcd' cannot be found. Using locale data for 'fr'.`)) { + throw new Error('locale data fallback warning not shown'); + } + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = 'en-US'; + appProject.architect['build'].options.localize = ['en-US']; + }); + + const { stderr: err2 } = await ng('build'); + if ( + err2.includes( + `Locale data for 'en-US' cannot be found. No locale data will be included for this locale.`, + ) + ) { + throw new Error('locale data not found warning shown'); + } + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = 'en-x-abc'; + appProject.architect['build'].options.localize = ['en-x-abc']; + }); + + const { stderr: err3 } = await ng('build', '--configuration=development'); + if ( + err3.includes( + `Locale data for 'en-x-abc' cannot be found. No locale data will be included for this locale.`, + ) + ) { + throw new Error('locale data not found warning shown'); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-merging.ts b/tests/e2e/tests/i18n/ivy-localize-merging.ts new file mode 100644 index 000000000000..f4e016951094 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-merging.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; +import { setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const i18n: Record = appProject.i18n; + + i18n.locales['fr'] = [i18n.locales['fr'], i18n.locales['fr']]; + appProject.architect['build'].options.localize = ['fr']; + }); + + const { stderr: err1 } = await ng('build'); + if (!err1.includes('Duplicate translations for message')) { + throw new Error('duplicate translations warning not shown'); + } + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + appProject.architect['build'].options.i18nDuplicateTranslation = 'error'; + }); + await expectToFail(() => ng('build')); + + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + appProject.architect['build'].options.i18nDuplicateTranslation = 'ignore'; + }); + const { stderr: err2 } = await ng('build'); + if (err2.includes('Duplicate translations for message')) { + throw new Error('duplicate translations message not ignore'); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-sourcelocale.ts b/tests/e2e/tests/i18n/ivy-localize-sourcelocale.ts new file mode 100644 index 000000000000..e88fc571e289 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-sourcelocale.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = 'fr'; + + delete i18n.locales['fr']; + }); + + // Build each locale and verify the output. + await ng('build', '--configuration=development'); + for (const { lang, outputPath } of langTranslations) { + // does not exist in this test due to the source locale change + if (lang === 'en-US') { + continue; + } + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // The only reference in a new application with Webpack is in @angular/core + await expectFileToMatch(`${outputPath}/vendor.js`, lang); + + // Verify the locale data is registered using the global files + await expectFileToMatch(`${outputPath}/vendor.js`, '.ng.common.locales'); + } else { + await expectFileToMatch(`${outputPath}/polyfills.js`, lang); + + // Verify the locale data is registered using the global files + await expectFileToMatch(`${outputPath}/polyfills.js`, '.ng.common.locales'); + } + + // Verify the HTML lang attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-sourcemaps.ts b/tests/e2e/tests/i18n/ivy-localize-sourcemaps.ts new file mode 100644 index 000000000000..8f65ef450c0e --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-sourcemaps.ts @@ -0,0 +1,22 @@ +import { readFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + await ng('build', '--source-map'); + + for (const { outputPath } of langTranslations) { + // Ensure sourcemap for modified file contains content + const mainSourceMap = JSON.parse(await readFile(`${outputPath}/main.js.map`)); + if ( + mainSourceMap.version !== 3 || + !Array.isArray(mainSourceMap.sources) || + typeof mainSourceMap.mappings !== 'string' + ) { + throw new Error('invalid localized sourcemap for main.js'); + } + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-ssr.ts b/tests/e2e/tests/i18n/ivy-localize-ssr.ts new file mode 100644 index 000000000000..dd0c75ae74fc --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-ssr.ts @@ -0,0 +1,80 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { getGlobalVariable } from '../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { updateJsonFile, useSha } from '../../utils/project'; +import { langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + // This test is for the `application` builder only + return; + } + + // Setup i18n tests and config. + await setupI18nConfig(); + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + // tslint:disable-next-line: no-any + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = { + baseHref: '', + }; + + i18n.locales['fr'] = { + translation: i18n.locales['fr'], + baseHref: '', + }; + + i18n.locales['de'] = { + translation: i18n.locales['de'], + baseHref: '', + }; + }); + + // forcibly remove in case another test doesn't clean itself up + await uninstallPackage('@angular/ssr'); + + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + + await useSha(); + await installWorkspacePackages(); + + // Build each locale and verify the output. + await ng('build', '--output-hashing=none'); + + for (const { lang, translation } of langTranslations) { + let foundTranslation = false; + let foundLocaleData = false; + + // The translation may be in any of the lazy-loaded generated chunks + for (const entry of readdirSync(`dist/test-project/server/${lang}/`)) { + if (!entry.endsWith('.mjs')) { + continue; + } + + const contents = readFileSync(`dist/test-project/server/${lang}/${entry}`, 'utf-8'); + + // Check for translated content + foundTranslation ||= contents.includes(translation.helloPartial); + // Check for the locale data month name to be present + foundLocaleData ||= contents.includes(translation.date); + + if (foundTranslation && foundLocaleData) { + break; + } + } + + if (!foundTranslation) { + throw new Error(`Translation not found in 'dist/test-project/server/${lang}/'`); + } + + if (!foundLocaleData) { + throw new Error(`Locale data not found in 'dist/test-project/server/${lang}/'`); + } + } +} diff --git a/tests/e2e/tests/i18n/ivy-localize-sub-path.ts b/tests/e2e/tests/i18n/ivy-localize-sub-path.ts new file mode 100644 index 000000000000..6116c438a49f --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-sub-path.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { join } from 'node:path'; +import { expectFileToMatch } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { baseDir, browserCheck, externalServer, langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + const URL_SUB_PATH: Record = { + 'en-US': '', + 'fr': 'fr', + 'de': 'deutsche', + }; + + // Update angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const i18n: Record = appProject.i18n; + + i18n.sourceLocale = { + subPath: URL_SUB_PATH['en-US'], + }; + + i18n.locales['fr'] = { + translation: i18n.locales['fr'], + subPath: URL_SUB_PATH['fr'], + }; + + i18n.locales['de'] = { + translation: i18n.locales['de'], + subPath: URL_SUB_PATH['de'], + }; + }); + + // Build each locale and verify the output. + await ng('build'); + for (const { lang } of langTranslations) { + const subPath = URL_SUB_PATH[lang]; + const baseHref = subPath ? `/${subPath}/` : '/'; + const outputPath = join(baseDir, subPath); + + // Verify the HTML lang attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); + + // Verify the HTML base HREF attribute is present + await expectFileToMatch(`${outputPath}/index.html`, `href="${baseHref}"`); + + // Execute Application E2E tests for a production build without dev server + const { server, url } = await externalServer(outputPath, baseHref); + + try { + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); + } finally { + server.close(); + } + } +} diff --git a/tests/e2e/tests/i18n/setup.ts b/tests/e2e/tests/i18n/setup.ts new file mode 100644 index 000000000000..8eade4e2783c --- /dev/null +++ b/tests/e2e/tests/i18n/setup.ts @@ -0,0 +1,275 @@ +import express from 'express'; +import { dirname, resolve } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, copyFile, createDir, replaceInFile, writeFile } from '../../utils/fs'; +import { installPackage } from '../../utils/packages'; +import { updateJsonFile } from '../../utils/project'; +import { readNgVersion } from '../../utils/version'; +import { Server } from 'node:http'; +import { AddressInfo } from 'node:net'; +import type { Page } from 'puppeteer'; + +// Configurations for each locale. +const translationFile = 'src/locale/messages.xlf'; +export const baseDir = 'dist/test-project/browser'; +export const langTranslations = [ + { + lang: 'en-US', + outputPath: `${baseDir}/en-US`, + translation: { + helloPartial: 'Hello', + hello: 'Hello i18n!', + plural: 'Updated 3 minutes ago', + date: 'January', + }, + }, + { + lang: 'fr', + outputPath: `${baseDir}/fr`, + translation: { + helloPartial: 'Bonjour', + hello: 'Bonjour i18n!', + plural: 'Mis à jour il y a 3 minutes', + date: 'janvier', + }, + translationReplacements: [ + ['Hello', 'Bonjour'], + ['Updated', 'Mis à jour'], + ['just now', 'juste maintenant'], + ['one minute ago', 'il y a une minute'], + [/other {/g, 'other {il y a '], + ['minutes ago', 'minutes'], + ], + }, + { + lang: 'de', + outputPath: `${baseDir}/de`, + translation: { + helloPartial: 'Hallo', + hello: 'Hallo i18n!', + plural: 'Aktualisiert vor 3 Minuten', + date: 'Januar', + }, + translationReplacements: [ + ['Hello', 'Hallo'], + ['Updated', 'Aktualisiert'], + ['just now', 'gerade jetzt'], + ['one minute ago', 'vor einer Minute'], + [/other {/g, 'other {vor '], + ['minutes ago', 'Minuten'], + ], + }, +]; +export const sourceLocale = langTranslations[0].lang; + +export async function browserCheck(page: Page, lang: string) { + const translation = langTranslations.find((t) => t.lang === lang)?.translation; + if (!translation) { + throw new Error(`Could not find translation for language '${lang}'`); + } + + const getParagraph = async (id: string) => page.$eval(`p#${id}`, (el) => el.textContent?.trim()); + + const hello = await getParagraph('hello'); + if (hello !== translation.hello) { + throw new Error(`Expected 'hello' to be '${translation.hello}', but got '${hello}'.`); + } + + const locale = await getParagraph('locale'); + if (locale !== lang) { + throw new Error(`Expected 'locale' to be '${lang}', but got '${locale}'.`); + } + + const date = await getParagraph('date'); + if (date !== translation.date) { + throw new Error(`Expected 'date' to be '${translation.date}', but got '${date}'.`); + } + + const plural = await getParagraph('plural'); + if (plural !== translation.plural) { + throw new Error(`Expected 'plural' to be '${translation.plural}', but got '${plural}'.`); + } +} + +export interface ExternalServer { + readonly server: Server; + readonly port: number; + readonly url: string; +} + +/** + * Create an `express` `http.Server` listening on a random port. + * + * Call .close() on the server return value to close the server. + */ +export async function externalServer(outputPath: string, baseUrl = '/'): Promise { + const app = express(); + app.use(baseUrl, express.static(resolve(outputPath))); + + return new Promise((resolve) => { + const server = app.listen(0, 'localhost', () => { + const { port } = server.address() as AddressInfo; + + resolve({ + server, + port, + url: `http://localhost:${port}${baseUrl}`, + }); + }); + }); +} + +export const baseHrefs: { [l: string]: string } = { + 'en-US': '/en/', + fr: '/fr-FR/', + de: '', +}; + +export async function setupI18nConfig() { + // Add component with i18n content, both translations and localeData (plural, dates). + await writeFile( + 'src/app/app.ts', + ` + import { Component, Inject, LOCALE_ID } from '@angular/core'; + import { DatePipe } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + + @Component({ + selector: 'app-root', + imports: [DatePipe, RouterOutlet], + templateUrl: './app.html' + }) + export class App { + constructor(@Inject(LOCALE_ID) public locale: string) { } + title = 'i18n'; + jan = new Date(2000, 0, 1); + minutes = 3; + } + `, + ); + await writeFile( + `src/app/app.html`, + ` +

Hello {{ title }}!

+

{{ locale }}

+

{{ jan | date : 'LLLL' }}

+

Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}

+ + `, + ); + + await createDir(dirname(translationFile)); + await writeFile( + translationFile, + ` + + + + + + Hello ! + + src/app/app.html + 2,3 + + An introduction header for this sample + + + Updated + + src/app/app.html + 5,6 + + + + {VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other { minutes ago}} + + src/app/app.html + 5,6 + + + + + `, + ); + + // Add a dynamic import to ensure syntax is supported + // ng serve support: https://github.com/angular/angular-cli/issues/16248 + await writeFile('src/app/dynamic.ts', `export const abc = 5;`); + await appendToFile( + 'src/app/app.ts', + ` + (async () => { await import('./dynamic'); })(); + `, + ); + + // Update angular.json to build, serve, and test each locale. + await updateJsonFile('angular.json', (workspaceJson) => { + const appProject = workspaceJson.projects['test-project']; + const appArchitect = workspaceJson.projects['test-project'].architect; + const buildConfigs = appArchitect['build'].configurations; + const serveConfigs = appArchitect['serve'].configurations; + + appArchitect['build'].defaultConfiguration = undefined; + + // Always error on missing translations. + appArchitect['build'].options.optimization = true; + appArchitect['build'].options.aot = true; + appArchitect['build'].options.i18nMissingTranslation = 'error'; + appArchitect['build'].options.sourceMap = true; + appArchitect['build'].options.outputHashing = 'none'; + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + if (useWebpackBuilder) { + appArchitect['build'].options.buildOptimizer = true; + appArchitect['build'].options.vendorChunk = true; + } + + // Enable localization for all locales + appArchitect['build'].options.localize = true; + + // Add i18n config items (app, build, serve, e2e). + // tslint:disable-next-line: no-any + const i18n: Record = (appProject.i18n = { locales: {} }); + for (const { lang } of langTranslations) { + if (lang === sourceLocale) { + i18n.sourceLocale = lang; + } else { + i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; + } + + buildConfigs[lang] = { localize: [lang] }; + serveConfigs[lang] = { buildTarget: `test-project:build:${lang}` }; + } + }); + + // Install the localize package if using ivy + let localizeVersion = '@angular/localize@' + readNgVersion(); + if (getGlobalVariable('argv')['ng-snapshots']) { + localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; + } + + await installPackage(localizeVersion); + + // Make translations for each language. + for (const { lang, translationReplacements } of langTranslations) { + if (lang != sourceLocale) { + await copyFile(translationFile, `src/locale/messages.${lang}.xlf`); + for (const replacements of translationReplacements!) { + await replaceInFile( + `src/locale/messages.${lang}.xlf`, + new RegExp(replacements[0], 'g'), + replacements[1] as string, + ); + } + + for (const replacement of [[/source/g, 'target']]) { + await replaceInFile( + `src/locale/messages.${lang}.xlf`, + new RegExp(replacement[0], 'g'), + replacement[1] as string, + ); + } + } + } +} diff --git a/tests/e2e/tests/mcp/ai-tutor.ts b/tests/e2e/tests/mcp/ai-tutor.ts new file mode 100644 index 000000000000..ed4d51a20c14 --- /dev/null +++ b/tests/e2e/tests/mcp/ai-tutor.ts @@ -0,0 +1,43 @@ +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + try { + // Ensure `get_best_practices` returns the markdown content + const { stdout: stdoutInsideWorkspace } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'ai_tutor', + ); + + assert.match(stdoutInsideWorkspace, /# `airules.md` - Modern Angular Tutor 🧑‍🏫/); + } finally { + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } +} diff --git a/tests/e2e/tests/mcp/best-practices.ts b/tests/e2e/tests/mcp/best-practices.ts new file mode 100644 index 000000000000..ba83733446dc --- /dev/null +++ b/tests/e2e/tests/mcp/best-practices.ts @@ -0,0 +1,46 @@ +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + try { + // Ensure `get_best_practices` returns the markdown content + const { stdout: stdoutInsideWorkspace } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'get_best_practices', + ); + + assert.match( + stdoutInsideWorkspace, + /You are an expert in TypeScript, Angular, and scalable web application development./, + ); + } finally { + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } +} diff --git a/tests/e2e/tests/mcp/projects-sourceroot-resolution.ts b/tests/e2e/tests/mcp/projects-sourceroot-resolution.ts new file mode 100644 index 000000000000..01ebb8c1ca05 --- /dev/null +++ b/tests/e2e/tests/mcp/projects-sourceroot-resolution.ts @@ -0,0 +1,47 @@ +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + return exec(MCP_INSPECTOR_COMMAND_NAME, '--cli', 'npx', '--no', '@angular/cli', 'mcp', ...args); +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + try { + // 1. Add a sample project with a non-root path to angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + workspaceJson.projects ??= {}; + workspaceJson.projects['sample-lib'] = { + root: 'projects/sample-lib', + sourceRoot: 'projects/sample-lib/src', + projectType: 'library', + }; + }); + + // 2. Call list_projects + const { stdout } = await runInspector('--method', 'tools/call', '--tool-name', 'list_projects'); + + // 3. Verify output + assert.match(stdout, /"name": "sample-lib"/); + // Assert that sourceRoot is NOT duplicated + assert.match(stdout, /"sourceRoot": "projects\/sample-lib\/src"/); + assert.doesNotMatch(stdout, /"sourceRoot": "projects\/sample-lib\/projects\/sample-lib\/src"/); + } finally { + // 4. Cleanup angular.json + await updateJsonFile('angular.json', (workspaceJson) => { + delete workspaceJson.projects['sample-lib']; + }); + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } +} diff --git a/tests/e2e/tests/mcp/registers-tools.ts b/tests/e2e/tests/mcp/registers-tools.ts new file mode 100644 index 000000000000..97e04459f440 --- /dev/null +++ b/tests/e2e/tests/mcp/registers-tools.ts @@ -0,0 +1,51 @@ +import { chdir } from 'node:process'; +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + const initialCwd = process.cwd(); + // Ensure 'list_projects' is registered when inside an Angular workspace + try { + const { stdout: stdoutInsideWorkspace } = await runInspector('--method', 'tools/list'); + + assert.match(stdoutInsideWorkspace, /"list_projects"/); + assert.match(stdoutInsideWorkspace, /"get_best_practices"/); + assert.match(stdoutInsideWorkspace, /"search_documentation"/); + + chdir('..'); + + const { stdout: stdoutOutsideWorkspace } = await runInspector('--method', 'tools/list'); + + assert.match(stdoutOutsideWorkspace, /"list_projects"/); + assert.match(stdoutOutsideWorkspace, /"get_best_practices"/); + assert.match(stdoutOutsideWorkspace, /"search_documentation"/); + } finally { + chdir(initialCwd); + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } +} diff --git a/tests/e2e/tests/mcp/run-target.ts b/tests/e2e/tests/mcp/run-target.ts new file mode 100644 index 000000000000..16548fc4f3ca --- /dev/null +++ b/tests/e2e/tests/mcp/run-target.ts @@ -0,0 +1,80 @@ +import { getGlobalVariable } from '../../utils/env'; +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + try { + // 1. Ensure `run_target` is registered by default (now stable) + const { stdout: stdoutDefault } = await runInspector('--method', 'tools/list'); + assert.match(stdoutDefault, /"run_target"/); + + // 2. Ensure `run_target` is also registered when using the deprecated experimental-tool flag + const { stdout: stdoutEnabled } = await runInspector( + '-E', + 'run_target', + '--method', + 'tools/list', + ); + assert.match(stdoutEnabled, /"run_target"/); + + // 3. Call run_target with build target + const { stdout: stdoutCall } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'run_target', + '--tool-arg', + 'target=build', + ); + assert.match(stdoutCall, /"status":\s*"success"/); + // Webpack-based browser builder does not print output paths to stdout logs. + // Only esbuild-based application builders output 'Output location: ...' and support outputPath extraction. + const esbuild = getGlobalVariable('argv')['esbuild']; + if (esbuild) { + assert.match(stdoutCall, /"outputPath":\s*"dist\/.+"/); + } else { + assert.doesNotMatch(stdoutCall, /"outputPath"/); + } + + // 4. Call run_target with test target (only for esbuild/Vite test runner, as webpack-based Karma fails on this bazel CI headless runner) + if (esbuild) { + const { stdout: stdoutTestCall } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'run_target', + '--tool-arg', + 'target=test', + ); + assert.match(stdoutTestCall, /"status":\s*"success"/); + } + } finally { + // 5. Clean up global installation + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } +} diff --git a/tests/e2e/tests/misc/ask-missing-builder.ts b/tests/e2e/tests/misc/ask-missing-builder.ts new file mode 100644 index 000000000000..ce4270cdbb47 --- /dev/null +++ b/tests/e2e/tests/misc/ask-missing-builder.ts @@ -0,0 +1,24 @@ +import { execAndWaitForOutputToMatch, killAllProcesses } from '../../utils/process'; + +export default async function () { + // Execute a command with TTY force enabled and check that the prompt is shown. + await execAndWaitForOutputToMatch( + 'ng', + ['deploy'], + /Would you like to add a package with "deploy" capabilities/, + { + ...process.env, + NG_FORCE_TTY: '1', + NG_CLI_ANALYTICS: 'false', + }, + ); + + await killAllProcesses(); + + // Execute a command with TTY force enabled and check that the prompt is shown. + await execAndWaitForOutputToMatch('ng', ['lint'], /Would you like to add ESLint now/, { + ...process.env, + NG_FORCE_TTY: '1', + NG_CLI_ANALYTICS: 'false', + }); +} diff --git a/tests/e2e/tests/misc/browsers.ts b/tests/e2e/tests/misc/browsers.ts new file mode 100644 index 000000000000..d91258b95345 --- /dev/null +++ b/tests/e2e/tests/misc/browsers.ts @@ -0,0 +1,91 @@ +import express from 'express'; +import path from 'node:path'; +import { copyProjectAsset } from '../../utils/assets'; +import { appendToFile, createDir, replaceInFile, writeFile } from '../../utils/fs'; +import { exec, ng } from '../../utils/process'; +import { installPackage } from '../../utils/packages'; + +/** + * The list of development dependencies used by the E2E protractor-based builder. + */ +const E2E_DEV_DEPENDENCIES = [ + 'protractor@~7.0.0', + 'jasmine-spec-reporter@~7.0.0', + 'ts-node@~10.9.0', + '@types/node@^20.17.19', +]; + +export default async function () { + // Ensure SauceLabs configuration + if (!process.env['SAUCE_USERNAME'] || !process.env['SAUCE_ACCESS_KEY']) { + throw new Error('SauceLabs is not configured.'); + } + + await installPackage(E2E_DEV_DEPENDENCIES); + + await appendToFile( + 'src/app/app.config.ts', + "import { provideProtractorTestingSupport } from '@angular/platform-browser';\n", + ); + await replaceInFile( + 'src/app/app.config.ts', + 'providers: [', + 'providers: [\n provideProtractorTestingSupport(),\n', + ); + + // Workaround for https://github.com/angular/angular/issues/32192 + await replaceInFile('src/app/app.html', /class="material-icons"/g, ''); + + await ng('build'); + + // Add Protractor configuration + await copyProjectAsset('protractor-saucelabs.conf.js', 'e2e/protractor-saucelabs.conf.js'); + + // Add App E2E test file + await createDir('e2e/src'); + await writeFile( + 'e2e/src/app.e2e-spec.ts', + ` +import { browser, by, element, logging } from 'protractor'; + +describe('workspace-project App', () => { + it('should display welcome message', async () => { + await browser.get(browser.baseUrl); + expect((await element(by.css('h1')).getText()).trim()).toEqual('Hello, test-project'); + }); +}); +`, + ); + + // Add App E2E tsconfig file + await writeFile( + 'e2e/tsconfig.json', + ` +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "out-tsc/e2e", + "module": "commonjs", + "target": "es2019", + "types": [ + "jasmine", + "node" + ] + } +} +`, + ); + + // Setup server + const app = express(); + app.use(express.static(path.resolve('dist/test-project/browser'))); + const server = app.listen(2000, 'localhost'); + + try { + // Execute application's E2E tests with SauceLabs + const binPath = path.join('node_modules', '.bin', 'protractor'); + await exec(binPath, 'e2e/protractor-saucelabs.conf.js'); + } finally { + server.close(); + } +} diff --git a/tests/e2e/tests/misc/check-postinstalls.ts b/tests/e2e/tests/misc/check-postinstalls.ts new file mode 100644 index 000000000000..7c1d63e6ef97 --- /dev/null +++ b/tests/e2e/tests/misc/check-postinstalls.ts @@ -0,0 +1,69 @@ +import glob from 'fast-glob'; +import { readFile } from '../../utils/fs'; + +const CURRENT_SCRIPT_PACKAGES: ReadonlySet = new Set([ + '@parcel/watcher (install)', + 'esbuild (postinstall)', + 'lmdb (install)', + 'msgpackr-extract (install)', + 'nice-napi (install)', + 'unrs-resolver (postinstall)', +]); + +const POTENTIAL_SCRIPTS: ReadonlyArray = ['preinstall', 'install', 'postinstall']; + +// Some packages include test and/or example code that causes false positives +const FALSE_POSITIVE_PATHS: ReadonlySet = new Set([ + 'jasmine-spec-reporter/examples/protractor/package.json', + 'resolve/test/resolver/multirepo/package.json', + 'resolve/test/list-exports/packages/tests/fixtures/resolve-1/project/test/resolver/multirepo/package.json', + 'resolve/test/list-exports/packages/tests/fixtures/resolve-2/project/test/resolver/multirepo/package.json', +]); + +const INNER_NODE_MODULES_SEGMENT = '/node_modules/'; + +export default async function () { + const manifestPaths = await glob('node_modules/**/package.json'); + const newPackages: string[] = []; + + for (const manifestPath of manifestPaths) { + const lastNodeModuleIndex = manifestPath.lastIndexOf(INNER_NODE_MODULES_SEGMENT); + const packageRelativePath = manifestPath.slice( + lastNodeModuleIndex === -1 + ? INNER_NODE_MODULES_SEGMENT.length - 1 + : lastNodeModuleIndex + INNER_NODE_MODULES_SEGMENT.length, + ); + if (FALSE_POSITIVE_PATHS.has(packageRelativePath)) { + continue; + } + + let manifest; + try { + manifest = JSON.parse(await readFile(manifestPath)); + } catch { + continue; + } + + if (!manifest.scripts) { + continue; + } + + for (const script of POTENTIAL_SCRIPTS) { + if (!manifest.scripts[script]) { + continue; + } + + const packageScript = `${manifest.name} (${script})`; + + if (!CURRENT_SCRIPT_PACKAGES.has(packageScript)) { + newPackages.push(packageScript + `[${manifestPath}]`); + } + } + } + + if (newPackages.length) { + throw new Error( + 'New install script package(s) detected:\n' + JSON.stringify(newPackages, null, 2), + ); + } +} diff --git a/tests/e2e/tests/misc/create-angular.ts b/tests/e2e/tests/misc/create-angular.ts new file mode 100644 index 000000000000..2b060d90ac33 --- /dev/null +++ b/tests/e2e/tests/misc/create-angular.ts @@ -0,0 +1,53 @@ +import { equal } from 'node:assert'; +import { join } from 'node:path'; +import { expectFileToExist, readFile, rimraf } from '../../utils/fs'; +import { getActivePackageManager } from '../../utils/packages'; +import { silentBun, silentNpm, silentPnpm, silentYarn } from '../../utils/process'; +import { mktempd } from '../../utils/utils'; + +export default async function () { + const currentDirectory = process.cwd(); + const newDirectory = await mktempd('create-angular-test-'); + const projectName = 'test-project-create'; + + try { + process.chdir(newDirectory); + const packageManager = getActivePackageManager(); + + switch (packageManager) { + case 'npm': + await silentNpm('init', '@angular', projectName, '--', '--style=scss'); + + break; + case 'yarn': + await silentYarn('create', '@angular', projectName, '--style=scss'); + + break; + case 'bun': + await silentBun('create', '@angular', projectName, '--style=scss'); + + break; + case 'pnpm': + await silentPnpm('create', '@angular', projectName, '--style=scss'); + + break; + default: + throw new Error(`This test is not configured to use ${packageManager}.`); + } + + // Check that package manager has been configured based on the package manager used to invoke the create command. + const workspace = JSON.parse(await readFile(join(projectName, 'angular.json'))); + equal( + workspace.cli?.packageManager, + packageManager, + `Expected 'packageManager' option to be configured to ${packageManager}.`, + ); + + // Verify styles was create with correct extension. + await expectFileToExist(join(projectName, 'src/styles.scss')); + } finally { + await rimraf(projectName); + // Change directory back + process.chdir(currentDirectory); + } +} diff --git a/tests/e2e/tests/misc/dedupe-duplicate-modules.ts b/tests/e2e/tests/misc/dedupe-duplicate-modules.ts new file mode 100644 index 000000000000..5047021566eb --- /dev/null +++ b/tests/e2e/tests/misc/dedupe-duplicate-modules.ts @@ -0,0 +1,65 @@ +import { expectFileToMatch, rimraf, writeFile } from '../../utils/fs'; +import { gitClean } from '../../utils/git'; +import { installWorkspacePackages } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + try { + // Force duplicate modules + await updateJsonFile('package.json', (json) => { + json.dependencies = { + ...json.dependencies, + 'tslib': '^2.0.0', + 'tslib-1': 'npm:tslib@1.13.0', + 'tslib-1-copy': 'npm:tslib@1.13.0', + }; + }); + + await installWorkspacePackages(); + + await writeFile( + './src/main.ts', + ` + import { __assign as __assign_0 } from 'tslib'; + import { __assign as __assign_1 } from 'tslib-1'; + import { __assign as __assign_2 } from 'tslib-1-copy'; + + console.log({ + __assign_0, + __assign_1, + __assign_2, + }) + `, + ); + + const { stderr } = await ng( + 'build', + '--verbose', + '--no-vendor-chunk', + '--no-progress', + '--configuration=development', + ); + const outFile = 'dist/test-project/browser/main.js'; + + if (/\[DedupeModuleResolvePlugin\]:.+tslib-1-copy.+ -> .+tslib-1.+/.test(stderr)) { + await expectFileToMatch(outFile, './node_modules/tslib-1/tslib.es6.js'); + await expectToFail(() => + expectFileToMatch(outFile, './node_modules/tslib-1-copy/tslib.es6.js'), + ); + } else if (/\[DedupeModuleResolvePlugin\]:.+tslib-1.+ -> .+tslib-1-copy.+/.test(stderr)) { + await expectFileToMatch(outFile, './node_modules/tslib-1-copy/tslib.es6.js'); + await expectToFail(() => expectFileToMatch(outFile, './node_modules/tslib-1/tslib.es6.js')); + } else { + console.error(`\n\n\n${stderr}\n\n\n`); + throw new Error('Expected stderr to contain [DedupeModuleResolvePlugin] log for tslib.'); + } + + await expectFileToMatch(outFile, './node_modules/tslib/tslib.es6.mjs'); + } finally { + await rimraf('node_modules/tslib'); + await gitClean(); + await installWorkspacePackages(); + } +} diff --git a/tests/e2e/tests/misc/duplicate-command-line-option.ts b/tests/e2e/tests/misc/duplicate-command-line-option.ts new file mode 100644 index 000000000000..0042a363e156 --- /dev/null +++ b/tests/e2e/tests/misc/duplicate-command-line-option.ts @@ -0,0 +1,19 @@ +import { ng } from '../../utils/process'; +import { expectFileToExist } from '../../utils/fs'; + +export default async function () { + const { stderr } = await ng( + 'generate', + 'component', + 'test-component', + '--style=scss', + '--style=sass', + ); + + const warningMatch = `Option 'style' has been specified multiple times. The value 'sass' will be used`; + if (!stderr.includes(warningMatch)) { + throw new Error(`Expected stderr to contain: "${warningMatch}".`); + } + + await expectFileToExist('src/app/test-component/test-component.sass'); +} diff --git a/tests/e2e/tests/misc/es2015-nometa.ts b/tests/e2e/tests/misc/es2015-nometa.ts new file mode 100644 index 000000000000..c8fad0e07954 --- /dev/null +++ b/tests/e2e/tests/misc/es2015-nometa.ts @@ -0,0 +1,18 @@ +import { prependToFile, replaceInFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + await ng('generate', 'service', 'user-service'); + + // Update the application to use the new service + await prependToFile('src/app/app.ts', "import { UserService } from './user-service';"); + + await replaceInFile( + 'src/app/app.ts', + 'export class App {', + 'export class App {\n constructor(user: UserService) {}', + ); + + // Execute the application's tests with emitDecoratorMetadata disabled (default) + await ng('test', '--no-watch'); +} diff --git a/tests/e2e/tests/misc/forwardref-es2015.ts b/tests/e2e/tests/misc/forwardref-es2015.ts new file mode 100644 index 000000000000..48c28086cd0d --- /dev/null +++ b/tests/e2e/tests/misc/forwardref-es2015.ts @@ -0,0 +1,43 @@ +import { appendToFile, replaceInFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + // Update the application to use a forward reference + await replaceInFile( + 'src/app/app.ts', + "import { Component, signal } from '@angular/core';", + "import { Component, Inject, Injectable, forwardRef, signal } from '@angular/core';", + ); + await appendToFile('src/app/app.ts', '\n@Injectable() export class Lock { }\n'); + await replaceInFile( + 'src/app/app.ts', + 'export class App {', + 'export class App {\n constructor(@Inject(forwardRef(() => Lock)) lock: Lock) {}', + ); + + // Update the application's unit tests to include the new injectable + await replaceInFile( + 'src/app/app.spec.ts', + "import { App } from './app';", + "import { App, Lock } from './app';", + ); + await replaceInFile( + 'src/app/app.spec.ts', + 'TestBed.configureTestingModule({', + 'TestBed.configureTestingModule({ providers: [Lock],', + ); + + // Execute the application's tests with emitDecoratorMetadata disabled (default) + await ng('test', '--no-watch'); + + // Turn on emitDecoratorMetadata + await replaceInFile( + 'tsconfig.json', + '"experimentalDecorators": true', + '"experimentalDecorators": true, "emitDecoratorMetadata": true', + ); + + // Execute the application's tests with emitDecoratorMetadata enabled + await expectToFail(() => ng('test', '--no-watch')); +} diff --git a/tests/e2e/tests/misc/invalid-schematic-dependencies.ts b/tests/e2e/tests/misc/invalid-schematic-dependencies.ts new file mode 100644 index 000000000000..88300951965e --- /dev/null +++ b/tests/e2e/tests/misc/invalid-schematic-dependencies.ts @@ -0,0 +1,60 @@ +import { join } from 'node:path'; +import { expectFileToMatch } from '../../utils/fs'; +import { + execWithEnv, + extractCIAndInfraEnv, + extractNpmEnv, + ng, + silentNpm, +} from '../../utils/process'; +import { getActivePackageManager, installPackage, uninstallPackage } from '../../utils/packages'; +import { isPrereleaseCli } from '../../utils/project'; +import { appendFile, writeFile } from 'node:fs/promises'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + // Must publish old version to local registry to allow install. This is especially important + // for release commits as npm will try to request tooling packages that are not on the npm registry yet + await publishOutdated('@schematics/angular@7'); + await publishOutdated('@angular-devkit/core@7'); + await publishOutdated('@angular-devkit/schematics@7'); + + // Install outdated and incompatible version + await installPackage('@schematics/angular@7'); + + const isPrerelease = await isPrereleaseCli(); + const tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + await ng('add', `@angular/material${tag}`, '--skip-confirmation'); + await expectFileToMatch('package.json', /@angular\/material/); + + // Clean up existing cdk package + // Not doing so can cause adding material to fail if an incompatible cdk is present + await uninstallPackage('@angular/cdk'); +} + +async function publishOutdated(npmSpecifier: string): Promise { + const npmrc = join(getGlobalVariable('tmp-root'), '.npmrc-publish'); + const testRegistry = (getGlobalVariable('package-registry') as string).replace(/^\w+:/, ''); + await writeFile( + npmrc, + ` + ${testRegistry.replace(/^https?:/, '')}/:_authToken=fake-secret + `, + ); + + const { stdout: stdoutPack } = await silentNpm( + 'pack', + npmSpecifier, + '--registry=https://registry.npmjs.org', + ); + + await execWithEnv('npm', ['publish', stdoutPack.trim(), '--tag=outdated'], { + ...extractNpmEnv(), + ...extractCIAndInfraEnv(), + 'NPM_CONFIG_USERCONFIG': npmrc, + }); +} diff --git a/tests/e2e/tests/misc/loaders-resolution.ts b/tests/e2e/tests/misc/loaders-resolution.ts new file mode 100644 index 000000000000..b411ab60514a --- /dev/null +++ b/tests/e2e/tests/misc/loaders-resolution.ts @@ -0,0 +1,45 @@ +import { createDir, moveFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { assertIsError } from '../../utils/utils'; + +export default async function () { + await createDir('node_modules/@angular-devkit/build-angular/node_modules'); + let originalInRootNodeModules = true; + + try { + await moveFile( + 'node_modules/@ngtools', + 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools', + ); + } catch (e) { + assertIsError(e); + + if (e.code !== 'ENOENT') { + throw e; + } + + // In some cases due to module resolution '@ngtools' might already been under `@angular-devkit/build-angular`. + originalInRootNodeModules = false; + await moveFile( + 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools', + 'node_modules/@ngtools', + ); + } + + await ng('build', '--configuration=development'); + + // Move it back. + await moveBack(originalInRootNodeModules); +} + +function moveBack(originalInRootNodeModules: Boolean): Promise { + return originalInRootNodeModules + ? moveFile( + 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools', + 'node_modules/@ngtools', + ) + : moveFile( + 'node_modules/@ngtools', + 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools', + ); +} diff --git a/tests/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts b/tests/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts new file mode 100644 index 000000000000..d2710b07b8be --- /dev/null +++ b/tests/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts @@ -0,0 +1,41 @@ +import { createDir, moveFile } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; +import { updateJsonFile } from '../../../utils/project'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.paths = { + '*': ['./node_modules/*'], + }; + }); + await ng('build', '--configuration=development'); + + await createDir('xyz'); + await moveFile('node_modules/@angular/platform-browser', 'xyz/platform-browser'); + await expectToFail(() => ng('build', '--configuration=development')); + + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.paths = { + '@angular/platform-browser': ['./xyz/platform-browser'], + }; + }); + await ng('build', '--configuration=development'); + + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.paths = { + '*': ['./node_modules/*'], + '@angular/platform-browser': ['./xyz/platform-browser'], + }; + }); + await ng('build', '--configuration=development'); + + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.paths = { + '@angular/platform-browser': ['./xyz/platform-browser'], + '*': ['./node_modules/*'], + }; + }); + await ng('build', '--configuration=development'); + await moveFile('xyz/platform-browser', 'node_modules/@angular/platform-browser'); +} diff --git a/tests/e2e/tests/misc/multiple-targets.ts b/tests/e2e/tests/misc/multiple-targets.ts new file mode 100644 index 000000000000..a99a37d54b06 --- /dev/null +++ b/tests/e2e/tests/misc/multiple-targets.ts @@ -0,0 +1,9 @@ +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + await ng('generate', 'app', 'secondary-app'); + await ng('build', 'secondary-app', '--configuration=development'); + await expectFileToExist('dist/secondary-app/browser/index.html'); + await expectFileToExist('dist/secondary-app/browser/main.js'); +} diff --git a/tests/e2e/tests/misc/negated-boolean-options.ts b/tests/e2e/tests/misc/negated-boolean-options.ts new file mode 100644 index 000000000000..377967785496 --- /dev/null +++ b/tests/e2e/tests/misc/negated-boolean-options.ts @@ -0,0 +1,18 @@ +import { copyAssets } from '../../utils/assets'; +import { execAndWaitForOutputToMatch } from '../../utils/process'; + +export default async function () { + await copyAssets('schematic-boolean-option-negated', 'schematic-boolean-option-negated'); + + await execAndWaitForOutputToMatch( + 'ng', + ['generate', './schematic-boolean-option-negated:test', '--no-watch'], + /noWatch: true/, + ); + + await execAndWaitForOutputToMatch( + 'ng', + ['generate', './schematic-boolean-option-negated:test', '--watch'], + /noWatch: false/, + ); +} diff --git a/tests/e2e/tests/misc/nested-schematic-packages.ts b/tests/e2e/tests/misc/nested-schematic-packages.ts new file mode 100644 index 000000000000..3398a293c837 --- /dev/null +++ b/tests/e2e/tests/misc/nested-schematic-packages.ts @@ -0,0 +1,11 @@ +import { copyAssets } from '../../utils/assets'; +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + await copyAssets('nested-schematic-main', 'nested'); + await copyAssets('nested-schematic-dependency', 'nested/node_modules/empty-app-nested'); + + await ng('generate', './nested:test'); + await expectFileToExist('empty-file'); +} diff --git a/tests/legacy-cli/e2e/tests/misc/supported-angular.ts b/tests/e2e/tests/misc/supported-angular.ts similarity index 78% rename from tests/legacy-cli/e2e/tests/misc/supported-angular.ts rename to tests/e2e/tests/misc/supported-angular.ts index 271e8663c4c4..d5299485bb7f 100644 --- a/tests/legacy-cli/e2e/tests/misc/supported-angular.ts +++ b/tests/e2e/tests/misc/supported-angular.ts @@ -4,7 +4,6 @@ import { readFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; - export default async function () { if (getGlobalVariable('argv')['ng-snapshots']) { // The snapshots job won't work correctly because it doesn't use semver for Angular. @@ -25,12 +24,14 @@ export default async function () { // Major should succeed, but we don't need to test it here since it's tested everywhere else. // Major+1 and -1 should fail architect commands, but allow other commands. - await fakeCoreVersion(cliMajor + 1); - await expectToFail(() => ng('build'), 'Should fail Major+1'); - await ng('version'); - await fakeCoreVersion(cliMajor - 1); - await ng('version'); - - // Restore the original core package.json. - await writeFile(angularCorePkgPath, originalAngularCorePkgJson); + try { + await fakeCoreVersion(cliMajor + 1); + await expectToFail(() => ng('build'), 'Should fail Major+1'); + await ng('version'); + await fakeCoreVersion(cliMajor - 1); + await ng('version'); + } finally { + // Restore the original core package.json. + await writeFile(angularCorePkgPath, originalAngularCorePkgJson); + } } diff --git a/tests/e2e/tests/misc/target-default-configuration.ts b/tests/e2e/tests/misc/target-default-configuration.ts new file mode 100644 index 000000000000..d5f381b2db97 --- /dev/null +++ b/tests/e2e/tests/misc/target-default-configuration.ts @@ -0,0 +1,35 @@ +import { expectFileToExist } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + await updateJsonFile('angular.json', (workspace) => { + const build = workspace.projects['test-project'].architect.build; + build.defaultConfiguration = undefined; + build.options = { + ...build.options, + optimization: false, + buildOptimizer: false, + outputHashing: 'none', + sourceMap: true, + }; + }); + + await ng('build'); + await expectFileToExist('dist/test-project/browser/main.js'); + await expectFileToExist('dist/test-project/browser/main.js.map'); + + // Add new configuration and set "defaultConfiguration" + await updateJsonFile('angular.json', (workspace) => { + const build = workspace.projects['test-project'].architect.build; + build.defaultConfiguration = 'foo'; + build.configurations.foo = { + sourceMap: false, + }; + }); + + await ng('build'); + await expectFileToExist('dist/test-project/browser/main.js'); + await expectToFail(() => expectFileToExist('dist/test-project/browser/main.js.map')); +} diff --git a/tests/e2e/tests/misc/trace-resolution.ts b/tests/e2e/tests/misc/trace-resolution.ts new file mode 100644 index 000000000000..0827223e58a0 --- /dev/null +++ b/tests/e2e/tests/misc/trace-resolution.ts @@ -0,0 +1,22 @@ +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; + +export default async function () { + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.traceResolution = true; + }); + + const { stdout: stdoutTraced } = await ng('build', '--configuration=development'); + if (!/Resolving module/.test(stdoutTraced)) { + throw new Error(`Modules resolutions must be printed when 'traceResolution' is enabled.`); + } + + await updateJsonFile('tsconfig.json', (tsconfig) => { + tsconfig.compilerOptions.traceResolution = false; + }); + + const { stdout: stdoutUnTraced } = await ng('build', '--configuration=development'); + if (/Resolving module/.test(stdoutUnTraced)) { + throw new Error(`Modules resolutions must not be printed when 'traceResolution' is disabled.`); + } +} diff --git a/tests/e2e/tests/misc/trusted-types.ts b/tests/e2e/tests/misc/trusted-types.ts new file mode 100644 index 000000000000..21deb03223dd --- /dev/null +++ b/tests/e2e/tests/misc/trusted-types.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert/strict'; +import { replaceInFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + // Add lazy route. + await ng('generate', 'component', 'lazy'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [{path: 'lazy', loadComponent: () => import('./lazy/lazy').then(c => c.Lazy)}];`, + ); + + const testCases = [ + { + aot: false, + csp: `trusted-types angular angular#unsafe-bypass angular#unsafe-jit angular#bundler; require-trusted-types-for 'script';`, + }, + { + aot: true, + csp: `trusted-types angular angular#unsafe-bypass angular#bundler; require-trusted-types-for 'script';`, + }, + ]; + + for (const { aot, csp } of testCases) { + await updateJsonFile('angular.json', (json) => { + const architect = json['projects']['test-project']['architect']; + architect['build']['options']['aot'] = aot; + if (!architect['serve']['options']) architect['serve']['options'] = {}; + architect['serve']['options']['headers'] = { + 'Content-Security-Policy': csp, + }; + }); + + try { + await executeBrowserTest({ + checkFn: async (page) => { + const baseUrl = page.url(); + await page.goto(new URL('/lazy', baseUrl).href); + + await page.waitForSelector('app-lazy p'); + const lazyText = await page.$eval('app-lazy p', (el) => el.textContent); + assert.strictEqual(lazyText, 'lazy works!'); + }, + }); + } catch (error) { + console.error(`Test case AOT ${aot} with CSP header ${csp} failed.`); + throw error; + } + } +} diff --git a/tests/e2e/tests/misc/update-git-clean-subdirectory.ts b/tests/e2e/tests/misc/update-git-clean-subdirectory.ts new file mode 100644 index 000000000000..733a91164019 --- /dev/null +++ b/tests/e2e/tests/misc/update-git-clean-subdirectory.ts @@ -0,0 +1,25 @@ +import { getGlobalVariable } from '../../utils/env'; +import { createDir, writeFile } from '../../utils/fs'; +import { ng, silentGit } from '../../utils/process'; +import { prepareProjectForE2e } from '../../utils/project'; + +export default async function () { + process.chdir(getGlobalVariable('projects-root')); + + await createDir('./subdirectory'); + process.chdir('./subdirectory'); + + await silentGit('init', '.'); + + await ng('new', 'subdirectory-test-project', '--skip-install', '--test-runner', 'karma'); + process.chdir('./subdirectory-test-project'); + await prepareProjectForE2e('subdirectory-test-project'); + + await writeFile('../added.ts', "console.log('created');\n"); + await silentGit('add', '../added.ts'); + + const { stderr } = await ng('update', '@angular/cli'); + if (stderr && stderr.includes('Repository is not clean.')) { + throw new Error('Expected clean repository'); + } +} diff --git a/tests/e2e/tests/misc/update-git-clean.ts b/tests/e2e/tests/misc/update-git-clean.ts new file mode 100644 index 000000000000..c992c695c4e3 --- /dev/null +++ b/tests/e2e/tests/misc/update-git-clean.ts @@ -0,0 +1,12 @@ +import { appendToFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + await appendToFile('src/main.ts', "console.log('changed');\n"); + + const { message } = await expectToFail(() => ng('update', '@angular/cli')); + if (!message || !message.includes('Repository is not clean.')) { + throw new Error('Expected unclean repository'); + } +} diff --git a/tests/e2e/tests/misc/version.ts b/tests/e2e/tests/misc/version.ts new file mode 100644 index 000000000000..4ad57adc9726 --- /dev/null +++ b/tests/e2e/tests/misc/version.ts @@ -0,0 +1,22 @@ +import { deleteFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; + +export default async function () { + const { stdout: commandOutput } = await ng('version'); + + if (commandOutput.includes(process.versions.node + ' (Unsupported)')) { + throw new Error('Node version should not show unsupported entry'); + } + + if (commandOutput.includes('Warning: The current version of Node ')) { + throw new Error('Node support warning should not be shown'); + } + + // doesn't fail on a project with missing angular.json + await deleteFile('angular.json'); + await ng('version'); + + // Doesn't fail outside a project. + process.chdir('/'); + await ng('version'); +} diff --git a/tests/e2e/tests/misc/workspace-verification.ts b/tests/e2e/tests/misc/workspace-verification.ts new file mode 100644 index 000000000000..bf55841a9398 --- /dev/null +++ b/tests/e2e/tests/misc/workspace-verification.ts @@ -0,0 +1,14 @@ +import { deleteFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default function () { + return ( + ng('generate', 'component', 'foo', '--dry-run') + .then(() => deleteFile('angular.json')) + // fails because it needs to be inside a project + // without a workspace file + .then(() => expectToFail(() => ng('generate', 'component', 'foo', '--dry-run'))) + .then(() => ng('version')) + ); +} diff --git a/tests/e2e/tests/schematics_cli/basic.ts b/tests/e2e/tests/schematics_cli/basic.ts new file mode 100644 index 000000000000..62128e1e32db --- /dev/null +++ b/tests/e2e/tests/schematics_cli/basic.ts @@ -0,0 +1,37 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { exec, execAndWaitForOutputToMatch, silentNpm } from '../../utils/process'; +import { rimraf } from '../../utils/fs'; + +export default async function () { + // setup + const argv = getGlobalVariable('argv'); + if (argv.noglobal) { + return; + } + + await silentNpm('install', '-g', '@angular-devkit/schematics-cli'); + await exec(process.platform.startsWith('win') ? 'where' : 'which', 'schematics'); + + const startCwd = process.cwd(); + const schematicPath = join(startCwd, 'test-schematic'); + + try { + // create blank schematic + await exec('schematics', 'schematic', '--name', 'test-schematic'); + + process.chdir(join(startCwd, 'test-schematic')); + await execAndWaitForOutputToMatch( + 'schematics', + ['.:', '--list-schematics'], + /my-full-schematic/, + ); + } finally { + // restore path + process.chdir(startCwd); + await Promise.all([ + rimraf(schematicPath), + silentNpm('uninstall', '-g', '@angular-devkit/schematics-cli'), + ]); + } +} diff --git a/tests/e2e/tests/schematics_cli/blank-test.ts b/tests/e2e/tests/schematics_cli/blank-test.ts new file mode 100644 index 000000000000..4087f7476db9 --- /dev/null +++ b/tests/e2e/tests/schematics_cli/blank-test.ts @@ -0,0 +1,34 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { exec, silentNpm } from '../../utils/process'; +import { rimraf } from '../../utils/fs'; + +export default async function () { + // setup + const argv = getGlobalVariable('argv'); + if (argv.noglobal) { + return; + } + + await silentNpm('install', '-g', '@angular-devkit/schematics-cli'); + await exec(process.platform.startsWith('win') ? 'where' : 'which', 'schematics'); + + const startCwd = process.cwd(); + const schematicPath = join(startCwd, 'test-schematic'); + + try { + // create schematic + await exec('schematics', 'blank', '--name', 'test-schematic'); + + process.chdir(schematicPath); + + await silentNpm('test'); + } finally { + // restore path + process.chdir(startCwd); + await Promise.all([ + rimraf(schematicPath), + silentNpm('uninstall', '-g', '@angular-devkit/schematics-cli'), + ]); + } +} diff --git a/tests/e2e/tests/schematics_cli/schematic-test.ts b/tests/e2e/tests/schematics_cli/schematic-test.ts new file mode 100644 index 000000000000..7d7d26e7304b --- /dev/null +++ b/tests/e2e/tests/schematics_cli/schematic-test.ts @@ -0,0 +1,34 @@ +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { exec, silentNpm } from '../../utils/process'; +import { rimraf } from '../../utils/fs'; + +export default async function () { + // setup + const argv = getGlobalVariable('argv'); + if (argv.noglobal) { + return; + } + + await silentNpm('install', '-g', '@angular-devkit/schematics-cli'); + await exec(process.platform.startsWith('win') ? 'where' : 'which', 'schematics'); + + const startCwd = process.cwd(); + const schematicPath = join(startCwd, 'test-schematic'); + + try { + // create schematic + await exec('schematics', 'schematic', '--name', 'test-schematic'); + + process.chdir(schematicPath); + + await silentNpm('test'); + } finally { + // restore path + process.chdir(startCwd); + await Promise.all([ + rimraf(schematicPath), + silentNpm('uninstall', '-g', '@angular-devkit/schematics-cli'), + ]); + } +} diff --git a/tests/e2e/tests/test/karma-junit-output.ts b/tests/e2e/tests/test/karma-junit-output.ts new file mode 100644 index 000000000000..dbc61c3fafc5 --- /dev/null +++ b/tests/e2e/tests/test/karma-junit-output.ts @@ -0,0 +1,27 @@ +import { expectFileMatchToExist, replaceInFile } from '../../utils/fs'; +import { installPackage } from '../../utils/packages'; +import { silentNg } from '../../utils/process'; + +const E2E_CUSTOM_LAUNCHER = ` + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], + }, + }, + restartOnFileChange: true +`; + +export default async function () { + await installPackage('karma-junit-reporter'); + await silentNg('generate', 'config', 'karma'); + + await replaceInFile('karma.conf.js', 'karma-jasmine-html-reporter', 'karma-junit-reporter'); + await replaceInFile('karma.conf.js', `'kjhtml'`, `'junit'`); + + await replaceInFile('karma.conf.js', `restartOnFileChange: true`, E2E_CUSTOM_LAUNCHER); + + await silentNg('test', '--no-watch'); + + await expectFileMatchToExist('.', /TESTS\-.+\.xml/); +} diff --git a/tests/e2e/tests/test/test-code-coverage-exclude.ts b/tests/e2e/tests/test/test-code-coverage-exclude.ts new file mode 100644 index 000000000000..808bcb59e2d9 --- /dev/null +++ b/tests/e2e/tests/test/test-code-coverage-exclude.ts @@ -0,0 +1,26 @@ +import { getGlobalVariable } from '../../utils/env'; +import { expectFileToExist, rimraf } from '../../utils/fs'; +import { silentNg } from '../../utils/process'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + const coverageOptionName = isWebpack ? '--code-coverage' : '--coverage'; + + // This test is already in build-angular, but that doesn't run on Windows. + await silentNg('test', '--no-watch', coverageOptionName); + await expectFileToExist('coverage/test-project/app.ts.html'); + // Delete coverage directory + await rimraf('coverage'); + + await silentNg( + 'test', + '--no-watch', + coverageOptionName, + `${coverageOptionName}-exclude='src/**/app.ts'`, + ); + + // Doesn't include excluded. + await expectFileToExist('coverage/test-project/index.html'); + await expectToFail(() => expectFileToExist('coverage/test-project/app.ts.html')); +} diff --git a/tests/e2e/tests/test/test-environment.ts b/tests/e2e/tests/test/test-environment.ts new file mode 100644 index 000000000000..1670cb246521 --- /dev/null +++ b/tests/e2e/tests/test/test-environment.ts @@ -0,0 +1,71 @@ +import { ng } from '../../utils/process'; +import { writeFile, writeMultipleFiles } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + + // Tests run in 'dev' environment by default. + await writeMultipleFiles({ + 'src/environment.prod.ts': ` + export const environment = { + production: true + };`, + 'src/environment.ts': ` + export const environment = { + production: false + }; + `, + 'src/app/environment.spec.ts': ` + import { environment } from '../environment'; + + describe('Test environment', () => { + it('should have production disabled', () => { + expect(environment.production).toBe(false); + }); + }); + `, + }); + + await ng('test', '--watch=false'); + + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + appArchitect[isWebpack ? 'test' : 'build'].configurations = { + production: { + fileReplacements: [ + { + replace: 'src/environment.ts', + with: 'src/environment.prod.ts', + }, + ], + }, + }; + if (!isWebpack) { + appArchitect.test.options ??= {}; + appArchitect.test.options.buildTarget = '::production'; + } + }); + + // Tests can run in different environment. + + await writeFile( + 'src/app/environment.spec.ts', + ` + import { environment } from '../environment'; + + describe('Test environment', () => { + it('should have production enabled', () => { + expect(environment.production).toBe(true); + }); + }); + `, + ); + + if (isWebpack) { + await ng('test', '--watch=false', '--configuration=production'); + } else { + await ng('test', '--watch=false'); + } +} diff --git a/tests/e2e/tests/test/test-fail-single-run.ts b/tests/e2e/tests/test/test-fail-single-run.ts new file mode 100644 index 000000000000..d2054e7c37ee --- /dev/null +++ b/tests/e2e/tests/test/test-fail-single-run.ts @@ -0,0 +1,12 @@ +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { expectToFail } from '../../utils/utils'; + +export default function () { + // TODO(architect): Delete this test. It is now in devkit/build-angular. + + // Fails on single run with broken compilation. + return writeFile('src/app.spec.ts', '

definitely not typescript

').then(() => + expectToFail(() => ng('test', '--watch=false')), + ); +} diff --git a/tests/e2e/tests/test/test-include-glob.ts b/tests/e2e/tests/test/test-include-glob.ts new file mode 100644 index 000000000000..5dc55edbf8c7 --- /dev/null +++ b/tests/e2e/tests/test/test-include-glob.ts @@ -0,0 +1,5 @@ +import { ng } from '../../utils/process'; + +export default async function () { + await ng('test', '--no-watch', `--include='**/*.spec.ts'`); +} diff --git a/tests/e2e/tests/test/test-jasmine-clock.ts b/tests/e2e/tests/test/test-jasmine-clock.ts new file mode 100644 index 000000000000..37b164ff5914 --- /dev/null +++ b/tests/e2e/tests/test/test-jasmine-clock.ts @@ -0,0 +1,33 @@ +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; + +export default async function () { + await writeFile( + 'src/app/app.spec.ts', + ` + import { TestBed } from '@angular/core/testing'; + import { App } from './app'; + + describe('App', () => { + beforeAll(() => { + jasmine.clock().install(); + }); + + afterAll(() => { + jasmine.clock().uninstall(); + }); + + beforeEach(() => TestBed.configureTestingModule({ + imports: [App] + })); + + it('should create the app', () => { + const fixture = TestBed.createComponent(App); + expect(fixture.componentInstance).toBeTruthy(); + }); + }); + `, + ); + + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/test/test-scripts.ts b/tests/e2e/tests/test/test-scripts.ts new file mode 100644 index 000000000000..953ed52cfbd7 --- /dev/null +++ b/tests/e2e/tests/test/test-scripts.ts @@ -0,0 +1,71 @@ +import { getGlobalVariable } from '../../utils/env'; +import { writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + // prepare global scripts test files + await writeMultipleFiles({ + 'src/string-script.js': `globalThis.stringScriptGlobal = 'string-scripts.js';`, + 'src/input-script.js': `globalThis.inputScriptGlobal = 'input-scripts.js';`, + 'src/typings.d.ts': ` + declare var stringScriptGlobal: any; + declare var inputScriptGlobal: any; + `, + 'src/app/app.ts': ` + import { Component } from '@angular/core'; + + @Component({ selector: 'app-root', template: '', standalone: false }) + export class App { + stringScriptGlobalProp = stringScriptGlobal; + inputScriptGlobalProp = inputScriptGlobal; + } + `, + 'src/app/app.spec.ts': ` + import { TestBed } from '@angular/core/testing'; + import { App } from './app'; + + describe('App', () => { + beforeEach(() => TestBed.configureTestingModule({ + declarations: [App] + })); + + it('should have access to string-script.js', () => { + let app = TestBed.createComponent(App).debugElement.componentInstance; + expect(app.stringScriptGlobalProp).toEqual('string-scripts.js'); + }); + + it('should have access to input-script.js', () => { + let app = TestBed.createComponent(App).debugElement.componentInstance; + expect(app.inputScriptGlobalProp).toEqual('input-scripts.js'); + }); + }); + + describe('Spec', () => { + it('should have access to string-script.js', () => { + expect(stringScriptGlobal).toBe('string-scripts.js'); + }); + + it('should have access to input-script.js', () => { + expect(inputScriptGlobal).toBe('input-scripts.js'); + }); + }); + `, + }); + + // should fail because the global scripts were not added to scripts array + await expectToFail(() => ng('test', '--watch=false')); + + const isWebpack = !getGlobalVariable('argv')['esbuild']; + await updateJsonFile('angular.json', (workspaceJson) => { + const appArchitect = workspaceJson.projects['test-project'].architect; + appArchitect[isWebpack ? 'test' : 'build'].options.scripts = [ + { input: 'src/string-script.js' }, + { input: 'src/input-script.js' }, + ]; + }); + + // should pass now + await ng('test', '--watch=false'); +} diff --git a/tests/e2e/tests/test/test-sourcemap.ts b/tests/e2e/tests/test/test-sourcemap.ts new file mode 100644 index 000000000000..5d4e668c54b6 --- /dev/null +++ b/tests/e2e/tests/test/test-sourcemap.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert'; +import { writeFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { assertIsError } from '../../utils/utils'; +import { updateJsonFile } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + + await writeFile( + 'src/app/app.spec.ts', + ` + it('should fail', () => { + expect(undefined).toBeTruthy(); + }); + `, + ); + + // when sourcemaps are 'on' the stacktrace will point to the spec.ts file. + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + if (isWebpack) { + appArchitect['test'].options.sourceMap = true; + } else { + appArchitect['build'].configurations.development.sourceMap = true; + } + }); + try { + await ng('test', '--no-watch'); + throw new Error('ng test should have failed.'); + } catch (error) { + assertIsError(error); + assert.match(error.message, /\(src\/app\/app\.spec\.ts:3:27/); + assert.doesNotMatch(error.message, /webpack/); + } + + // when sourcemaps are 'off' the stacktrace won't point to the spec.ts file. + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + if (isWebpack) { + appArchitect['test'].options.sourceMap = false; + } else { + appArchitect['build'].configurations.development.sourceMap = false; + } + }); + try { + await ng('test', '--no-watch'); + throw new Error('ng test should have failed.'); + } catch (error) { + assertIsError(error); + assert.match(error.message, /main\.js/); + } +} diff --git a/tests/e2e/tests/update/update-application-builder.ts b/tests/e2e/tests/update/update-application-builder.ts new file mode 100644 index 000000000000..2769fe943138 --- /dev/null +++ b/tests/e2e/tests/update/update-application-builder.ts @@ -0,0 +1,36 @@ +import { match } from 'node:assert'; +import { createProjectFromAsset } from '../../utils/assets'; +import { + expectFileMatchToExist, + expectFileNotToExist, + expectFileToExist, + expectFileToMatch, +} from '../../utils/fs'; +import { execAndWaitForOutputToMatch, ng, noSilentNg } from '../../utils/process'; +import { findFreePort } from '../../utils/network'; + +export default async function () { + await createProjectFromAsset('ssr-project-webpack', false, false); + await ng('update', `@angular/cli`, '--name=use-application-builder'); + + await Promise.all([ + expectFileNotToExist('tsconfig.server.json'), + expectFileToMatch('tsconfig.json', 'esModuleInterop'), + expectFileToMatch('src/server.ts', 'import.meta.url'), + ]); + + // Verify project now creates bundles + await noSilentNg('build', '--configuration=production'); + + await Promise.all([ + expectFileToExist('dist/ssr-project-webpack/server/server.mjs'), + expectFileMatchToExist('dist/ssr-project-webpack/browser', /main-[a-zA-Z0-9]{8}\.js/), + ]); + + // Verify that the app runs + const port = await findFreePort(); + await execAndWaitForOutputToMatch('ng', ['serve', '--port', String(port)], /complete\./); + const response = await fetch(`http://localhost:${port}/`); + const text = await response.text(); + match(text, /app is running!/); +} diff --git a/tests/e2e/tests/update/update-multiple-versions.ts b/tests/e2e/tests/update/update-multiple-versions.ts new file mode 100644 index 000000000000..c9070b1a090b --- /dev/null +++ b/tests/e2e/tests/update/update-multiple-versions.ts @@ -0,0 +1,43 @@ +import { createProjectFromAsset } from '../../utils/assets'; +import { setRegistry } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { isPrereleaseCli } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +export default async function () { + let restoreRegistry: (() => Promise) | undefined; + try { + restoreRegistry = await createProjectFromAsset('20.0-project', true); + await setRegistry(true); + + const extraArgs = ['--force']; + if (isPrereleaseCli()) { + extraArgs.push('--next'); + } + + // TODO(alanagius): investigate how to re-enable this. This is failing but it's correct since we are using the public registry. + // Update Angular from v13 to 14 + // const { stdout } = await ng('update', ...extraArgs); + // if (!/@angular\/core\s+13\.\d\.\d+ -> 14\.\d\.\d+\s+ng update @angular\/core@14/.test(stdout)) { + // // @angular/core 13.x.x -> 14.x.x ng update @angular/core@14 + // throw new Error( + // `Output didn't match "@angular/core 13.x.x -> 14.x.x ng update @angular/core@14". OUTPUT: \n` + + // stdout, + // ); + // } + + const { message } = await expectToFail(() => ng('update', '@angular/core', ...extraArgs)); + if ( + !message.includes( + `Updating multiple major versions of '@angular/core' at once is not supported`, + ) + ) { + throw new Error( + `Expected error message to include "Updating multiple major versions of '@angular/core' at once is not supported" but didn't. OUTPUT: \n` + + message, + ); + } + } finally { + await restoreRegistry?.(); + } +} diff --git a/tests/e2e/tests/update/update-pnpm-workspace.ts b/tests/e2e/tests/update/update-pnpm-workspace.ts new file mode 100644 index 000000000000..29aff7bff42a --- /dev/null +++ b/tests/e2e/tests/update/update-pnpm-workspace.ts @@ -0,0 +1,33 @@ +import { createProjectFromAsset } from '../../utils/assets'; +import { readFile, writeFile } from '../../utils/fs'; +import { getActivePackageManager } from '../../utils/packages'; +import { ng } from '../../utils/process'; + +export default async function () { + if (getActivePackageManager() !== 'pnpm') { + return; + } + + let restoreRegistry: (() => Promise) | undefined; + + try { + // Setup project from older asset using the public registry + restoreRegistry = await createProjectFromAsset('20.0-project', true); + + // Create pnpm-workspace.yaml inside the project directory + await writeFile('pnpm-workspace.yaml', "packages:\n - '.'\n"); + + // Run ng update on @angular/cli to trigger the update from version 20 to the next major version + await ng('update', '@angular/cli@21', '@angular/core@21'); + + // Verify that the pnpm lockfile does not contain references to the temporary package directory + const lockfileContent = await readFile('pnpm-lock.yaml'); + if (lockfileContent.includes('angular-cli-tmp-packages-')) { + throw new Error( + 'pnpm-lock.yaml contains reference to temporary package directory, isolation failed!', + ); + } + } finally { + await restoreRegistry?.(); + } +} diff --git a/tests/e2e/tests/update/update-secure-registry.ts b/tests/e2e/tests/update/update-secure-registry.ts new file mode 100644 index 000000000000..47a9db657cd8 --- /dev/null +++ b/tests/e2e/tests/update/update-secure-registry.ts @@ -0,0 +1,39 @@ +import { exec, ng } from '../../utils/process'; +import { createNpmConfigForAuthentication } from '../../utils/registry'; +import { expectToFail } from '../../utils/utils'; +import { isPrereleaseCli } from '../../utils/project'; +import { getActivePackageManager } from '../../utils/packages'; +import assert from 'node:assert'; + +export default async function () { + // The environment variable has priority over the .npmrc + delete process.env['NPM_CONFIG_REGISTRY']; + const worksMessage = 'We analyzed your package.json'; + + const extraArgs: string[] = []; + if (isPrereleaseCli()) { + extraArgs.push('--next'); + } + + // Valid authentication token + + await createNpmConfigForAuthentication(); + const { stdout: stdout2 } = await ng('update', ...extraArgs); + if (!stdout2.includes(worksMessage)) { + throw new Error(`Expected stdout to contain "${worksMessage}"`); + } + + // Invalid authentication token + + await createNpmConfigForAuthentication(true, true); + await expectToFail(() => ng('update', ...extraArgs)); + + if (getActivePackageManager() === 'yarn') { + // When running `ng update` using yarn (`yarn ng update`), yarn will set the `npm_config_registry` env variable to `https://registry.yarnpkg.com` + // Validate the registry in the RC is used. + await createNpmConfigForAuthentication(true, true); + + const error = await expectToFail(() => exec('yarn', 'ng', 'update', ...extraArgs)); + assert.match(error.message, /not allowed to access package|status code 403/); + } +} diff --git a/tests/e2e/tests/update/update.ts b/tests/e2e/tests/update/update.ts new file mode 100644 index 000000000000..fd8663503ecc --- /dev/null +++ b/tests/e2e/tests/update/update.ts @@ -0,0 +1,94 @@ +import { appendFile } from 'node:fs/promises'; +import { createProjectFromAsset } from '../../utils/assets'; +import { expectFileMatchToExist } from '../../utils/fs'; +import { getActivePackageManager } from '../../utils/packages'; +import { ng, noSilentNg } from '../../utils/process'; +import { isPrereleaseCli, useCIChrome, useCIDefaults, getNgCLIVersion } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; + +export default async function () { + let restoreRegistry: (() => Promise) | undefined; + + try { + // We need to use the public registry because in the local NPM server we don't have + // older versions @angular/cli packages which would cause `npm install` during `ng update` to fail. + restoreRegistry = await createProjectFromAsset('20.0-project', true); + + // CLI project version + const cliMajorProjectVersion = 20; + + // If using npm, enable legacy peer deps mode to avoid defects in npm 7+'s peer dependency resolution + // Example error where 11.2.14 satisfies the SemVer range ^11.0.0 but still fails: + // npm ERR! Conflicting peer dependency: @angular/compiler-cli@11.2.14 + // npm ERR! node_modules/@angular/compiler-cli + // npm ERR! peer @angular/compiler-cli@"^11.0.0 || ^11.2.0-next" from @angular-devkit/build-angular@0.1102.19 + // npm ERR! node_modules/@angular-devkit/build-angular + // npm ERR! dev @angular-devkit/build-angular@"~0.1102.19" from the root project + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + // CLI current version. + const cliMajorVersion = getNgCLIVersion().major; + + for (let version = cliMajorProjectVersion + 1; version < cliMajorVersion; version++) { + // Run all the migrations until the current build major version - 1. + // Example: when the project is using CLI version 10 and the build CLI version is 14. + // We will run the following migrations: + // - 10 -> 11 + // - 11 -> 12 + // - 12 -> 13 + const { stdout } = await ng('update', `@angular/cli@${version}`, `@angular/core@${version}`); + if ( + !stdout.includes("Executing migrations of package '@angular/cli'") && + !stdout.includes("Optional migrations of package '@angular/cli'") + ) { + throw new Error('Update did not execute migrations for @angular/cli. OUTPUT: \n' + stdout); + } + if (!stdout.includes("Executing migrations of package '@angular/core'")) { + throw new Error('Update did not execute migrations for @angular/core. OUTPUT: \n' + stdout); + } + } + } finally { + await restoreRegistry?.(); + } + + // Update Angular current build + const extraUpdateArgs = isPrereleaseCli() ? ['--next', '--force'] : []; + + // For the latest/next release we purposely don't run `ng update @angular/core`. + + // During a major release when the branch version is bumped from `12.0.0-rc.x` to `12.0.0` there would be a period were in + // the local NPM registry `@angular/cli@latest` will point to `12.0.0`, but on the public NPM repository `@angular/core@latest` will be `11.2.x`. + + // This causes `ng update @angular/core` to fail because of mismatching peer dependencies. + + // The reason for this is because of our bumping and release strategy. When we release a major version on NPM we don't tag it + // `@latest` right away, but we wait for all teams to release their packages before doing so. While this is good because all team + // packages gets tagged with `@latest` at the same time. This is problematic for our CI, since we test against the public NPM repo and are dependent on tags. + + // NB: `ng update @angular/cli` will still cause `@angular/core` packages to be updated therefore we still test updating the core package without running the command. + + await ng('update', '@angular/cli', ...extraUpdateArgs); + + // Setup testing to use CI Chrome. + await useCIChrome('twenty-project', './'); + await useCIDefaults('twenty-project'); + + // Run CLI commands. + await ng('generate', 'component', 'my-comp'); + await ng('test', '--watch=false'); + + await executeBrowserTest({ + configuration: 'production', + expectedTitleText: 'Hello, twenty-project', + }); + await executeBrowserTest({ + configuration: 'development', + expectedTitleText: 'Hello, twenty-project', + }); + + // Verify project now creates bundles + await noSilentNg('build', '--configuration=production'); + await expectFileMatchToExist('dist/twenty-project/browser', /main-[a-zA-Z0-9]{8}\.js/); +} diff --git a/tests/e2e/tests/vite/reuse-dep-optimization-cache.ts b/tests/e2e/tests/vite/reuse-dep-optimization-cache.ts new file mode 100644 index 000000000000..07be3f2a911b --- /dev/null +++ b/tests/e2e/tests/vite/reuse-dep-optimization-cache.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert'; +import { findFreePort } from '../../utils/network'; +import { execAndWaitForOutputToMatch, killAllProcesses, ng } from '../../utils/process'; + +export default async function () { + await ng('cache', 'clean'); + await ng('cache', 'on'); + + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'ng', + ['serve', '--port', `${port}`], + /dependencies optimized/, + // Use CI:0 to force caching + { ...process.env, DEBUG: 'vite:deps', CI: '0', NO_COLOR: 'true' }, + ); + + const response = await fetch(`http://localhost:${port}/main.js`); + + assert(response.ok, `Expected 'response.ok' to be 'true'.`); + + // Terminate the dev-server + await killAllProcesses(); + + await execAndWaitForOutputToMatch( + 'ng', + ['serve', '--port=0'], + /Hash is consistent\. Skipping/, + // Use CI:0 to force caching + { ...process.env, DEBUG: 'vite:deps', CI: '0', NO_COLOR: 'true' }, + ); +} diff --git a/tests/e2e/tests/vite/ssr-base-href.ts b/tests/e2e/tests/vite/ssr-base-href.ts new file mode 100644 index 000000000000..140f2582689a --- /dev/null +++ b/tests/e2e/tests/vite/ssr-base-href.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert'; +import { ng } from '../../utils/process'; +import { replaceInFile } from '../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, updateJsonFile, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await updateJsonFile('angular.json', (json) => { + json.projects['test-project'].architect.build.options['baseHref'] = '/base'; + }); + + await replaceInFile( + 'src/server.ts', + /express\(\);/, + `express(); + + app.use('/ping', (req, res) => { + return res.json({ pong: true }); + });`, + ); + + const port = await ngServe(); + + // Angular application and bundled should be affected by baseHref + await matchResponse(`http://localhost:${port}/base`, /ng-server-context/); + await matchResponse(`http://localhost:${port}/base/main.js`, /App/); + + // Server endpoint should not be affected by baseHref + await matchResponse(`http://localhost:${port}/ping`, /pong/); +} + +async function matchResponse(url: string, match: RegExp): Promise { + const response = await fetch(url); + const text = await response.text(); + + assert.match(text, match); +} diff --git a/tests/e2e/tests/vite/ssr-default.ts b/tests/e2e/tests/vite/ssr-default.ts new file mode 100644 index 000000000000..8b64a4b30f67 --- /dev/null +++ b/tests/e2e/tests/vite/ssr-default.ts @@ -0,0 +1,36 @@ +import assert from 'node:assert'; +import { ng } from '../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Enable caching to test real development workflow. + await ng('cache', 'clean'); + await ng('cache', 'on'); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + const port = await ngServe(); + + // Verify the server is running and the API response is correct. + await validateResponse('/main.js', /bootstrapApplication/); + await validateResponse('/', /Hello,/); + await validateResponse('/unknown', /Cannot GET/, 404); + + async function validateResponse(pathname: string, match: RegExp, status = 200): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, status); + } +} diff --git a/tests/e2e/tests/vite/ssr-entry-express.ts b/tests/e2e/tests/vite/ssr-entry-express.ts new file mode 100644 index 000000000000..11cf671becbf --- /dev/null +++ b/tests/e2e/tests/vite/ssr-entry-express.ts @@ -0,0 +1,130 @@ +import assert from 'node:assert'; +import { setTimeout } from 'node:timers/promises'; +import { replaceInFile, writeMultipleFiles } from '../../utils/fs'; +import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + + export const routes: Routes = [ + { path: 'home', component: Home } + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: '**', renderMode: RenderMode.Server } + ]; + `, + 'src/server.ts': ` + import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node'; + import express from 'express'; + import { join } from 'node:path'; + + export function app(): express.Express { + const server = express(); + const browserDistFolder = join(import.meta.dirname, '../browser'); + const angularNodeAppEngine = new AngularNodeAppEngine(); + + server.use('/api/{*splat}', (req, res) => { + res.json({ hello: 'foo' }) + }); + + server.use(express.static(browserDistFolder, { + maxAge: '1y', + index: 'index.html' + })); + + server.use(async(req, res, next) => { + const response = await angularNodeAppEngine.handle(req); + if (response) { + writeResponseToNodeResponse(response, res); + } else { + next(); + } + }); + + return server; + } + + const server = app(); + if (isMainModule(import.meta.url)) { + const port = process.env['PORT'] || 4000; + server.listen(port, (error) => { + if (error) { + throw error; + } + + console.log(\`Node Express server listening on http://localhost:\${port}\`); + }); + } + + export const reqHandler = createNodeRequestHandler(server); + `, + }); + + await silentNg('generate', 'component', 'home'); + + const port = await ngServe(); + + // Verify the server is running and the API response is correct. + await validateResponse('/main.js', /bootstrapApplication/); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /home works/); + + // Modify the home component and validate the change. + await modifyFileAndWaitUntilUpdated( + 'src/app/home/home.html', + 'home works', + 'yay home works!!!', + true, + ); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /yay home works/); + + // Modify the API response and validate the change. + await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`); + await validateResponse('/api/test', /bar/); + await validateResponse('/home', /yay home works/); + + async function validateResponse(pathname: string, match: RegExp): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); + } +} + +async function modifyFileAndWaitUntilUpdated( + filePath: string, + searchValue: string, + replaceValue: string, + hmr = false, +): Promise { + await Promise.all([ + waitForAnyProcessOutputToMatch( + hmr ? /Component update sent to client/ : /Page reload sent to client/, + ), + setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)), + ]); +} diff --git a/tests/e2e/tests/vite/ssr-entry-fastify.ts b/tests/e2e/tests/vite/ssr-entry-fastify.ts new file mode 100644 index 000000000000..c50e8c2200f6 --- /dev/null +++ b/tests/e2e/tests/vite/ssr-entry-fastify.ts @@ -0,0 +1,123 @@ +import assert from 'node:assert'; +import { setTimeout } from 'node:timers/promises'; +import { replaceInFile, writeMultipleFiles } from '../../utils/fs'; +import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { installPackage, installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await installPackage('fastify@5'); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + + export const routes: Routes = [ + { path: 'home', component: Home } + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: '**', renderMode: RenderMode.Server } + ]; + `, + 'src/server.ts': ` + import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node'; + import fastify from 'fastify'; + + export function app() { + const server = fastify(); + const angularNodeAppEngine = new AngularNodeAppEngine(); + server.get('/api/*', (req, reply) => reply.send({ hello: 'foo' })); + server.get('*', async (req, reply) => { + try { + const response = await angularNodeAppEngine.handle(req.raw); + if (response) { + await writeResponseToNodeResponse(response, reply.raw); + } else { + reply.callNotFound(); + } + } catch (error) { + reply.send(error); + } + }); + + return server; + } + + const server = app(); + if (isMainModule(import.meta.url)) { + const port = +(process.env['PORT'] || 4000); + server.listen({ port }, () => { + console.log(\`Fastify server listening on http://localhost:\${port}\`); + }); + } + + export const reqHandler = createNodeRequestHandler(async (req, res) => { + await server.ready(); + server.server.emit('request', req, res); + }); + `, + }); + + await silentNg('generate', 'component', 'home'); + + const port = await ngServe(); + + // Verify the server is running and the API response is correct. + await validateResponse('/main.js', /bootstrapApplication/); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /home works/); + + // Modify the home component and validate the change. + await modifyFileAndWaitUntilUpdated( + 'src/app/home/home.html', + 'home works', + 'yay home works!!!', + true, + ); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /yay home works/); + + // Modify the API response and validate the change. + await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`); + await validateResponse('/api/test', /bar/); + await validateResponse('/home', /yay home works/); + + async function validateResponse(pathname: string, match: RegExp): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); + } +} + +async function modifyFileAndWaitUntilUpdated( + filePath: string, + searchValue: string, + replaceValue: string, + hmr = false, +): Promise { + await Promise.all([ + waitForAnyProcessOutputToMatch( + hmr ? /Component update sent to client/ : /Page reload sent to client/, + ), + setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)), + ]); +} diff --git a/tests/e2e/tests/vite/ssr-entry-h3.ts b/tests/e2e/tests/vite/ssr-entry-h3.ts new file mode 100644 index 000000000000..4a4f91066000 --- /dev/null +++ b/tests/e2e/tests/vite/ssr-entry-h3.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert'; +import { setTimeout } from 'node:timers/promises'; +import { replaceInFile, writeMultipleFiles } from '../../utils/fs'; +import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { installPackage, installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await installPackage('h3@1'); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + + export const routes: Routes = [ + { path: 'home', component: Home } + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: '**', renderMode: RenderMode.Server } + ]; + `, + 'src/server.ts': ` + import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; + import { createApp, createRouter, toWebHandler, defineEventHandler, toWebRequest } from 'h3'; + + export function app() { + const server = createApp(); + const router = createRouter(); + const angularAppEngine = new AngularAppEngine(); + + router.use( + '/api/**', + defineEventHandler(() => ({ hello: 'foo' })), + ); + + router.use( + '/**', + defineEventHandler((event) => angularAppEngine.handle(toWebRequest(event))), + ); + + server.use(router); + + return server; + } + + const server = app(); + + export const reqHandler = createRequestHandler(toWebHandler(server)); + `, + }); + + await silentNg('generate', 'component', 'home'); + + const port = await ngServe(); + + // Verify the server is running and the API response is correct. + await validateResponse('/main.js', /bootstrapApplication/); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /home works/); + + // Modify the home component and validate the change. + await modifyFileAndWaitUntilUpdated( + 'src/app/home/home.html', + 'home works', + 'yay home works!!!', + true, + ); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /yay home works/); + + // Modify the API response and validate the change. + await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`); + await validateResponse('/api/test', /bar/); + await validateResponse('/home', /yay home works/); + + async function validateResponse(pathname: string, match: RegExp): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); + } +} + +async function modifyFileAndWaitUntilUpdated( + filePath: string, + searchValue: string, + replaceValue: string, + hmr = false, +): Promise { + await Promise.all([ + waitForAnyProcessOutputToMatch( + hmr ? /Component update sent to client/ : /Page reload sent to client/, + ), + setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)), + ]); +} diff --git a/tests/e2e/tests/vite/ssr-entry-hono.ts b/tests/e2e/tests/vite/ssr-entry-hono.ts new file mode 100644 index 000000000000..0b0b8220fe6b --- /dev/null +++ b/tests/e2e/tests/vite/ssr-entry-hono.ts @@ -0,0 +1,106 @@ +import assert from 'node:assert'; +import { setTimeout } from 'node:timers/promises'; +import { replaceInFile, writeMultipleFiles } from '../../utils/fs'; +import { ng, silentNg, waitForAnyProcessOutputToMatch } from '../../utils/process'; +import { installPackage, installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await installPackage('hono@4'); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + + export const routes: Routes = [ + { path: 'home', component: Home } + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: '**', renderMode: RenderMode.Server } + ]; + `, + 'src/server.ts': ` + import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; + import { Hono } from 'hono'; + + export function app() { + const server = new Hono(); + const angularAppEngine = new AngularAppEngine(); + + server.get('/api/*', (c) => c.json({ hello: 'foo' })); + server.get('/*', async (c) => { + const res = await angularAppEngine.handle(c.req.raw); + return res || undefined + }); + + return server; + } + + const server = app(); + export const reqHandler = createRequestHandler(server.fetch); + `, + }); + + await silentNg('generate', 'component', 'home'); + + const port = await ngServe(); + + // Verify the server is running and the API response is correct. + await validateResponse('/main.js', /bootstrapApplication/); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /home works/); + + // Modify the home component and validate the change. + await modifyFileAndWaitUntilUpdated( + 'src/app/home/home.html', + 'home works', + 'yay home works!!!', + true, + ); + await validateResponse('/api/test', /foo/); + await validateResponse('/home', /yay home works/); + + // Modify the API response and validate the change. + await modifyFileAndWaitUntilUpdated('src/server.ts', `{ hello: 'foo' }`, `{ hello: 'bar' }`); + await validateResponse('/api/test', /bar/); + await validateResponse('/home', /yay home works/); + + async function validateResponse(pathname: string, match: RegExp): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); + } +} + +async function modifyFileAndWaitUntilUpdated( + filePath: string, + searchValue: string, + replaceValue: string, + hmr = false, +): Promise { + await Promise.all([ + waitForAnyProcessOutputToMatch( + hmr ? /Component update sent to client/ : /Page reload sent to client/, + ), + setTimeout(100).then(() => replaceInFile(filePath, searchValue, replaceValue)), + ]); +} diff --git a/tests/e2e/tests/vite/ssr-error-stack.ts b/tests/e2e/tests/vite/ssr-error-stack.ts new file mode 100644 index 000000000000..8fce78b9e7ad --- /dev/null +++ b/tests/e2e/tests/vite/ssr-error-stack.ts @@ -0,0 +1,34 @@ +import { doesNotMatch, match } from 'node:assert'; +import { ng } from '../../utils/process'; +import { appendToFile } from '../../utils/fs'; +import { ngServe, useSha } from '../../utils/project'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; + +export default async function () { + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + // Create Error. + await appendToFile( + 'src/app/app.ts', + ` + (() => { + throw new Error('something happened!'); + })(); + `, + ); + + const port = await ngServe(); + const response = await fetch(`http://localhost:${port}/`); + const text = await response.text(); + + // The error is also sent in the browser, so we don't need to scrap the stderr. + match( + text, + /something happened.+at eval \(.+[\\/]+e2e-test[\\/]+test-project[\\/]+src[\\/]+app[\\/]+app\.ts:\d+:\d+\)/, + ); + doesNotMatch(text, /vite-root/); +} diff --git a/tests/e2e/tests/vite/ssr-new-dep-optimization.ts b/tests/e2e/tests/vite/ssr-new-dep-optimization.ts new file mode 100644 index 000000000000..291e8df20170 --- /dev/null +++ b/tests/e2e/tests/vite/ssr-new-dep-optimization.ts @@ -0,0 +1,60 @@ +import assert from 'node:assert'; +import { + execAndWaitForOutputToMatch, + ng, + waitForAnyProcessOutputToMatch, +} from '../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; +import { readFile, writeFile } from '../../utils/fs'; +import { findFreePort } from '../../utils/network'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Enable caching to test real development workflow. + await ng('cache', 'clean'); + await ng('cache', 'on'); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + const port = await findFreePort(); + await execAndWaitForOutputToMatch( + 'ng', + ['serve', '--port', port.toString()], + /Application bundle generation complete/, + { ...process.env, CI: '0', NO_COLOR: 'true' }, + ); + await validateResponse('/', /Hello,/); + + await Promise.all([ + waitForAnyProcessOutputToMatch( + /optimized: @angular\/platform-browser\/animations\/async/, + 6000, + ), + writeFile( + 'src/app/app.config.ts', + ` + import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; + ${(await readFile('src/app/app.config.ts')).replace('provideRouter(routes),', 'provideAnimationsAsync(), provideRouter(routes),')} + `, + ), + ]); + + // Verify the app still works. + await validateResponse('/', /Hello,/); + + async function validateResponse(pathname: string, match: RegExp): Promise { + const response = await fetch(new URL(pathname, `http://localhost:${port}`)); + const text = await response.text(); + assert.match(text, match); + } +} diff --git a/tests/e2e/tests/vite/ssr-with-ssl.ts b/tests/e2e/tests/vite/ssr-with-ssl.ts new file mode 100644 index 000000000000..e07d01b06fcc --- /dev/null +++ b/tests/e2e/tests/vite/ssr-with-ssl.ts @@ -0,0 +1,71 @@ +import { Agent, fetch } from 'undici'; +import assert from 'node:assert'; +import { writeMultipleFiles } from '../../utils/fs'; +import { ng, silentNg } from '../../utils/process'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + // Forcibly remove in case another test doesn't clean itself up. + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Replace the template of app.ng.html as it makes it harder to debug + 'src/app/app.html': '', + 'src/app/app.routes.ts': ` + import { Routes } from '@angular/router'; + import { Home } from './home/home'; + + export const routes: Routes = [ + { path: 'home', component: Home } + ]; + `, + 'src/app/app.routes.server.ts': ` + import { RenderMode, ServerRoute } from '@angular/ssr'; + + export const serverRoutes: ServerRoute[] = [ + { path: '**', renderMode: RenderMode.Server } + ]; + `, + }); + + await silentNg('generate', 'component', 'home'); + + const port = await ngServe('--ssl'); + + // http 2 + await validateResponse('/main.js', /bootstrapApplication/, true); + await validateResponse('/home', /home works/, true); + + // http 1.1 + await validateResponse('/main.js', /bootstrapApplication/, false); + await validateResponse('/home', /home works/, false); + + async function validateResponse( + pathname: string, + match: RegExp, + allowH2: boolean, + ): Promise { + const response = await fetch(new URL(pathname, `https://localhost:${port}`), { + dispatcher: new Agent({ + connect: { + allowH2, + rejectUnauthorized: false, + }, + }), + }); + + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); + } +} diff --git a/tests/e2e/tests/vite/wasi.ts b/tests/e2e/tests/vite/wasi.ts new file mode 100644 index 000000000000..b7ddafb4e82c --- /dev/null +++ b/tests/e2e/tests/vite/wasi.ts @@ -0,0 +1,23 @@ +import assert from 'node:assert'; +import { getGlobalVariable } from '../../utils/env'; +import { ng } from '../../utils/process'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + const originalForceWasi = process.env['NAPI_RS_FORCE_WASI']; + process.env['NAPI_RS_FORCE_WASI'] = 'error'; + + try { + await ng('build'); + } finally { + if (originalForceWasi === undefined) { + delete process.env['NAPI_RS_FORCE_WASI']; + } else { + process.env['NAPI_RS_FORCE_WASI'] = originalForceWasi; + } + } +} diff --git a/tests/e2e/tests/vitest/browser-coverage-istanbul.ts b/tests/e2e/tests/vitest/browser-coverage-istanbul.ts new file mode 100644 index 000000000000..66f73162d586 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-coverage-istanbul.ts @@ -0,0 +1,35 @@ +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; +import { expectFileToExist, readFile } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; + +export default async function (): Promise { + // Install ONLY Istanbul coverage package. + // This will trigger the auto-detection logic to use Istanbul even for Node tests. + await applyVitestBuilder({ + coverageIstanbul: true, + }); + + // Use the 'json' reporter to get a machine-readable output for assertions. + await updateJsonFile('angular.json', (json) => { + const project = Object.values(json['projects'])[0] as any; + const test = project['architect']['test']; + test.options = { + coverageReporters: ['json', 'text'], + }; + }); + + // Run tests with coverage (defaults to Node/jsdom environment) + const { stdout } = await ng('test', '--no-watch', '--coverage'); + + // Verify that tests passed + assert.match(stdout, /1 passed/, 'Expected tests to run successfully.'); + + // Verify that coverage files are generated + const coverageJsonPath = 'coverage/test-project/coverage-final.json'; + await expectFileToExist(coverageJsonPath); + + const coverageSummary = JSON.parse(await readFile(coverageJsonPath)); + assert.ok(Object.keys(coverageSummary).length > 0, 'Expected coverage report to not be empty.'); +} diff --git a/tests/e2e/tests/vitest/browser-coverage-sourcemaps.ts b/tests/e2e/tests/vitest/browser-coverage-sourcemaps.ts new file mode 100644 index 000000000000..476c15c41d38 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-coverage-sourcemaps.ts @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { expectFileToExist, readFile } from '../../utils/fs'; + +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + coverageV8: true, + }); + + // Run tests with coverage in browser mode. + // We use the default passing tests generated for the project. + const { stdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'chromiumHeadless', + '--coverage', + '--coverage-reporters=json-summary', + ); + + // Verify that tests passed + assert.match(stdout, /pass/, 'Expected tests to run successfully.'); + + // Verify that coverage files are generated + const summaryPath = 'coverage/test-project/coverage-summary.json'; + await expectFileToExist(summaryPath); + + const summary = JSON.parse(await readFile(summaryPath)); + + // Find the key for app.ts (it might be an absolute path) + const appFileKey = Object.keys(summary).find((key) => key.endsWith('app.ts')); + assert.ok(appFileKey, 'Expected coverage summary to contain app.ts.'); + + const appCoverage = summary[appFileKey]; + assert.ok(appCoverage.lines.pct > 0, 'Expected lines percentage to be greater than 0.'); + + // Also verify that spec files are NOT present in the summary + const specFileKey = Object.keys(summary).find((key) => key.endsWith('.spec.ts')); + assert.ok(!specFileKey, 'Expected coverage report to not contain .spec.ts files.'); +} diff --git a/tests/e2e/tests/vitest/browser-coverage-validation.ts b/tests/e2e/tests/vitest/browser-coverage-validation.ts new file mode 100644 index 000000000000..66342746a91a --- /dev/null +++ b/tests/e2e/tests/vitest/browser-coverage-validation.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { execAndCaptureError } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { stripVTControlCharacters } from 'node:util'; +import { unlink } from 'node:fs/promises'; + +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + }); + + // === Case 1: Browser configured via CLI option === + const error1 = await execAndCaptureError('ng', [ + 'test', + '--no-watch', + '--coverage', + '--browsers', + 'firefox', + ]); + const output1 = stripVTControlCharacters(error1.message); + assert.match( + output1, + /Code coverage requires either "@vitest\/coverage-v8" or "@vitest\/coverage-istanbul" to be installed./, + 'Expected validation error for missing coverage packages.', + ); + + await applyVitestBuilder({ + playwright: true, + coverageV8: true, + }); + + const configPath = 'vitest.config.mts'; + const absoluteConfigPath = path.resolve(configPath); + + try { + // === Case 2: Browser configured via vitest.config.mts (name) === + await writeFile( + configPath, + ` + import { defineConfig } from 'vitest/config'; + import { playwright } from '@vitest/browser-playwright'; + + export default defineConfig({ + test: { + coverage: { provider: 'v8' }, + browser: { + enabled: true, + name: 'firefox', + provider: playwright(), + }, + }, + }); + `, + ); + + const error2 = await execAndCaptureError('ng', [ + 'test', + '--no-watch', + '--coverage', + `--runner-config=${absoluteConfigPath}`, + ]); + const output2 = stripVTControlCharacters(error2.message); + assert.match( + output2, + /Code coverage is enabled, but the following configured browsers do not support the V8 coverage provider: firefox/, + 'Expected validation error for unsupported browser with coverage (config name).', + ); + assert.match( + output2, + /Please use the "istanbul" coverage provider/, + 'Expected the error to suggest the istanbul coverage provider.', + ); + + // === Case 3: Browser configured via vitest.config.mts (instances) === + await writeFile( + configPath, + ` + import { defineConfig } from 'vitest/config'; + import { playwright } from '@vitest/browser-playwright'; + + export default defineConfig({ + test: { + coverage: { provider: 'v8' }, + browser: { + enabled: true, + provider: playwright(), + instances: [{ browser: 'firefox' }], + } as any, + }, + }); + `, + ); + + const error3 = await execAndCaptureError('ng', [ + 'test', + '--no-watch', + '--coverage', + `--runner-config=${absoluteConfigPath}`, + ]); + const output3 = stripVTControlCharacters(error3.message); + assert.match( + output3, + /Code coverage is enabled, but the following configured browsers do not support the V8 coverage provider: firefox/, + 'Expected validation error for unsupported browser with coverage (config instances).', + ); + } finally { + // Clean up the config file so it doesn't affect other tests + try { + await unlink(configPath); + } catch {} + } +} diff --git a/tests/e2e/tests/vitest/browser-custom-config-vitest-v4.ts b/tests/e2e/tests/vitest/browser-custom-config-vitest-v4.ts new file mode 100644 index 000000000000..7865830f3b82 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-custom-config-vitest-v4.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { installWorkspacePackages } from '../../utils/packages'; +import { updateJsonFile } from '../../utils/project'; + +export default async function (): Promise { + await applyVitestBuilder({ + skipInstall: true, + }); + + await updateJsonFile('package.json', (json) => { + json.devDependencies = { + ...json.devDependencies, + '@vitest/browser-playwright': '^4', + 'vitest': '^4', + 'playwright': '^1', + }; + }); + + await installWorkspacePackages(); + + await ng('generate', 'component', 'my-comp'); + + // Create vitest-base.config.mts + await writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + import { playwright } from '@vitest/browser-playwright'; + + export default defineConfig({ + test: { + browser: { + enabled: true, + provider: playwright({launchOptions: {executablePath: process.env['CHROME_BIN']}}), + instances: [ + { browser: 'chromium' }, + ], + headless: true, + }, + }, + }); + `, + ); + + // Create a spec file that asserts browser environment + await writeFile( + 'src/browser.spec.ts', + ` + describe('Browser Environment Check', () => { + it('should be running in Chromium', () => { + const ua = navigator.userAgent; + // Fail the test if it's not Chrome/Chromium + if (!ua.includes('Chrome') && !ua.includes('Chromium')) { + throw new Error('Expected to be running in Chrome/Chromium, but User Agent is: ' + ua); + } + }); + }); + `, + ); + + const { stdout } = await ng('test', '--no-watch', '--runner-config'); + + assert.match(stdout, /3 passed/, 'Expected 3 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-custom-config.ts b/tests/e2e/tests/vitest/browser-custom-config.ts new file mode 100644 index 000000000000..ab9092d038af --- /dev/null +++ b/tests/e2e/tests/vitest/browser-custom-config.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; + +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + }); + + await ng('generate', 'component', 'my-comp'); + + // Create vitest-base.config.mts + await writeFile( + 'vitest-base.config.mts', + ` + import { defineConfig } from 'vitest/config'; + import { playwright } from '@vitest/browser-playwright'; + + export default defineConfig({ + test: { + browser: { + enabled: true, + provider: playwright({launchOptions: {executablePath: process.env['CHROME_BIN']}}), + instances: [ + { browser: 'chromium' }, + ], + headless: true, + }, + }, + }); + `, + ); + + // Create a spec file that asserts browser environment + await writeFile( + 'src/browser.spec.ts', + ` + describe('Browser Environment Check', () => { + it('should be running in Chromium', () => { + const ua = navigator.userAgent; + // Fail the test if it's not Chrome/Chromium + if (!ua.includes('Chrome') && !ua.includes('Chromium')) { + throw new Error('Expected to be running in Chrome/Chromium, but User Agent is: ' + ua); + } + }); + }); + `, + ); + + const { stdout } = await ng('test', '--no-watch', '--runner-config'); + + assert.match(stdout, /3 passed/, 'Expected 3 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-no-globals.ts b/tests/e2e/tests/vitest/browser-no-globals.ts new file mode 100644 index 000000000000..3a4fcde4b96c --- /dev/null +++ b/tests/e2e/tests/vitest/browser-no-globals.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { writeFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; + +/** + * Allow `vitest` import in browser mode. + * @see https://github.com/angular/angular-cli/issues/31745 + */ +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + }); + + await writeFile( + 'src/app/app.spec.ts', + ` + import { test, expect } from 'vitest'; + + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { stdout } = await ng('test', '--browsers', 'ChromiumHeadless'); + + assert.match(stdout, /1 passed/, 'Expected 1 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-playwright.ts b/tests/e2e/tests/vitest/browser-playwright.ts new file mode 100644 index 000000000000..54d744e10208 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-playwright.ts @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; + +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + }); + await ng('generate', 'component', 'my-comp'); + + await writeFile( + 'src/setup1.ts', + ` + import { getTestBed } from '@angular/core/testing'; + + getTestBed().configureTestingModule({}); + `, + ); + + await updateJsonFile('tsconfig.spec.json', (json) => { + json.include = [...(json.include || []), 'src/setup1.ts']; + }); + + const { stdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'chromiumHeadless', + '--setup-files', + 'src/setup1.ts', + ); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-sourcemaps.ts b/tests/e2e/tests/vitest/browser-sourcemaps.ts new file mode 100644 index 000000000000..4bc025a7d2b9 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-sourcemaps.ts @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng, noSilentNg } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function (): Promise { + await applyVitestBuilder({ + playwright: true, + }); + + await ng('generate', 'component', 'my-comp'); + + // Add a failing test to verify source map support + await writeFile( + 'src/app/failing.spec.ts', + ` + describe('Failing Test', () => { + it('should fail', () => { + expect(true).toBe(false); + }); + }); + `, + ); + + try { + await noSilentNg('test', '--no-watch', '--browsers', 'chromiumHeadless'); + throw new Error('Expected "ng test" to fail.'); + } catch (error: any) { + const stdout = stripVTControlCharacters(error.stdout || error.message); + // We expect the failure from failing.spec.ts + assert.match(stdout, /1 failed/, 'Expected 1 test to fail.'); + // Check that the stack trace points to the correct file + assert.match( + stdout, + /\bsrc[\/\\]app[\/\\]failing\.spec\.ts:4:\d+/, + 'Expected stack trace to point to the source file.', + ); + } +} diff --git a/tests/e2e/tests/vitest/component.ts b/tests/e2e/tests/vitest/component.ts new file mode 100644 index 000000000000..421587892196 --- /dev/null +++ b/tests/e2e/tests/vitest/component.ts @@ -0,0 +1,12 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; + +export default async function (): Promise { + await applyVitestBuilder(); + await ng('generate', 'component', 'my-comp'); + + const { stdout } = await ng('test'); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/include.ts b/tests/e2e/tests/vitest/include.ts new file mode 100644 index 000000000000..4585194ef3c2 --- /dev/null +++ b/tests/e2e/tests/vitest/include.ts @@ -0,0 +1,14 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import path from 'node:path'; + +export default async function (): Promise { + await applyVitestBuilder(); + + const { stdout: stdout1 } = await ng('test', '--include', path.resolve('src/app/app.spec.ts')); + assert.match(stdout1, /1 passed/, 'Expected 1 test to pass with absolute include.'); + + const { stdout: stdout2 } = await ng('test', '--include', path.normalize('src/app/app.spec.ts')); + assert.match(stdout2, /1 passed/, 'Expected 1 test to pass with relative include.'); +} diff --git a/tests/e2e/tests/vitest/larger-project-coverage.ts b/tests/e2e/tests/vitest/larger-project-coverage.ts new file mode 100644 index 000000000000..d5fa94c0b82c --- /dev/null +++ b/tests/e2e/tests/vitest/larger-project-coverage.ts @@ -0,0 +1,108 @@ +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; +import { updateJsonFile } from '../../utils/project'; +import { readFile } from '../../utils/fs'; + +export default async function () { + await applyVitestBuilder({ + coverageV8: true, + playwright: true, + }); + + // Add coverage and threshold configuration to ensure coverage is calculated. + // Use the 'json' reporter to get a machine-readable output for assertions. + await updateJsonFile('angular.json', (json) => { + const project = Object.values(json['projects'])[0] as any; + const test = project['architect']['test']; + test.options = { + coverageReporters: ['json', 'text'], + coverageThresholds: { + // The generated component/service/pipe files are basic + // A threshold of 75 should be safe. + statements: 75, + }, + }; + }); + + const artifactCount = 100; + const initialTestCount = 1; + const generatedFiles = await generateArtifactsInBatches(artifactCount); + + const totalTests = initialTestCount + artifactCount; + const expectedMessage = new RegExp(`${totalTests} passed`); + const coverageJsonPath = 'coverage/test-project/coverage-final.json'; + + // Run tests in default (JSDOM) mode with coverage + const { stdout: jsdomStdout } = await ng('test', '--no-watch', '--coverage'); + assert.match(jsdomStdout, expectedMessage, `Expected ${totalTests} tests to pass in JSDOM mode.`); + + // Assert that every generated file is in the coverage report by reading the JSON output. + const jsdomSummary = JSON.parse(await readFile(coverageJsonPath)); + const jsdomSummaryKeys = Object.keys(jsdomSummary); + for (const file of generatedFiles) { + const found = jsdomSummaryKeys.some((key) => key.endsWith(file)); + assert.ok(found, `Expected ${file} to be in the JSDOM coverage report.`); + } + + // Run tests in browser mode with coverage + const { stdout: browserStdout } = await ng( + 'test', + '--no-watch', + '--coverage', + '--browsers', + 'ChromiumHeadless', + ); + assert.match( + browserStdout, + expectedMessage, + `Expected ${totalTests} tests to pass in browser mode.`, + ); + + // Assert that every generated file is in the coverage report for browser mode. + const browserSummary = JSON.parse(await readFile(coverageJsonPath)); + const browserSummaryKeys = Object.keys(browserSummary); + for (const file of generatedFiles) { + const found = browserSummaryKeys.some((key) => key.endsWith(file)); + assert.ok(found, `Expected ${file} to be in the browser coverage report.`); + } +} + +async function generateArtifactsInBatches(artifactCount: number): Promise { + const BATCH_SIZE = 5; + const generatedFiles: string[] = []; + let commands: Promise[] = []; + + for (let i = 0; i < artifactCount; i++) { + const type = i % 3; + const name = `test-artifact-${i}`; + + let generateType: string; + let fileSuffix: string; + + switch (type) { + case 0: + generateType = 'component'; + fileSuffix = '.ts'; + break; + case 1: + generateType = 'service'; + fileSuffix = '.ts'; + break; + default: + generateType = 'pipe'; + fileSuffix = '-pipe.ts'; + break; + } + + commands.push(ng('generate', generateType, name, '--skip-tests=false')); + generatedFiles.push(`${name}${fileSuffix}`); + + if (commands.length === BATCH_SIZE || i === artifactCount - 1) { + await Promise.all(commands); + commands = []; + } + } + + return generatedFiles; +} diff --git a/tests/e2e/tests/vitest/larger-project.ts b/tests/e2e/tests/vitest/larger-project.ts new file mode 100644 index 000000000000..9b9db25bb067 --- /dev/null +++ b/tests/e2e/tests/vitest/larger-project.ts @@ -0,0 +1,147 @@ +import assert from 'node:assert'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; + +export default async function () { + await applyVitestBuilder({ + playwright: true, + }); + + const artifactCount = 500; + // A new project starts with 1 test file (app.spec.ts) + // Each generated artifact will add one more test file. + const initialTestCount = 1; + + await generateArtifactsInBatches(artifactCount); + + const totalTests = initialTestCount + artifactCount; + const expectedMessage = new RegExp(`${totalTests} passed`); + + // Run tests in default (JSDOM) mode + const { stdout: jsdomStdout } = await ng('test', '--no-watch'); + assert.match(jsdomStdout, expectedMessage, `Expected ${totalTests} tests to pass in JSDOM mode.`); + + // Run tests in browser mode + const { stdout: browserStdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'ChromiumHeadless', + ); + assert.match( + browserStdout, + expectedMessage, + `Expected ${totalTests} tests to pass in browser mode.`, + ); +} + +async function generateArtifactsInBatches(artifactCount: number): Promise { + const files: { [path: string]: string } = {}; + + for (let i = 0; i < artifactCount; i++) { + const type = i % 3; + const name = `test-artifact-${i}`; + + switch (type) { + case 0: + files[`src/app/${name}/${name}.ts`] = ` +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-${name}', + template: '', +}) +export class TestArtifact${i}Component {} +`; + files[`src/app/${name}/${name}.spec.ts`] = ` +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { TestArtifact${i}Component } from './${name}'; + +describe('TestArtifact${i}Component', () => { + let component: TestArtifact${i}Component; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [TestArtifact${i}Component], + }).compileComponents(); + + fixture = TestBed.createComponent(TestArtifact${i}Component); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); +`; + break; + case 1: + files[`src/app/${name}.ts`] = ` +import { Injectable } from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class TestArtifact${i}Service {} +`; + files[`src/app/${name}.spec.ts`] = ` +import { TestBed } from '@angular/core/testing'; +import { TestArtifact${i}Service } from './${name}'; + +describe('TestArtifact${i}Service', () => { + let service: TestArtifact${i}Service; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(TestArtifact${i}Service); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); +`; + break; + default: + files[`src/app/${name}-pipe.ts`] = ` +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ + name: 'testArtifact${i}', +}) +export class TestArtifact${i}Pipe implements PipeTransform { + transform(value: unknown): unknown { + return null; + } +} +`; + files[`src/app/${name}-pipe.spec.ts`] = ` +import { TestArtifact${i}Pipe } from './${name}-pipe'; + +describe('TestArtifact${i}Pipe', () => { + it('create an instance', () => { + const pipe = new TestArtifact${i}Pipe(); + expect(pipe).toBeTruthy(); + }); +}); +`; + break; + } + } + + const entries = Object.entries(files); + const CONCURRENCY_LIMIT = 100; + for (let i = 0; i < entries.length; i += CONCURRENCY_LIMIT) { + const chunk = entries.slice(i, i + CONCURRENCY_LIMIT); + await Promise.all( + chunk.map(async ([filePath, content]) => { + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, content.trim()); + }), + ); + } +} diff --git a/tests/e2e/tests/vitest/library.ts b/tests/e2e/tests/vitest/library.ts new file mode 100644 index 000000000000..5d515681272b --- /dev/null +++ b/tests/e2e/tests/vitest/library.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert/strict'; +import { updateJsonFile } from '../../utils/project'; +import { ng } from '../../utils/process'; +import { appendToFile, createDir, writeFile } from '../../utils/fs'; + +export default async function (): Promise { + // Generate a library + await ng('generate', 'library', 'my-lib', '--test-runner', 'vitest'); + + // Setup Style Include Paths test + // 1. Create a shared SCSS file + await createDir('projects/my-lib/src/styles'); + await writeFile('projects/my-lib/src/styles/_vars.scss', '$primary-color: red;'); + + // 2. Update angular.json to include the styles directory + await updateJsonFile('angular.json', (json) => { + const buildOptions = (json['projects']['my-lib']['architect']['build']['options'] ??= {}); + buildOptions.stylePreprocessorOptions = { + includePaths: ['projects/my-lib/src/styles'], + }; + }); + + // 3. Update the component to use SCSS and import the shared file + // Rename CSS to SCSS + await ng('generate', 'component', 'styled-comp', '--project=my-lib', '--style=scss'); + + await appendToFile( + 'projects/my-lib/src/lib/styled-comp/styled-comp.scss', + ` + @use 'vars'; + p { color: vars.$primary-color; } + `, + ); + + // 4. Generate a secondary entry point and verify its tests are also executed + await ng('generate', 'entry-point', 'secondary', '--project=my-lib'); + + // Run the library tests + const { stdout } = await ng('test', 'my-lib'); + + // Expect tests to pass (my-lib, styled-comp, and secondary) + assert.match(stdout, /3 passed/, 'Expected 3 library tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/node-sourcemaps.ts b/tests/e2e/tests/vitest/node-sourcemaps.ts new file mode 100644 index 000000000000..8e317b2b72cf --- /dev/null +++ b/tests/e2e/tests/vitest/node-sourcemaps.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng, noSilentNg } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function (): Promise { + await applyVitestBuilder(); + await ng('generate', 'component', 'my-comp'); + + // Add a failing test to verify source map support + await writeFile( + 'src/app/failing.spec.ts', + ` + describe('Failing Test', () => { + it('should fail', () => { + expect(true).toBe(false); + }); + }); + `, + ); + + try { + await noSilentNg('test', '--no-watch'); + throw new Error('Expected "ng test" to fail.'); + } catch (error: any) { + const stdout = stripVTControlCharacters(error.stdout || error.message); + // We expect the failure from failing.spec.ts + assert.match(stdout, /1 failed/, 'Expected 1 test to fail.'); + // Check that the stack trace points to the correct file + assert.match( + stdout, + /\bsrc[\/\\]app[\/\\]failing\.spec\.ts:4:\d+/, + 'Expected stack trace to point to the source file.', + ); + } +} diff --git a/tests/e2e/tests/vitest/runner-config-path.ts b/tests/e2e/tests/vitest/runner-config-path.ts new file mode 100644 index 000000000000..456469b2d6a4 --- /dev/null +++ b/tests/e2e/tests/vitest/runner-config-path.ts @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; + +export default async function (): Promise { + await applyVitestBuilder(); + + // Create a custom Vitest configuration file. + const customConfigPath = 'vitest.custom.mjs'; + await writeMultipleFiles({ + [customConfigPath]: ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + // A unique option to confirm this file is being used. + passWithNoTests: true, + }, + }); + `, + }); + + const absoluteConfigPath = path.resolve(customConfigPath); + const { stdout } = await ng('test', `--runner-config=${absoluteConfigPath}`); + + // Assert that the CLI logs the use of the specified configuration file. + assert.match( + stdout, + /vitest\.custom\.mjs/, + 'Expected a message confirming the use of the custom config file.', + ); +} diff --git a/tests/e2e/tests/vitest/snapshot.ts b/tests/e2e/tests/vitest/snapshot.ts new file mode 100644 index 000000000000..0334ad4906ce --- /dev/null +++ b/tests/e2e/tests/vitest/snapshot.ts @@ -0,0 +1,150 @@ +import { execWithEnv, ng } from '../../utils/process'; +import { replaceInFile, readFile, writeFile } from '../../utils/fs'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert/strict'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function () { + // Set up the test project to use the vitest runner + await applyVitestBuilder(); + + // Add snapshot assertions to the test file + await replaceInFile( + 'src/app/app.spec.ts', + `describe('App', () => {`, + ` +describe('App', () => { + it('should match file snapshot', () => { + const fixture = TestBed.createComponent(App); + const app = fixture.componentInstance; + expect((app as any).title()).toMatchSnapshot(); + }); + + it('should match inline snapshot', () => { + const fixture = TestBed.createComponent(App); + const app = fixture.componentInstance; + expect((app as any).title()).toMatchInlineSnapshot(); + }); +`, + ); + + // Synchronize line endings for Vitest which currently may miscalculate line counts + // with mixed file line endings. + let content = await readFile('src/app/app.spec.ts'); + content = content.replace(/\r\n/g, '\n'); + content = content.replace(/\r/g, '\n'); + await writeFile('src/app/app.spec.ts', content); + + // First run: create snapshots + const { stdout: firstRunStdout } = await ng('test'); + assert.match( + stripVTControlCharacters(firstRunStdout), + /Snapshots\s+2 written/, + 'Snapshots were not written on the first run.', + ); + + const specContent = await readFile('src/app/app.spec.ts'); + assert.match( + specContent, + /toMatchInlineSnapshot\(`"test-project"`\)/, + 'Inline snapshot was not written to the spec file.', + ); + + const snapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap'); + assert.match( + snapshotContent, + /exports\[`App > should match file snapshot 1`\] = `"test-project"`;/, + 'File snapshot was not written to disk.', + ); + + // Second run: tests should pass with existing snapshots + await ng('test'); + + // Modify component to break snapshots. The new title keeps the original value as a prefix so + // the default `should render title` spec, which uses a substring assertion, continues to pass. + // The snapshots compare the exact value and therefore still fail. + await replaceInFile('src/app/app.ts', 'test-project', 'test-project (updated)'); + + // Third run: tests should fail with snapshot mismatch + await assert.rejects( + () => ng('test'), + (err: any) => { + assert.match( + stripVTControlCharacters(err.toString()), + /Snapshots\s+2 failed/, + 'Expected snapshot mismatch error, but a different error occurred.', + ); + return true; + }, + 'Snapshot mismatch did not cause the test to fail.', + ); + + // Fourth run: update the snapshots to match the new output. + // Vitest reads the `UPDATE_SNAPSHOT` environment variable directly. The builder does not + // currently forward Vitest's `--update` flag, so the variable is the way to request an update + // without a Vitest configuration file. + const { stdout: updateRunStdout } = await execWithEnv('ng', ['test'], { + ...process.env, + UPDATE_SNAPSHOT: 'all', + }); + assert.match( + stripVTControlCharacters(updateRunStdout), + /Snapshots\s+2 updated/, + 'Snapshots were not updated when UPDATE_SNAPSHOT=all was set.', + ); + + const updatedSpecContent = await readFile('src/app/app.spec.ts'); + assert.match( + updatedSpecContent, + /toMatchInlineSnapshot\(`"test-project \(updated\)"`\)/, + 'Inline snapshot was not updated in the spec file.', + ); + assert.doesNotMatch( + updatedSpecContent, + /toMatchInlineSnapshot\(`"test-project"`\)/, + 'Stale inline snapshot is still present in the spec file.', + ); + + const updatedSnapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap'); + assert.match( + updatedSnapshotContent, + /exports\[`App > should match file snapshot 1`\] = `"test-project \(updated\)"`;/, + 'File snapshot was not updated on disk.', + ); + assert.doesNotMatch( + updatedSnapshotContent, + /"test-project"/, + 'Stale file snapshot is still present on disk.', + ); + + // Fifth run: tests should pass with the updated snapshots and no snapshot should be rewritten + const { stdout: finalRunStdout } = await ng('test'); + assert.doesNotMatch( + stripVTControlCharacters(finalRunStdout), + /Snapshots\s+\d+ (written|updated|failed|obsolete)/, + 'Snapshots were unexpectedly modified after being updated.', + ); + + // Sixth run: update snapshots via `-- --update` passthrough + await replaceInFile('src/app/app.ts', 'test-project (updated)', 'test-project (passthrough)'); + const { stdout: passthroughUpdateStdout } = await ng('test', '--', '--update'); + assert.match( + stripVTControlCharacters(passthroughUpdateStdout), + /Snapshots\s+2 updated/, + 'Snapshots were not updated when `-- --update` was passed.', + ); + + const passthroughSpecContent = await readFile('src/app/app.spec.ts'); + assert.match( + passthroughSpecContent, + /toMatchInlineSnapshot\(`"test-project \(passthrough\)"`\)/, + 'Inline snapshot was not updated via `-- --update`.', + ); + + const passthroughSnapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap'); + assert.match( + passthroughSnapshotContent, + /exports\[`App > should match file snapshot 1`\] = `"test-project \(passthrough\)"`;/, + 'File snapshot was not updated via `-- --update`.', + ); +} diff --git a/tests/e2e/tests/vitest/tslib-resolution.ts b/tests/e2e/tests/vitest/tslib-resolution.ts new file mode 100644 index 000000000000..091f5105ba7f --- /dev/null +++ b/tests/e2e/tests/vitest/tslib-resolution.ts @@ -0,0 +1,70 @@ +import { writeFile } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; + +export default async function () { + await applyVitestBuilder({ + playwright: true, + }); + + // Add a custom decorator to trigger tslib usage + await writeFile( + 'src/app/custom-decorator.ts', + ` + export function MyDecorator() { + return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { + // do nothing + }; + } + `, + ); + + // Add a service that uses the decorator + await writeFile( + 'src/app/test.service.ts', + ` + import { Injectable } from '@angular/core'; + import { MyDecorator } from './custom-decorator'; + + @Injectable({ + providedIn: 'root' + }) + export class TestService { + @MyDecorator() + myMethod() { + return true; + } + } + `, + ); + + // Add a test for the service + await writeFile( + 'src/app/test.service.spec.ts', + ` + import { TestBed } from '@angular/core/testing'; + import { TestService } from './test.service'; + + describe('TestService', () => { + let service: TestService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(TestService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('myMethod should return true', () => { + expect(service.myMethod()).toBe(true); + }); + }); + `, + ); + + const { stdout } = await ng('test', '--no-watch', '--browsers', 'chromiumHeadless'); + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/unix-browser-webdriverio.ts b/tests/e2e/tests/vitest/unix-browser-webdriverio.ts new file mode 100644 index 000000000000..231f5fca4041 --- /dev/null +++ b/tests/e2e/tests/vitest/unix-browser-webdriverio.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { writeFile } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; + +export default async function (): Promise { + await applyVitestBuilder({ + webdriver: true, + }); + + await ng('generate', 'component', 'my-comp'); + + await writeFile( + 'src/setup1.ts', + ` + import { getTestBed } from '@angular/core/testing'; + + getTestBed().configureTestingModule({}); + `, + ); + + await updateJsonFile('tsconfig.spec.json', (json) => { + json.include = [...(json.include || []), 'src/setup1.ts']; + }); + + const { stdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'chromeHeadless', + '--setup-files', + 'src/setup1.ts', + ); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/windows-subst-drive.ts b/tests/e2e/tests/vitest/windows-subst-drive.ts new file mode 100644 index 000000000000..3106ff846b21 --- /dev/null +++ b/tests/e2e/tests/vitest/windows-subst-drive.ts @@ -0,0 +1,61 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { ng, silentExec } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function (): Promise { + // This test uses `subst` to map the project directory to a virtual drive letter + // to simulate running tests from a non-C drive on Windows. + if (process.platform !== 'win32') { + return; + } + + await applyVitestBuilder(); + + const originalCwd = process.cwd(); + const driveLetter = 'X:'; // Pick a drive letter that is unlikely to be in use. + + try { + // 1. Map the parent directory of the project to the virtual drive. + // This avoids running the project from the root of the drive (X:\), which can cause + // issues with workspace detection. + const projectParentDir = path.dirname(originalCwd); + const projectName = path.basename(originalCwd); + + await silentExec('subst', driveLetter, projectParentDir); + + // 2. Change the current process's working directory to the project folder on the virtual drive. + const newCwd = path.join(driveLetter + '\\', projectName); + process.chdir(newCwd); + + // Verify that the file system mapping is working as expected. + assert(fs.existsSync('angular.json'), 'angular.json should exist on the subst drive'); + + // 3. Run `ng test`. + const { stdout } = await ng('test', '--watch=false'); + const output = stripVTControlCharacters(stdout); + + // 4. Verify that Vitest found the test file and identified the tests within it. + assert.match( + output, + /src\/app\/app\.spec\.ts \(2 tests/, + 'Expected tests to be discovered and loaded, even if execution fails due to subst aliasing.', + ); + } finally { + // 5. Teardown: Restore CWD and remove the virtual drive mapping. + try { + process.chdir(originalCwd); + } catch (e) { + console.error('Failed to restore CWD:', e); + } + + try { + await silentExec('subst', driveLetter, '/d'); + } catch (e) { + // Ignore errors if the drive wasn't mounted or if unmount fails (best effort) + console.error(`Failed to unmount ${driveLetter}:`, e); + } + } +} diff --git a/tests/e2e/utils/BUILD.bazel b/tests/e2e/utils/BUILD.bazel new file mode 100644 index 000000000000..dbbda05702cd --- /dev/null +++ b/tests/e2e/utils/BUILD.bazel @@ -0,0 +1,24 @@ +load("//tools:defaults.bzl", "ts_project") + +package(default_visibility = ["//visibility:public"]) + +ts_project( + name = "utils", + testonly = True, + srcs = glob(["**/*.ts"]), + data = [ + "//tests/e2e/ng-snapshot", + ], + deps = [ + "//:node_modules/@types/jasmine", + "//:node_modules/@types/node", + "//:node_modules/@types/semver", + "//:node_modules/fast-glob", + "//:node_modules/puppeteer", + "//:node_modules/semver", + "//:node_modules/verdaccio", + "//:node_modules/verdaccio-auth-memory", + "//tests:node_modules/@types/tar-stream", + "//tests:node_modules/tar-stream", + ], +) diff --git a/tests/e2e/utils/assets.ts b/tests/e2e/utils/assets.ts new file mode 100644 index 000000000000..153fdaccc6de --- /dev/null +++ b/tests/e2e/utils/assets.ts @@ -0,0 +1,69 @@ +import { join } from 'node:path'; +import { chmod } from 'node:fs/promises'; +import glob from 'fast-glob'; +import { getGlobalVariable } from './env'; +import { resolve } from 'node:path'; +import { copyFile } from './fs'; +import { installWorkspacePackages, setRegistry } from './packages'; +import { getTestProjectDir, useBuiltPackagesVersions } from './project'; + +export function assetDir(assetName: string) { + return join(__dirname, '../e2e/assets', assetName); +} + +export function copyProjectAsset(assetName: string, to?: string) { + const tempRoot = join(getGlobalVariable('projects-root'), 'test-project'); + const sourcePath = assetDir(assetName); + const targetPath = join(tempRoot, to || assetName); + + return copyFile(sourcePath, targetPath); +} + +export function copyAssets(assetName: string, to?: string) { + const seed = +Date.now(); + const tempRoot = join(getTestAssetsDir(), assetName + '-' + seed); + const root = assetDir(assetName); + + return Promise.resolve() + .then(() => { + const allFiles = glob.sync('**/*', { dot: true, cwd: root }); + + return allFiles.reduce((promise, filePath) => { + const toPath = + to !== undefined ? resolve(getTestProjectDir(), to, filePath) : join(tempRoot, filePath); + + return promise + .then(() => copyFile(join(root, filePath), toPath)) + .then(() => chmod(toPath, 0o777)); + }, Promise.resolve()); + }) + .then(() => tempRoot); +} + +/** + * @returns a method that once called will restore the environment + * to use the local NPM registry. + * */ +export async function createProjectFromAsset( + assetName: string, + useNpmPackages = false, + skipInstall = false, +): Promise<() => Promise> { + const dir = await copyAssets(assetName); + process.chdir(dir); + + await setRegistry(!useNpmPackages /** useTestRegistry */); + + if (!useNpmPackages) { + await useBuiltPackagesVersions(); + } + if (!skipInstall) { + await installWorkspacePackages(); + } + + return () => setRegistry(true /** useTestRegistry */); +} + +export function getTestAssetsDir(): string { + return join(getGlobalVariable('projects-root'), 'assets'); +} diff --git a/tests/e2e/utils/env.ts b/tests/e2e/utils/env.ts new file mode 100644 index 000000000000..d2f0feece0a7 --- /dev/null +++ b/tests/e2e/utils/env.ts @@ -0,0 +1,26 @@ +const ENV_PREFIX = 'LEGACY_CLI__'; + +export function setGlobalVariable(name: string, value: any) { + if (value === undefined) { + delete process.env[ENV_PREFIX + name]; + } else { + process.env[ENV_PREFIX + name] = JSON.stringify(value); + } +} + +export function getGlobalVariable(name: string): T { + const value = process.env[ENV_PREFIX + name]; + if (value === undefined) { + throw new Error(`Trying to access variable "${name}" but it's not defined.`); + } + return JSON.parse(value) as T; +} + +export function getGlobalVariablesEnv(): NodeJS.ProcessEnv { + return Object.keys(process.env) + .filter((v) => v.startsWith(ENV_PREFIX)) + .reduce((vars, n) => { + vars[n] = process.env[n]; + return vars; + }, {}); +} diff --git a/tests/e2e/utils/fs.ts b/tests/e2e/utils/fs.ts new file mode 100644 index 000000000000..2ebf7af9d28a --- /dev/null +++ b/tests/e2e/utils/fs.ts @@ -0,0 +1,134 @@ +import { promises as fs, constants } from 'node:fs'; +import { dirname, join } from 'node:path'; + +export function readFile(fileName: string): Promise { + return fs.readFile(fileName, 'utf-8'); +} + +export function writeFile(fileName: string, content: string, options?: any): Promise { + return fs.writeFile(fileName, content, options); +} + +export function deleteFile(path: string): Promise { + return fs.unlink(path); +} + +export function rimraf(path: string): Promise { + return fs.rm(path, { + force: true, + recursive: true, + maxRetries: 3, + }); +} + +export function moveFile(from: string, to: string): Promise { + return fs.rename(from, to); +} + +export function symlinkFile(from: string, to: string, type?: string): Promise { + return fs.symlink(from, to, type); +} + +export function createDir(path: string): Promise { + return fs.mkdir(path, { recursive: true }); +} + +export async function copyFile(from: string, to: string): Promise { + await createDir(dirname(to)); + + return fs.copyFile(from, to, constants.COPYFILE_FICLONE); +} + +export async function moveDirectory(from: string, to: string): Promise { + await rimraf(to); + await createDir(to); + + for (const entry of await fs.readdir(from)) { + const fromEntry = join(from, entry); + const toEntry = join(to, entry); + if ((await fs.stat(fromEntry)).isFile()) { + await copyFile(fromEntry, toEntry); + } else { + await moveDirectory(fromEntry, toEntry); + } + } +} + +export function writeMultipleFiles(fs: { [path: string]: string }) { + return Promise.all(Object.keys(fs).map((fileName) => writeFile(fileName, fs[fileName]))); +} + +export function replaceInFile(filePath: string, match: RegExp | string, replacement: string) { + return readFile(filePath).then((content: string) => + writeFile(filePath, content.replace(match, replacement)), + ); +} + +export function appendToFile(filePath: string, text: string, options?: any) { + return readFile(filePath).then((content: string) => + writeFile(filePath, content.concat(text), options), + ); +} + +export function prependToFile(filePath: string, text: string, options?: any) { + return readFile(filePath).then((content: string) => + writeFile(filePath, text.concat(content), options), + ); +} + +export async function expectFileMatchToExist(dir: string, regex: RegExp): Promise { + const files = await fs.readdir(dir); + const fileName = files.find((name) => regex.test(name)); + + if (!fileName) { + throw new Error(`File ${regex} was expected to exist but not found...`); + } + + return fileName; +} + +export async function expectFileNotToExist(fileName: string): Promise { + try { + await fs.access(fileName, constants.F_OK); + } catch { + return; + } + + throw new Error(`File ${fileName} was expected not to exist but found...`); +} + +export async function expectFileToExist(fileName: string): Promise { + try { + await fs.access(fileName, constants.F_OK); + } catch { + throw new Error(`File ${fileName} was expected to exist but not found...`); + } +} + +export async function expectFileToMatch(fileName: string, regEx: RegExp | string): Promise { + const content = await readFile(fileName); + + const found = typeof regEx === 'string' ? content.includes(regEx) : content.match(regEx); + + if (!found) { + throw new Error( + `File "${fileName}" did not contain "${regEx}"...\nContent:\n${content}\n------`, + ); + } +} + +export async function getFileSize(fileName: string) { + const stats = await fs.stat(fileName); + + return stats.size; +} + +export async function expectFileSizeToBeUnder(fileName: string, sizeInBytes: number) { + const fileSize = await getFileSize(fileName); + + if (fileSize > sizeInBytes) { + throw new Error( + `File "${fileName}" exceeded file size of "${sizeInBytes}". Size is ${fileSize}.`, + ); + } +} diff --git a/tests/e2e/utils/git.ts b/tests/e2e/utils/git.ts new file mode 100644 index 000000000000..39bb47ce7d52 --- /dev/null +++ b/tests/e2e/utils/git.ts @@ -0,0 +1,21 @@ +import { git, silentGit } from './process'; + +export async function gitClean(): Promise { + await silentGit('clean', '-df'); + await silentGit('reset', '--hard'); +} + +export async function expectGitToBeClean(): Promise { + const { stdout } = await silentGit('status', '--porcelain'); + if (stdout != '') { + throw new Error('Git repo is not clean...\n' + stdout); + } +} + +export async function gitCommit(message: string): Promise { + await git('add', '-A'); + const { stdout } = await silentGit('status', '--porcelain'); + if (stdout != '') { + await git('commit', '-am', message); + } +} diff --git a/tests/e2e/utils/network.ts b/tests/e2e/utils/network.ts new file mode 100644 index 000000000000..48602f0000d2 --- /dev/null +++ b/tests/e2e/utils/network.ts @@ -0,0 +1,30 @@ +import { createServer } from 'node:net'; + +/** + * Finds an available network port on the loopback interface (127.0.0.1). + * This is useful for tests that need to bind to a free port to avoid conflicts. + * Explicitly binds to IPv4 localhost to avoid firewall prompts, IPv6 binding issues, and ensure consistency. + * + * @returns A promise that resolves with an available port number. + */ +export function findFreePort(): Promise { + return new Promise((resolve, reject) => { + const srv = createServer(); + srv.once('listening', () => { + const address = srv.address(); + if (!address || typeof address === 'string') { + // Should not happen with TCP, but good for type safety + srv.close(() => reject(new Error('Failed to get server address'))); + return; + } + const port = address.port; + srv.close((e) => (e ? reject(e) : resolve(port))); + }); + + // If an error happens (e.g. during bind), the server is not listening, + // so we should not call close(). + srv.once('error', (e) => reject(e)); + // Explicitly listen on IPv4 localhost to avoid firewall prompts, IPv6 binding issues, and ensure consistency. + srv.listen(0, '127.0.0.1'); + }); +} diff --git a/tests/e2e/utils/packages.ts b/tests/e2e/utils/packages.ts new file mode 100644 index 000000000000..407f0f1d8573 --- /dev/null +++ b/tests/e2e/utils/packages.ts @@ -0,0 +1,84 @@ +import { getGlobalVariable } from './env'; +import { type ProcessOutput, silentBun, silentNpm, silentPnpm, silentYarn } from './process'; + +export interface PkgInfo { + readonly name: string; + readonly version: string; + readonly path: string; +} + +export function getActivePackageManager(): 'npm' | 'yarn' | 'bun' | 'pnpm' { + return getGlobalVariable('package-manager'); +} + +export async function installWorkspacePackages(options?: { force?: boolean }): Promise { + switch (getActivePackageManager()) { + case 'npm': + const npmArgs = ['install']; + if (options?.force) { + npmArgs.push('--force'); + } + await silentNpm(...npmArgs); + break; + case 'yarn': + await silentYarn('install'); + break; + case 'pnpm': + await silentPnpm('install'); + break; + case 'bun': + await silentBun('install'); + break; + } +} + +export function installPackage( + specifier: string | string[], + registry?: string, +): Promise { + const registryOption = registry ? [`--registry=${registry}`] : []; + const specifiers = Array.isArray(specifier) ? specifier : [specifier]; + + switch (getActivePackageManager()) { + case 'npm': + return silentNpm('install', ...specifiers, ...registryOption); + case 'yarn': + return silentYarn('add', ...specifiers, ...registryOption); + case 'bun': + return silentBun('add', ...specifiers, ...registryOption); + case 'pnpm': + return silentPnpm('add', ...specifiers, ...registryOption); + } +} + +export async function uninstallPackage(name: string): Promise { + try { + switch (getActivePackageManager()) { + case 'npm': + await silentNpm('uninstall', name); + break; + case 'yarn': + await silentYarn('remove', name); + break; + case 'bun': + await silentBun('remove', name); + break; + case 'pnpm': + await silentPnpm('remove', name); + break; + } + } catch (e) { + // Yarn throws an error when trying to remove a package that is not installed. + console.error(e); + } +} + +export async function setRegistry(useTestRegistry: boolean): Promise { + const url = useTestRegistry + ? getGlobalVariable('package-registry') + : 'https://registry.npmjs.org'; + + // Ensure local test registry is used when outside a project + // Yarn supports both `NPM_CONFIG_REGISTRY` and `YARN_REGISTRY`. + process.env['NPM_CONFIG_REGISTRY'] = url; +} diff --git a/tests/e2e/utils/process.ts b/tests/e2e/utils/process.ts new file mode 100644 index 000000000000..021536af1688 --- /dev/null +++ b/tests/e2e/utils/process.ts @@ -0,0 +1,493 @@ +import { spawn, SpawnOptions } from 'node:child_process'; +import * as child_process from 'node:child_process'; +import { getGlobalVariable, getGlobalVariablesEnv } from './env'; +import { delimiter, join, resolve } from 'node:path'; +import { stripVTControlCharacters, styleText } from 'node:util'; +import { assertIsError } from './utils'; + +interface ExecOptions { + silent?: boolean; + waitForMatch?: RegExp; + env?: NodeJS.ProcessEnv; + stdin?: string; + cwd?: string; +} + +/** + * While `NPM_CONFIG_` and `YARN_` are case insensitive we filter based on case. + * This is because when invoking a command using `yarn` it will add a bunch of these variables in lower case. + * This causes problems when we try to update the variables during the test setup. + */ +const NPM_CONFIG_RE = /^(NPM_CONFIG_|YARN_|NO_UPDATE_NOTIFIER)/; + +let _processes: child_process.ChildProcess[] = []; + +export type ProcessOutput = { + stdout: string; + stderr: string; +}; + +function _exec(options: ExecOptions, cmd: string, args: string[]): Promise { + const cwd = options.cwd ?? process.cwd(); + const env = options.env ?? process.env; + + console.log( + `==========================================================================================`, + ); + + // Ensure the custom npm and yarn global bin is on the PATH + // https://docs.npmjs.com/cli/v8/configuring-npm/folders#executables + const paths = [ + join(getGlobalVariable('yarn-global'), 'bin'), + join(getGlobalVariable('npm-global'), process.platform.startsWith('win') ? '' : 'bin'), + env.PATH || process.env['PATH'], + ].join(delimiter); + + args = args.filter((x) => x !== undefined); + const flags = [ + options.silent && 'silent', + options.waitForMatch && `matching(${options.waitForMatch})`, + ] + .filter((x) => !!x) // Remove false and undefined. + .join(', ') + .replace(/^(.+)$/, ' [$1]'); // Proper formatting. + + console.log( + styleText(['blue'], `Running \`${cmd} ${args.map((x) => `"${x}"`).join(' ')}\`${flags}...`), + ); + console.log(styleText(['blue'], `CWD: ${cwd}`)); + + const spawnOptions: SpawnOptions = { + cwd, + env: { ...env, PATH: paths }, + }; + + if (process.platform.startsWith('win')) { + args.unshift('/c', cmd); + cmd = 'cmd.exe'; + spawnOptions['stdio'] = 'pipe'; + } + + const childProcess = child_process.spawn(cmd, args, spawnOptions); + + _processes.push(childProcess); + + // Create the error here so the stack shows who called this function. + const error = new Error(); + + const processPromise = new Promise((resolve, reject) => { + let stdout = ''; + let stderr = ''; + let matched = false; + + // Return log info about the current process status + function envDump() { + return `STDOUT:\n${stdout}\n\nSTDERR:\n${stderr}`; + } + + childProcess.stdout!.on('data', (data: Buffer) => { + stdout += data.toString('utf-8'); + + if (options.waitForMatch && stdout.match(options.waitForMatch)) { + resolve({ stdout, stderr }); + matched = true; + } + + if (options.silent) { + return; + } + + data + .toString('utf-8') + .split(/[\n\r]+/) + .filter((line) => line !== '') + .forEach((line) => console.log(' ' + line)); + }); + + childProcess.stderr!.on('data', (data: Buffer) => { + stderr += data.toString('utf-8'); + + if (options.waitForMatch && stderr.match(options.waitForMatch)) { + resolve({ stdout, stderr }); + matched = true; + } + + if (options.silent) { + return; + } + + data + .toString('utf-8') + .split(/[\n\r]+/) + .filter((line) => line !== '') + .forEach((line) => console.error(styleText(['yellow'], ' ' + line))); + }); + + childProcess.on('close', (code) => { + _processes = _processes.filter((p) => p !== childProcess); + + if (options.waitForMatch && !matched) { + reject( + `Process output didn't match - "${cmd} ${args.join(' ')}": '${ + options.waitForMatch + }': ${code}...\n\n${envDump()}\n`, + ); + return; + } + + if (!code) { + resolve({ stdout, stderr }); + return; + } + + reject(`Process exit error - "${cmd} ${args.join(' ')}": ${code}...\n\n${envDump()}\n`); + }); + + childProcess.on('error', (err) => { + reject(`Process error - "${cmd} ${args.join(' ')}": ${err}...\n\n${envDump()}\n`); + }); + + // Provide input to stdin if given. + if (options.stdin) { + childProcess.stdin!.write(options.stdin); + childProcess.stdin!.end(); + } + }).catch((err) => { + error.message = err.toString(); + return Promise.reject(error); + }); + + if (!options.waitForMatch) { + return processPromise; + } + + let timeout: NodeJS.Timeout | undefined; + const timeoutPromise: Promise = new Promise((_resolve, reject) => { + // Wait for 60 seconds and timeout. + const duration = 60_000; + timeout = setTimeout(() => { + reject( + new Error(`Waiting for ${options.waitForMatch} timed out (timeout: ${duration}msec)...`), + ); + }, duration); + }); + + return Promise.race([timeoutPromise, processPromise]).finally( + () => timeout && clearTimeout(timeout), + ); +} + +export function extractNpmEnv() { + return Object.keys(process.env) + .filter((v) => NPM_CONFIG_RE.test(v)) + .reduce((vars, n) => { + vars[n] = process.env[n]; + return vars; + }, {}); +} + +export function extractCIAndInfraEnv(): NodeJS.ProcessEnv { + return Object.keys(process.env) + .filter( + (v) => + v.startsWith('SAUCE_') || + v === 'CI' || + v === 'CHROME_BIN' || + v === 'CHROME_PATH' || + v === 'CHROMEDRIVER_BIN' || + v.startsWith('JS_BINARY__'), + ) + .reduce((vars, n) => { + vars[n] = process.env[n]; + return vars; + }, {}); +} + +function extractNgEnv() { + return Object.keys(process.env) + .filter((v) => v.startsWith('NG_')) + .reduce((vars, n) => { + vars[n] = process.env[n]; + return vars; + }, {}); +} + +export async function waitForAnyProcessOutputToMatch( + match: RegExp, + timeout = 30000, +): Promise { + let timeoutId: ReturnType | null = null; + + // Race between _all_ processes, and the timeout. First one to resolve/reject wins. + const timeoutPromise: Promise = new Promise((_resolve, reject) => { + // Wait for 30 seconds and timeout. + timeoutId = setTimeout(() => { + reject(new Error(`Waiting for ${match} timed out (timeout: ${timeout}msec)...`)); + }, timeout); + }); + + const matchPromises: Promise[] = _processes.map( + (childProcess) => + new Promise((resolve) => { + let stdout = ''; + let stderr = ''; + + childProcess.stdout!.on('data', (data: Buffer) => { + stdout += data.toString(); + if (stripVTControlCharacters(stdout).match(match)) { + resolve({ stdout, stderr }); + } + }); + + childProcess.stderr!.on('data', (data: Buffer) => { + stderr += data.toString(); + if (stripVTControlCharacters(stderr).match(match)) { + resolve({ stdout, stderr }); + } + }); + }), + ); + + const matchingProcess = await Promise.race(matchPromises.concat([timeoutPromise])); + if (timeoutId !== null) { + clearTimeout(timeoutId); + } + return matchingProcess; +} + +/** + * Kills a process by PID + * @param pid The PID of the process to kill + * @param signal The signal to send to the process + */ +async function killProcess(pid: number, signal: NodeJS.Signals): Promise { + if (process.platform === 'win32') { + // /T kills child processes, /F forces it + await new Promise((resolve) => { + child_process.exec(`taskkill /pid ${pid} /T /F`, () => resolve()); + }); + } else { + // Use -pid to signal the entire process group + try { + process.kill(-pid, signal); + } catch (error) { + assertIsError(error); + if (error.code !== 'ESRCH') { + throw error; + } + } + } +} + +/** + * Kills all tracked processes + */ +export async function killAllProcesses(signal: NodeJS.Signals = 'SIGTERM'): Promise { + const processesToKill: Promise[] = []; + + while (_processes.length) { + const childProc = _processes.pop(); + if (!childProc || childProc.pid === undefined || childProc.killed) { + continue; + } + + processesToKill.push(killProcess(childProc.pid, signal)); + } + + await Promise.all(processesToKill); +} + +export function exec(cmd: string, ...args: string[]) { + return _exec({}, cmd, args); +} + +export function silentExec(cmd: string, ...args: string[]) { + return _exec({ silent: true }, cmd, args); +} + +export function execWithEnv(cmd: string, args: string[], env: NodeJS.ProcessEnv, stdin?: string) { + return _exec({ env, stdin }, cmd, args); +} + +export async function execAndCaptureError( + cmd: string, + args: string[], + env?: NodeJS.ProcessEnv, + stdin?: string, +): Promise { + try { + await _exec({ env, stdin }, cmd, args); + throw new Error('Tried to capture subprocess exception, but it completed successfully.'); + } catch (err) { + if (err instanceof Error) { + return err; + } + throw new Error('Subprocess exception was not an Error instance'); + } +} + +export async function execAndWaitForOutputToMatch( + cmd: string, + args: string[], + match: RegExp, + env?: NodeJS.ProcessEnv, +) { + if (cmd === 'ng' && args[0] === 'serve') { + // Accept matches up to 20 times after the initial match. + // Useful because the Webpack watcher can rebuild a few times due to files changes that + // happened just before the build (e.g. `git clean`). + // This seems to be due to host file system differences, see + // https://nodejs.org/docs/latest/api/fs.html#fs_caveats + const maxRetries = 20; + let lastResult = await _exec({ waitForMatch: match, env }, cmd, args); + + for (let i = 0; i < maxRetries; i++) { + try { + lastResult = await waitForAnyProcessOutputToMatch(match, 2500); + } catch { + // If we timeout (no new match found), we assume the process is stable. + break; + } + } + + return lastResult; + } else { + return _exec({ waitForMatch: match, env }, cmd, args); + } +} + +export function ng(...args: string[]) { + const argv = getGlobalVariable('argv'); + const maybeSilentNg = argv['nosilent'] ? noSilentNg : silentNg; + if (['build', 'serve', 'test', 'e2e', 'extract-i18n'].indexOf(args[0]) != -1) { + if (args[0] == 'e2e') { + // Wait 1 second before running any end-to-end test. + return new Promise((resolve) => setTimeout(resolve, 1000)).then(() => maybeSilentNg(...args)); + } + + return maybeSilentNg(...args); + } else { + return noSilentNg(...args); + } +} + +export function noSilentNg(...args: string[]) { + return _exec({}, 'ng', args); +} + +export function silentNg(...args: string[]) { + return _exec({ silent: true }, 'ng', args); +} + +export function silentNpm(...args: string[]): Promise; +export function silentNpm(args: string[], options?: { cwd?: string }): Promise; +export function silentNpm( + ...args: string[] | [args: string[], options?: { cwd?: string }] +): Promise { + if (Array.isArray(args[0])) { + const [params, options] = args; + return _exec( + { + silent: true, + cwd: (options as { cwd?: string } | undefined)?.cwd, + }, + 'npm', + params, + ); + } else { + return _exec({ silent: true }, 'npm', args as string[]); + } +} + +export function silentYarn(...args: string[]) { + return _exec({ silent: true }, 'yarn', args); +} + +export function silentPnpm(...args: string[]) { + return _exec({ silent: true }, 'pnpm', args); +} + +export function silentBun(...args: string[]) { + return _exec({ silent: true }, 'bun', args); +} + +export function globalNpm(args: string[], env?: NodeJS.ProcessEnv) { + if (!process.env.LEGACY_CLI_RUNNER) { + throw new Error( + 'The global npm cli should only be executed from the primary e2e runner process', + ); + } + + return _exec({ silent: true, env }, 'npm', args); +} + +export function node(...args: string[]) { + return _exec({}, process.execPath, args); +} + +export function git(...args: string[]) { + return _exec({}, process.env.GIT_BIN || 'git', args); +} + +export function silentGit(...args: string[]) { + return _exec({ silent: true }, process.env.GIT_BIN || 'git', args); +} + +/** + * Launch the given entry in an child process isolated to the test environment. + * + * The test environment includes the local NPM registry, isolated NPM globals, + * the PATH variable only referencing the local node_modules and local NPM + * registry (not the test runner or standard global node_modules). + */ +export async function launchTestProcess(entry: string, ...args: any[]): Promise { + const tempRoot: string = getGlobalVariable('tmp-root'); + + // Extract explicit environment variables for the test process. + const env: NodeJS.ProcessEnv = { + TEMP: tempRoot, + TMPDIR: tempRoot, + HOME: tempRoot, + + // Use BAZEL_TARGET as a metadata variable to show it is a + // process managed by bazel + BAZEL_TARGET: process.env.BAZEL_TARGET, + + ...extractNpmEnv(), + ...extractCIAndInfraEnv(), + ...extractNgEnv(), + ...getGlobalVariablesEnv(), + }; + + // Only include paths within the sandboxed test environment or external + // non angular-cli paths such as /usr/bin for generic commands. + env.PATH = process.env + .PATH!.split(delimiter) + .filter((p) => p.startsWith(tempRoot) || !p.includes('angular-cli')) + .join(delimiter); + + const testProcessArgs = [ + // Note: `__dirname` is the bundle directory here. + resolve(__dirname, 'e2e/utils/test_process.js'), + entry, + ...args, + ]; + + return new Promise((resolve, reject) => { + spawn(process.execPath, testProcessArgs, { + stdio: 'inherit', + env, + }) + .on('close', (code) => { + if (!code) { + resolve(); + return; + } + + reject(`Process error - "${testProcessArgs}`); + }) + .on('error', (err) => { + reject(`Process exit error - "${testProcessArgs}]\n\n${err}`); + }); + }); +} diff --git a/tests/e2e/utils/project.ts b/tests/e2e/utils/project.ts new file mode 100644 index 000000000000..0deb6ea48262 --- /dev/null +++ b/tests/e2e/utils/project.ts @@ -0,0 +1,250 @@ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { prerelease, SemVer } from 'semver'; +import { getGlobalVariable } from './env'; +import { readFile, replaceInFile, writeFile } from './fs'; +import { gitCommit } from './git'; +import { findFreePort } from './network'; +import { installWorkspacePackages, PkgInfo } from './packages'; +import { execAndWaitForOutputToMatch, git, ng } from './process'; +import { join } from 'node:path'; + +export function updateJsonFile(filePath: string, fn: (json: any) => any | void) { + return readFile(filePath).then((tsConfigJson) => { + // Remove single and multiline comments + const tsConfig = JSON.parse(tsConfigJson.replace(/\/\*\s(.|\n|\r)*\s\*\/|\/\/.*/g, '')) as any; + const result = fn(tsConfig) || tsConfig; + + return writeFile(filePath, JSON.stringify(result, null, 2)); + }); +} + +export function updateTsConfig(fn: (json: any) => any | void) { + return updateJsonFile('tsconfig.json', fn); +} + +export async function ngServe(...args: string[]) { + const port = await findFreePort(); + + const esbuild = getGlobalVariable('argv')['esbuild']; + const validBundleRegEx = esbuild ? /complete\./ : /Compiled successfully\./; + + await execAndWaitForOutputToMatch( + 'ng', + ['serve', '--port', String(port), ...args], + validBundleRegEx, + ); + + return port; +} + +export async function prepareProjectForE2e(name: string) { + const argv: Record = getGlobalVariable('argv'); + + await git('config', 'user.email', 'angular-core+e2e@google.com'); + await git('config', 'user.name', 'Angular CLI E2E'); + await git('config', 'commit.gpgSign', 'false'); + await git('config', 'core.longpaths', 'true'); + + if (argv['ng-snapshots'] || argv['ng-tag']) { + await useSha(); + } + + console.log(`Project ${name} created... Installing packages.`); + await installWorkspacePackages(); + + await useCIChrome(name, ''); + await useCIDefaults(name); + + // Force sourcemaps to be from the root of the filesystem. + await updateJsonFile('tsconfig.json', (json) => { + json['compilerOptions']['sourceRoot'] = '/'; + }); + await gitCommit('prepare-project-for-e2e'); +} + +export function useBuiltPackagesVersions(): Promise { + const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars'); + + return updateJsonFile('package.json', (json) => { + json['dependencies'] ??= {}; + json['devDependencies'] ??= {}; + + for (const packageName of Object.keys(packages)) { + if (packageName in json['dependencies']) { + json['dependencies'][packageName] = packages[packageName].version; + } else if (packageName in json['devDependencies']) { + json['devDependencies'][packageName] = packages[packageName].version; + } + } + }); +} + +export async function useSha(): Promise { + const argv = getGlobalVariable('argv'); + if (!argv['ng-snapshots'] && !argv['ng-tag']) { + return; + } + + // We need more than the sha here, version is also needed. Examples of latest tags: + // 7.0.0-beta.4+dd2a650 + // 6.1.6+4a8d56a + const label = argv['ng-tag'] || ''; + const ngSnapshotVersions = require('../ng-snapshot/package.json'); + + return updateJsonFile('package.json', (json) => { + // Install over the project with snapshot builds. + function replaceDependencies(key: string) { + const missingSnapshots: string[] = []; + Object.keys(json[key] || {}) + .filter((name) => name.startsWith('@angular/')) + .forEach((name) => { + const pkgName = name.split(/\//)[1]; + if (pkgName === 'cli' || pkgName === 'ssr' || pkgName === 'build') { + return; + } + + if (label) { + json[key][`@angular/${pkgName}`] = `github:angular/${pkgName}-builds${label}`; + } else { + const replacement = ngSnapshotVersions.dependencies[`@angular/${pkgName}`]; + if (!replacement) { + missingSnapshots.push(`missing @angular/${pkgName}`); + } + json[key][`@angular/${pkgName}`] = replacement; + } + }); + if (missingSnapshots.length > 0) { + throw new Error( + 'e2e test with --ng-snapshots requires all angular packages be ' + + 'listed in tests/e2e/ng-snapshot/package.json.\nErrors:\n' + + missingSnapshots.join('\n '), + ); + } + } + + replaceDependencies('dependencies'); + replaceDependencies('devDependencies'); + }); +} + +export function useCIDefaults(projectName = 'test-project'): Promise { + return updateJsonFile('angular.json', (workspaceJson) => { + // Disable progress reporting on CI to reduce spam. + const project = workspaceJson.projects[projectName]; + const appTargets = project.targets || project.architect; + appTargets.build.options.progress = false; + appTargets.test.options.progress = false; + + if (appTargets.serve) { + // Use a random port in serve. + appTargets.serve.options ??= {}; + appTargets.serve.options.port = 0; + } + }); +} + +export async function useCIChrome(projectName: string, projectDir = ''): Promise { + const karmaConf = path.join(projectDir, 'karma.conf.js'); + if (fs.existsSync(karmaConf)) { + // Ensure the headless sandboxed chrome is configured in the karma config + await replaceInFile( + karmaConf, + `browsers: ['Chrome'],`, + `browsers: ['ChromeHeadlessNoSandbox'], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], + }, + },`, + ); + } + + // Update to use the headless sandboxed chrome + return updateJsonFile('angular.json', (workspaceJson) => { + const project = workspaceJson.projects[projectName]; + const appTargets = project.targets || project.architect; + if (appTargets.test.builder === '@angular/build:unit-test') { + appTargets.test.options.browsers = ['ChromeHeadlessNoSandbox']; + } else { + appTargets.test.options.browsers = 'ChromeHeadlessNoSandbox'; + } + }); +} + +export function getNgCLIVersion(): SemVer { + const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars'); + + return new SemVer(packages['@angular/cli'].version); +} + +export function isPrereleaseCli(): boolean { + return (prerelease(getNgCLIVersion())?.length ?? 0) > 0; +} + +export function updateServerFileForEsbuild(filepath: string): Promise { + return writeFile( + filepath, + ` + import { APP_BASE_HREF } from '@angular/common'; + import { CommonEngine } from '@angular/ssr/node'; + import express from 'express'; + import { join, resolve } from 'node:path'; + import bootstrap from './main.server'; + + // The Express app is exported so that it can be used by serverless Functions. + export function app(): express.Express { + const server = express(); + const serverDistFolder = import.meta.dirname; + const browserDistFolder = resolve(serverDistFolder, '../browser'); + const indexHtml = join(serverDistFolder, 'index.server.html'); + + const commonEngine = new CommonEngine(); + + server.set('view engine', 'html'); + server.set('views', browserDistFolder); + + server.use(express.static(browserDistFolder, { + maxAge: '1y', + index: false, + })); + + // All regular routes use the Angular engine + server.use((req, res, next) => { + const { protocol, originalUrl, baseUrl, headers } = req; + + commonEngine + .render({ + bootstrap, + documentFilePath: indexHtml, + url: \`\${protocol}://\${headers.host}\${originalUrl}\`, + publicPath: browserDistFolder, + providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }], + }) + .then((html) => res.send(html)) + .catch((err) => next(err)); + }); + + return server; + } + + function run(): void { + const port = process.env['PORT'] || 4000; + const server = app(); + server.listen(port, (error) => { + if (error) { + throw error; + } + console.log(\`Node Express server listening on http://localhost:\${port}\`); + }); + } + + run(); + `, + ); +} + +export function getTestProjectDir(): string { + return join(getGlobalVariable('projects-root'), 'test-project'); +} diff --git a/tests/e2e/utils/puppeteer.ts b/tests/e2e/utils/puppeteer.ts new file mode 100644 index 000000000000..ae8aae45761a --- /dev/null +++ b/tests/e2e/utils/puppeteer.ts @@ -0,0 +1,93 @@ +import { type Page, launch } from 'puppeteer'; +import { execAndWaitForOutputToMatch, killAllProcesses } from './process'; +import { stripVTControlCharacters } from 'node:util'; + +export interface BrowserTestOptions { + project?: string; + configuration?: string; + baseUrl?: string; + checkFn?: (page: Page) => Promise; + expectedTitleText?: string; +} + +export async function executeBrowserTest(options: BrowserTestOptions = {}) { + let url = options.baseUrl; + let hasStartedServer = false; + + try { + if (!url) { + // Start serving and find address (1 - Webpack; 2 - Vite) + const match = /(?:open your browser on|Local:)\s+(http:\/\/localhost:\d+\/)/; + const serveArgs = ['serve', '--port=0', '--no-watch', '--no-live-reload']; + if (options.project) { + serveArgs.push(options.project); + } + if (options.configuration) { + serveArgs.push(`--configuration=${options.configuration}`); + } + + const { stdout } = await execAndWaitForOutputToMatch('ng', serveArgs, match, { + ...process.env, + 'NO_COLOR': '1', + }); + url = stripVTControlCharacters(stdout).match(match)?.[1]; + if (!url) { + throw new Error('Could not find serving URL'); + } + hasStartedServer = true; + } + + const browser = await launch({ + executablePath: process.env['CHROME_BIN'], + headless: true, + args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'], + }); + try { + const page = await browser.newPage(); + + // Capture errors + const errors: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'error') { + errors.push(msg.text()); + } + }); + page.on('pageerror', (err) => { + const error = `${err}`; + if (!error.includes('Hot Module Replacement is disabled')) { + errors.push(error); + } + }); + + await page.goto(url); + + if (options.checkFn) { + await options.checkFn(page); + } else { + // Default check: verify h1 content and no browser errors + const expectedText = options.expectedTitleText || 'Hello, test-project'; + + // Wait for the h1 element to appear and contain the expected text + await page.waitForFunction( + (selector: string, text: string) => { + const doc = (globalThis as any).document; + return doc.querySelector(selector)?.textContent?.includes(text); + }, + { timeout: 10000 }, // Max 10 seconds wait time + 'h1', + expectedText, + ); + } + + if (errors.length > 0) { + throw new Error(`Browser console errors detected:\n${errors.join('\n')}`); + } + } finally { + await browser.close(); + } + } finally { + if (hasStartedServer) { + await killAllProcesses(); + } + } +} diff --git a/tests/e2e/utils/registry.ts b/tests/e2e/utils/registry.ts new file mode 100644 index 000000000000..5a871fb20ce6 --- /dev/null +++ b/tests/e2e/utils/registry.ts @@ -0,0 +1,124 @@ +import { ChildProcess, fork } from 'node:child_process'; +import { on } from 'node:events'; +import { mkdir } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { getGlobalVariable } from './env'; +import { writeFile, readFile } from './fs'; +import { existsSync } from 'node:fs'; + +export async function createNpmRegistry( + port: number, + httpsPort: number, + withAuthentication = false, +): Promise { + // Setup local package registry + const registryPath = join(getGlobalVariable('tmp-root'), 'registry'); + if (!existsSync(registryPath)) { + await mkdir(registryPath); + } + + const configFileName = withAuthentication ? 'verdaccio_auth.yaml' : 'verdaccio.yaml'; + let configContent = await readFile(join(__dirname, '../', configFileName)); + configContent = configContent + .replace(/\$\{HTTP_PORT\}/g, String(port)) + .replace(/\$\{HTTPS_PORT\}/g, String(httpsPort)); + const configPath = join(registryPath, configFileName); + + await writeFile(configPath, configContent); + + const verdaccioBin = join(dirname(require.resolve('verdaccio/package.json')), 'bin/verdaccio'); + const verdaccioServer = fork(verdaccioBin, ['-c', configPath]); + for await (const events of on(verdaccioServer, 'message', { + signal: AbortSignal.timeout(30_000), + })) { + if ( + events.some( + (event: unknown) => + event && + typeof event === 'object' && + 'verdaccio_started' in event && + event.verdaccio_started, + ) + ) { + break; + } + } + + return verdaccioServer; +} + +// Token was generated using `echo -n 'testing:s3cret' | openssl base64`. +const VALID_TOKEN = `dGVzdGluZzpzM2NyZXQ=`; + +export async function createNpmConfigForAuthentication( + /** + * When true, the authentication token will be scoped to the registry URL. + * @example + * ```ini + * //localhost:4876/:_auth="dGVzdGluZzpzM2NyZXQ=" + * ``` + * + * When false, the authentication will be added as seperate key. + * @example + * ```ini + * _auth="dGVzdGluZzpzM2NyZXQ="` + * ``` + */ + scopedAuthentication = true, + /** When true, an incorrect token is used. Use this to validate authentication failures. */ + invalidToken = false, +): Promise { + const token = invalidToken ? `invalid=` : VALID_TOKEN; + const registry = (getGlobalVariable('package-secure-registry') as string).replace(/^\w+:/, ''); + + await writeFile( + '.npmrc', + scopedAuthentication + ? ` +${registry}/:_auth="${token}" +${registry}/:always-auth=true +always-auth=true +registry=http:${registry} +` + : ` +_auth="${token}" +always-auth=true +registry=http:${registry} +`, + ); + + await writeFile( + '.yarnrc', + scopedAuthentication + ? ` +${registry}/:_auth "${token}" +${registry}/:always-auth true +always-auth true +registry http:${registry} +` + : ` +_auth "${token}" +always-auth true +registry http:${registry} +`, + ); +} + +export function setNpmEnvVarsForAuthentication( + /** When true, an incorrect token is used. Use this to validate authentication failures. */ + invalidToken = false, + /** When true, `YARN_REGISTRY` is used instead of `NPM_CONFIG_REGISTRY`. */ + useYarnEnvVariable = false, +): void { + delete process.env['YARN_REGISTRY']; + delete process.env['NPM_CONFIG_REGISTRY']; + + const registryKey = useYarnEnvVariable ? 'YARN_REGISTRY' : 'NPM_CONFIG_REGISTRY'; + process.env[registryKey] = getGlobalVariable('package-secure-registry'); + + process.env['NPM_CONFIG__AUTH'] = invalidToken ? `invalid=` : VALID_TOKEN; + + // Needed for verdaccio when used with yarn + // https://verdaccio.org/docs/en/cli-registry#yarn + process.env['NPM_CONFIG_ALWAYS_AUTH'] = 'true'; +} diff --git a/tests/e2e/utils/tar.ts b/tests/e2e/utils/tar.ts new file mode 100644 index 000000000000..016e88f25024 --- /dev/null +++ b/tests/e2e/utils/tar.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { createReadStream } from 'node:fs'; +import { normalize } from 'node:path'; +import { createGunzip } from 'node:zlib'; +import { extract } from 'tar-stream'; + +/** + * Extract and return the contents of a single file out of a tar file. + * + * @param tarball the tar file to extract from + * @param filePath the path of the file to extract + * @returns the Buffer of file or an error on fs/tar error or file not found + */ +export function extractFile(tarball: string, filePath: string): Promise { + const normalizedFilePath = normalize(filePath); + + return new Promise((resolve, reject) => { + const extractor = extract(); + + extractor.on('entry', (header, stream, next) => { + if (normalize(header.name) !== normalizedFilePath) { + stream.resume(); + next(); + + return; + } + + const chunks: Buffer[] = []; + stream.on('data', (chunk) => chunks.push(chunk as Buffer)); + stream.on('error', reject); + stream.on('end', () => { + resolve(Buffer.concat(chunks)); + next(); + }); + }); + + extractor.on('finish', () => reject(new Error(`'${filePath}' not found in '${tarball}'.`))); + + const readStream = createReadStream(tarball); + const gunzip = createGunzip(); + + readStream.on('error', reject); + gunzip.on('error', reject); + extractor.on('error', reject); + + readStream.pipe(gunzip).pipe(extractor as unknown as NodeJS.WritableStream); + }); +} diff --git a/tests/e2e/utils/test_process.ts b/tests/e2e/utils/test_process.ts new file mode 100644 index 000000000000..eda6677b5912 --- /dev/null +++ b/tests/e2e/utils/test_process.ts @@ -0,0 +1,34 @@ +import { killAllProcesses } from './process'; + +const testScript: string = process.argv[2]; +const testModule = require(testScript); +const testFunction: () => Promise | void = + typeof testModule == 'function' + ? testModule + : typeof testModule.default == 'function' + ? testModule.default + : () => { + throw new Error('Invalid test module.'); + }; + +// 8-minute timeout to prevent hanging tests from blocking the runner indefinitely. +const TEST_TIMEOUT_MS = 8 * 60 * 1000; + +(async () => { + let timeoutId: NodeJS.Timeout | undefined; + try { + const timeoutPromise = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject(new Error(`Test "${testScript}" timed out after 8 minutes.`)); + }, TEST_TIMEOUT_MS); + }); + + await Promise.race([testFunction(), timeoutPromise]); + } catch (e) { + console.error('Test Process error', e); + process.exitCode = -1; + } finally { + clearTimeout(timeoutId); + await killAllProcesses().finally(() => process.exit()); + } +})(); diff --git a/tests/e2e/utils/utils.ts b/tests/e2e/utils/utils.ts new file mode 100644 index 000000000000..0c255f53eb86 --- /dev/null +++ b/tests/e2e/utils/utils.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert'; +import { mkdtemp, realpath, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +export function expectToFail(fn: () => Promise, errorMessage?: string): Promise { + return fn().then( + () => { + const functionSource = fn.name || (fn).source || fn.toString(); + const errorDetails = errorMessage ? `\n\tDetails:\n\t${errorMessage}` : ''; + throw new Error( + `Function ${functionSource} was expected to fail, but succeeded.${errorDetails}`, + ); + }, + (err) => { + return err instanceof Error ? err : new Error(err); + }, + ); +} + +export async function mktempd(prefix: string, tempRoot?: string): Promise { + return realpath( + await mkdtemp( + path.join(tempRoot || process.env.E2E_TEMP || process.env.TEST_TMPDIR || tmpdir(), prefix), + ), + ); +} + +export async function mockHome(cb: (home: string) => Promise): Promise { + const tempHome = await mktempd('angular-cli-e2e-home-'); + + const oldHome = process.env.HOME; + process.env.HOME = tempHome; + + try { + await cb(tempHome); + } finally { + process.env.HOME = oldHome; + + await rm(tempHome, { recursive: true, force: true }); + } +} + +export function assertIsError(value: unknown): asserts value is Error & { code?: string } { + const isError = + value instanceof Error || + // The following is needing to identify errors coming from RxJs. + (typeof value === 'object' && value && 'name' in value && 'message' in value); + assert(isError, 'catch clause variable is not an Error instance'); +} diff --git a/tests/e2e/utils/version.ts b/tests/e2e/utils/version.ts new file mode 100644 index 000000000000..34dc29720b91 --- /dev/null +++ b/tests/e2e/utils/version.ts @@ -0,0 +1,13 @@ +import * as fs from 'node:fs'; +import * as semver from 'semver'; + +export function readNgVersion(): string { + const packageJson: any = JSON.parse( + fs.readFileSync('./node_modules/@angular/core/package.json', 'utf8'), + ) as { version: string }; + return packageJson['version']; +} + +export function ngVersionMatches(range: string): boolean { + return semver.satisfies(readNgVersion(), range); +} diff --git a/tests/e2e/utils/vitest.ts b/tests/e2e/utils/vitest.ts new file mode 100644 index 000000000000..ebb9d9d12298 --- /dev/null +++ b/tests/e2e/utils/vitest.ts @@ -0,0 +1,88 @@ +import { createRequire } from 'node:module'; +import { installWorkspacePackages } from './packages'; +import { updateJsonFile } from './project'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +/** Updates the `test` builder in the current workspace to use Vitest. */ +export async function applyVitestBuilder(options?: { + coverageV8?: boolean; + coverageIstanbul?: boolean; + playwright?: boolean; + webdriver?: boolean; + skipInstall?: boolean; +}): Promise { + const { coverageV8, coverageIstanbul, playwright, webdriver, skipInstall } = options ?? {}; + + const schematicsAngular = createRequire(process.cwd() + '/').resolve( + '@schematics/angular/package.json', + ); + + const latestVersionsPath = resolve(schematicsAngular, '../utility/latest-versions/package.json'); + + const { dependencies: latestVersion } = JSON.parse(await readFile(latestVersionsPath, 'utf-8')); + + await updateJsonFile('package.json', (json) => { + [ + 'karma', + 'karma-chrome-launcher', + 'karma-coverage', + 'karma-jasmine', + 'karma-jasmine-html-reporter', + 'jasmine-core', + '@types/jasmine', + 'istanbul-lib-instrument', + ].forEach((dep) => { + delete json.devDependencies[dep]; + }); + + json.devDependencies['vitest'] = latestVersion['vitest']; + json.devDependencies['jsdom'] = latestVersion['jsdom']; + + if (webdriver) { + json.devDependencies['webdriverio'] = latestVersion['webdriverio']; + json.devDependencies['@vitest/browser-webdriverio'] = + latestVersion['@vitest/browser-webdriverio']; + } + + if (playwright) { + json.devDependencies['playwright'] = latestVersion['playwright']; + json.devDependencies['@vitest/browser-playwright'] = + latestVersion['@vitest/browser-playwright']; + } + + if (coverageV8) { + json.devDependencies['@vitest/coverage-v8'] = latestVersion['@vitest/coverage-v8']; + } + + if (coverageIstanbul) { + json.devDependencies['@vitest/coverage-istanbul'] = + latestVersion['@vitest/coverage-istanbul']; + } + }); + + if (!skipInstall) { + await installWorkspacePackages(); + } + + await updateJsonFile('angular.json', (json) => { + const projects = Object.values(json['projects']); + if (projects.length !== 1) { + throw new Error( + `Expected exactly one project but found ${projects.length} projects named ${Object.keys( + json['projects'], + ).join(', ')}`, + ); + } + const project = projects[0]! as any; + + // Update to Vitest builder. + const test = project['architect']['test']; + test['builder'] = '@angular/build:unit-test'; + test['options'] = {}; + }); + + await updateJsonFile('tsconfig.spec.json', (tsconfig) => { + tsconfig['compilerOptions']['types'] = ['vitest/globals']; + }); +} diff --git a/tests/e2e_runner.ts b/tests/e2e_runner.ts new file mode 100644 index 000000000000..1fa0c294d4ee --- /dev/null +++ b/tests/e2e_runner.ts @@ -0,0 +1,424 @@ +import { parseArgs, styleText } from 'node:util'; +import glob from 'fast-glob'; +import * as path from 'node:path'; +import * as fs from 'node:fs'; +import { rm } from 'node:fs/promises'; +import { getGlobalVariable, setGlobalVariable } from './e2e/utils/env'; +import { gitClean } from './e2e/utils/git'; +import { createNpmRegistry } from './e2e/utils/registry'; +import { launchTestProcess } from './e2e/utils/process'; +import { delimiter, dirname, join } from 'node:path'; +import { findFreePort } from './e2e/utils/network'; +import { extractFile } from './e2e/utils/tar'; +import { realpathSync } from 'node:fs'; +import { PkgInfo } from './e2e/utils/packages'; +import { getTestProjectDir } from './e2e/utils/project'; +import { mktempd } from './e2e/utils/utils'; + +Error.stackTraceLimit = Infinity; + +// tslint:disable:no-global-tslint-disable no-console + +/** + * Here's a short description of those flags: + * --debug If a test fails, block the thread so the temporary directory isn't deleted. + * --noproject Skip creating a project or using one. + * --noglobal Skip linking your local @angular/cli directory. Can save a few seconds. + * --nosilent Never silence ng commands. + * --ng-tag=TAG Use a specific tag for build snapshots. Similar to ng-snapshots but point to a + * tag instead of using the latest `main`. + * --ng-snapshots Install angular snapshot builds in the test project. + * --glob Run tests matching this glob pattern (relative to tests/e2e/). + * --ignore Ignore tests matching this glob pattern. + * --nb-shards Total number of shards that this is part of. Default is 2 if --shard is + * passed in. + * --shard Index of this processes' shard. + * --package-manager Package manager to use. + * --package=path An npm package to be published before running tests + * + * If unnamed flags are passed in, the list of tests will be filtered to include only those passed. + */ +const parsed = parseArgs({ + allowPositionals: true, + options: { + 'debug': { type: 'boolean', default: !!process.env.BUILD_WORKSPACE_DIRECTORY }, + 'esbuild': { type: 'boolean' }, + 'glob': { type: 'string', default: 'tests/**/*.js' }, + 'ignore': { type: 'string', multiple: true }, + 'ng-snapshots': { type: 'boolean' }, + 'ng-tag': { type: 'string' }, + 'ng-version': { type: 'string' }, + 'noglobal': { type: 'boolean' }, + 'noproject': { type: 'boolean' }, + 'nosilent': { type: 'boolean' }, + 'package': { type: 'string', multiple: true, default: ['./dist/_*.tgz'] }, + 'package-manager': { type: 'string', default: 'npm' }, + 'verbose': { type: 'boolean' }, + + 'nb-shards': { type: 'string' }, + 'shard': { type: 'string' }, + }, +}); + +const argv = { + ...parsed.values, + _: parsed.positionals, + 'nb-shards': + parsed.values['nb-shards'] ?? + (Number(process.env.E2E_SHARD_TOTAL ?? 1) * Number(process.env.TEST_TOTAL_SHARDS ?? 1) || 1), + shard: + parsed.values.shard ?? + (process.env.E2E_SHARD_INDEX === undefined && process.env.TEST_SHARD_INDEX === undefined + ? undefined + : Number(process.env.E2E_SHARD_INDEX ?? 0) * Number(process.env.TEST_TOTAL_SHARDS ?? 1) + + Number(process.env.TEST_SHARD_INDEX ?? 0)), +}; + +// Indicate sharding support for Bazel. +if (process.env['TEST_SHARD_STATUS_FILE']) { + fs.writeFileSync(process.env['TEST_SHARD_STATUS_FILE'], '', 'utf8'); +} + +/** + * Set the error code of the process to 255. This is to ensure that if something forces node + * to exit without finishing properly, the error code will be 255. Right now that code is not used. + * + * - 1 When tests succeed we already call `process.exit(0)`, so this doesn't change any correct + * behaviour. + * + * One such case that would force node <= v6 to exit with code 0, is a Promise that doesn't resolve. + */ +process.exitCode = 255; + +/** + * Mark this process as the main e2e_runner + */ +process.env.LEGACY_CLI_RUNNER = '1'; + +/** + * Add external git toolchain onto PATH + */ +if (process.env.GIT_BIN) { + process.env.PATH = process.env.PATH! + delimiter + dirname(process.env.GIT_BIN!); +} + +/** + * Add external browser toolchains onto PATH + */ +if (process.env.CHROME_BIN) { + process.env.PATH = process.env.PATH! + delimiter + dirname(process.env.CHROME_BIN!); +} + +// Under bazel the compiled file (.js) and types (.d.ts) are available. +const SRC_FILE_EXT_RE = /\.js$/; +const testGlob = (process.env.TESTBRIDGE_TEST_ONLY ?? argv.glob).replace(/\.ts$/, '.js'); + +const e2eRoot = path.join(__dirname, 'e2e'); +const allSetups = glob.sync(`setup/**/*.js`, { cwd: e2eRoot }).sort(); +const allInitializers = glob.sync(`initialize/**/*.js`, { cwd: e2eRoot }).sort(); +const isWindows = process.platform === 'win32'; + +const allTests = glob + .sync(testGlob, { cwd: e2eRoot, ignore: argv.ignore }) + // Replace windows slashes. + .map((name) => name.replace(/\\/g, '/')) + .filter((name) => { + if (name.endsWith('/setup.js')) { + return false; + } + if (!SRC_FILE_EXT_RE.test(name)) { + return false; + } + + // The below is to exclude specific tests that are not intented to run for the current package manager. + // This is also important as without the trickery the tests that take the longest ex: update.ts (2.5mins) + // will be executed on the same shard. + const fileName = path.basename(name); + if ( + (fileName.startsWith('yarn-') && argv['package-manager'] !== 'yarn') || + (fileName.startsWith('npm-') && argv['package-manager'] !== 'npm') + ) { + return false; + } + + if (isWindows) { + if (fileName.startsWith('unix-')) { + return false; + } + } else if (fileName.startsWith('windows-')) { + return false; + } + + return true; + }) + .sort(); + +const shardId = argv['shard'] !== undefined ? Number(argv['shard']) : null; +const nbShards = shardId === null ? 1 : Number(argv['nb-shards']); +const tests = allTests.filter((name) => { + // Check for naming tests on command line. + if (argv._.length == 0) { + return true; + } + + return argv._.some((argName) => { + return ( + path.join(process.cwd(), argName + '') == path.join(__dirname, 'e2e', name) || + argName == name || + argName == name.replace(SRC_FILE_EXT_RE, '') + ); + }); +}); + +console.log(`Running with shard configuration:`); +console.log(`Total shards: ${nbShards}, current shard: ${shardId}`); + +// Remove tests that are not part of this shard. +const testsToRun = tests.filter((name, i) => shardId === null || i % nbShards == shardId); + +if (testsToRun.length === 0) { + if (shardId !== null && tests.length <= shardId) { + console.log(`No tests to run on shard ${shardId}, exiting`); + console.log(`Without sharding, there were ${tests.length} tests found.`); + process.exit(0); + } else { + console.log(`No tests would be ran, aborting.`); + process.exit(1); + } +} + +if (shardId !== null) { + console.log(`Running shard ${shardId} of ${nbShards}`); +} + +/** + * Load all the files from the e2e, filter and sort them and build a promise of their default + * export. + */ +if (testsToRun.length == allTests.length) { + console.log(`Running ${testsToRun.length} tests`); +} else { + console.log(`Running ${testsToRun.length} tests (${allTests.length} total)`); +} + +console.log(['Tests:', ...testsToRun].join('\n ')); + +setGlobalVariable('argv', argv); +setGlobalVariable('package-manager', argv['package-manager']); + +// Use the chrome supplied by bazel or the puppeteer chrome and webdriver-manager driver outside. +// This is needed by karma-chrome-launcher, protractor etc. +// https://github.com/karma-runner/karma-chrome-launcher#headless-chromium-with-puppeteer +// +// Resolve from relative paths to absolute paths within the bazel runfiles tree +// so subprocesses spawned in a different working directory can still find them. +process.env.CHROME_BIN = path.resolve(process.env.CHROME_BIN!); +process.env.CHROME_PATH = path.resolve(process.env.CHROME_PATH!); +process.env.CHROMEDRIVER_BIN = path.resolve(process.env.CHROMEDRIVER_BIN!); + +(async () => { + const tempRoot = await mktempd('angular-cli-e2e-'); + setGlobalVariable('tmp-root', tempRoot); + + process.on('SIGINT', deleteTemporaryRoot); + process.on('exit', deleteTemporaryRoot); + + const [httpPort, httpsPort, packageTars] = await Promise.all([ + findFreePort(), + findFreePort(), + findPackageTars(), + ]); + setGlobalVariable('package-registry', 'http://localhost:' + httpPort); + setGlobalVariable('package-secure-registry', 'http://localhost:' + httpsPort); + setGlobalVariable('package-tars', packageTars); + + // NPM registries for the lifetime of the test execution + const registryProcess = await createNpmRegistry(httpPort, httpPort); + const secureRegistryProcess = await createNpmRegistry(httpPort, httpsPort, true); + + try { + console.log(` Using "${tempRoot}" as temporary directory for a new project.`); + + await runSteps(runSetup, allSetups, 'setup'); + await runSteps(runInitializer, allInitializers, 'initializer'); + await runSteps(runTest, testsToRun, 'test'); + + if (shardId !== null) { + console.log(styleText(['green'], `Done shard ${shardId} of ${nbShards}.`)); + } else { + console.log(styleText(['green'], 'Done.')); + } + + process.exitCode = 0; + } catch (err) { + if (err instanceof Error) { + console.log('\n'); + console.error(styleText(['red'], err.message)); + if (err.stack) { + console.error(styleText(['red'], err.stack)); + } + } else { + console.error(styleText(['red'], String(err))); + } + + if (argv.debug) { + console.log(`Current Directory: ${process.cwd()}`); + console.log('Will loop forever while you debug... CTRL-C to quit.'); + + // Wait forever until user explicitly cancels. + await new Promise(() => {}); + } + + process.exitCode = 1; + } finally { + registryProcess.kill(); + secureRegistryProcess.kill(); + } +})().catch((err) => { + console.error(styleText(['red'], `Unkown Error: ${err}`)); + process.exitCode = 1; +}); + +async function runSteps( + run: (name: string) => Promise | void, + steps: string[], + type: 'setup' | 'test' | 'initializer', +) { + const capsType = type[0].toUpperCase() + type.slice(1); + + for (const [stepIndex, relativeName] of steps.entries()) { + // Make sure this is a windows compatible path. + let absoluteName = path.join(e2eRoot, relativeName).replace(SRC_FILE_EXT_RE, ''); + if (/^win/.test(process.platform)) { + absoluteName = absoluteName.replace(/\\/g, path.posix.sep); + } + + const name = relativeName.replace(SRC_FILE_EXT_RE, ''); + const start = Date.now(); + + printHeader(name, stepIndex, steps.length, type); + + // Run the test function with the current file. + try { + await run(absoluteName); + } catch (e) { + console.log('\n'); + console.error(styleText(['red'], `${capsType} "${name}" failed...`)); + + throw e; + } + + console.log('----'); + printFooter(name, type, start); + } +} + +function runSetup(absoluteName: string): Promise { + const module = require(absoluteName); + + return (typeof module === 'function' ? module : module.default)(); +} + +/** + * Run a file from the projects root directory in a subprocess via launchTestProcess(). + */ +function runInitializer(absoluteName: string): Promise { + process.chdir(getGlobalVariable('projects-root')); + + return launchTestProcess(absoluteName); +} + +/** + * Run a file from the main 'test-project' directory in a subprocess via launchTestProcess(). + */ +async function runTest(absoluteName: string): Promise { + process.chdir(getTestProjectDir()); + + await launchTestProcess(absoluteName); + await cleanTestProject(); +} + +async function cleanTestProject() { + await gitClean(); + + const testProject = getTestProjectDir(); + + // Note: Dist directory is not cleared between tests, as `git clean` + // doesn't delete it. + await rm(join(testProject, 'dist/'), { recursive: true, force: true }); +} + +function printHeader( + testName: string, + testIndex: number, + count: number, + type: 'setup' | 'initializer' | 'test', +) { + const text = `(${testIndex + 1} of ${count})`; + const fullIndex = testIndex * nbShards + (shardId ?? 0) + 1; + const shard = + shardId === null || type !== 'test' + ? '' + : styleText( + ['yellow'], + ` [${shardId}:${nbShards}]` + styleText(['bold'], ` (${fullIndex}/${tests.length})`), + ); + console.log( + styleText(['green'], `Running ${type} "`) + + styleText(['bold', 'blue'], testName) + + styleText(['green'], '" ') + + styleText(['bold', 'white'], text) + + shard + + styleText(['green'], '...'), + ); +} + +function printFooter(testName: string, type: 'setup' | 'initializer' | 'test', startTime: number) { + const capsType = type[0].toUpperCase() + type.slice(1); + + // Round to hundredth of a second. + const t = Math.round((Date.now() - startTime) / 10) / 100; + console.log( + styleText(['green'], `${capsType} "`) + + styleText(['bold', 'blue'], testName) + + styleText(['green'], '" took ') + + styleText(['bold', 'blue'], t.toFixed(2)) + + styleText(['green'], 's...'), + ); + console.log(''); +} + +// Collect the packages passed as arguments and return as {package-name => pkg-path} +async function findPackageTars(): Promise<{ [pkg: string]: PkgInfo }> { + const pkgs: string[] = (getGlobalVariable('argv').package as string[]).flatMap((p) => + glob.sync(p), + ); + + const pkgJsons = await Promise.all( + pkgs.map((pkg) => realpathSync(pkg)).map((pkg) => extractFile(pkg, 'npm_package/package.json')), + ); + + return pkgs.reduce( + (all, pkg, i) => { + const json = pkgJsons[i].toString('utf8'); + const { name, version } = JSON.parse(json) as { name: string; version: string }; + if (!name) { + throw new Error(`Package ${pkg} - package.json name/version not found`); + } + + all[name] = { path: realpathSync(pkg), name, version }; + return all; + }, + {} as { [pkg: string]: PkgInfo }, + ); +} + +function deleteTemporaryRoot(): void { + try { + fs.rmSync(getGlobalVariable('tmp-root'), { + recursive: true, + force: true, + maxRetries: 3, + }); + } catch {} +} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/.angular-cli.json b/tests/legacy-cli/e2e/assets/1.0-project/.angular-cli.json deleted file mode 100644 index 87c52afc90b8..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/.angular-cli.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "project": { - "name": "one-oh-project" - }, - "apps": [ - { - "root": "src", - "outDir": "dist", - "assets": [ - "assets", - "favicon.ico" - ], - "index": "index.html", - "main": "main.ts", - "polyfills": "polyfills.ts", - "test": "test.ts", - "tsconfig": "tsconfig.app.json", - "testTsconfig": "tsconfig.spec.json", - "prefix": "app", - "styles": [ - "styles.css" - ], - "scripts": [], - "environmentSource": "environments/environment.ts", - "environments": { - "dev": "environments/environment.ts", - "prod": "environments/environment.prod.ts" - } - } - ], - "e2e": { - "protractor": { - "config": "./protractor.conf.js" - } - }, - "lint": [ - { - "project": "src/tsconfig.app.json" - }, - { - "project": "src/tsconfig.spec.json" - }, - { - "project": "e2e/tsconfig.e2e.json" - } - ], - "test": { - "karma": { - "config": "./karma.conf.js" - } - }, - "defaults": { - "styleExt": "css", - "component": {} - } -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/.editorconfig b/tests/legacy-cli/e2e/assets/1.0-project/.editorconfig deleted file mode 100644 index e89330a618c1..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# Editor configuration, see https://editorconfig.org -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/tests/legacy-cli/e2e/assets/1.0-project/.gitignore b/tests/legacy-cli/e2e/assets/1.0-project/.gitignore deleted file mode 100644 index 54bfd2001e64..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/.gitignore +++ /dev/null @@ -1,42 +0,0 @@ -# See http://help.github.com/ignore-files/ for more about ignoring files. - -# compiled output -/dist -/tmp -/out-tsc - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# IDE - VSCode -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# misc -/.sass-cache -/connect.lock -/coverage -/libpeerconnection.log -npm-debug.log -testem.log -/typings - -# e2e -/e2e/*.js -/e2e/*.map - -# System Files -.DS_Store -Thumbs.db diff --git a/tests/legacy-cli/e2e/assets/1.0-project/README.md b/tests/legacy-cli/e2e/assets/1.0-project/README.md deleted file mode 100644 index f0369813ccea..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# OneOhProject - -This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.0.0. - -## Development server - -Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. - -## Code scaffolding - -Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class/module`. - -## Build - -Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. - -## Running unit tests - -Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). - -## Running end-to-end tests - -Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). -Before running the tests make sure you are serving the app via `ng serve`. - -## Further help - -To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.e2e-spec.ts b/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.e2e-spec.ts deleted file mode 100644 index 28aa6669b387..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.e2e-spec.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { OneOhProjectPage } from './app.po'; - -describe('one-oh-project App', () => { - let page: OneOhProjectPage; - - beforeEach(() => { - page = new OneOhProjectPage(); - }); - - it('should display message saying app works', () => { - page.navigateTo(); - expect(page.getParagraphText()).toEqual('app works!'); - }); -}); diff --git a/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.po.ts b/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.po.ts deleted file mode 100644 index 5a8e232ac895..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/e2e/app.po.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { browser, element, by } from 'protractor'; - -export class OneOhProjectPage { - navigateTo() { - return browser.get('/'); - } - - getParagraphText() { - return element(by.css('app-root h1')).getText(); - } -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/e2e/tsconfig.e2e.json b/tests/legacy-cli/e2e/assets/1.0-project/e2e/tsconfig.e2e.json deleted file mode 100644 index ac7a37325798..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/e2e/tsconfig.e2e.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/e2e", - "module": "commonjs", - "target": "es5", - "types":[ - "jasmine", - "node" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/karma.conf.js b/tests/legacy-cli/e2e/assets/1.0-project/karma.conf.js deleted file mode 100644 index ca70e74eee47..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/karma.conf.js +++ /dev/null @@ -1,45 +0,0 @@ -/*eslint-disable*/ -// Karma configuration file, see link for more information -// https://karma-runner.github.io/0.13/config/configuration-file.html - -module.exports = function (config) { - config.set({ - basePath: '', - frameworks: ['jasmine', '@angular/cli'], - plugins: [ - require('karma-jasmine'), - require('karma-chrome-launcher'), - require('karma-jasmine-html-reporter'), - require('karma-coverage-istanbul-reporter'), - require('@angular/cli/plugins/karma') - ], - client:{ - clearContext: false // leave Jasmine Spec Runner output visible in browser - }, - files: [ - { pattern: './src/test.ts', watched: false } - ], - preprocessors: { - './src/test.ts': ['@angular/cli'] - }, - mime: { - 'text/x-typescript': ['ts','tsx'] - }, - coverageIstanbulReporter: { - reports: [ 'html', 'lcovonly' ], - fixWebpackSourcePaths: true - }, - angularCli: { - environment: 'dev' - }, - reporters: config.angularCli && config.angularCli.codeCoverage - ? ['progress', 'coverage-istanbul'] - : ['progress', 'kjhtml'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Chrome'], - singleRun: false - }); -}; diff --git a/tests/legacy-cli/e2e/assets/1.0-project/package.json b/tests/legacy-cli/e2e/assets/1.0-project/package.json deleted file mode 100644 index 713912dc4a80..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "one-oh-project", - "version": "0.0.0", - "license": "MIT", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "^5.2.0", - "@angular/common": "^5.2.0", - "@angular/compiler": "^5.2.0", - "@angular/core": "^5.2.0", - "@angular/forms": "^5.2.0", - "@angular/http": "^5.2.0", - "@angular/platform-browser": "^5.2.0", - "@angular/platform-browser-dynamic": "^5.2.0", - "@angular/router": "^5.2.0", - "core-js": "^2.4.1", - "rxjs": "^5.5.6", - "zone.js": "^0.8.19" - }, - "devDependencies": { - "@angular/cli": "0.0.0", - "@angular/compiler-cli": "^5.2.0", - "@types/jasmine": "2.5.38", - "@types/node": "~6.0.60", - "codelyzer": "^4.0.1", - "jasmine-core": "~2.5.2", - "jasmine-spec-reporter": "~3.2.0", - "karma": "~1.4.1", - "karma-chrome-launcher": "~2.0.0", - "karma-cli": "~1.0.1", - "karma-jasmine": "~1.1.0", - "karma-jasmine-html-reporter": "^0.2.2", - "karma-coverage-istanbul-reporter": "^0.2.0", - "protractor": "~5.1.0", - "ts-node": "~4.1.0", - "tslint": "~5.9.1", - "typescript": "~2.4.2" - } -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/protractor.conf.js b/tests/legacy-cli/e2e/assets/1.0-project/protractor.conf.js deleted file mode 100644 index cdb43c5b4ab6..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/protractor.conf.js +++ /dev/null @@ -1,31 +0,0 @@ -/*eslint-disable*/ -// Protractor configuration file, see link for more information -// https://github.com/angular/protractor/blob/master/lib/config.ts - -const { SpecReporter } = require('jasmine-spec-reporter'); - -exports.config = { - allScriptsTimeout: 11000, - specs: [ - './e2e/**/*.e2e-spec.ts' - ], - capabilities: { - browserName: 'chrome' - }, - directConnect: true, - baseUrl: 'http://localhost:4200/', - framework: 'jasmine', - jasmineNodeOpts: { - showColors: true, - defaultTimeoutInterval: 30000, - print: function() {} - }, - beforeLaunch: function() { - require('ts-node').register({ - project: 'e2e/tsconfig.e2e.json' - }); - }, - onPrepare() { - jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); - } -}; diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.html b/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.html deleted file mode 100644 index b6931b538a2c..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.html +++ /dev/null @@ -1,3 +0,0 @@ -

- {{title}} -

diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.spec.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.spec.ts deleted file mode 100644 index c740bcd745ed..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { TestBed, async } from '@angular/core/testing'; - -import { AppComponent } from './app.component'; - -describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ - AppComponent - ], - }).compileComponents(); - })); - - it('should create the app', async(() => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app).toBeTruthy(); - })); - - it(`should have as title 'app works!'`, async(() => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app.title).toEqual('app works!'); - })); - - it('should render title in a h1 tag', async(() => { - const fixture = TestBed.createComponent(AppComponent); - fixture.detectChanges(); - const compiled = fixture.debugElement.nativeElement; - expect(compiled.querySelector('h1').textContent).toContain('app works!'); - })); -}); diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.ts deleted file mode 100644 index ff63e0504887..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] -}) -export class AppComponent { - title = 'app works!'; -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.module.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.module.ts deleted file mode 100644 index d39d998af88f..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.module.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { BrowserModule } from '@angular/platform-browser'; -import { NgModule } from '@angular/core'; -import { FormsModule } from '@angular/forms'; - -import { AppComponent } from './app.component'; - -@NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - FormsModule, - ], - providers: [], - bootstrap: [AppComponent] -}) -export class AppModule { } diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/assets/.gitkeep b/tests/legacy-cli/e2e/assets/1.0-project/src/assets/.gitkeep deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.prod.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.prod.ts deleted file mode 100644 index 3612073bc31c..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.prod.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const environment = { - production: true -}; diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.ts deleted file mode 100644 index b7f639aecac5..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/environments/environment.ts +++ /dev/null @@ -1,8 +0,0 @@ -// The file contents for the current environment will overwrite these during build. -// The build system defaults to the dev environment which uses `environment.ts`, but if you do -// `ng build --env=prod` then `environment.prod.ts` will be used instead. -// The list of which env maps to which file can be found in `.angular-cli.json`. - -export const environment = { - production: false -}; diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/favicon.ico b/tests/legacy-cli/e2e/assets/1.0-project/src/favicon.ico deleted file mode 100644 index 8081c7ceaf2b..000000000000 Binary files a/tests/legacy-cli/e2e/assets/1.0-project/src/favicon.ico and /dev/null differ diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/index.html b/tests/legacy-cli/e2e/assets/1.0-project/src/index.html deleted file mode 100644 index 06219472244b..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - OneOhProject - - - - - - - Loading... - - diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/main.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/main.ts deleted file mode 100644 index a9ca1caf8cee..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/main.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { enableProdMode } from '@angular/core'; -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} - -platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/polyfills.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/polyfills.ts deleted file mode 100644 index a8f13561140d..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/polyfills.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/guide/browser-support - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/set'; - -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. - -/** IE10 and IE11 requires the following to support `@angular/animation`. */ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - -/** Evergreen browsers require these. **/ -import 'core-js/es6/reflect'; -import 'core-js/es7/reflect'; - - -/** ALL Firefox browsers require the following to support `@angular/animation`. **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - - - -/*************************************************************************************************** - * Zone JS is required by Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ - -/** - * Date, currency, decimal and percent pipes. - * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 - */ -// import 'intl'; // Run `npm install --save intl`. diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/styles.css b/tests/legacy-cli/e2e/assets/1.0-project/src/styles.css deleted file mode 100644 index 90d4ee0072ce..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/styles.css +++ /dev/null @@ -1 +0,0 @@ -/* You can add global styles to this file, and also import other style files */ diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/test.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/test.ts deleted file mode 100644 index 9bf72267e9b1..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/test.ts +++ /dev/null @@ -1,32 +0,0 @@ -// This file is required by karma.conf.js and loads recursively all the .spec and framework files - -import 'zone.js/dist/long-stack-trace-zone'; -import 'zone.js/dist/proxy.js'; -import 'zone.js/dist/sync-test'; -import 'zone.js/dist/jasmine-patch'; -import 'zone.js/dist/async-test'; -import 'zone.js/dist/fake-async-test'; -import { getTestBed } from '@angular/core/testing'; -import { - BrowserDynamicTestingModule, - platformBrowserDynamicTesting -} from '@angular/platform-browser-dynamic/testing'; - -// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. -declare var __karma__: any; -declare var require: any; - -// Prevent Karma from running prematurely. -__karma__.loaded = function () {}; - -// First, initialize the Angular testing environment. -getTestBed().initTestEnvironment( - BrowserDynamicTestingModule, - platformBrowserDynamicTesting() -); -// Then we find all the tests. -const context = require.context('./', true, /\.spec\.ts$/); -// And load the modules. -context.keys().map(context); -// Finally, start Karma to run the tests. -__karma__.start(); diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.app.json b/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.app.json deleted file mode 100644 index 5e2507db58c9..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.app.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "module": "es2015", - "baseUrl": "", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.spec.json b/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.spec.json deleted file mode 100644 index 510e3f1fdae1..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/tsconfig.spec.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/spec", - "module": "commonjs", - "target": "es5", - "baseUrl": "", - "types": [ - "jasmine", - "node" - ] - }, - "files": [ - "test.ts" - ], - "include": [ - "**/*.spec.ts", - "**/*.d.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/typings.d.ts b/tests/legacy-cli/e2e/assets/1.0-project/src/typings.d.ts deleted file mode 100644 index ef5c7bd62057..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/src/typings.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* SystemJS module definition */ -declare var module: NodeModule; -interface NodeModule { - id: string; -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/tsconfig.json b/tests/legacy-cli/e2e/assets/1.0-project/tsconfig.json deleted file mode 100644 index a35a8ee3a40d..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "outDir": "./dist/out-tsc", - "baseUrl": "src", - "sourceMap": true, - "declaration": false, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2016", - "dom" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/1.0-project/tslint.json b/tests/legacy-cli/e2e/assets/1.0-project/tslint.json deleted file mode 100644 index 9113f1368b22..000000000000 --- a/tests/legacy-cli/e2e/assets/1.0-project/tslint.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "eofline": true, - "forin": true, - "import-blacklist": [true, "rxjs"], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - "static-before-instance", - "variables-before-functions" - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-variable": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [true, "ignore-params"], - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "typeof-compare": true, - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - - "directive-selector": [true, "attribute", "app", "camelCase"], - "component-selector": [true, "element", "app", "kebab-case"], - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true, - "no-access-missing-member": true, - "templates-use-public": true, - "invoke-injectable": true - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/.angular-cli.json b/tests/legacy-cli/e2e/assets/1.7-project/.angular-cli.json deleted file mode 100644 index 0e54ed353cee..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/.angular-cli.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "project": { - "name": "latest-project" - }, - "apps": [ - { - "root": "src", - "outDir": "dist", - "assets": [ - "assets", - "favicon.ico" - ], - "index": "index.html", - "main": "main.ts", - "polyfills": "polyfills.ts", - "test": "test.ts", - "tsconfig": "tsconfig.app.json", - "testTsconfig": "tsconfig.spec.json", - "prefix": "app", - "styles": [ - "styles.css" - ], - "scripts": [], - "environmentSource": "environments/environment.ts", - "environments": { - "dev": "environments/environment.ts", - "prod": "environments/environment.prod.ts" - } - } - ], - "e2e": { - "protractor": { - "config": "./protractor.conf.js" - } - }, - "lint": [ - { - "project": "src/tsconfig.app.json", - "exclude": "**/node_modules/**" - }, - { - "project": "src/tsconfig.spec.json", - "exclude": "**/node_modules/**" - }, - { - "project": "e2e/tsconfig.e2e.json", - "exclude": "**/node_modules/**" - } - ], - "test": { - "karma": { - "config": "./karma.conf.js" - } - }, - "defaults": { - "styleExt": "css", - "component": {} - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/.editorconfig b/tests/legacy-cli/e2e/assets/1.7-project/.editorconfig deleted file mode 100644 index e89330a618c1..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# Editor configuration, see https://editorconfig.org -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/tests/legacy-cli/e2e/assets/1.7-project/.gitignore b/tests/legacy-cli/e2e/assets/1.7-project/.gitignore deleted file mode 100644 index 4ae2c37916a5..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -# See http://help.github.com/ignore-files/ for more about ignoring files. - -# compiled output -/dist -/dist-server -/tmp -/out-tsc - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# IDE - VSCode -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# misc -/.sass-cache -/connect.lock -/coverage -/libpeerconnection.log -npm-debug.log -testem.log -/typings - -# e2e -/e2e/*.js -/e2e/*.map - -# System Files -.DS_Store -Thumbs.db diff --git a/tests/legacy-cli/e2e/assets/1.7-project/README.md b/tests/legacy-cli/e2e/assets/1.7-project/README.md deleted file mode 100644 index 281d381e31db..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# LatestProject - -This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.0-beta.1. - -## Development server - -Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. - -## Code scaffolding - -Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. - -## Build - -Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. - -## Running unit tests - -Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). - -## Running end-to-end tests - -Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). - -## Further help - -To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.e2e-spec.ts b/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.e2e-spec.ts deleted file mode 100644 index 343be839f981..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.e2e-spec.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { AppPage } from './app.po'; - -describe('latest-project App', () => { - let page: AppPage; - - beforeEach(() => { - page = new AppPage(); - }); - - it('should display welcome message', () => { - page.navigateTo(); - expect(page.getParagraphText()).toEqual('Welcome to app!'); - }); -}); diff --git a/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.po.ts b/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.po.ts deleted file mode 100644 index 82ea75ba504a..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/e2e/app.po.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { browser, by, element } from 'protractor'; - -export class AppPage { - navigateTo() { - return browser.get('/'); - } - - getParagraphText() { - return element(by.css('app-root h1')).getText(); - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/e2e/tsconfig.e2e.json b/tests/legacy-cli/e2e/assets/1.7-project/e2e/tsconfig.e2e.json deleted file mode 100644 index 1d9e5edf0965..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/e2e/tsconfig.e2e.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/e2e", - "baseUrl": "./", - "module": "commonjs", - "target": "es5", - "types": [ - "jasmine", - "jasminewd2", - "node" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/karma.conf.js b/tests/legacy-cli/e2e/assets/1.7-project/karma.conf.js deleted file mode 100644 index 7754379974fb..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/karma.conf.js +++ /dev/null @@ -1,34 +0,0 @@ -/*eslint-disable*/ -// Karma configuration file, see link for more information -// https://karma-runner.github.io/1.0/config/configuration-file.html - -module.exports = function (config) { - config.set({ - basePath: '', - frameworks: ['jasmine', '@angular/cli'], - plugins: [ - require('karma-jasmine'), - require('karma-chrome-launcher'), - require('karma-jasmine-html-reporter'), - require('karma-coverage-istanbul-reporter'), - require('@angular/cli/plugins/karma') - ], - client: { - clearContext: false // leave Jasmine Spec Runner output visible in browser - }, - coverageIstanbulReporter: { - reports: ['html', 'lcovonly'], - fixWebpackSourcePaths: true - }, - angularCli: { - environment: 'dev' - }, - reporters: ['progress', 'kjhtml'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Chrome'], - singleRun: false - }); -}; diff --git a/tests/legacy-cli/e2e/assets/1.7-project/package.json b/tests/legacy-cli/e2e/assets/1.7-project/package.json deleted file mode 100644 index 17dfbf92a873..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "latest-project", - "version": "0.0.0", - "license": "MIT", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build --prod", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "^5.2.0", - "@angular/common": "^5.2.0", - "@angular/compiler": "^5.2.0", - "@angular/core": "^5.2.0", - "@angular/forms": "^5.2.0", - "@angular/http": "^5.2.0", - "@angular/platform-browser": "^5.2.0", - "@angular/platform-browser-dynamic": "^5.2.0", - "@angular/router": "^5.2.0", - "core-js": "^2.4.1", - "rxjs": "^5.5.6", - "zone.js": "^0.8.19" - }, - "devDependencies": { - "@angular/cli": "0.0.0", - "@angular/compiler-cli": "^5.2.0", - "@angular/language-service": "^5.2.0", - "@types/jasmine": "2.8.3", - "@types/jasminewd2": "~2.0.2", - "@types/node": "~6.0.60", - "codelyzer": "^4.0.1", - "jasmine-core": "~2.8.0", - "jasmine-spec-reporter": "~4.2.1", - "karma": "~2.0.0", - "karma-chrome-launcher": "~2.2.0", - "karma-coverage-istanbul-reporter": "^1.2.1", - "karma-jasmine": "~1.1.0", - "karma-jasmine-html-reporter": "^0.2.2", - "protractor": "~5.1.2", - "ts-node": "~4.1.0", - "tslint": "~5.9.1", - "typescript": "~2.5.3" - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/protractor.conf.js b/tests/legacy-cli/e2e/assets/1.7-project/protractor.conf.js deleted file mode 100644 index 513957968bc5..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/protractor.conf.js +++ /dev/null @@ -1,29 +0,0 @@ -/*eslint-disable*/ -// Protractor configuration file, see link for more information -// https://github.com/angular/protractor/blob/master/lib/config.ts - -const { SpecReporter } = require('jasmine-spec-reporter'); - -exports.config = { - allScriptsTimeout: 11000, - specs: [ - './e2e/**/*.e2e-spec.ts' - ], - capabilities: { - browserName: 'chrome' - }, - directConnect: true, - baseUrl: 'http://localhost:4200/', - framework: 'jasmine', - jasmineNodeOpts: { - showColors: true, - defaultTimeoutInterval: 30000, - print: function () { } - }, - onPrepare() { - require('ts-node').register({ - project: 'e2e/tsconfig.e2e.json' - }); - jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); - } -}; diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.css b/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.css deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.html b/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.html deleted file mode 100644 index fa2706a406ba..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.html +++ /dev/null @@ -1,20 +0,0 @@ - -
-

- Welcome to {{ title }}! -

- Angular Logo -
-

Here are some links to help you start:

-
- diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.spec.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.spec.ts deleted file mode 100644 index bcbdf36b3e50..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { TestBed, async } from '@angular/core/testing'; -import { AppComponent } from './app.component'; -describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ - AppComponent - ], - }).compileComponents(); - })); - it('should create the app', async(() => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app).toBeTruthy(); - })); - it(`should have as title 'app'`, async(() => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app.title).toEqual('app'); - })); - it('should render title in a h1 tag', async(() => { - const fixture = TestBed.createComponent(AppComponent); - fixture.detectChanges(); - const compiled = fixture.debugElement.nativeElement; - expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!'); - })); -}); diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.ts deleted file mode 100644 index 7b0f67283151..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.component.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] -}) -export class AppComponent { - title = 'app'; -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.module.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.module.ts deleted file mode 100644 index 926975afe8af..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/app/app.module.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { BrowserModule } from '@angular/platform-browser'; -import { NgModule } from '@angular/core'; - - -import { AppComponent } from './app.component'; - - -@NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule - ], - providers: [], - bootstrap: [AppComponent] -}) -export class AppModule { } diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/assets/.gitkeep b/tests/legacy-cli/e2e/assets/1.7-project/src/assets/.gitkeep deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.prod.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.prod.ts deleted file mode 100644 index 3612073bc31c..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.prod.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const environment = { - production: true -}; diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.ts deleted file mode 100644 index b7f639aecac5..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/environments/environment.ts +++ /dev/null @@ -1,8 +0,0 @@ -// The file contents for the current environment will overwrite these during build. -// The build system defaults to the dev environment which uses `environment.ts`, but if you do -// `ng build --env=prod` then `environment.prod.ts` will be used instead. -// The list of which env maps to which file can be found in `.angular-cli.json`. - -export const environment = { - production: false -}; diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/favicon.ico b/tests/legacy-cli/e2e/assets/1.7-project/src/favicon.ico deleted file mode 100644 index 8081c7ceaf2b..000000000000 Binary files a/tests/legacy-cli/e2e/assets/1.7-project/src/favicon.ico and /dev/null differ diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/index.html b/tests/legacy-cli/e2e/assets/1.7-project/src/index.html deleted file mode 100644 index 94e4418225bf..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - LatestProject - - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/main.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/main.ts deleted file mode 100644 index 91ec6da5f078..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/main.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { enableProdMode } from '@angular/core'; -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} - -platformBrowserDynamic().bootstrapModule(AppModule) - .catch(err => console.log(err)); diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/polyfills.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/polyfills.ts deleted file mode 100644 index 02dd2ab75de2..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/polyfills.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/guide/browser-support - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/weak-map'; -// import 'core-js/es6/set'; - -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. - -/** IE10 and IE11 requires the following for the Reflect API. */ -// import 'core-js/es6/reflect'; - - -/** Evergreen browsers require these. **/ -// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. -import 'core-js/es7/reflect'; - - -/** - * Required to support Web Animations `@angular/platform-browser/animations`. - * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation - **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - -/** - * By default, zone.js will patch all possible macroTask and DomEvents - * user can disable parts of macroTask/DomEvents patch by setting following flags - */ - - // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame - // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick - // (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames - - /* - * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js - * with the following flag, it will bypass `zone.js` patch for IE/Edge - */ -// (window as any).__Zone_enable_cross_context_check = true; - -/*************************************************************************************************** - * Zone JS is required by default for Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/styles.css b/tests/legacy-cli/e2e/assets/1.7-project/src/styles.css deleted file mode 100644 index 90d4ee0072ce..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/styles.css +++ /dev/null @@ -1 +0,0 @@ -/* You can add global styles to this file, and also import other style files */ diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/test.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/test.ts deleted file mode 100644 index 16317897b1c5..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// This file is required by karma.conf.js and loads recursively all the .spec and framework files - -import 'zone.js/dist/zone-testing'; -import { getTestBed } from '@angular/core/testing'; -import { - BrowserDynamicTestingModule, - platformBrowserDynamicTesting -} from '@angular/platform-browser-dynamic/testing'; - -declare const require: any; - -// First, initialize the Angular testing environment. -getTestBed().initTestEnvironment( - BrowserDynamicTestingModule, - platformBrowserDynamicTesting() -); -// Then we find all the tests. -const context = require.context('./', true, /\.spec\.ts$/); -// And load the modules. -context.keys().map(context); diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.app.json b/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.app.json deleted file mode 100644 index 39ba8dbacbbe..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.app.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "baseUrl": "./", - "module": "es2015", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.spec.json b/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.spec.json deleted file mode 100644 index ac22a298acaa..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/tsconfig.spec.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/spec", - "baseUrl": "./", - "module": "commonjs", - "types": [ - "jasmine", - "node" - ] - }, - "files": [ - "test.ts" - ], - "include": [ - "**/*.spec.ts", - "**/*.d.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/src/typings.d.ts b/tests/legacy-cli/e2e/assets/1.7-project/src/typings.d.ts deleted file mode 100644 index ef5c7bd62057..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/src/typings.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* SystemJS module definition */ -declare var module: NodeModule; -interface NodeModule { - id: string; -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/tsconfig.json b/tests/legacy-cli/e2e/assets/1.7-project/tsconfig.json deleted file mode 100644 index a6c016bf38ad..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "outDir": "./dist/out-tsc", - "sourceMap": true, - "declaration": false, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2017", - "dom" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/1.7-project/tslint.json b/tests/legacy-cli/e2e/assets/1.7-project/tslint.json deleted file mode 100644 index 9963d6c3954c..000000000000 --- a/tests/legacy-cli/e2e/assets/1.7-project/tslint.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "deprecation": { - "severity": "warn" - }, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs", - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": true, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "directive-selector": [ - true, - "attribute", - "app", - "camelCase" - ], - "component-selector": [ - true, - "element", - "app", - "kebab-case" - ], - "no-output-on-prefix": true, - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true - } -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/.editorconfig b/tests/legacy-cli/e2e/assets/7.0-project/.editorconfig deleted file mode 100644 index e89330a618c1..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# Editor configuration, see https://editorconfig.org -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -insert_final_newline = true -trim_trailing_whitespace = true - -[*.md] -max_line_length = off -trim_trailing_whitespace = false diff --git a/tests/legacy-cli/e2e/assets/7.0-project/.gitignore b/tests/legacy-cli/e2e/assets/7.0-project/.gitignore deleted file mode 100644 index ee5c9d8336b7..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# See http://help.github.com/ignore-files/ for more about ignoring files. - -# compiled output -/dist -/tmp -/out-tsc - -# dependencies -/node_modules - -# IDEs and editors -/.idea -.project -.classpath -.c9/ -*.launch -.settings/ -*.sublime-workspace - -# IDE - VSCode -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -# misc -/.sass-cache -/connect.lock -/coverage -/libpeerconnection.log -npm-debug.log -yarn-error.log -testem.log -/typings - -# System Files -.DS_Store -Thumbs.db diff --git a/tests/legacy-cli/e2e/assets/7.0-project/README.md b/tests/legacy-cli/e2e/assets/7.0-project/README.md deleted file mode 100644 index 5223c63955d2..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# SevenOhProject - -This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.7. - -## Development server - -Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. - -## Code scaffolding - -Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. - -## Build - -Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. - -## Running unit tests - -Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). - -## Running end-to-end tests - -Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). - -## Further help - -To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/tests/legacy-cli/e2e/assets/7.0-project/angular.json b/tests/legacy-cli/e2e/assets/7.0-project/angular.json deleted file mode 100644 index 98de2c2a14ed..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/angular.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", - "version": 1, - "newProjectRoot": "projects", - "projects": { - "seven-oh-project": { - "root": "", - "sourceRoot": "src", - "projectType": "application", - "prefix": "app", - "schematics": {}, - "architect": { - "build": { - "builder": "@angular-devkit/build-angular:browser", - "options": { - "outputPath": "dist/seven-oh-project", - "index": "src/index.html", - "main": "src/main.ts", - "polyfills": "src/polyfills.ts", - "tsConfig": "src/tsconfig.app.json", - "assets": [ - "src/favicon.ico", - "src/assets" - ], - "styles": [ - "src/styles.css" - ], - "scripts": [] - }, - "configurations": { - "production": { - "fileReplacements": [ - { - "replace": "src/environments/environment.ts", - "with": "src/environments/environment.prod.ts" - } - ], - "optimization": true, - "outputHashing": "all", - "sourceMap": false, - "extractCss": true, - "namedChunks": false, - "aot": true, - "extractLicenses": true, - "vendorChunk": false, - "buildOptimizer": true, - "budgets": [ - { - "type": "initial", - "maximumWarning": "2mb", - "maximumError": "5mb" - } - ] - } - } - }, - "serve": { - "builder": "@angular-devkit/build-angular:dev-server", - "options": { - "browserTarget": "seven-oh-project:build" - }, - "configurations": { - "production": { - "browserTarget": "seven-oh-project:build:production" - } - } - }, - "extract-i18n": { - "builder": "@angular-devkit/build-angular:extract-i18n", - "options": { - "browserTarget": "seven-oh-project:build" - } - }, - "test": { - "builder": "@angular-devkit/build-angular:karma", - "options": { - "main": "src/test.ts", - "polyfills": "src/polyfills.ts", - "tsConfig": "src/tsconfig.spec.json", - "karmaConfig": "src/karma.conf.js", - "styles": [ - "src/styles.css" - ], - "scripts": [], - "assets": [ - "src/favicon.ico", - "src/assets" - ] - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": [ - "src/tsconfig.app.json", - "src/tsconfig.spec.json" - ], - "exclude": [ - "**/node_modules/**" - ] - } - } - } - }, - "seven-oh-project-e2e": { - "root": "e2e/", - "projectType": "application", - "prefix": "", - "architect": { - "e2e": { - "builder": "@angular-devkit/build-angular:protractor", - "options": { - "protractorConfig": "e2e/protractor.conf.js", - "devServerTarget": "seven-oh-project:serve" - }, - "configurations": { - "production": { - "devServerTarget": "seven-oh-project:serve:production" - } - } - }, - "lint": { - "builder": "@angular-devkit/build-angular:tslint", - "options": { - "tsConfig": "e2e/tsconfig.e2e.json", - "exclude": [ - "**/node_modules/**" - ] - } - } - } - } - }, - "defaultProject": "seven-oh-project" -} \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/7.0-project/e2e/protractor.conf.js b/tests/legacy-cli/e2e/assets/7.0-project/e2e/protractor.conf.js deleted file mode 100644 index fda004eb85fd..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/e2e/protractor.conf.js +++ /dev/null @@ -1,28 +0,0 @@ -// Protractor configuration file, see link for more information -// https://github.com/angular/protractor/blob/master/lib/config.ts - -const { SpecReporter } = require('jasmine-spec-reporter'); - -exports.config = { - allScriptsTimeout: 11000, - specs: [ - './src/**/*.e2e-spec.ts' - ], - capabilities: { - browserName: 'chrome' - }, - directConnect: true, - baseUrl: 'http://localhost:4200/', - framework: 'jasmine', - jasmineNodeOpts: { - showColors: true, - defaultTimeoutInterval: 30000, - print: function() {} - }, - onPrepare() { - require('ts-node').register({ - project: require('path').join(__dirname, './tsconfig.e2e.json') - }); - jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); - } -}; \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.e2e-spec.ts b/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.e2e-spec.ts deleted file mode 100644 index 137ce38ff589..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.e2e-spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { browser, logging, element, by } from 'protractor'; - -describe('workspace-project App', () => { - it('should display lazy route', () => { - browser.get(browser.baseUrl + '/lazy'); - expect(element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); -}); diff --git a/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.po.ts b/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.po.ts deleted file mode 100644 index 72e463a33539..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/e2e/src/app.po.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { browser, by, element } from 'protractor'; - -export class AppPage { - navigateTo() { - return browser.get('/'); - } - - getTitleText() { - return element(by.css('app-root h1')).getText(); - } -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/e2e/tsconfig.e2e.json b/tests/legacy-cli/e2e/assets/7.0-project/e2e/tsconfig.e2e.json deleted file mode 100644 index a6dd62202824..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/e2e/tsconfig.e2e.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "module": "commonjs", - "target": "es5", - "types": [ - "jasmine", - "jasminewd2", - "node" - ] - } -} \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/7.0-project/package.json b/tests/legacy-cli/e2e/assets/7.0-project/package.json deleted file mode 100644 index fa5e065c8a6b..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "seven-oh-project", - "version": "0.0.0", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "test": "ng test", - "lint": "ng lint", - "e2e": "ng e2e" - }, - "private": true, - "dependencies": { - "@angular/animations": "~7.0.0", - "@angular/common": "~7.0.0", - "@angular/compiler": "~7.0.0", - "@angular/core": "~7.0.0", - "@angular/forms": "~7.0.0", - "@angular/http": "~7.0.0", - "@angular/platform-browser": "~7.0.0", - "@angular/platform-browser-dynamic": "~7.0.0", - "@angular/router": "~7.0.0", - "core-js": "^2.5.4", - "rxjs": "~6.3.3", - "zone.js": "~0.8.26" - }, - "devDependencies": { - "@angular-devkit/build-angular": "~0.10.0", - "@angular/cli": "~7.0.7", - "@angular/compiler-cli": "~7.0.0", - "@angular/language-service": "~7.0.0", - "@types/node": "~8.9.4", - "@types/jasmine": "~2.8.8", - "@types/jasminewd2": "~2.0.3", - "codelyzer": "~4.5.0", - "jasmine-core": "~2.99.1", - "jasmine-spec-reporter": "~4.2.1", - "karma": "~3.0.0", - "karma-chrome-launcher": "~2.2.0", - "karma-coverage-istanbul-reporter": "~2.0.1", - "karma-jasmine": "~1.1.2", - "karma-jasmine-html-reporter": "^0.2.2", - "protractor": "~5.4.0", - "ts-node": "~7.0.0", - "tslint": "~5.11.0", - "typescript": "~3.1.6" - } -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app-routing.module.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app-routing.module.ts deleted file mode 100644 index 942c8098dc82..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app-routing.module.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { NgModule } from '@angular/core'; -import { Routes, RouterModule } from '@angular/router'; - -const routes: Routes = [{ path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule' }]; - -@NgModule({ - imports: [RouterModule.forRoot(routes)], - exports: [RouterModule] -}) -export class AppRoutingModule { } diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.css b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.css deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.html b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.html deleted file mode 100644 index 1094e7ebdfb8..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.html +++ /dev/null @@ -1,21 +0,0 @@ - -
-

- Welcome to {{ title }}! -

- Angular Logo -
-

Here are some links to help you start:

- - - diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.spec.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.spec.ts deleted file mode 100644 index 14df92cc2d95..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { TestBed, async } from '@angular/core/testing'; -import { RouterModule } from '@angular/router'; -import { AppComponent } from './app.component'; - -describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ - AppComponent - ], - imports: [ - RouterModule.forRoot([]) - ], - }).compileComponents(); - })); - - it('should create the app', () => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app).toBeTruthy(); - }); - - it(`should have as title 'seven-oh-project'`, () => { - const fixture = TestBed.createComponent(AppComponent); - const app = fixture.debugElement.componentInstance; - expect(app.title).toEqual('seven-oh-project'); - }); - - it('should render title in a h1 tag', () => { - const fixture = TestBed.createComponent(AppComponent); - fixture.detectChanges(); - const compiled = fixture.debugElement.nativeElement; - expect(compiled.querySelector('h1').textContent).toContain('Welcome to seven-oh-project!'); - }); -}); diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.ts deleted file mode 100644 index 156d6109afa3..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.component.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Component } from '@angular/core'; - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] -}) -export class AppComponent { - title = 'seven-oh-project'; -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.module.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.module.ts deleted file mode 100644 index d718d9ba2b50..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/app.module.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { BrowserModule } from '@angular/platform-browser'; -import { NgModule } from '@angular/core'; - -import { AppRoutingModule } from './app-routing.module'; -import { AppComponent } from './app.component'; - -@NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - AppRoutingModule, - ], - providers: [], - bootstrap: [AppComponent] -}) -export class AppModule { } diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.css b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.css deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.html b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.html deleted file mode 100644 index 77d85a09faef..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.html +++ /dev/null @@ -1,3 +0,0 @@ -

- lazy-comp works! -

diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.spec.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.spec.ts deleted file mode 100644 index b8f42f6a5deb..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; - -import { LazyCompComponent } from './lazy-comp.component'; - -describe('LazyCompComponent', () => { - let component: LazyCompComponent; - let fixture: ComponentFixture; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ LazyCompComponent ] - }) - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(LazyCompComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - }); - - it('should create', () => { - expect(component).toBeTruthy(); - }); -}); diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.ts deleted file mode 100644 index ef413e598468..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-comp/lazy-comp.component.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Component, OnInit } from '@angular/core'; - -@Component({ - selector: 'app-lazy-comp', - templateUrl: './lazy-comp.component.html', - styleUrls: ['./lazy-comp.component.css'] -}) -export class LazyCompComponent implements OnInit { - - constructor() { } - - ngOnInit() { - } - -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-routing.module.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-routing.module.ts deleted file mode 100644 index e5b323332e9e..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy-routing.module.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { NgModule } from '@angular/core'; -import { Routes, RouterModule } from '@angular/router'; - -import { LazyCompComponent } from './lazy-comp/lazy-comp.component'; - - -const routes: Routes = [{ path: '', component: LazyCompComponent }]; - -@NgModule({ - imports: [RouterModule.forChild(routes)], - exports: [RouterModule] -}) -export class LazyRoutingModule { } diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy.module.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy.module.ts deleted file mode 100644 index 44f745b3ca84..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/app/lazy/lazy.module.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { NgModule } from '@angular/core'; -import { CommonModule } from '@angular/common'; - -import { LazyRoutingModule } from './lazy-routing.module'; -import { LazyCompComponent } from './lazy-comp/lazy-comp.component'; - -@NgModule({ - declarations: [LazyCompComponent], - imports: [ - CommonModule, - LazyRoutingModule - ] -}) -export class LazyModule { } diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/assets/.gitkeep b/tests/legacy-cli/e2e/assets/7.0-project/src/assets/.gitkeep deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/browserslist b/tests/legacy-cli/e2e/assets/7.0-project/src/browserslist deleted file mode 100644 index 37371cb04b9f..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/browserslist +++ /dev/null @@ -1,11 +0,0 @@ -# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers -# For additional information regarding the format and rule options, please see: -# https://github.com/browserslist/browserslist#queries -# -# For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed - -> 0.5% -last 2 versions -Firefox ESR -not dead -not IE 9-11 \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.prod.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.prod.ts deleted file mode 100644 index 3612073bc31c..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.prod.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const environment = { - production: true -}; diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.ts deleted file mode 100644 index 7b4f817adb75..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/environments/environment.ts +++ /dev/null @@ -1,16 +0,0 @@ -// This file can be replaced during build by using the `fileReplacements` array. -// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. -// The list of file replacements can be found in `angular.json`. - -export const environment = { - production: false -}; - -/* - * For easier debugging in development mode, you can import the following file - * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. - * - * This import should be commented out in production mode because it will have a negative impact - * on performance if an error is thrown. - */ -// import 'zone.js/dist/zone-error'; // Included with Angular CLI. diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/favicon.ico b/tests/legacy-cli/e2e/assets/7.0-project/src/favicon.ico deleted file mode 100644 index 8081c7ceaf2b..000000000000 Binary files a/tests/legacy-cli/e2e/assets/7.0-project/src/favicon.ico and /dev/null differ diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/index.html b/tests/legacy-cli/e2e/assets/7.0-project/src/index.html deleted file mode 100644 index 18e71f811dcc..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - SevenOhProject - - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/karma.conf.js b/tests/legacy-cli/e2e/assets/7.0-project/src/karma.conf.js deleted file mode 100644 index b6e00421c95f..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/karma.conf.js +++ /dev/null @@ -1,31 +0,0 @@ -// Karma configuration file, see link for more information -// https://karma-runner.github.io/1.0/config/configuration-file.html - -module.exports = function (config) { - config.set({ - basePath: '', - frameworks: ['jasmine', '@angular-devkit/build-angular'], - plugins: [ - require('karma-jasmine'), - require('karma-chrome-launcher'), - require('karma-jasmine-html-reporter'), - require('karma-coverage-istanbul-reporter'), - require('@angular-devkit/build-angular/plugins/karma') - ], - client: { - clearContext: false // leave Jasmine Spec Runner output visible in browser - }, - coverageIstanbulReporter: { - dir: require('path').join(__dirname, '../coverage'), - reports: ['html', 'lcovonly'], - fixWebpackSourcePaths: true - }, - reporters: ['progress', 'kjhtml'], - port: 9876, - colors: true, - logLevel: config.LOG_INFO, - autoWatch: true, - browsers: ['Chrome'], - singleRun: false - }); -}; \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/main.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/main.ts deleted file mode 100644 index c7b673cf44b3..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/main.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { enableProdMode } from '@angular/core'; -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { AppModule } from './app/app.module'; -import { environment } from './environments/environment'; - -if (environment.production) { - enableProdMode(); -} - -platformBrowserDynamic().bootstrapModule(AppModule) - .catch(err => console.error(err)); diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/polyfills.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/polyfills.ts deleted file mode 100644 index ee8b84da807c..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/polyfills.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * This file includes polyfills needed by Angular and is loaded before the app. - * You can add your own extra polyfills to this file. - * - * This file is divided into 2 sections: - * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. - * 2. Application imports. Files imported after ZoneJS that should be loaded before your main - * file. - * - * The current setup is for so-called "evergreen" browsers; the last versions of browsers that - * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), - * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. - * - * Learn more in https://angular.io/guide/browser-support - */ - -/*************************************************************************************************** - * BROWSER POLYFILLS - */ - -/** IE9, IE10 and IE11 requires all of the following polyfills. **/ -// import 'core-js/es6/symbol'; -// import 'core-js/es6/object'; -// import 'core-js/es6/function'; -// import 'core-js/es6/parse-int'; -// import 'core-js/es6/parse-float'; -// import 'core-js/es6/number'; -// import 'core-js/es6/math'; -// import 'core-js/es6/string'; -// import 'core-js/es6/date'; -// import 'core-js/es6/array'; -// import 'core-js/es6/regexp'; -// import 'core-js/es6/map'; -// import 'core-js/es6/weak-map'; -// import 'core-js/es6/set'; - -/** - * If the application will be indexed by Google Search, the following is required. - * Googlebot uses a renderer based on Chrome 41. - * https://developers.google.com/search/docs/guides/rendering - **/ -// import 'core-js/es6/array'; - -/** IE10 and IE11 requires the following for NgClass support on SVG elements */ -// import 'classlist.js'; // Run `npm install --save classlist.js`. - -/** IE10 and IE11 requires the following for the Reflect API. */ -// import 'core-js/es6/reflect'; - -/** - * Web Animations `@angular/platform-browser/animations` - * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. - * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). - **/ -// import 'web-animations-js'; // Run `npm install --save web-animations-js`. - -/** - * By default, zone.js will patch all possible macroTask and DomEvents - * user can disable parts of macroTask/DomEvents patch by setting following flags - */ - - // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame - // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick - // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames - - /* - * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js - * with the following flag, it will bypass `zone.js` patch for IE/Edge - */ -// (window as any).__Zone_enable_cross_context_check = true; - -/*************************************************************************************************** - * Zone JS is required by default for Angular itself. - */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - -/*************************************************************************************************** - * APPLICATION IMPORTS - */ diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/styles.css b/tests/legacy-cli/e2e/assets/7.0-project/src/styles.css deleted file mode 100644 index 90d4ee0072ce..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/styles.css +++ /dev/null @@ -1 +0,0 @@ -/* You can add global styles to this file, and also import other style files */ diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/test.ts b/tests/legacy-cli/e2e/assets/7.0-project/src/test.ts deleted file mode 100644 index 16317897b1c5..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// This file is required by karma.conf.js and loads recursively all the .spec and framework files - -import 'zone.js/dist/zone-testing'; -import { getTestBed } from '@angular/core/testing'; -import { - BrowserDynamicTestingModule, - platformBrowserDynamicTesting -} from '@angular/platform-browser-dynamic/testing'; - -declare const require: any; - -// First, initialize the Angular testing environment. -getTestBed().initTestEnvironment( - BrowserDynamicTestingModule, - platformBrowserDynamicTesting() -); -// Then we find all the tests. -const context = require.context('./', true, /\.spec\.ts$/); -// And load the modules. -context.keys().map(context); diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.app.json b/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.app.json deleted file mode 100644 index 190fd300b601..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.app.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/app", - "types": [] - }, - "exclude": [ - "test.ts", - "**/*.spec.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.spec.json b/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.spec.json deleted file mode 100644 index de7733630eb2..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/tsconfig.spec.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "outDir": "../out-tsc/spec", - "types": [ - "jasmine", - "node" - ] - }, - "files": [ - "test.ts", - "polyfills.ts" - ], - "include": [ - "**/*.spec.ts", - "**/*.d.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/src/tslint.json b/tests/legacy-cli/e2e/assets/7.0-project/src/tslint.json deleted file mode 100644 index 52e2c1a5a74c..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/src/tslint.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../tslint.json", - "rules": { - "directive-selector": [ - true, - "attribute", - "app", - "camelCase" - ], - "component-selector": [ - true, - "element", - "app", - "kebab-case" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/tsconfig.json b/tests/legacy-cli/e2e/assets/7.0-project/tsconfig.json deleted file mode 100644 index 46aeded1b278..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "baseUrl": "./", - "outDir": "./dist/out-tsc", - "sourceMap": true, - "declaration": false, - "module": "es2015", - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es5", - "typeRoots": [ - "node_modules/@types" - ], - "lib": [ - "es2018", - "dom" - ] - } -} diff --git a/tests/legacy-cli/e2e/assets/7.0-project/tslint.json b/tests/legacy-cli/e2e/assets/7.0-project/tslint.json deleted file mode 100644 index 6ddb6b293151..000000000000 --- a/tests/legacy-cli/e2e/assets/7.0-project/tslint.json +++ /dev/null @@ -1,131 +0,0 @@ -{ - "rulesDirectory": [ - "node_modules/codelyzer" - ], - "rules": { - "arrow-return-shorthand": true, - "callable-types": true, - "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "curly": true, - "deprecation": { - "severity": "warn" - }, - "eofline": true, - "forin": true, - "import-blacklist": [ - true, - "rxjs/Rx" - ], - "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-over-type-literal": true, - "label-position": true, - "max-line-length": [ - true, - 140 - ], - "member-access": false, - "member-ordering": [ - true, - { - "order": [ - "static-field", - "instance-field", - "static-method", - "instance-method" - ] - } - ], - "no-arg": true, - "no-bitwise": true, - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], - "no-construct": true, - "no-debugger": true, - "no-duplicate-super": true, - "no-empty": false, - "no-empty-interface": true, - "no-eval": true, - "no-inferrable-types": [ - true, - "ignore-params" - ], - "no-misused-new": true, - "no-non-null-assertion": true, - "no-redundant-jsdoc": true, - "no-shadowed-variable": true, - "no-string-literal": false, - "no-string-throw": true, - "no-switch-case-fall-through": true, - "no-trailing-whitespace": true, - "no-unnecessary-initializer": true, - "no-unused-expression": true, - "no-use-before-declare": true, - "no-var-keyword": true, - "object-literal-sort-keys": false, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "prefer-const": true, - "quotemark": [ - true, - "single" - ], - "radix": true, - "semicolon": [ - true, - "always" - ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef-whitespace": [ - true, - { - "call-signature": "nospace", - "index-signature": "nospace", - "parameter": "nospace", - "property-declaration": "nospace", - "variable-declaration": "nospace" - } - ], - "unified-signatures": true, - "variable-name": false, - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-separator", - "check-type" - ], - "no-output-on-prefix": true, - "use-input-property-decorator": true, - "use-output-property-decorator": true, - "use-host-property-decorator": true, - "no-input-rename": true, - "no-output-rename": true, - "use-life-cycle-interface": true, - "use-pipe-transform-interface": true, - "component-class-suffix": true, - "directive-class-suffix": true - } -} diff --git a/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js b/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js deleted file mode 100644 index 867b3a4eb6fd..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file-peer-bad', ''); diff --git a/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js b/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js deleted file mode 100644 index 4d5dbdca2f69..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file-peer-good', ''); diff --git a/tests/legacy-cli/e2e/assets/add-collection/index.js b/tests/legacy-cli/e2e/assets/add-collection/index.js deleted file mode 100644 index cf404a768650..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file', ''); diff --git a/tests/legacy-cli/e2e/assets/images/spectrum.png b/tests/legacy-cli/e2e/assets/images/spectrum.png deleted file mode 100644 index 2a5f123afc84..000000000000 Binary files a/tests/legacy-cli/e2e/assets/images/spectrum.png and /dev/null differ diff --git a/tests/legacy-cli/e2e/assets/protractor-saucelabs.conf.js b/tests/legacy-cli/e2e/assets/protractor-saucelabs.conf.js deleted file mode 100644 index c7208b1f6a81..000000000000 --- a/tests/legacy-cli/e2e/assets/protractor-saucelabs.conf.js +++ /dev/null @@ -1,124 +0,0 @@ -// @ts-check -// Protractor configuration file, see link for more information -// https://github.com/angular/protractor/blob/master/lib/config.ts - -const { SpecReporter } = require('jasmine-spec-reporter'); - -const tunnelIdentifier = process.env['SAUCE_TUNNEL_IDENTIFIER']; - -/** - * @type { import("protractor").Config } - */ -exports.config = { - sauceUser: process.env['SAUCE_USERNAME'], - sauceKey: process.env['SAUCE_ACCESS_KEY'], - - allScriptsTimeout: 11000, - specs: ['./src/**/*.e2e-spec.ts'], - - multiCapabilities: [ - { - browserName: 'chrome', - version: '41', - tunnelIdentifier, - }, - { - browserName: 'chrome', - version: '75', - tunnelIdentifier, - }, - { - browserName: 'safari', - platform: 'OS X 10.11', - version: '9.0', - tunnelIdentifier, - }, - { - browserName: 'safari', - platform: 'OS X 10.12', - version: '10.1', - // This specific version is needed as otherwise it will not pass - // See: https://github.com/angular/angular-cli/issues/15084 - seleniumVersion: '3.4.0', - tunnelIdentifier, - }, - { - browserName: 'safari', - platform: 'macOS 10.13', - version: '11.1', - tunnelIdentifier, - }, - { - browserName: 'safari', - platform: 'macOS 10.13', - version: '12.1', - tunnelIdentifier, - }, - { - browserName: 'firefox', - version: '48', - tunnelIdentifier, - }, - { - browserName: 'firefox', - version: '60', - tunnelIdentifier, - }, - { - browserName: 'firefox', - version: '68', - tunnelIdentifier, - }, - { - browserName: 'internet explorer', - platform: 'Windows 8', - version: '10', - tunnelIdentifier, - }, - { - browserName: 'internet explorer', - platform: 'Windows 8.1', - version: '11', - tunnelIdentifier, - }, - { - browserName: "MicrosoftEdge", - platform: 'Windows 10', - version: "14.14393", - tunnelIdentifier, - }, - { - browserName: "MicrosoftEdge", - platform: 'Windows 10', - version: "17.17134", - tunnelIdentifier, - }, - { - browserName: "MicrosoftEdge", - platform: 'Windows 10', - version: "18.17763", - tunnelIdentifier, - }, - ], - - // Only allow one session at a time to prevent over saturation of Saucelabs sessions. - maxSessions: 1, - - baseUrl: 'http://localhost:2000/', - framework: 'jasmine', - jasmineNodeOpts: { - showColors: true, - defaultTimeoutInterval: 30000, - print: function() {}, - }, - - onPrepare() { - // Fix for Safari 12 -- https://github.com/angular/protractor/issues/4964 - browser.resetUrl = 'about:blank'; - - require('ts-node').register({ - project: require('path').join(__dirname, './tsconfig.json'), - }); - jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); - }, -}; diff --git a/tests/legacy-cli/e2e/assets/ssl/server.crt b/tests/legacy-cli/e2e/assets/ssl/server.crt deleted file mode 100644 index 6891c4c67573..000000000000 --- a/tests/legacy-cli/e2e/assets/ssl/server.crt +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID5jCCAs6gAwIBAgIJAJOebwfGCm61MA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAlVTMRAwDgYDVQQIEwdHZW9yZ2lhMRAwDgYDVQQHEwdBdGxhbnRhMRAwDgYD -VQQKEwdBbmd1bGFyMRAwDgYDVQQLEwdBbmd1bGFyMB4XDTE2MTAwNDAxMDAyMVoX -DTI2MTAwMjAxMDAyMVowVTELMAkGA1UEBhMCVVMxEDAOBgNVBAgTB0dlb3JnaWEx -EDAOBgNVBAcTB0F0bGFudGExEDAOBgNVBAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0Fu -Z3VsYXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDT6Q4d1+mw81SC -4K1qLbsMn4O459XDiDDU/cGBiE0byqi6RpaB0MujCPn35xdeCf1mdDw929leEIRB -w/fCN3VwE+4ZDM7sF6SgoSDN8YT/OOush4tDu0djH110I+i1Bfg4m7gVkUnJLUCv -vMMOlD19LDqqaxdY3ojXx8gZJW9sNtUH2vCICwsZ7aNZp2NcCNKpU7LppP4IomCd -GfG501kY/UtELVgNGX+zuJwIiH/2AQZ+fsaDBBD0Azanck2M/aq5yVKMG8y/S5WP -7LMvZs8ZHPSG73QINogRTYW0EKx7nT87vmrHRtCc9u4coPdqOzQN9BigCYVkYrTv -xkOX9VDHAgMBAAGjgbgwgbUwHQYDVR0OBBYEFG4VV6/aNLx/qFIS9MhAWuyeV5OX -MIGFBgNVHSMEfjB8gBRuFVev2jS8f6hSEvTIQFrsnleTl6FZpFcwVTELMAkGA1UE -BhMCVVMxEDAOBgNVBAgTB0dlb3JnaWExEDAOBgNVBAcTB0F0bGFudGExEDAOBgNV -BAoTB0FuZ3VsYXIxEDAOBgNVBAsTB0FuZ3VsYXKCCQCTnm8HxgputTAMBgNVHRME -BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDO4jZT/oKVxaiWr+jV5TD+qwThl9zT -Uw/ZpFDkdbZdY/baCFaLCiJwkK9+puMOabLvm1VzcnHHWCoiUNbWpw8AOumLEnTv -ze/5OZXJ6XlA9kd9f3hDlN5zNB3S+Z2nKIrkPGfxQZ603QCbWaptip5dxgek6oDZ -YXVtnbOnPznRsG5jh07U49RO8CNebqZLzdRToLgObbqYlfRMcbUxCOHXjnB5wUlp -377Iivm4ldnCTvFOjEiDh+FByWL5xic7PjyJPZFMidiYTmsGilP9XTFC83CRZwz7 -vW+RCSlU6x8Uejz98BPmASoqCuCTUeOo+2pFelFhX9NwR/Sb6b7ybdPv ------END CERTIFICATE----- diff --git a/tests/legacy-cli/e2e/assets/ssl/server.key b/tests/legacy-cli/e2e/assets/ssl/server.key deleted file mode 100644 index e0e0af0f8da8..000000000000 --- a/tests/legacy-cli/e2e/assets/ssl/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA0+kOHdfpsPNUguCtai27DJ+DuOfVw4gw1P3BgYhNG8qoukaW -gdDLowj59+cXXgn9ZnQ8PdvZXhCEQcP3wjd1cBPuGQzO7BekoKEgzfGE/zjrrIeL -Q7tHYx9ddCPotQX4OJu4FZFJyS1Ar7zDDpQ9fSw6qmsXWN6I18fIGSVvbDbVB9rw -iAsLGe2jWadjXAjSqVOy6aT+CKJgnRnxudNZGP1LRC1YDRl/s7icCIh/9gEGfn7G -gwQQ9AM2p3JNjP2quclSjBvMv0uVj+yzL2bPGRz0hu90CDaIEU2FtBCse50/O75q -x0bQnPbuHKD3ajs0DfQYoAmFZGK078ZDl/VQxwIDAQABAoIBAEl17kXcNo/4GqDw -QE2hoslCdwhfnhQVn1AG09ESriBnRcylccF4308aaoVM4CXicqzUuJl9IEJimWav -B7GVRinfTtfyP71KiPCCSvv5sPBFDDYYGugVAS9UjTIYzLAMbLs7CDq5zglmnZkO -Z9QjAZnl/kRbsZFGO8wJ3s0Q1Cp/ygZcvFU331K2jHXW7B4YXiFOH/lBQrjdz0Gy -WBjX4zIdNWnwarvxu46IS/0z1P1YOHM8+B1Uv54MG94A6szBdd/Vp0cQRs78t/Cu -BQ1Rnuk16Pi+ieC5K04yUgeuNusYW0PWLtPX1nKNp9z46bmD1NHKAxaoDFXr7qP3 -pZCaDMkCgYEA8mmTYrhXJTRIrOxoUwM1e3OZ0uOxVXJJ8HF6X8t+UO6dFxXB/JC9 -ZBc+94cZQapaKFOeMmd/j3L2CQIjChk5yKV/G3Io+raxIoAAKPCkMF4NQQVvvNkS -CAGl61Qa78DoF5Habumz0AC1R9P877kNTC0aPSt4lhPWgfotbZNNMlMCgYEA38nM -s4a0pZseXPkuOtPYX/3Ms3E+d70XKSFuIMCHCg79YGsQ8h/9apYcPyeYkpQ0a4gs -I3IUqMaXC2OyqWA5LU1BZv51mXb6zcb2pokZfpiSWk+7sy5XjkE9EmQxp3xHfV3c -EO/DxHfWNvtMjESMbhu0yVzM2O/Aa53Tl9lqAT0CgYEA1dXBuHyqCtyTG08zO78B -55Ny5rAJ1zkI9jvz2hr0o0nJcvqzcyruliNXXRxkcCNoglg4nXfk81JSrGGhLSBR -c6hhdoF+mqKboLZO7c5Q14WvpWK5TVoiaMOja/J2DHYbhecYS2yGPH7TargaUBDq -JP9IPRtitOhs+Z0Jg7ZDi5cCgYAMb7B6gY/kbBxh2k8hYchyfS41AqQQD2gMFxmB -pHFcs7yM8SY97l0s4S6sq8ykyKupFiYtyhcv0elu7pltJDXJOLPbv2RVpPEHInlu -g8vw5xWrAydRK9Adza5RKVRBFHz8kIy8PDbK4kX7RDfay6xqKgv/7LJNk/VDhb/O -fnyPmQKBgQDg/o8Ubf/gxA9Husnuld4DBu3wwFhkMlWqyO9QH3cKgojQ2JGSrfDz -xHhetmhionEyzg0JCaMSpzgIHY+8o/NAwc++OjNHEoYp3XWM9GTp81ROMz6b83jV -biVR9N0MhONdwF6vtzDCcJxNIUe2p4lTvLf/Xd9jaQDNXe35Gxsdyg== ------END RSA PRIVATE KEY----- diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/aotplugin.config.json b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/aotplugin.config.json deleted file mode 100644 index b6d2d7a7816d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/aotplugin.config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "tsConfigPath": "./not/so/source/tsconfig.json", - "mainPath": "app/main.jit.ts" -} \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.html b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.html deleted file mode 100644 index 3505c196ea74..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.html +++ /dev/null @@ -1,13 +0,0 @@ -
-

hello world

- lazy - -
- - -

DEBUG_ONLY

- - - -

PRODUCTION_ONLY

- diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.scss b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.scss deleted file mode 100644 index ba143f5d5da1..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.scss +++ /dev/null @@ -1,15 +0,0 @@ -:host { - background-color: blue; -} - -// @ifdef DEBUG -:host::before { - content: 'DEBUG_ONLY'; -} -// @endif - -// @ifndef DEBUG -:host::before { - content: 'PRODUCTION_ONLY'; -} -// @endif diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.ts deleted file mode 100644 index 09a19ad8f1ac..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.component.ts +++ /dev/null @@ -1,10 +0,0 @@ -import {Component, ViewEncapsulation} from '@angular/core'; - - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.scss'], - encapsulation: ViewEncapsulation.None -}) -export class AppComponent { } diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.module.ts deleted file mode 100644 index 2bcd6c4883bd..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/app.module.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { NgModule, Component } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { RouterModule } from '@angular/router'; -import { AppComponent } from './app.component'; - -@Component({ - selector: 'home-view', - template: 'home!' -}) -export class HomeView {} - - -// @ifdef DEBUG -console.log("DEBUG_ONLY"); -// @endif - -// @ifndef DEBUG -console.log("PRODUCTION_ONLY"); -// @endif - - -@NgModule({ - declarations: [ - AppComponent, - HomeView - ], - imports: [ - BrowserModule, - RouterModule.forRoot([ - {path: 'lazy', loadChildren: './lazy.module#LazyModule'}, - {path: '', component: HomeView} - ]) - ], - bootstrap: [AppComponent] -}) -export class AppModule { } diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/feature.module.ts deleted file mode 100644 index f464ca028b05..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/feature.module.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'feature-component', - template: 'foo.html' -}) -export class FeatureComponent {} - -@NgModule({ - declarations: [ - FeatureComponent - ], - imports: [ - RouterModule.forChild([ - { path: '', component: FeatureComponent} - ]) - ] -}) -export class FeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/lazy-feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/lazy-feature.module.ts deleted file mode 100644 index b7d72eab327b..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/feature/lazy-feature.module.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-feature-comp', - template: 'lazy feature!' -}) -export class LazyFeatureComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyFeatureComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature.module#FeatureModule'} - ]) - ], - declarations: [LazyFeatureComponent] -}) -export class LazyFeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/lazy.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/lazy.module.ts deleted file mode 100644 index 32c07594ac3d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/lazy.module.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-comp', - template: 'lazy!' -}) -export class LazyComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature/feature.module#FeatureModule'}, - {path: 'lazy-feature', loadChildren: './feature/lazy-feature.module#LazyFeatureModule'} - ]), - ], - declarations: [LazyComponent] -}) -export class LazyModule {} - -export class SecondModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/main.jit.ts b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/main.jit.ts deleted file mode 100644 index a2a7a6c6b76c..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/app/main.jit.ts +++ /dev/null @@ -1,5 +0,0 @@ -import 'core-js/proposals/reflect-metadata'; -import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; -import {AppModule} from './app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/index.html b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/index.html deleted file mode 100644 index 89fb0893c35d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - Document - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/tsconfig.json b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/tsconfig.json deleted file mode 100644 index 20c6851c877c..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/not/so/source/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "module": "es2015", - "moduleResolution": "node", - "target": "es5", - "noImplicitAny": false, - "sourceMap": true, - "mapRoot": "", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "lib": [ - "es2017", - "dom" - ], - "outDir": "lib", - "skipLibCheck": true, - "rootDir": "." - }, - "angularCompilerOptions": { - "enableIvy": true, - "disableTypeScriptVersionCheck": true - "genDir": "app/generated/", - "entryModule": "app/app.module#AppModule" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/package.json b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/package.json deleted file mode 100644 index 89f2612aecff..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test", - "license": "MIT", - "dependencies": { - "@angular/common": "9.0.0-next.11", - "@angular/compiler": "9.0.0-next.11", - "@angular/compiler-cli": "9.0.0-next.11", - "@angular/core": "9.0.0-next.11", - "@angular/platform-browser": "9.0.0-next.11", - "@angular/platform-browser-dynamic": "9.0.0-next.11", - "@angular/platform-server": "9.0.0-next.11", - "@angular/router": "9.0.0-next.11", - "@ngtools/webpack": "0.0.0", - "core-js": "^3.0.0", - "rxjs": "^6.4.2", - "zone.js": "^0.9.1" - }, - "devDependencies": { - "node-sass": "^4.7.0", - "performance-now": "^0.2.0", - "preprocess-loader": "^0.2.2", - "raw-loader": "^0.5.1", - "sass-loader": "^6.0.0", - "typescript": "~3.6.4", - "webpack": "~4.0.1", - "webpack-cli": "~2.0.9" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.config.js b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.config.js deleted file mode 100644 index cf5f4020dde2..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.config.js +++ /dev/null @@ -1,38 +0,0 @@ -const ngToolsWebpack = require('@ngtools/webpack'); -const path = require('path'); - -const flags = require('./webpack.flags.json'); - -const preprocessLoader = 'preprocess-loader' + (flags.DEBUG ? '?+DEBUG' : ''); - - -module.exports = { - resolve: { - extensions: ['.ts', '.js'] - }, - entry: './not/so/source/app/main.jit.ts', - output: { - path: path.resolve('./dist'), - publicPath: 'dist/', - filename: 'app.main.js' - }, - plugins: [ - new ngToolsWebpack.AngularCompilerPlugin(require('./aotplugin.config.json')) - ], - module: { - rules: [ - { test: /\.scss$/, loaders: ['raw-loader', 'sass-loader', preprocessLoader] }, - { test: /\.css$/, loader: 'raw-loader' }, - { test: /\.html$/, loaders: ['raw-loader', preprocessLoader] }, - // Use preprocess to remove DEBUG only code. - // @ngtools/webpack must be the first (right most) loader. - { test: /\.ts$/, use: [ - { loader: preprocessLoader }, - { loader: '@ngtools/webpack' } - ] } - ] - }, - devServer: { - historyApiFallback: true - } -}; diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.flags.json b/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.flags.json deleted file mode 100644 index aac05f738dc8..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app-weird/webpack.flags.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "DEBUG": false -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.html b/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.html deleted file mode 100644 index 5a532db9308f..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.html +++ /dev/null @@ -1,5 +0,0 @@ -
-

hello world

- lazy - -
diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.scss b/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.scss deleted file mode 100644 index 5cde7b922336..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.scss +++ /dev/null @@ -1,3 +0,0 @@ -:host { - background-color: blue; -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.ts deleted file mode 100644 index 82a4059565d3..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.component.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {Component, ViewEncapsulation} from '@angular/core'; -import {MyInjectable} from './injectable'; - - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.scss'], - encapsulation: ViewEncapsulation.None -}) -export class AppComponent { - constructor(public inj: MyInjectable) { - console.log(inj); - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.module.ts deleted file mode 100644 index ded686868a22..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/app.module.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { NgModule, Component } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { RouterModule } from '@angular/router'; -import { AppComponent } from './app.component'; - -@Component({ - selector: 'home-view', - template: 'home!' -}) -export class HomeView {} - - -@NgModule({ - declarations: [ - AppComponent, - HomeView - ], - imports: [ - BrowserModule, - RouterModule.forRoot([ - {path: 'lazy', loadChildren: './lazy.module#LazyModule'}, - {path: '', component: HomeView} - ]) - ], - bootstrap: [AppComponent] -}) -export class AppModule { } diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/feature.module.ts deleted file mode 100644 index f464ca028b05..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/feature.module.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'feature-component', - template: 'foo.html' -}) -export class FeatureComponent {} - -@NgModule({ - declarations: [ - FeatureComponent - ], - imports: [ - RouterModule.forChild([ - { path: '', component: FeatureComponent} - ]) - ] -}) -export class FeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/lazy-feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/lazy-feature.module.ts deleted file mode 100644 index b7d72eab327b..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/feature/lazy-feature.module.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-feature-comp', - template: 'lazy feature!' -}) -export class LazyFeatureComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyFeatureComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature.module#FeatureModule'} - ]) - ], - declarations: [LazyFeatureComponent] -}) -export class LazyFeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/injectable.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/injectable.ts deleted file mode 100644 index feb7ab0b76a8..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/injectable.ts +++ /dev/null @@ -1,8 +0,0 @@ -import {Injectable, Inject, ViewContainerRef} from '@angular/core'; -import {DOCUMENT} from '@angular/common'; - - -@Injectable() -export class MyInjectable { - constructor(public viewContainer: ViewContainerRef, @Inject(DOCUMENT) public doc) {} -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/lazy.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/lazy.module.ts deleted file mode 100644 index 32c07594ac3d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/lazy.module.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-comp', - template: 'lazy!' -}) -export class LazyComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature/feature.module#FeatureModule'}, - {path: 'lazy-feature', loadChildren: './feature/lazy-feature.module#LazyFeatureModule'} - ]), - ], - declarations: [LazyComponent] -}) -export class LazyModule {} - -export class SecondModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/app/main.ts b/tests/legacy-cli/e2e/assets/webpack/test-app/app/main.ts deleted file mode 100644 index a2a7a6c6b76c..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/app/main.ts +++ /dev/null @@ -1,5 +0,0 @@ -import 'core-js/proposals/reflect-metadata'; -import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; -import {AppModule} from './app.module'; - -platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/index.html b/tests/legacy-cli/e2e/assets/webpack/test-app/index.html deleted file mode 100644 index 89fb0893c35d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - Document - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/package.json b/tests/legacy-cli/e2e/assets/webpack/test-app/package.json deleted file mode 100644 index b068a17fd97e..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "test", - "license": "MIT", - "dependencies": { - "@angular/common": "9.0.0-next.11", - "@angular/compiler": "9.0.0-next.11", - "@angular/compiler-cli": "9.0.0-next.11", - "@angular/core": "9.0.0-next.11", - "@angular/platform-browser": "9.0.0-next.11", - "@angular/platform-browser-dynamic": "9.0.0-next.11", - "@angular/platform-server": "9.0.0-next.11", - "@angular/router": "9.0.0-next.11", - "@ngtools/webpack": "0.0.0", - "core-js": "^3.0.0", - "rxjs": "^6.4.0", - "zone.js": "^0.9.1" - }, - "devDependencies": { - "node-sass": "^4.7.0", - "performance-now": "^0.2.0", - "raw-loader": "^0.5.1", - "sass-loader": "^6.0.0", - "typescript": "~3.6.4", - "webpack": "~4.0.1", - "webpack-cli": "~2.0.9" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/tsconfig.json b/tests/legacy-cli/e2e/assets/webpack/test-app/tsconfig.json deleted file mode 100644 index 7a47bfc4b3ac..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "baseUrl": "", - "module": "es2015", - "moduleResolution": "node", - "target": "es5", - "noImplicitAny": false, - "sourceMap": true, - "mapRoot": "", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "lib": [ - "es2017", - "dom" - ], - "outDir": "lib", - "skipLibCheck": true, - "rootDir": "." - }, - "angularCompilerOptions": { - "enableIvy": true, - "disableTypeScriptVersionCheck": true, - "genDir": "./app/ngfactory", - "entryModule": "app/app.module#AppModule" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-app/webpack.config.js b/tests/legacy-cli/e2e/assets/webpack/test-app/webpack.config.js deleted file mode 100644 index 2e6f55628a10..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-app/webpack.config.js +++ /dev/null @@ -1,30 +0,0 @@ -const ngToolsWebpack = require('@ngtools/webpack'); -const path = require('path'); - -module.exports = { - resolve: { - extensions: ['.ts', '.js'] - }, - entry: './app/main.ts', - output: { - path: path.resolve('./dist'), - publicPath: 'dist/', - filename: 'app.main.js' - }, - plugins: [ - new ngToolsWebpack.AngularCompilerPlugin({ - tsConfigPath: './tsconfig.json' - }) - ], - module: { - rules: [ - { test: /\.scss$/, loaders: ['raw-loader', 'sass-loader'] }, - { test: /\.css$/, loader: 'raw-loader' }, - { test: /\.html$/, loader: 'raw-loader' }, - { test: /\.ts$/, loader: '@ngtools/webpack' } - ] - }, - devServer: { - historyApiFallback: true - } -}; diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.html b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.html deleted file mode 100644 index 5a532db9308f..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.html +++ /dev/null @@ -1,5 +0,0 @@ -
-

hello world

- lazy - -
diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.scss b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.scss deleted file mode 100644 index 5cde7b922336..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.scss +++ /dev/null @@ -1,3 +0,0 @@ -:host { - background-color: blue; -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.ts deleted file mode 100644 index 82a4059565d3..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.component.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {Component, ViewEncapsulation} from '@angular/core'; -import {MyInjectable} from './injectable'; - - -@Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.scss'], - encapsulation: ViewEncapsulation.None -}) -export class AppComponent { - constructor(public inj: MyInjectable) { - console.log(inj); - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.module.ts deleted file mode 100644 index 7c8a0c296448..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/app.module.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { NgModule, Component } from '@angular/core'; -import { ServerModule } from '@angular/platform-server'; -import { BrowserModule } from '@angular/platform-browser'; -import { RouterModule } from '@angular/router'; - -import { AppComponent } from './app.component'; -import { MyInjectable } from './injectable'; - -@Component({ - selector: 'home-view', - template: 'home!' -}) -export class HomeView {} - - -@NgModule({ - declarations: [ - AppComponent, - HomeView - ], - imports: [ - BrowserModule.withServerTransition({ - appId: 'app' - }), - ServerModule, - RouterModule.forRoot([ - {path: 'lazy', loadChildren: './lazy.module#LazyModule'}, - {path: '', component: HomeView} - ]) - ], - providers: [MyInjectable], - bootstrap: [AppComponent] -}) -export class AppModule { - static testProp: string; -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/feature.module.ts deleted file mode 100644 index f464ca028b05..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/feature.module.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'feature-component', - template: 'foo.html' -}) -export class FeatureComponent {} - -@NgModule({ - declarations: [ - FeatureComponent - ], - imports: [ - RouterModule.forChild([ - { path: '', component: FeatureComponent} - ]) - ] -}) -export class FeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/lazy-feature.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/lazy-feature.module.ts deleted file mode 100644 index b7d72eab327b..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/feature/lazy-feature.module.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-feature-comp', - template: 'lazy feature!' -}) -export class LazyFeatureComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyFeatureComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature.module#FeatureModule'} - ]) - ], - declarations: [LazyFeatureComponent] -}) -export class LazyFeatureModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/injectable.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/injectable.ts deleted file mode 100644 index 3ed533966fe7..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/injectable.ts +++ /dev/null @@ -1,8 +0,0 @@ -import {Injectable, Inject} from '@angular/core'; -import {DOCUMENT} from '@angular/common'; - - -@Injectable() -export class MyInjectable { - constructor(@Inject(DOCUMENT) public doc) {} -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/lazy.module.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/lazy.module.ts deleted file mode 100644 index 7430b634ec68..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/lazy.module.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {NgModule, Component} from '@angular/core'; -import {RouterModule} from '@angular/router'; - -@Component({ - selector: 'lazy-comp', - template: 'lazy!' -}) -export class LazyComponent {} - -@NgModule({ - imports: [ - RouterModule.forChild([ - {path: '', component: LazyComponent, pathMatch: 'full'}, - {path: 'feature', loadChildren: './feature/feature.module#FeatureModule'}, - {path: 'lazy-feature', loadChildren: './feature/lazy-feature.module#LazyFeatureModule'} - ]) - ], - declarations: [LazyComponent] -}) -export class LazyModule {} - -export class SecondModule {} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.commonjs.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.commonjs.ts deleted file mode 100644 index ce26d93a11de..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.commonjs.ts +++ /dev/null @@ -1 +0,0 @@ -export { AppModule } from './app.module'; diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.ts b/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.ts deleted file mode 100644 index 647681b8b76c..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/app/main.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'core-js/proposals/reflect-metadata'; -import {platformDynamicServer, renderModule} from '@angular/platform-server'; -import {AppModule} from './app.module'; - -AppModule.testProp = 'testing'; - -platformDynamicServer().bootstrapModule(AppModule); - -renderModule(AppModule, { - document: '', - url: '/' -}); diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.html b/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.html deleted file mode 100644 index 89fb0893c35d..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - Document - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.js b/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.js deleted file mode 100644 index bdfb2e792acd..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/index.js +++ /dev/null @@ -1,12 +0,0 @@ -const fs = require('fs'); -const { AppModuleNgFactory } = require('./dist/app.main'); -const { renderModuleFactory } = require('@angular/platform-server'); - -require('zone.js/dist/zone-node'); - -renderModuleFactory(AppModuleNgFactory, { - url: '/', - document: '' -}).then(html => { - fs.writeFileSync('dist/index.html', html); -}) diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/package.json b/tests/legacy-cli/e2e/assets/webpack/test-server-app/package.json deleted file mode 100644 index 31096c2551f6..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "test", - "license": "MIT", - "dependencies": { - "@angular/animations": "9.0.0-next.11", - "@angular/common": "9.0.0-next.11", - "@angular/compiler": "9.0.0-next.11", - "@angular/compiler-cli": "9.0.0-next.11", - "@angular/core": "9.0.0-next.11", - "@angular/platform-browser": "9.0.0-next.11", - "@angular/platform-browser-dynamic": "9.0.0-next.11", - "@angular/platform-server": "9.0.0-next.11", - "@angular/router": "9.0.0-next.11", - "@ngtools/webpack": "0.0.0", - "core-js": "^3.0.0", - "rxjs": "^6.4.2", - "zone.js": "^0.9.1" - }, - "devDependencies": { - "node-sass": "^4.5.0", - "performance-now": "^0.2.0", - "raw-loader": "^0.5.1", - "sass-loader": "^6.0.3", - "typescript": "~3.6.4", - "webpack": "~4.0.1", - "webpack-cli": "~2.0.9" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/tsconfig.json b/tests/legacy-cli/e2e/assets/webpack/test-server-app/tsconfig.json deleted file mode 100644 index 5e63e01f6871..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "baseUrl": "", - "module": "es2015", - "moduleResolution": "node", - "target": "es5", - "noImplicitAny": false, - "sourceMap": true, - "mapRoot": "", - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "lib": [ - "es2017", - "dom" - ], - "outDir": "lib", - "skipLibCheck": true, - "rootDir": "." - }, - "angularCompilerOptions": { - "enableIvy": false, - "disableTypeScriptVersionCheck": true, - "genDir": "./app/ngfactory", - "entryModule": "app/app.module#AppModule" - } -} diff --git a/tests/legacy-cli/e2e/assets/webpack/test-server-app/webpack.config.js b/tests/legacy-cli/e2e/assets/webpack/test-server-app/webpack.config.js deleted file mode 100644 index 2905841b3e54..000000000000 --- a/tests/legacy-cli/e2e/assets/webpack/test-server-app/webpack.config.js +++ /dev/null @@ -1,33 +0,0 @@ -const { AngularCompilerPlugin, PLATFORM } = require('@ngtools/webpack'); -const path = require('path'); - -module.exports = { - resolve: { - extensions: ['.ts', '.js'] - }, - target: 'web', - entry: './app/main.ts', - output: { - path: path.resolve('./dist'), - publicPath: 'dist/', - filename: 'app.main.js' - }, - plugins: [ - new AngularCompilerPlugin({ - tsConfigPath: './tsconfig.json', - mainPath: './app/main.ts', - platform: PLATFORM.Server - }) - ], - module: { - rules: [ - { test: /\.scss$/, loaders: ['raw-loader', 'sass-loader'] }, - { test: /\.css$/, loader: 'raw-loader' }, - { test: /\.html$/, loader: 'raw-loader' }, - { test: /\.ts$/, loader: '@ngtools/webpack' } - ] - }, - devServer: { - historyApiFallback: true - } -}; diff --git a/tests/legacy-cli/e2e/ng-snapshot/package.json b/tests/legacy-cli/e2e/ng-snapshot/package.json deleted file mode 100644 index 380098e3a6f5..000000000000 --- a/tests/legacy-cli/e2e/ng-snapshot/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "description": "snapshot versions of Angular for e2e testing", - "private": true, - "dependencies": { - "@angular/animations": "github:angular/animations-builds#338727806489e5374a16afef4027166b6630659e", - "@angular/common": "github:angular/common-builds#66fd80621caf1bbc7d18a9759c2672b44e509acd", - "@angular/compiler": "github:angular/compiler-builds#249e7763935274b648dbc71e4e1cc3d96f96128d", - "@angular/compiler-cli": "github:angular/compiler-cli-builds#fde8a961ea3cad28d3e56305e814f7b0d08cfad5", - "@angular/core": "github:angular/core-builds#4a2961f1a93b13545af867904dbf2255027eeccc", - "@angular/forms": "github:angular/forms-builds#4324856f759ee981e2d5c93a769d27646b591d84", - "@angular/language-service": "github:angular/language-service-builds#7d3c3e695aee97faf831f61da0f42060eaa467ce", - "@angular/localize": "github:angular/localize-builds#cc78a279c32321493970f7325bc07692ecbe8ccb", - "@angular/platform-browser": "github:angular/platform-browser-builds#b246c530bad51af938664e54695a70975f1e44f5", - "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#dbc34707b897ec15d18e51c7004684d3ef1f5b6f", - "@angular/platform-server": "github:angular/platform-server-builds#47cc3d46eec48622dd59c9dff36207c38cb927d4", - "@angular/router": "github:angular/router-builds#3e3f8d0e93222c32efebf80148abc5b6210faac3" - } -} \ No newline at end of file diff --git a/tests/legacy-cli/e2e/setup/010-local-publish.ts b/tests/legacy-cli/e2e/setup/010-local-publish.ts deleted file mode 100644 index ad25029fdedd..000000000000 --- a/tests/legacy-cli/e2e/setup/010-local-publish.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { prerelease } from 'semver'; -import { packages } from '../../../../lib/packages'; -import { npm } from '../utils/process'; - -export default async function() { - const publishArgs = [ - 'run', - 'admin', - '--', - 'publish', - '--versionCheck=false', - '--branchCheck=false', - '--registry=http://localhost:4873', - ]; - - const pre = prerelease(packages['@angular/cli'].version); - if (pre && pre.length > 0) { - publishArgs.push('--tag', 'next'); - } - - await npm(...publishArgs); -} diff --git a/tests/legacy-cli/e2e/setup/100-global-cli.ts b/tests/legacy-cli/e2e/setup/100-global-cli.ts deleted file mode 100644 index 21ed8749789c..000000000000 --- a/tests/legacy-cli/e2e/setup/100-global-cli.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { getGlobalVariable } from '../utils/env'; -import { exec, silentNpm } from '../utils/process'; - -export default async function() { - const argv = getGlobalVariable('argv'); - if (argv.noglobal) { - return; - } - - // Install global Angular CLI. - await silentNpm( - 'install', - '--global', - '@angular/cli', - '--registry=http://localhost:4873', - ); - - try { - await exec(process.platform.startsWith('win') ? 'where' : 'which', 'ng'); - } catch {} -} diff --git a/tests/legacy-cli/e2e/setup/200-create-tmp-dir.ts b/tests/legacy-cli/e2e/setup/200-create-tmp-dir.ts deleted file mode 100644 index ae4b16ebec6d..000000000000 --- a/tests/legacy-cli/e2e/setup/200-create-tmp-dir.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { mkdtempSync, realpathSync } from 'fs'; -import { tmpdir } from 'os'; -import { dirname, join } from 'path'; -import { getGlobalVariable, setGlobalVariable } from '../utils/env'; - -export default function() { - const argv = getGlobalVariable('argv'); - - // Get to a temporary directory. - let tempRoot: string; - if (argv.reuse) { - tempRoot = dirname(argv.reuse); - } else if (argv.tmpdir) { - tempRoot = argv.tmpdir; - } else { - tempRoot = mkdtempSync(join(realpathSync(tmpdir()), 'angular-cli-e2e-')); - } - console.log(` Using "${tempRoot}" as temporary directory for a new project.`); - setGlobalVariable('tmp-root', tempRoot); - process.chdir(tempRoot); -} diff --git a/tests/legacy-cli/e2e/setup/300-log-environment.ts b/tests/legacy-cli/e2e/setup/300-log-environment.ts deleted file mode 100644 index ab60477ba4ca..000000000000 --- a/tests/legacy-cli/e2e/setup/300-log-environment.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ng, node, npm } from '../utils/process'; - -export default async function() { - console.log('Environment:'); - - Object.keys(process.env).forEach(envName => { - // CI Logs should not contain environment variables that are considered secret - const lowerName = envName.toLowerCase(); - if (lowerName.includes('key') || lowerName.includes('secret')) { - return; - } - - console.log(` ${envName}: ${process.env[envName].replace(/[\n\r]+/g, '\n ')}`); - }); - - await node('--version'); - await npm('--version'); - await ng('version'); -} diff --git a/tests/legacy-cli/e2e/setup/500-create-project.ts b/tests/legacy-cli/e2e/setup/500-create-project.ts deleted file mode 100644 index 43bb0c8b9015..000000000000 --- a/tests/legacy-cli/e2e/setup/500-create-project.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { join } from 'path'; -import { getGlobalVariable } from '../utils/env'; -import { expectFileToExist } from '../utils/fs'; -import { gitClean } from '../utils/git'; -import { ng } from '../utils/process'; -import { prepareProjectForE2e, updateJsonFile } from '../utils/project'; - -export default async function() { - const argv = getGlobalVariable('argv'); - - if (argv.noproject) { - return; - } - - if (argv.reuse) { - process.chdir(argv.reuse); - await gitClean(); - } else { - const extraArgs = []; - - await ng('new', 'test-project', '--skip-install', ...extraArgs); - await expectFileToExist(join(process.cwd(), 'test-project')); - process.chdir('./test-project'); - - if (argv['ve']) { - await updateJsonFile('tsconfig.json', config => { - config.angularCompilerOptions.enableIvy = false; - }); - - // In VE non prod builds are non AOT by default - await updateJsonFile('angular.json', config => { - const build = config.projects['test-project'].architect.build; - build.options.aot = false; - build.configurations.production.aot = true; - }); - } - } - - await prepareProjectForE2e('test-project'); - await ng('version'); -} diff --git a/tests/legacy-cli/e2e/tests/basic/aot.ts b/tests/legacy-cli/e2e/tests/basic/aot.ts deleted file mode 100644 index a4dd67d5018d..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/aot.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function () { - await ng('build', '--aot=true'); - - if (getGlobalVariable('argv')['ve']) { - await expectFileToMatch('dist/test-project/main-es5.js', - /platformBrowser.*bootstrapModuleFactory.*AppModuleNgFactory/); - await expectFileToMatch('dist/test-project/main-es2015.js', - /platformBrowser.*bootstrapModuleFactory.*AppModuleNgFactory/); - } else { - await expectFileToMatch('dist/test-project/main-es5.js', - /platformBrowser.*bootstrapModule.*AppModule/); - await expectFileToMatch('dist/test-project/main-es2015.js', - /platformBrowser.*bootstrapModule.*AppModule/); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/build.ts b/tests/legacy-cli/e2e/tests/basic/build.ts deleted file mode 100644 index 119e1b2c5c4a..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/build.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function() { - // Development build - await ng('build'); - await expectFileToMatch('dist/test-project/index.html', 'main-es5.js'); - await expectFileToMatch('dist/test-project/index.html', 'main-es2015.js'); - - // Named Development build - await ng('build', 'test-project'); - await ng('build', 'test-project', '--no-progress'); - await ng('build', '--no-progress', 'test-project'); - - // Production build - await ng('build', '--prod'); - await expectFileToMatch('dist/test-project/index.html', /main-es2015\.[a-zA-Z0-9]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es5\.[a-zA-Z0-9]{20}\.js/); - await ng('build', '--prod', '--no-progress', 'test-project'); -} diff --git a/tests/legacy-cli/e2e/tests/basic/e2e.ts b/tests/legacy-cli/e2e/tests/basic/e2e.ts deleted file mode 100644 index c3c7db2d6c49..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/e2e.ts +++ /dev/null @@ -1,75 +0,0 @@ -// TODO(architect): edit the architect config instead of the cli config. - -import { - ng, - npm, - execAndWaitForOutputToMatch, - killAllProcesses -} from '../../utils/process'; -import {updateJsonFile} from '../../utils/project'; -import {expectToFail} from '../../utils/utils'; -import {moveFile, copyFile, replaceInFile} from '../../utils/fs'; - -export default function () { - // Should fail without updated webdriver - return updateJsonFile('package.json', packageJson => { - // Add to npm scripts to make running the binary compatible with Windows - const scripts = packageJson['scripts']; - scripts['wd:clean'] = 'webdriver-manager clean'; - }) - .then(() => npm('run', 'wd:clean')) - .then(() => expectToFail(() => ng('e2e', 'test-project', '--no-webdriver-update', '--devServerTarget='))) - // Add back the pre-defined version of webdriver. This script is defined when making projects. - .then(() => npm('run', 'webdriver-update')) - // Should fail without serving - .then(() => expectToFail(() => ng('e2e', 'test-project', '--devServerTarget='))) - // These should work. - .then(() => ng('e2e', 'test-project')) - .then(() => ng('e2e', 'test-project', '--devServerTarget=test-project:serve:production')) - // Should accept different config file - .then(() => moveFile('./e2e/protractor.conf.js', - './e2e/renamed-protractor.conf.js')) - .then(() => ng('e2e', 'test-project', - '--protractorConfig=e2e/renamed-protractor.conf.js')) - .then(() => moveFile('./e2e/renamed-protractor.conf.js', './e2e/protractor.conf.js')) - // Should accept different multiple spec files - .then(() => moveFile('./e2e/src/app.e2e-spec.ts', - './e2e/src/renamed-app.e2e-spec.ts')) - .then(() => copyFile('./e2e/src/renamed-app.e2e-spec.ts', - './e2e/src/another-app.e2e-spec.ts')) - .then(() => ng('e2e', 'test-project', '--specs', './e2e/renamed-app.e2e-spec.ts', - '--specs', './e2e/another-app.e2e-spec.ts')) - // Rename the spec back to how it was. - .then(() => moveFile('./e2e/src/renamed-app.e2e-spec.ts', - './e2e/src/app.e2e-spec.ts')) - // Suites block need to be added in the protractor.conf.js file to test suites - .then(() => replaceInFile('e2e/protractor.conf.js', `allScriptsTimeout: 11000,`, - `allScriptsTimeout: 11000, - suites: { - app: './e2e/src/app.e2e-spec.ts' - }, - `)) - .then(() => ng('e2e', 'test-project', '--suite=app')) - // Remove suites block from protractor.conf.js file after testing suites - .then(() => replaceInFile('e2e/protractor.conf.js', `allScriptsTimeout: 11000, - suites: { - app: './e2e/src/app.e2e-spec.ts' - }, - `, `allScriptsTimeout: 11000,` - )) - // Should start up Element Explorer - .then(() => execAndWaitForOutputToMatch('ng', ['e2e', 'test-project', '--element-explorer'], - /Element Explorer/)) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }) - // Should run side-by-side with `ng serve` - .then(() => execAndWaitForOutputToMatch('ng', ['serve'], - /: Compiled successfully./)) - .then(() => ng('e2e', 'test-project', '--devServerTarget=')) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }); -} diff --git a/tests/legacy-cli/e2e/tests/basic/in-project-logic.ts b/tests/legacy-cli/e2e/tests/basic/in-project-logic.ts deleted file mode 100644 index 5bf34c937a61..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/in-project-logic.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as os from 'os'; -import { join } from 'path'; -import { writeFile, deleteFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - - -export default function() { - const homedir = os.homedir(); - const globalConfigPath = join(homedir, '.angular-config.json'); - return Promise.resolve() - .then(() => writeFile(globalConfigPath, '{"version":1}')) - .then(() => process.chdir(homedir)) - .then(() => ng('new', 'proj-name', '--dry-run')) - .then(() => deleteFile(globalConfigPath)) - // Test that we cannot create a project inside another project. - .then(() => writeFile(join(homedir, '.angular.json'), '{"version":1}')) - .then(() => expectToFail(() => ng('new', 'proj-name', '--dry-run'))) - .then(() => deleteFile(join(homedir, '.angular.json'))); -} diff --git a/tests/legacy-cli/e2e/tests/basic/ivy-opt-out.ts b/tests/legacy-cli/e2e/tests/basic/ivy-opt-out.ts deleted file mode 100644 index aad19225ce3b..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/ivy-opt-out.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { getGlobalVariable } from '../../utils/env'; -import { request } from '../../utils/http'; -import { killAllProcesses, ng } from '../../utils/process'; -import { ngServe, updateJsonFile } from '../../utils/project'; - -export default async function() { - if (getGlobalVariable('argv')['ve']) { - // Don't run this test for VE jobs. It only applies to Ivy. - return; - } - - try { - // trigger an Ivy builds to process packages with NGCC - await ng('e2e', '--prod'); - - // View Engine (NGC) compilation should work after running NGCC from Webpack - await updateJsonFile('tsconfig.json', config => { - config.angularCompilerOptions.enableIvy = false; - }); - - // verify that VE compilation works during runtime - await ng('e2e', '--prod'); - - // verify that it is not Ivy - await ngServe('--prod'); - // Verify the index.html - const body = await request('http://localhost:4200/'); - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - - // Verify it's compiled with NGC - const mainUrlMatch = body.match(/src="(main\.[a-z0-9]{0,32}\.js)"/); - const mainUrl = mainUrlMatch && mainUrlMatch[1]; - const main = await request('http://localhost:4200/' + mainUrl); - - if (main.match(/ɵcmp\s*=/)) { - throw new Error('Loaded Ivy but expected View Engine applicatiom.'); - } - - } finally { - await killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/ivy.ts b/tests/legacy-cli/e2e/tests/basic/ivy.ts deleted file mode 100644 index 80bb9fff78f0..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/ivy.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { getGlobalVariable } from '../../utils/env'; -import { expectFileToExist, replaceInFile } from '../../utils/fs'; -import { request } from '../../utils/http'; -import { killAllProcesses, ng } from '../../utils/process'; -import { ngServe } from '../../utils/project'; - -export default async function() { - if (getGlobalVariable('argv')['ve']) { - // Don't run this test for VE jobs. It only applies to Ivy. - return; - } - - try { - // Add in a reference to a secondary entry-point to check that ngcc processes it correctly - await replaceInFile( - 'src/app/app.module.ts', - `import { AppComponent } from './app.component';`, - `import { AppComponent } from './app.component';\nimport { HttpClientModule } from '@angular/common/http';`, - ); - await replaceInFile('src/app/app.module.ts', `imports: [`, `imports: [\n HttpClientModule,`); - - await ngServe('--prod'); - - // Check that @angular/common/http was processed by ngcc - await expectFileToExist('node_modules/@angular/common/http/http.d.ts.__ivy_ngcc_bak'); - - // Verify the index.html - const body = await request('http://localhost:4200/'); - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - - // Verify it's Ivy. - const mainUrlMatch = body.match(/src="(main\.[a-z0-9]{0,32}\.js)"/); - const mainUrl = mainUrlMatch && mainUrlMatch[1]; - const main = await request('http://localhost:4200/' + mainUrl); - - if (!main.match(/ɵcmp\s*=/)) { - throw new Error('Ivy could not be found.'); - } - if (main.match(/ngDevMode/)) { - throw new Error('NgDevMode was not tree shaken away.'); - } - } finally { - killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/ngcc-es2015-only.ts b/tests/legacy-cli/e2e/tests/basic/ngcc-es2015-only.ts deleted file mode 100644 index fb6996319467..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/ngcc-es2015-only.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { getGlobalVariable } from '../../utils/env'; -import { ng } from '../../utils/process'; - -export default async function() { - if (getGlobalVariable('argv')['ve']) { - // Don't run this test for VE jobs. It only applies to Ivy. - return; - } - const { stderr, stdout } = await ng('build', '--prod'); - - if (stdout.includes('as esm5') || stderr.includes('as esm5')) { - throw new Error('ngcc should not process ES5 during differential loading builds.'); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/rebuild.ts b/tests/legacy-cli/e2e/tests/basic/rebuild.ts deleted file mode 100644 index 30410249760b..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/rebuild.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { - killAllProcesses, - waitForAnyProcessOutputToMatch, - execAndWaitForOutputToMatch, - ng, -} from '../../utils/process'; -import {writeFile, writeMultipleFiles} from '../../utils/fs'; -import {wait} from '../../utils/utils'; -import {request} from '../../utils/http'; - -const validBundleRegEx = /: Compiled successfully./; - -export default function() { - return execAndWaitForOutputToMatch('ng', ['serve'], validBundleRegEx) - // Add a lazy module. - .then(() => ng('generate', 'module', 'lazy', '--routing')) - // Should trigger a rebuild with a new bundle. - // We need to use Promise.all to ensure we are waiting for the rebuild just before we write - // the file, otherwise rebuilds can be too fast and fail CI. - .then(() => Promise.all([ - waitForAnyProcessOutputToMatch(validBundleRegEx, 20000), - writeFile('src/app/app.module.ts', ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - import { FormsModule } from '@angular/forms'; - import { HttpClientModule } from '@angular/common/http'; - - import { AppComponent } from './app.component'; - import { RouterModule } from '@angular/router'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - FormsModule, - HttpClientModule, - RouterModule.forRoot([ - { path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) } - ]) - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - `) - ])) - // Count the bundles. - .then((results) => { - const stdout = results[0].stdout; - if (!/(lazy-module|0)\.js/g.test(stdout)) { - throw new Error('Expected webpack to create a new chunk, but did not.'); - } - }) - // Change multiple files and check that all of them are invalidated and recompiled. - .then(() => Promise.all([ - waitForAnyProcessOutputToMatch(validBundleRegEx, 20000), - writeMultipleFiles({ - 'src/app/app.module.ts': ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - - console.log('$$_E2E_GOLDEN_VALUE_1'); - export let X = '$$_E2E_GOLDEN_VALUE_2'; - `, - 'src/main.ts': ` - import { enableProdMode } from '@angular/core'; - import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } - - platformBrowserDynamic().bootstrapModule(AppModule); - - import * as m from './app/app.module'; - console.log(m.X); - console.log('$$_E2E_GOLDEN_VALUE_3'); - ` - }) - ])) - .then(() => wait(2000)) - .then(() => request('http://localhost:4200/main.js')) - .then((body) => { - if (!body.match(/\$\$_E2E_GOLDEN_VALUE_1/)) { - throw new Error('Expected golden value 1.'); - } - if (!body.match(/\$\$_E2E_GOLDEN_VALUE_2/)) { - throw new Error('Expected golden value 2.'); - } - if (!body.match(/\$\$_E2E_GOLDEN_VALUE_3/)) { - throw new Error('Expected golden value 3.'); - } - }) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }); -} diff --git a/tests/legacy-cli/e2e/tests/basic/scripts-array.ts b/tests/legacy-cli/e2e/tests/basic/scripts-array.ts deleted file mode 100644 index fd7f869b6cc9..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/scripts-array.ts +++ /dev/null @@ -1,92 +0,0 @@ -// TODO(architect): edit the architect config instead of the cli config. - -import { oneLineTrim } from 'common-tags'; -import { appendToFile, expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - await writeMultipleFiles({ - 'src/string-script.js': "console.log('string-script'); var number = 1+1;", - 'src/zstring-script.js': "console.log('zstring-script');", - 'src/fstring-script.js': "console.log('fstring-script');", - 'src/ustring-script.js': "console.log('ustring-script');", - 'src/bstring-script.js': "console.log('bstring-script');", - 'src/astring-script.js': "console.log('astring-script');", - 'src/cstring-script.js': "console.log('cstring-script');", - 'src/input-script.js': "console.log('input-script');", - 'src/lazy-script.js': "console.log('lazy-script');", - 'src/pre-rename-script.js': "console.log('pre-rename-script');", - 'src/pre-rename-lazy-script.js': "console.log('pre-rename-lazy-script');", - }); - - await appendToFile('src/main.ts', "import './string-script.js';"); - - await updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.build.options.scripts = [ - { input: 'src/string-script.js' }, - { input: 'src/zstring-script.js' }, - { input: 'src/fstring-script.js' }, - { input: 'src/ustring-script.js' }, - { input: 'src/bstring-script.js' }, - { input: 'src/astring-script.js' }, - { input: 'src/cstring-script.js' }, - { input: 'src/input-script.js' }, - { input: 'src/lazy-script.js', inject: false }, - { input: 'src/pre-rename-script.js', bundleName: 'renamed-script' }, - { - input: 'src/pre-rename-lazy-script.js', - bundleName: 'renamed-lazy-script', - inject: false, - }, - ]; - }); - - await ng('build', '--extract-css'); - - // files were created successfully - await expectFileToMatch('dist/test-project/scripts.js', 'string-script'); - await expectFileToMatch('dist/test-project/scripts.js', 'input-script'); - await expectFileToMatch('dist/test-project/lazy-script.js', 'lazy-script'); - await expectFileToMatch('dist/test-project/renamed-script.js', 'pre-rename-script'); - await expectFileToMatch('dist/test-project/renamed-lazy-script.js', 'pre-rename-lazy-script'); - - // index.html lists the right bundles - if (process.env['NG_BUILD_DIFFERENTIAL_FULL']) { - await expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - - - - - - - - - `, - ); - } else { - await expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - - - - - - - - - `, - ); - } - // Ensure scripts can be separately imported from the app. - await expectFileToMatch('dist/test-project/main-es5.js', /console\.log\((['"])string\-script\1\);/); - await expectFileToMatch('dist/test-project/main-es2015.js', /console\.log\((['"])string\-script\1\);/); -} diff --git a/tests/legacy-cli/e2e/tests/basic/size-tracking.ts b/tests/legacy-cli/e2e/tests/basic/size-tracking.ts deleted file mode 100644 index 24a5ab3984d2..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/size-tracking.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { appendToFile, moveDirectory, prependToFile, replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function () { - // Store the production build for artifact storage on CircleCI - if (process.env['CIRCLECI']) { - - // Add initial app routing. - // This is done automatically on a new app with --routing but must be done manually on - // existing apps. - const appRoutingModulePath = 'src/app/app-routing.module.ts'; - await writeFile(appRoutingModulePath, ` - import { NgModule } from '@angular/core'; - import { Routes, RouterModule } from '@angular/router'; - - const routes: Routes = []; - - @NgModule({ - imports: [RouterModule.forRoot(routes)], - exports: [RouterModule] - }) - export class AppRoutingModule { } - `); - await prependToFile('src/app/app.module.ts', - `import { AppRoutingModule } from './app-routing.module';`); - await replaceInFile('src/app/app.module.ts', `imports: [`, `imports: [ AppRoutingModule,`); - await appendToFile('src/app/app.component.html', ''); - - // Add a lazy module. - await ng('generate', 'module', 'lazy', '--route=lazy', '--module=app.module'); - - // Build without hashing and with named chunks to keep have consistent file names. - await ng('build', '--prod', '--output-hashing=none', '--named-chunks=true'); - - // Upload to the store_artifacts dir listed in .circleci/config.yml - await moveDirectory('dist', '/tmp/dist'); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/styles-array.ts b/tests/legacy-cli/e2e/tests/basic/styles-array.ts deleted file mode 100644 index 72b082f3d18c..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/styles-array.ts +++ /dev/null @@ -1,75 +0,0 @@ -// TODO(architect): edit the architect config instead of the cli config. -import { oneLineTrim } from 'common-tags'; -import { expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function() { - await writeMultipleFiles({ - 'src/string-style.css': '.string-style { color: red }', - 'src/input-style.css': '.input-style { color: red }', - 'src/lazy-style.css': '.lazy-style { color: red }', - 'src/pre-rename-style.css': '.pre-rename-style { color: red }', - 'src/pre-rename-lazy-style.css': '.pre-rename-lazy-style { color: red }', - }); - - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/string-style.css' }, - { input: 'src/input-style.css' }, - { input: 'src/lazy-style.css', inject: false }, - { input: 'src/pre-rename-style.css', bundleName: 'renamed-style' }, - { - input: 'src/pre-rename-lazy-style.css', - bundleName: 'renamed-lazy-style', - inject: false, - }, - ]; - }); - - await ng('build', '--extract-css'); - - await expectFileToMatch('dist/test-project/styles.css', '.string-style'); - await expectFileToMatch('dist/test-project/styles.css', '.input-style'); - await expectFileToMatch('dist/test-project/lazy-style.css', '.lazy-style'); - await expectFileToMatch('dist/test-project/renamed-style.css', '.pre-rename-style'); - await expectFileToMatch('dist/test-project/renamed-lazy-style.css', '.pre-rename-lazy-style'); - await expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - `, - ); - - if (process.env['NG_BUILD_DIFFERENTIAL_FULL']) { - await expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - - - - - - - `, - ); - } else { - await expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - - - - - - - `, - ); - } -} diff --git a/tests/legacy-cli/e2e/tests/basic/test.ts b/tests/legacy-cli/e2e/tests/basic/test.ts deleted file mode 100644 index 9ae72b9026d1..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { ng } from '../../utils/process'; -import { moveFile } from '../../utils/fs'; - -export default function () { - // make sure both --watch=false work - return ng('test', '--watch=false') - .then(() => moveFile('./karma.conf.js', './karma.conf.bis.js')) - .then(() => ng('test', '--watch=false', '--karmaConfig=karma.conf.bis.js')); -} diff --git a/tests/legacy-cli/e2e/tests/build/allow-js.ts b/tests/legacy-cli/e2e/tests/build/allow-js.ts deleted file mode 100644 index 2cdf49d5352f..000000000000 --- a/tests/legacy-cli/e2e/tests/build/allow-js.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { ng } from '../../utils/process'; -import { updateTsConfig } from '../../utils/project'; -import { appendToFile, writeFile } from '../../utils/fs'; - -export default async function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - await writeFile('src/my-js-file.js', 'console.log(1); export const a = 2;'); - await appendToFile('src/main.ts', ` - import { a } from './my-js-file'; - console.log(a); - `); - - await updateTsConfig(json => { - json['compilerOptions'].allowJs = true; - }); - - await ng('build'); - await ng('build', '--aot'); -} diff --git a/tests/legacy-cli/e2e/tests/build/aot/aot-decorators.ts b/tests/legacy-cli/e2e/tests/build/aot/aot-decorators.ts deleted file mode 100644 index c6d56342e2b0..000000000000 --- a/tests/legacy-cli/e2e/tests/build/aot/aot-decorators.ts +++ /dev/null @@ -1,28 +0,0 @@ -import {ng} from '../../../utils/process'; -import {appendToFile, expectFileToMatch, prependToFile, replaceInFile} from '../../../utils/fs'; -import {expectToFail} from '../../../utils/utils'; -import {ngVersionMatches} from '../../../utils/version'; - -export default function() { - // TODO(architect): This behaviour seems to have changed in devkit/build-angular. Figure out why. - return; - - return ng('generate', 'component', 'test-component', '--module', 'app.module.ts') - .then(() => prependToFile('src/app/test-component/test-component.component.ts', ` - import { Optional, SkipSelf } from '@angular/core'; - `)) - .then(() => replaceInFile('src/app/test-component/test-component.component.ts', - /constructor.*/, ` - constructor(@Optional() @SkipSelf() public test: TestComponentComponent) { - console.log(test); - } - `)) - .then(() => appendToFile('src/app/app.component.html', ` - - `)) - .then(() => ng('build', '--aot')) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/main.js', /\bComponent\b/))) - // Check that the decorators are still kept. - .then(() => expectFileToMatch('dist/test-project/main.js', /ctorParameters.*Optional.*SkipSelf/)) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/main.js', /\bNgModule\b/))); -} diff --git a/tests/legacy-cli/e2e/tests/build/barrel-file.ts b/tests/legacy-cli/e2e/tests/build/barrel-file.ts deleted file mode 100644 index b39480f308ec..000000000000 --- a/tests/legacy-cli/e2e/tests/build/barrel-file.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function() { - await writeFile('src/app/index.ts', `export { AppModule } from './app.module';`); - await replaceInFile('src/main.ts', './app/app.module', './app'); - await ng('build'); -} diff --git a/tests/legacy-cli/e2e/tests/build/base-href.ts b/tests/legacy-cli/e2e/tests/build/base-href.ts deleted file mode 100644 index e8a5769448f3..000000000000 --- a/tests/legacy-cli/e2e/tests/build/base-href.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ng } from '../../utils/process'; -import { expectFileToMatch } from '../../utils/fs'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('build', '--base-href', '/myUrl') - .then(() => expectFileToMatch('dist/test-project/index.html', //)); -} diff --git a/tests/legacy-cli/e2e/tests/build/build-app-shell-with-schematic.ts b/tests/legacy-cli/e2e/tests/build/build-app-shell-with-schematic.ts deleted file mode 100644 index 6f5c87f12b84..000000000000 --- a/tests/legacy-cli/e2e/tests/build/build-app-shell-with-schematic.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { appendToFile, expectFileToMatch } from '../../utils/fs'; -import { ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { readNgVersion } from '../../utils/version'; - - -export default async function () { - await appendToFile('src/app/app.component.html', ''); - await ng('generate', 'appShell', '--client-project', 'test-project'); - await updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/platform-server'] = getGlobalVariable('argv')['ng-snapshots'] - ? require('../../ng-snapshot/package.json').dependencies['@angular/platform-server'] - : readNgVersion(); - }); - - await silentNpm('install'); - await ng('run', 'test-project:app-shell'); - await expectFileToMatch('dist/test-project/browser/index.html', /app-shell works!/); - - await ng('run', 'test-project:app-shell:production'); - await expectFileToMatch('dist/test-project/browser/index.html', /app-shell works!/); -} diff --git a/tests/legacy-cli/e2e/tests/build/build-app-shell.ts b/tests/legacy-cli/e2e/tests/build/build-app-shell.ts deleted file mode 100644 index e74e4f1de8c0..000000000000 --- a/tests/legacy-cli/e2e/tests/build/build-app-shell.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { stripIndent } from 'common-tags'; -import { getGlobalVariable } from '../../utils/env'; -import { expectFileToMatch, writeFile } from '../../utils/fs'; -import { ng, npm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { readNgVersion } from '../../utils/version'; - -export default function() { - let platformServerVersion = readNgVersion(); - - if (getGlobalVariable('argv')['ng-snapshots']) { - platformServerVersion = require('../../ng-snapshot/package.json') - .dependencies['@angular/platform-server']; - } - - return Promise.resolve() - .then(() => - updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect['server'] = { - builder: '@angular-devkit/build-angular:server', - options: { - outputPath: 'dist/test-project-server', - main: 'src/main.server.ts', - tsConfig: 'tsconfig.server.json', - }, - }; - appArchitect['app-shell'] = { - builder: '@angular-devkit/build-angular:app-shell', - options: { - browserTarget: 'test-project:build:production', - serverTarget: 'test-project:server', - route: '/shell', - }, - }; - }), - ) - .then(() => - writeFile( - './tsconfig.server.json', - ` - { - "extends": "./tsconfig.app.json", - "compilerOptions": { - "outDir": "../dist-server", - "baseUrl": "./", - "module": "commonjs", - "types": [] - }, - "files": [ - "src/main.server.ts" - ], - "include": [ - "src/**/*.d.ts" - ], - "angularCompilerOptions": { - "entryModule": "src/app/app.server.module#AppServerModule" - } - } - `, - ), - ) - .then(() => - writeFile( - './src/main.server.ts', - ` - import { enableProdMode } from '@angular/core'; - - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } - - export { AppServerModule } from './app/app.server.module'; - export { renderModule, renderModuleFactory } from '@angular/platform-server'; - `, - ), - ) - .then(() => - writeFile( - './src/app/app.component.html', - stripIndent` - Hello World - - `, - ), - ) - .then(() => - writeFile( - './src/app/app.module.ts', - stripIndent` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - import { RouterModule } from '@angular/router'; - - import { AppComponent } from './app.component'; - - @NgModule({ - imports: [ - BrowserModule.withServerTransition({ appId: 'appshell-play' }), - RouterModule - ], - declarations: [AppComponent], - bootstrap: [AppComponent] - }) - export class AppModule { } - `, - ), - ) - .then(() => - writeFile( - './src/app/app.server.module.ts', - stripIndent` - import {NgModule} from '@angular/core'; - import {ServerModule} from '@angular/platform-server'; - import { Routes, RouterModule } from '@angular/router'; - - import { AppModule } from './app.module'; - import { AppComponent } from './app.component'; - import { ShellComponent } from './shell.component'; - - const routes: Routes = [ - { path: 'shell', component: ShellComponent } - ]; - - @NgModule({ - imports: [ - // The AppServerModule should import your AppModule followed - // by the ServerModule from @angular/platform-server. - AppModule, - ServerModule, - RouterModule.forRoot(routes), - ], - // Since the bootstrapped component is not inherited from your - // imported AppModule, it needs to be repeated here. - bootstrap: [AppComponent], - declarations: [ShellComponent], - }) - export class AppServerModule {} - `, - ), - ) - .then(() => - writeFile( - './src/app/shell.component.ts', - stripIndent` - import { Component } from '@angular/core'; - @Component({ - selector: 'app-shell', - template: '

shell Works!

', - styles: [] - }) - export class ShellComponent {} - `, - ), - ) - .then(() => - updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/platform-server'] = platformServerVersion; - }).then(() => npm('install')), - ) - .then(() => ng('run', 'test-project:app-shell')) - .then(() => expectFileToMatch('dist/test-project/index.html', /shell Works!/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/build-errors.ts b/tests/legacy-cli/e2e/tests/build/build-errors.ts deleted file mode 100644 index b8abc5b4dad3..000000000000 --- a/tests/legacy-cli/e2e/tests/build/build-errors.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { writeFile, appendToFile, readFile, replaceInFile } from '../../utils/fs'; -import { getGlobalVariable } from '../../utils/env'; -import { expectToFail } from '../../utils/utils'; - -const extraErrors = [ - `Final loader didn't return a Buffer or String`, - `doesn't contain a valid alias configuration`, - `main.ts is not part of the TypeScript compilation.`, -]; - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - if (process.platform.startsWith('win')) { - return Promise.resolve(); - } - - // Skip this test in Angular 2/4. - if (getGlobalVariable('argv').ng2 || getGlobalVariable('argv').ng4) { - return Promise.resolve(); - } - - let origContent: string; - - return ( - Promise.resolve() - // Save the original contents of `./src/app/app.component.ts`. - .then(() => readFile('./src/app/app.component.ts')) - .then(contents => (origContent = contents)) - // Check `part of the TypeScript compilation` errors. - // These should show an error only for the missing file. - .then(() => - updateJsonFile('./tsconfig.app.json', configJson => { - (configJson.include = undefined), (configJson.files = ['src/main.ts']); - }), - ) - .then(() => expectToFail(() => ng('build'))) - .then(({ message }) => { - if (!message.includes('polyfills.ts is missing from the TypeScript compilation')) { - throw new Error(`Expected missing TS file error, got this instead:\n${message}`); - } - if (extraErrors.some(e => message.includes(e))) { - throw new Error(`Did not expect extra errors but got:\n${message}`); - } - }) - .then(() => - updateJsonFile('./tsconfig.app.json', configJson => { - configJson.include = ['src/**/*.ts']; - configJson.exclude = ['**/**.spec.ts']; - configJson.files = undefined; - }), - ) - // Check simple single syntax errors. - // These shouldn't skip emit and just show a TS error. - .then(() => appendToFile('./src/app/app.component.ts', ']]]')) - .then(() => expectToFail(() => ng('build'))) - .then(({ message }) => { - if (!message.includes('Declaration or statement expected.')) { - throw new Error(`Expected syntax error, got this instead:\n${message}`); - } - if (extraErrors.some(e => message.includes(e))) { - throw new Error(`Did not expect extra errors but got:\n${message}`); - } - }) - .then(() => writeFile('./src/app/app.component.ts', origContent)) - // Check errors when files were not emitted due to static analysis errors. - .then(() => replaceInFile('./src/app/app.component.ts', `'app-root'`, `(() => 'app-root')()`)) - .then(() => expectToFail(() => ng('build', '--aot'))) - .then(({ message }) => { - if ( - !message.includes('Function calls are not supported') && - !message.includes('Function expressions are not supported in decorators') && - !message.includes('selector must be a string') - ) { - throw new Error(`Expected static analysis error, got this instead:\n${message}`); - } - if (extraErrors.some(e => message.includes(e))) { - throw new Error(`Did not expect extra errors but got:\n${message}`); - } - }) - .then(() => writeFile('./src/app/app.component.ts', origContent)) - ); -} \ No newline at end of file diff --git a/tests/legacy-cli/e2e/tests/build/build-optimizer.ts b/tests/legacy-cli/e2e/tests/build/build-optimizer.ts deleted file mode 100644 index 365c0e3d1067..000000000000 --- a/tests/legacy-cli/e2e/tests/build/build-optimizer.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ng } from '../../utils/process'; -import { expectFileToMatch, expectFileToExist } from '../../utils/fs'; -import { expectToFail } from '../../utils/utils'; - - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('build', '--aot', '--build-optimizer') - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/main.js', /\.decorators =/))) - .then(() => ng('build', '--prod')) - .then(() => expectToFail(() => expectFileToExist('dist/vendor.js'))) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/main.js', /\.decorators =/))) - .then(() => expectToFail(() => ng('build', '--aot=false', '--build-optimizer'))); -} diff --git a/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts b/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts deleted file mode 100644 index 63b0de08444e..000000000000 --- a/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -import { getGlobalVariable } from '../../utils/env'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -// tslint:disable:max-line-length -export default function () { - const budgetConfigs = [ - { - expectation: 'pass', - message: 'BIG max for all, should not error', - budget: { type: 'allScript', maximumError: '100mb' }, - }, - { - expectation: 'error', - message: 'Budget error: all, max error', - budget: { type: 'all', maximumError: '100b' }, - }, - { - expectation: 'warning', - message: 'Budget warning: all, min warning', - budget: { type: 'all', minimumWarning: '100mb' }, - }, - ]; - - const promiseFactories = budgetConfigs.map(cfg => { - if (cfg.expectation === 'error') { - return () => { - return updateJsonFile('angular.json', (json) => { - json.projects['test-project'].architect.build.options.budgets = [cfg.budget]; - }) - .then(() => expectToFail(() => ng('build', '--optimization'))) - .then(errorMessage => { - if (!/ERROR in budgets/.test(errorMessage)) { - throw new Error(cfg.message); - } - }); - }; - } else if (cfg.expectation === 'warning') { - return () => { - return updateJsonFile('angular.json', (json) => { - json.projects['test-project'].architect.build.options.budgets = [cfg.budget]; - }) - .then(() => ng('build', '--optimization')) - .then(({ stderr }) => { - if (!/WARNING in budgets/.test(stderr)) { - throw new Error(cfg.message); - } - }); - }; - } else { // pass - return () => { - return updateJsonFile('angular.json', (json) => { - json.projects['test-project'].architect.build.options.budgets = [cfg.budget]; - }) - .then(() => ng('build', '--optimization')) - .then(({ stderr }) => { - if (/(WARNING|ERROR)/.test(stderr)) { - throw new Error(cfg.message); - } - }); - }; - } - }); - - let promiseChain = Promise.resolve(); - for (let i = 0; i < promiseFactories.length; i++) { - promiseChain = promiseChain.then(promiseFactories[i]); - } - - return promiseChain; -} diff --git a/tests/legacy-cli/e2e/tests/build/chunk-hash.ts b/tests/legacy-cli/e2e/tests/build/chunk-hash.ts deleted file mode 100644 index b575305afb6c..000000000000 --- a/tests/legacy-cli/e2e/tests/build/chunk-hash.ts +++ /dev/null @@ -1,105 +0,0 @@ -import * as fs from 'fs'; - -import {ng} from '../../utils/process'; -import {writeFile, prependToFile, replaceInFile} from '../../utils/fs'; - -const OUTPUT_RE = /(main|polyfills|vendor|inline|styles|\d+)\.[a-z0-9]+\.(chunk|bundle)\.(js|css)$/; - -function generateFileHashMap(): Map { - const hashes = new Map(); - - fs.readdirSync('./dist') - .forEach(name => { - if (!name.match(OUTPUT_RE)) { - return; - } - - const [module, hash] = name.split('.'); - hashes.set(module, hash); - }); - - return hashes; -} - -function validateHashes( - oldHashes: Map, - newHashes: Map, - shouldChange: Array): void { - - console.log(' Validating hashes...'); - console.log(` Old hashes: ${JSON.stringify([...oldHashes])}`); - console.log(` New hashes: ${JSON.stringify([...newHashes])}`); - - oldHashes.forEach((hash, module) => { - if (hash == newHashes.get(module)) { - if (shouldChange.includes(module)) { - throw new Error(`Module "${module}" did not change hash (${hash})...`); - } - } else if (!shouldChange.includes(module)) { - throw new Error(`Module "${module}" changed hash (${hash})...`); - } - }); -} - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - return; - - let oldHashes: Map; - let newHashes: Map; - // First, collect the hashes. - return Promise.resolve() - .then(() => ng('generate', 'module', 'lazy', '--routing')) - .then(() => prependToFile('src/app/app.module.ts', ` - import { RouterModule } from '@angular/router'; - import { ReactiveFormsModule } from '@angular/forms'; - `)) - .then(() => replaceInFile('src/app/app.module.ts', 'imports: [', `imports: [ - RouterModule.forRoot([{ path: "lazy", loadChildren: "./lazy/lazy.module#LazyModule" }]), - ReactiveFormsModule, - `)) - .then(() => ng('build', '--output-hashing=all')) - .then(() => { - oldHashes = generateFileHashMap(); - }) - .then(() => ng('build', '--output-hashing=all')) - .then(() => { - newHashes = generateFileHashMap(); - }) - .then(() => { - validateHashes(oldHashes, newHashes, []); - oldHashes = newHashes; - }) - .then(() => writeFile('src/styles.css', 'body { background: blue; }')) - .then(() => ng('build', '--output-hashing=all')) - .then(() => { - newHashes = generateFileHashMap(); - }) - .then(() => { - validateHashes(oldHashes, newHashes, ['styles']); - oldHashes = newHashes; - }) - .then(() => writeFile('src/app/app.component.css', 'h1 { margin: 10px; }')) - .then(() => ng('build', '--output-hashing=all')) - .then(() => { - newHashes = generateFileHashMap(); - }) - .then(() => { - validateHashes(oldHashes, newHashes, ['main']); - oldHashes = newHashes; - }) - .then(() => prependToFile('src/app/lazy/lazy.module.ts', ` - import { ReactiveFormsModule } from '@angular/forms'; - `)) - .then(() => replaceInFile('src/app/lazy/lazy.module.ts', 'imports: [', ` - imports: [ - ReactiveFormsModule, - `)) - .then(() => ng('build', '--output-hashing=all')) - .then(() => { - newHashes = generateFileHashMap(); - }) - .then(() => { - validateHashes(oldHashes, newHashes, ['inline', '0']); - }); -} diff --git a/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts b/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts deleted file mode 100644 index 3dd987431b8a..000000000000 --- a/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts +++ /dev/null @@ -1,10 +0,0 @@ -import {ng} from '../../utils/process'; -import {moveFile} from '../../utils/fs'; - - -export default function() { - return Promise.resolve() - .then(() => ng('build')) - .then(() => moveFile('angular.json', '.angular.json')) - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/build/css-urls.ts b/tests/legacy-cli/e2e/tests/build/css-urls.ts deleted file mode 100644 index 4fce5d50156a..000000000000 --- a/tests/legacy-cli/e2e/tests/build/css-urls.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { ng } from '../../utils/process'; -import { - expectFileToMatch, - expectFileToExist, - expectFileMatchToExist, - writeMultipleFiles -} from '../../utils/fs'; -import { copyProjectAsset } from '../../utils/assets'; -import { expectToFail } from '../../utils/utils'; - -const imgSvg = ` - - - -`; - -export default function () { - return Promise.resolve() - // Verify absolute/relative paths in global/component css. - .then(() => writeMultipleFiles({ - 'src/styles.css': ` - h1 { background: url('/assets/global-img-absolute.svg'); } - h2 { background: url('./assets/global-img-relative.png'); } - `, - 'src/app/app.component.css': ` - h3 { background: url('/assets/component-img-absolute.svg'); } - h4 { background: url('../assets/component-img-relative.png'); } - `, - 'src/assets/global-img-absolute.svg': imgSvg, - 'src/assets/component-img-absolute.svg': imgSvg - })) - .then(() => copyProjectAsset('images/spectrum.png', './src/assets/global-img-relative.png')) - .then(() => copyProjectAsset('images/spectrum.png', './src/assets/component-img-relative.png')) - .then(() => ng('build', '--extract-css', '--aot')) - // Check paths are correctly generated. - .then(() => expectFileToMatch('dist/test-project/styles.css', 'assets/global-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /url\('\/assets\/global-img-absolute\.svg'\)/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /global-img-relative\.png/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - '/assets/component-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /component-img-relative\.png/)) - // Check files are correctly created. - .then(() => expectToFail(() => expectFileToExist('dist/test-project/global-img-absolute.svg'))) - .then(() => expectToFail(() => expectFileToExist('dist/test-project/component-img-absolute.svg'))) - .then(() => expectFileMatchToExist('./dist/test-project', /global-img-relative\.png/)) - .then(() => expectFileMatchToExist('./dist/test-project', /component-img-relative\.png/)) - // Check urls with deploy-url scheme are used as is. - .then(() => ng('build', '--base-href=/base/', '--deploy-url=http://deploy.url/', - '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /url\(\'\/assets\/global-img-absolute\.svg\'\)/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /url\(\'\/assets\/component-img-absolute\.svg\'\)/)) - // Check urls with base-href scheme are used as is (with deploy-url). - .then(() => ng('build', '--base-href=http://base.url/', '--deploy-url=deploy/', - '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /url\(\'\/assets\/global-img-absolute\.svg\'\)/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /url\(\'\/assets\/component-img-absolute\.svg\'\)/)) - // Check urls with deploy-url and base-href scheme only use deploy-url. - .then(() => ng('build', '--base-href=http://base.url/', '--deploy-url=http://deploy.url/', - '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /url\(\'\/assets\/global-img-absolute\.svg\'\)/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /url\(\'\/assets\/component-img-absolute\.svg\'\)/)) - // Check with base-href and deploy-url flags. - .then(() => ng('build', '--base-href=/base/', '--deploy-url=deploy/', - '--extract-css', '--aot')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - '/assets/global-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /global-img-relative\.png/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - '/assets/component-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /deploy\/component-img-relative\.png/)) - // Check with identical base-href and deploy-url flags. - .then(() => ng('build', '--base-href=/base/', '--deploy-url=/base/', - '--extract-css', '--aot')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - '/assets/global-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /global-img-relative\.png/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - '/assets/component-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /\/base\/component-img-relative\.png/)) - // Check with only base-href flag. - .then(() => ng('build', '--base-href=/base/', - '--extract-css', '--aot')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - '/assets/global-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /global-img-relative\.png/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - '/assets/component-img-absolute.svg')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /component-img-relative\.png/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/delete-output-path.ts b/tests/legacy-cli/e2e/tests/build/delete-output-path.ts deleted file mode 100644 index abb646d85d68..000000000000 --- a/tests/legacy-cli/e2e/tests/build/delete-output-path.ts +++ /dev/null @@ -1,18 +0,0 @@ -import {ng} from '../../utils/process'; -import {expectToFail} from '../../utils/utils'; -import {deleteFile, expectFileToExist} from '../../utils/fs'; -import {getGlobalVariable} from '../../utils/env'; - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('build') - // This is supposed to fail since there's a missing file - .then(() => deleteFile('src/app/app.component.ts')) - // The build fails but we don't delete the output of the previous build. - .then(() => expectToFail(() => ng('build', '--delete-output-path=false'))) - .then(() => expectFileToExist('dist')) - // By default, output path is always cleared. - .then(() => expectToFail(() => ng('build'))) - .then(() => expectToFail(() => expectFileToExist('dist/test-project'))); -} diff --git a/tests/legacy-cli/e2e/tests/build/deploy-url.ts b/tests/legacy-cli/e2e/tests/build/deploy-url.ts deleted file mode 100644 index a5cf9f769702..000000000000 --- a/tests/legacy-cli/e2e/tests/build/deploy-url.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { ng } from '../../utils/process'; -import { copyProjectAsset } from '../../utils/assets'; -import { expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; -import { updateJsonFile } from '../../utils/project'; -import { getGlobalVariable } from '../../utils/env'; - - -export default function () { - return Promise.resolve() - .then(() => writeMultipleFiles({ - 'src/styles.css': 'div { background: url("./assets/more.png"); }', - })) - // use image with file size >10KB to prevent inlining - .then(() => copyProjectAsset('images/spectrum.png', './src/assets/more.png')) - .then(() => ng('build', '--deploy-url=deployUrl/', '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/index.html', 'deployUrl/main-es5.js')) - // verify --deploy-url isn't applied to extracted css urls - .then(() => expectFileToMatch('dist/test-project/styles.css', - /url\(['"]?more\.png['"]?\)/)) - .then(() => ng('build', '--deploy-url=http://example.com/some/path/', '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/index.html', 'http://example.com/some/path/main-es5.js')) - // verify --deploy-url is applied to non-extracted css urls - .then(() => ng('build', '--deploy-url=deployUrl/', '--extract-css=false')) - .then(() => expectFileToMatch('dist/test-project/styles-es5.js', - /\(['"]?deployUrl\/more\.png['"]?\)/)) - .then(() => expectFileToMatch('dist/test-project/runtime-es5.js', - /__webpack_require__\.p\s*=\s*"deployUrl\/";/)); - // // verify slash is appended to the end of --deploy-url if missing - // .then(() => ng('build', '--deploy-url=deployUrl', '--extract-css=false')) - // .then(() => - // expectFileToMatch('dist/test-project/untime.js', /__webpack_require__\.p = "deployUrl\/";/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/differential-cache.ts b/tests/legacy-cli/e2e/tests/build/differential-cache.ts deleted file mode 100644 index fe9fc766a1ae..000000000000 --- a/tests/legacy-cli/e2e/tests/build/differential-cache.ts +++ /dev/null @@ -1,83 +0,0 @@ -import * as crypto from 'crypto'; -import * as fs from 'fs'; -import { rimraf } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -function generateFileHashMap(): Map { - const hashes = new Map(); - - fs.readdirSync('./dist/test-project').forEach(name => { - const data = fs.readFileSync('./dist/test-project/' + name); - const hash = crypto - .createHash('sha1') - .update(data) - .digest('hex'); - - hashes.set(name, hash); - }); - - return hashes; -} - -function validateHashes( - oldHashes: Map, - newHashes: Map, - shouldChange: Array, -): void { - oldHashes.forEach((hash, name) => { - if (hash === newHashes.get(name)) { - if (shouldChange.includes(name)) { - throw new Error(`"${name}" did not change hash (${hash})...`); - } - } else if (!shouldChange.includes(name)) { - throw new Error(`"${name}" changed hash (${hash})...`); - } - }); -} - -export default async function() { - let oldHashes: Map; - let newHashes: Map; - - // Remove the cache so that an initial build and build with cache can be tested - await rimraf('./node_modules/.cache'); - - let start = Date.now(); - await ng('build'); - let initial = Date.now() - start; - oldHashes = generateFileHashMap(); - - start = Date.now(); - await ng('build'); - let cached = Date.now() - start; - newHashes = generateFileHashMap(); - - validateHashes(oldHashes, newHashes, []); - - if (cached > initial * 0.70) { - throw new Error( - `Cached build time [${cached}] should not be greater than 70% of initial build time [${initial}].`, - ); - } - - // Remove the cache so that an initial build and build with cache can be tested - await rimraf('./node_modules/.cache'); - - start = Date.now(); - await ng('build', '--prod'); - initial = Date.now() - start; - oldHashes = generateFileHashMap(); - - start = Date.now(); - await ng('build', '--prod'); - cached = Date.now() - start; - newHashes = generateFileHashMap(); - - if (cached > initial * 0.70) { - throw new Error( - `Cached build time [${cached}] should not be greater than 70% of initial build time [${initial}].`, - ); - } - - validateHashes(oldHashes, newHashes, []); -} diff --git a/tests/legacy-cli/e2e/tests/build/dynamic-import.ts b/tests/legacy-cli/e2e/tests/build/dynamic-import.ts deleted file mode 100644 index cfa72e03e0ed..000000000000 --- a/tests/legacy-cli/e2e/tests/build/dynamic-import.ts +++ /dev/null @@ -1,56 +0,0 @@ -import * as fs from 'fs'; -import { getGlobalVariable } from '../../utils/env'; -import { writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - - -export default async function() { - if (!(getGlobalVariable('argv')['ve'])) { - // Only applicable to VE. Does not apply to Ivy. - return; - } - - // Add a lazy module - await ng('generate', 'module', 'lazy'); - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.lazyModules = [ - 'src/app/lazy/lazy.module', - ]; - }); - - await updateJsonFile('tsconfig.app.json', tsConfig => { - tsConfig.files.push('src/app/lazy/lazy.module.ts'); - }); - - // Update the app component to use the lazy module - await writeFile('src/app/app.component.ts', ` - import { Component, SystemJsNgModuleLoader } from '@angular/core'; - - @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'], - }) - export class AppComponent { - title = 'app'; - constructor(loader: SystemJsNgModuleLoader) { - // Module will be split at build time and loaded when requested below - loader.load('app/lazy/lazy.module#LazyModule') - .then((factory) => { /* Use factory here */ }); - } - } - `); - - // Build and look for the split lazy module - await ng('build'); - for (const file of fs.readdirSync('./dist/test-project')) { - if (file === 'src-app-lazy-lazy-module-es5.js') { - // Lazy module chunk was found and succesfully split - return; - } - } - - throw new Error('Lazy module chunk not created'); -} diff --git a/tests/legacy-cli/e2e/tests/build/environment.ts b/tests/legacy-cli/e2e/tests/build/environment.ts deleted file mode 100644 index e8f739be43fb..000000000000 --- a/tests/legacy-cli/e2e/tests/build/environment.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - - -export default function() { - // Try a prod build. - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.build.configurations['prod-env'] = { - fileReplacements: [ - { - src: 'src/environments/environment.ts', - replaceWith: 'src/environments/environment.prod.ts', - } - ], - }; - })) - .then(() => ng('build', '--configuration=prod-env')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /production:\s*true/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /production:\s*true/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/eval-sourcemap.ts b/tests/legacy-cli/e2e/tests/build/eval-sourcemap.ts deleted file mode 100644 index 37c811700c5b..000000000000 --- a/tests/legacy-cli/e2e/tests/build/eval-sourcemap.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {execAndWaitForOutputToMatch, killAllProcesses} from '../../utils/process'; - - -export default function() { - // TODO(architect): Dev-server does not yet do this. Fix, reenable, validate, then delete this test. - return; - - return Promise.resolve() - // Check that ng serve has eval sourcemaps by default. - .then(() => execAndWaitForOutputToMatch('ng', ['serve'], /: Compiled successfully/)) - .then((output) => { - const stdout = output.stdout; - if (/\.js\.map/.test(stdout)) { - throw new Error('Expected eval sourcemap but file sourcemap was present instead.'); - } - }) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }); -} diff --git a/tests/legacy-cli/e2e/tests/build/extract-licenses.ts b/tests/legacy-cli/e2e/tests/build/extract-licenses.ts deleted file mode 100644 index b809def92767..000000000000 --- a/tests/legacy-cli/e2e/tests/build/extract-licenses.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { expectFileToExist, expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - // Licenses should be left intact if extraction is disabled - await ng('build', '--prod', '--extract-licenses=false', '--output-hashing=none'); - - await expectToFail(() => expectFileToExist('dist/test-project/3rdpartylicenses.txt')); - await expectFileToMatch('dist/test-project/main-es2015.js', '@license'); - await expectFileToMatch('dist/test-project/main-es5.js', '@license'); - - // Licenses should be removed if extraction is enabled - await ng('build', '--prod', '--extract-licenses', '--output-hashing=none'); - - await expectFileToExist('dist/test-project/3rdpartylicenses.txt'); - await expectToFail(() => expectFileToMatch('dist/test-project/main-es2015.js', '@license')); - await expectToFail(() => expectFileToMatch('dist/test-project/main-es5.js', '@license')); -} diff --git a/tests/legacy-cli/e2e/tests/build/jit-prod.ts b/tests/legacy-cli/e2e/tests/build/jit-prod.ts deleted file mode 100644 index b4c8fe67a1a8..000000000000 --- a/tests/legacy-cli/e2e/tests/build/jit-prod.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - - -export default async function () { - // Make prod use JIT. - await updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.build.configurations['production'].aot = false; - appArchitect.build.configurations['production'].buildOptimizer = false; - }); - - // Test it works - await ng('e2e', '--prod'); -} diff --git a/tests/legacy-cli/e2e/tests/build/json.ts b/tests/legacy-cli/e2e/tests/build/json.ts deleted file mode 100644 index 337f77caefc0..000000000000 --- a/tests/legacy-cli/e2e/tests/build/json.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { expectFileToExist } from '../../utils/fs'; -import { expectGitToBeClean } from '../../utils/git'; -import { ng } from '../../utils/process'; - -export default async function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - await ng('build', '--stats-json'); - - if (process.env['NG_BUILD_DIFFERENTIAL_FULL']) { - await expectFileToExist('./dist/test-project/stats-es5.json'); - } - await expectFileToExist('./dist/test-project/stats-es2015.json'); - - await expectGitToBeClean(); -} diff --git a/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts b/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts deleted file mode 100644 index e04587e4c67c..000000000000 --- a/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { getGlobalVariable } from '../../utils/env'; -import { appendToFile, prependToFile, readFile, replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - const projectName = 'test-project'; - const appRoutingModulePath = 'src/app/app-routing.module.ts'; - - // Add app routing. - // This is done automatically on a new app with --routing. - await writeFile(appRoutingModulePath, ` - import { NgModule } from '@angular/core'; - import { Routes, RouterModule } from '@angular/router'; - - const routes: Routes = []; - - @NgModule({ - imports: [RouterModule.forRoot(routes)], - exports: [RouterModule] - }) - export class AppRoutingModule { } - `); - await prependToFile('src/app/app.module.ts', - `import { AppRoutingModule } from './app-routing.module';`); - await replaceInFile('src/app/app.module.ts', `imports: [`, `imports: [ AppRoutingModule,`); - await appendToFile('src/app/app.component.html', ''); - - const originalAppRoutingModule = await readFile(appRoutingModulePath); - // helper to replace loadChildren - const replaceLoadChildren = async (route: string) => { - const content = originalAppRoutingModule.replace('const routes: Routes = [];', ` - const routes: Routes = [{ path: 'lazy', loadChildren: ${route} }]; - `); - - return writeFile(appRoutingModulePath, content); - }; - - // Add lazy route. - await ng('generate', 'module', 'lazy', '--routing'); - await ng('generate', 'component', 'lazy/lazy-comp'); - await replaceInFile('src/app/lazy/lazy-routing.module.ts', 'const routes: Routes = [];', ` - import { LazyCompComponent } from './lazy-comp/lazy-comp.component'; - const routes: Routes = [{ path: '', component: LazyCompComponent }]; - `); - - // Add lazy route e2e - await writeFile('e2e/src/app.e2e-spec.ts', ` - import { browser, logging, element, by } from 'protractor'; - - describe('workspace-project App', () => { - it('should display lazy route', () => { - browser.get(browser.baseUrl + '/lazy'); - expect(element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); - }); - `); - - // Convert the default config to use JIT and prod to just do AOT. - // This way we can use `ng e2e` to test JIT and `ng e2e --prod` to test AOT. - await updateJsonFile('angular.json', json => { - const buildTarget = json['projects'][projectName]['architect']['build']; - buildTarget['options']['aot'] = false; - buildTarget['configurations']['production'] = { aot: true }; - }); - - // Test `import()` style lazy load. - // Both Ivy and View Engine should support it. - await replaceLoadChildren(`() => import('./lazy/lazy.module').then(m => m.LazyModule)`); - - await ng('e2e'); - await ng('e2e', '--prod'); - - // Test string import. - // Both Ivy and View Engine should support it. - await updateJsonFile('tsconfig.app.json', tsConfig => { - tsConfig.files.push('src/app/lazy/lazy.module.ts'); - }); - await replaceLoadChildren(`'./lazy/lazy.module#LazyModule'`); - await ng('e2e'); - await ng('e2e', '--prod'); -} diff --git a/tests/legacy-cli/e2e/tests/build/module-id.ts b/tests/legacy-cli/e2e/tests/build/module-id.ts deleted file mode 100644 index ad75d230a419..000000000000 --- a/tests/legacy-cli/e2e/tests/build/module-id.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ng } from '../../utils/process'; -import { replaceInFile } from '../../utils/fs'; - - -export default function() { - return Promise.resolve() - .then(() => replaceInFile('src/app/app.component.ts', - '@Component({', - '@Component({ moduleId: module.id,')) - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/build/multiple-configs.ts b/tests/legacy-cli/e2e/tests/build/multiple-configs.ts deleted file mode 100644 index 50b15f03517d..000000000000 --- a/tests/legacy-cli/e2e/tests/build/multiple-configs.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { expectFileToExist } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -export default async function () { - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - // These are the default options, that we'll overwrite in subsequent configs. - // extractCss defaults to false - // sourceMap defaults to true - appArchitect['options'] = { - outputPath: 'dist/latest-project', - index: 'src/index.html', - main: 'src/main.ts', - polyfills: 'src/polyfills.ts', - tsConfig: 'tsconfig.app.json', - assets: [ - 'src/favicon.ico', - 'src/assets', - ], - 'styles': [ - 'src/styles.css', - ], - 'scripts': [], - }; - const browserConfigs = appArchitect['build'].configurations; - browserConfigs['production'] = { - extractCss: true, - }; - browserConfigs['one'] = { - assets: [], - }; - browserConfigs['two'] = { - sourceMap: false, - }; - browserConfigs['three'] = { - extractCss: false, // Defaults to false when not set. - }; - }); - - // Test the base configuration. - await ng('build'); - await expectFileToExist('dist/test-project/favicon.ico'); - await expectFileToExist('dist/test-project/main-es2015.js.map'); - await expectFileToExist('dist/test-project/styles-es2015.js'); - await expectFileToExist('dist/test-project/vendor-es2015.js'); - // Test that --prod extracts css. - await ng('build', '--prod'); - await expectFileToExist('dist/test-project/styles.css'); - // But using a config overrides prod. - await ng('build', '--prod', '--configuration=three'); - await expectFileToExist('dist/test-project/styles-es2015.js'); - await expectToFail(() => expectFileToExist('dist/test-project/styles.css')); - // Use two configurations. - await ng('build', '--configuration=one,two', '--vendor-chunk=false'); - await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico')); - await expectToFail(() => expectFileToExist('dist/test-project/main-es2015.js.map')); - // Use two configurations and two overrides, one of which overrides a config. - await ng('build', '--configuration=one,two', '--vendor-chunk=false', '--sourceMap=true'); - await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico')); - await expectFileToExist('dist/test-project/main-es2015.js.map'); - await expectToFail(() => expectFileToExist('dist/test-project/vendor-es2015.js')); - // Use three configurations and a override, and prod at the end. - await ng('build', '--configuration=one,two,three', '--vendor-chunk=false', '--prod'); - await expectToFail(() => expectFileToExist('dist/test-project/favicon.ico')); - await expectToFail(() => expectFileToExist('dist/test-project/main-es2015.js.map')); - await expectToFail(() => expectFileToExist('dist/test-project/vendor-es2015.js')); - await expectFileToExist('dist/test-project/styles-es2015.js'); - await expectToFail(() => expectFileToExist('dist/test-project/styles.css')); -} diff --git a/tests/legacy-cli/e2e/tests/build/no-angular-router.ts b/tests/legacy-cli/e2e/tests/build/no-angular-router.ts deleted file mode 100644 index 5bf898d8824e..000000000000 --- a/tests/legacy-cli/e2e/tests/build/no-angular-router.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {ng} from '../../utils/process'; -import {expectFileToExist, moveFile} from '../../utils/fs'; -import {getGlobalVariable} from '../../utils/env'; -import * as path from 'path'; - - -export default function() { - const tmp = getGlobalVariable('tmp-root'); - - return Promise.resolve() - .then(() => moveFile('node_modules/@angular/router', path.join(tmp, '@angular-router.backup'))) - .then(() => ng('build')) - .then(() => expectFileToExist('./dist/test-project/index.html')) - .then(() => moveFile(path.join(tmp, '@angular-router.backup'), 'node_modules/@angular/router')); -} diff --git a/tests/legacy-cli/e2e/tests/build/no-entry-module.ts b/tests/legacy-cli/e2e/tests/build/no-entry-module.ts deleted file mode 100644 index 67f4857053ea..000000000000 --- a/tests/legacy-cli/e2e/tests/build/no-entry-module.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { readFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - const mainTs = await readFile('src/main.ts'); - - const newMainTs = mainTs - .replace(/platformBrowserDynamic.*?bootstrapModule.*?;/, '') - + 'console.log(AppModule);'; // Use AppModule to make sure it's imported properly. - - await writeFile('src/main.ts', newMainTs); - await ng('build'); -} diff --git a/tests/legacy-cli/e2e/tests/build/no-implicit-any.ts b/tests/legacy-cli/e2e/tests/build/no-implicit-any.ts deleted file mode 100644 index 08927a41467e..000000000000 --- a/tests/legacy-cli/e2e/tests/build/no-implicit-any.ts +++ /dev/null @@ -1,10 +0,0 @@ -import {updateTsConfig} from '../../utils/project'; -import {ng} from '../../utils/process'; - - -export default function() { - return updateTsConfig(json => { - json['compilerOptions']['noImplicitAny'] = true; - }) - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/build/output-dir.ts b/tests/legacy-cli/e2e/tests/build/output-dir.ts deleted file mode 100644 index 222ce06582af..000000000000 --- a/tests/legacy-cli/e2e/tests/build/output-dir.ts +++ /dev/null @@ -1,25 +0,0 @@ -import {expectFileToExist} from '../../utils/fs'; -import {expectGitToBeClean} from '../../utils/git'; -import {ng} from '../../utils/process'; -import {updateJsonFile} from '../../utils/project'; -import {expectToFail} from '../../utils/utils'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('build', '--output-path', 'build-output') - .then(() => expectFileToExist('./build-output/index.html')) - .then(() => expectFileToExist('./build-output/main-es5.js')) - .then(() => expectFileToExist('./build-output/main-es2015.js')) - .then(() => expectToFail(expectGitToBeClean)) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.outputPath = 'config-build-output'; - })) - .then(() => ng('build')) - .then(() => expectFileToExist('./config-build-output/index.html')) - .then(() => expectFileToExist('./config-build-output/main-es5.js')) - .then(() => expectFileToExist('./config-build-output/main-es2015.js')) - .then(() => expectToFail(expectGitToBeClean)); -} diff --git a/tests/legacy-cli/e2e/tests/build/output-hashing.ts b/tests/legacy-cli/e2e/tests/build/output-hashing.ts deleted file mode 100644 index 676fae3ac49b..000000000000 --- a/tests/legacy-cli/e2e/tests/build/output-hashing.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { copyProjectAsset } from '../../utils/assets'; -import { expectFileMatchToExist, expectFileToMatch, writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -async function verifyMedia(fileNameRe: RegExp, content: RegExp) { - const fileName = await expectFileMatchToExist('dist/test-project/', fileNameRe); - await expectFileToMatch(`dist/test-project/${fileName}`, content); -} - -export default async function () { - await writeMultipleFiles({ - 'src/styles.css': 'body { background-image: url("./assets/image.png"); }', - }); - // use image with file size >10KB to prevent inlining - await copyProjectAsset('images/spectrum.png', './src/assets/image.png'); - await ng('build', '--output-hashing=all'); - await expectFileToMatch('dist/test-project/index.html', /runtime-es2015\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es2015\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /runtime-es5\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es5\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /styles-es5\.[0-9a-f]{20}\.(css|js)/); - await expectFileToMatch('dist/test-project/index.html', /styles-es2015\.[0-9a-f]{20}\.(css|js)/); - await verifyMedia(/styles-es5\.[0-9a-f]{20}\.(css|js)/, /image\.[0-9a-f]{20}\.png/); - await verifyMedia(/styles-es2015\.[0-9a-f]{20}\.(css|js)/, /image\.[0-9a-f]{20}\.png/); - - await ng('build', '--output-hashing=none'); - await expectFileToMatch('dist/test-project/index.html', /runtime-es2015\.js/); - await expectFileToMatch('dist/test-project/index.html', /runtime-es5\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es5\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es2015\.js/); - await expectFileToMatch('dist/test-project/index.html', /styles-es5\.(css|js)/); - await expectFileToMatch('dist/test-project/index.html', /styles-es2015\.(css|js)/); - await verifyMedia(/styles-es5\.(css|js)/, /image\.png/); - await verifyMedia(/styles-es2015\.(css|js)/, /image\.png/); - - await ng('build', '--output-hashing=media'); - await expectFileToMatch('dist/test-project/index.html', /runtime-es2015\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es2015\.js/); - await expectFileToMatch('dist/test-project/index.html', /runtime-es5\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es5\.js/); - await expectFileToMatch('dist/test-project/index.html', /styles-es5\.(css|js)/); - await expectFileToMatch('dist/test-project/index.html', /styles-es2015\.(css|js)/); - await verifyMedia(/styles-es5\.(css|js)/, /image\.[0-9a-f]{20}\.png/); - await verifyMedia(/styles-es2015\.(css|js)/, /image\.[0-9a-f]{20}\.png/); - - await ng('build', '--output-hashing=bundles'); - await expectFileToMatch('dist/test-project/index.html', /runtime-es2015\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es2015\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /runtime-es5\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /main-es5\.[0-9a-f]{20}\.js/); - await expectFileToMatch('dist/test-project/index.html', /styles-es5\.[0-9a-f]{20}\.(css|js)/); - await expectFileToMatch('dist/test-project/index.html', /styles-es2015\.[0-9a-f]{20}\.(css|js)/); - await verifyMedia(/styles-es5\.[0-9a-f]{20}\.(css|js)/, /image\.png/); - await verifyMedia(/styles-es2015\.[0-9a-f]{20}\.(css|js)/, /image\.png/); -} diff --git a/tests/legacy-cli/e2e/tests/build/platform-server.ts b/tests/legacy-cli/e2e/tests/build/platform-server.ts deleted file mode 100644 index 75096038424c..000000000000 --- a/tests/legacy-cli/e2e/tests/build/platform-server.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { normalize } from 'path'; -import { getGlobalVariable } from '../../utils/env'; -import { appendToFile, expectFileToMatch, writeFile } from '../../utils/fs'; -import { exec, ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { readNgVersion } from '../../utils/version'; - -export default async function () { - const argv = getGlobalVariable('argv'); - const veEnabled = argv['ve']; - - await ng('add', '@nguniversal/express-engine@9.0.0-next.6'); - - await updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/platform-server'] = getGlobalVariable('argv')['ng-snapshots'] - ? require('../../ng-snapshot/package.json').dependencies['@angular/platform-server'] - : readNgVersion(); - }); - - await silentNpm('install'); - if (veEnabled) { - // todo: https://github.com/angular/angular-cli/issues/15851 - // We need to fix the 'export_ngfactory' transformer as with the - // new universal approach the factory is not exported. - await appendToFile( - './src/main.server.ts', - `export { AppServerModuleNgFactory } from './app/app.server.module.ngfactory'`, - ); - - await writeFile( - './server.ts', - ` import 'zone.js/dist/zone-node'; - import * as fs from 'fs'; - import { AppServerModuleNgFactory, renderModuleFactory } from './src/main.server'; - - renderModuleFactory(AppServerModuleNgFactory, { - url: '/', - document: '' - }).then(html => { - fs.writeFileSync('dist/test-project/server/index.html', html); - }); - `, - ); - } else { - await writeFile( - './server.ts', - ` import 'zone.js/dist/zone-node'; - import * as fs from 'fs'; - import { AppServerModule, renderModule } from './src/main.server'; - - renderModule(AppServerModule, { - url: '/', - document: '' - }).then(html => { - fs.writeFileSync('dist/test-project/server/index.html', html); - }); - `, - ); - } - - - await ng('run', 'test-project:server:production', '--optimization', 'false'); - - await expectFileToMatch('dist/test-project/server/main.js', veEnabled ? /exports.*AppServerModuleNgFactory/ : /exports.*AppServerModule/); - await exec(normalize('node'), 'dist/test-project/server/main.js'); - await expectFileToMatch( - 'dist/test-project/server/index.html', - /Here are some links to help you get started:<\/p>/, - ); - - // works with optimization and bundleDependencies enabled - await ng('run', 'test-project:server:production', '--optimization', '--bundleDependencies', 'all'); - await exec(normalize('node'), 'dist/test-project/server/main.js'); - await expectFileToMatch( - 'dist/test-project/server/index.html', - /Here are some links to help you get started:<\/p>/, - ); -} diff --git a/tests/legacy-cli/e2e/tests/build/poll.ts b/tests/legacy-cli/e2e/tests/build/poll.ts deleted file mode 100644 index e2aacf46f586..000000000000 --- a/tests/legacy-cli/e2e/tests/build/poll.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { appendToFile } from '../../utils/fs'; -import { - killAllProcesses, - waitForAnyProcessOutputToMatch, -} from '../../utils/process'; -import { ngServe } from '../../utils/project'; -import { expectToFail, wait } from '../../utils/utils'; - -const webpackGoodRegEx = /: Compiled successfully./; - -export default async function() { - try { - await ngServe('--poll=10000'); - - // Wait before editing a file. - // Editing too soon seems to trigger a rebuild and throw polling out of whack. - await wait(3000); - await appendToFile('src/main.ts', 'console.log(1);'); - - // We have to wait poll time + rebuild build time for the regex match. - await waitForAnyProcessOutputToMatch(webpackGoodRegEx, 14000); - - // No rebuilds should occur for a while - await appendToFile('src/main.ts', 'console.log(1);'); - await expectToFail(() => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 7000)); - - // But a rebuild should happen roughly within the 10 second window. - await waitForAnyProcessOutputToMatch(webpackGoodRegEx, 7000); - } finally { - killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/build/polyfills.ts b/tests/legacy-cli/e2e/tests/build/polyfills.ts deleted file mode 100644 index 3681ff77d127..000000000000 --- a/tests/legacy-cli/e2e/tests/build/polyfills.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { oneLineTrim } from 'common-tags'; -import { - expectFileSizeToBeUnder, - expectFileToExist, - expectFileToMatch, - getFileSize, -} from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function () { - await ng('build', '--aot=false'); - // files were created successfully - await expectFileToMatch('dist/test-project/polyfills-es5.js', 'core-js/proposals/reflect-metadata'); - await expectFileToMatch('dist/test-project/polyfills-es5.js', 'zone.js'); - if (process.env['NG_BUILD_DIFFERENTIAL_FULL']) { - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - `); - } else { - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - `); - } else { - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - `)), - ) - // also check when css isn't extracted - .then(() => ng('build', '--no-extract-css')) - // files were created successfully - .then(() => expectFileToMatch('dist/test-project/styles-es5.js', '.string-style')) - .then(() => expectFileToMatch('dist/test-project/styles-es5.js', '.input-style')) - .then(() => expectFileToMatch('dist/test-project/lazy-style-es5.js', '.lazy-style')) - .then(() => expectFileToMatch('dist/test-project/renamed-style-es5.js', '.pre-rename-style')) - .then(() => - expectFileToMatch('dist/test-project/renamed-lazy-style-es5.js', '.pre-rename-lazy-style'), - ) - .then(() => expectFileToMatch('dist/test-project/styles-es2015.js', '.string-style')) - .then(() => expectFileToMatch('dist/test-project/styles-es2015.js', '.input-style')) - .then(() => expectFileToMatch('dist/test-project/lazy-style-es2015.js', '.lazy-style')) - .then(() => - expectFileToMatch('dist/test-project/renamed-style-es2015.js', '.pre-rename-style'), - ) - .then(() => - expectFileToMatch( - 'dist/test-project/renamed-lazy-style-es2015.js', - '.pre-rename-lazy-style', - ), - ) - // index.html lists the right bundles - .then(() => - expectFileToMatch( - 'dist/test-project/index.html', - oneLineTrim` - - - - - `, - ), - ) - ); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/imports.ts b/tests/legacy-cli/e2e/tests/build/styles/imports.ts deleted file mode 100644 index 784d51f4f6c0..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/imports.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { - writeMultipleFiles, - expectFileToMatch, - replaceInFile -} from '../../../utils/fs'; -import { expectToFail } from '../../../utils/utils'; -import { ng } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; -import { getGlobalVariable } from '../../../utils/env'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - const extensions = ['css', 'scss', 'less', 'styl']; - let promise = Promise.resolve(); - - extensions.forEach(ext => { - promise = promise.then(() => { - return writeMultipleFiles({ - [`src/styles.${ext}`]: stripIndents` - @import './imported-styles.${ext}'; - body { background-color: #00f; } - `, - [`src/imported-styles.${ext}`]: stripIndents` - p { background-color: #f00; } - `, - [`src/app/app.component.${ext}`]: stripIndents` - @import './imported-component-styles.${ext}'; - .outer { - .inner { - background: #fff; - } - } - `, - [`src/app/imported-component-styles.${ext}`]: stripIndents` - h1 { background: #000; } - `}) - // change files to use preprocessor - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: `src/styles.${ext}` }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', `./app.component.${ext}`)) - // run build app - .then(() => ng('build', '--extract-css', '--source-map')) - // verify global styles - .then(() => expectFileToMatch('dist/test-project/styles.css', - /body\s*{\s*background-color: #00f;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /p\s*{\s*background-color: #f00;\s*}/)) - // verify global styles sourcemap - .then(() => expectToFail(() => - expectFileToMatch('dist/test-project/styles.css', '"mappings":""'))) - // verify component styles - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /.outer.*.inner.*background:\s*#[fF]+/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', - /h1.*background:\s*#000+/)) - // Also check imports work on ng test - .then(() => ng('test', '--watch=false')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: `src/styles.css` }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - `./app.component.${ext}`, './app.component.css')); - }); - }); - - return promise; -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts b/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts deleted file mode 100644 index 709dfc7784e6..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - writeMultipleFiles, - expectFileToMatch, - replaceInFile, - createDir -} from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { updateJsonFile } from '../../../utils/project'; - -export default function () { - return Promise.resolve() - .then(() => createDir('src/style-paths')) - .then(() => writeMultipleFiles({ - 'src/style-paths/_variables.scss': '$primary-color: red;', - 'src/styles.scss': ` - @import 'variables'; - h1 { color: $primary-color; } - `, - 'src/app/app.component.scss': ` - @import 'variables'; - h2 { background-color: $primary-color; } - `, - 'src/style-paths/variables.styl': '$primary-color = green', - 'src/styles.styl': ` - @import 'variables' - h3 - color: $primary-color - `, - 'src/app/app.component.styl': ` - @import 'variables' - h4 - background-color: $primary-color - `, - 'src/style-paths/variables.less': '@primary-color: #ADDADD;', - 'src/styles.less': ` - @import 'variables'; - h5 { color: @primary-color; } - `, - 'src/app/app.component.less': ` - @import 'variables'; - h6 { color: @primary-color; } - ` - })) - .then(() => replaceInFile('src/app/app.component.ts', `'./app.component.css\'`, - `'./app.component.scss', './app.component.styl', './app.component.less'`)) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.scss' }, - { input: 'src/styles.styl' }, - { input: 'src/styles.less' }, - ]; - appArchitect.build.options.stylePreprocessorOptions = { - includePaths: [ - 'src/style-paths' - ] - }; - })) - // files were created successfully - .then(() => ng('build', '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h1\s*{\s*color: red;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /h2.*{.*color: red;.*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h3\s*{\s*color: #008000;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /h4.*{.*color: #008000;.*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /h6.*{.*color: #ADDADD;.*}/)) - .then(() => ng('build', '--extract-css', '--aot')) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h1\s*{\s*color: red;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /h2.*{.*color: red;.*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h3\s*{\s*color: #008000;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /h4.*{.*color: #008000;.*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /h6.*{.*color: #ADDADD;.*}/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/less.ts b/tests/legacy-cli/e2e/tests/build/styles/less.ts deleted file mode 100644 index 947ccb52aa98..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/less.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { - writeMultipleFiles, - deleteFile, - expectFileToMatch, - replaceInFile -} from '../../../utils/fs'; -import { expectToFail } from '../../../utils/utils'; -import { ng } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return writeMultipleFiles({ - 'src/styles.less': stripIndents` - @import './imported-styles.less'; - body { background-color: blue; } - `, - 'src/imported-styles.less': stripIndents` - p { background-color: red; } - `, - 'src/app/app.component.less': stripIndents` - .outer { - .inner { - background: #fff; - } - } - `}) - .then(() => deleteFile('src/app/app.component.css')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.less' }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', './app.component.less')) - .then(() => ng('build', '--extract-css', '--source-map')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /body\s*{\s*background-color: blue;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /p\s*{\s*background-color: red;\s*}/)) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/styles.css', '"mappings":""'))) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /.outer.*.inner.*background:\s*#[fF]+/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/loaders.ts b/tests/legacy-cli/e2e/tests/build/styles/loaders.ts deleted file mode 100644 index fea92def021d..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/loaders.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - writeMultipleFiles, - deleteFile, - expectFileToMatch, - replaceInFile -} from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; -import { expectToFail } from '../../../utils/utils'; - -export default function () { - return writeMultipleFiles({ - 'src/styles.scss': stripIndents` - @import './imported-styles.scss'; - body { background-color: blue; } - `, - 'src/imported-styles.scss': stripIndents` - p { background-color: red; } - `, - 'src/app/app.component.scss': stripIndents` - .outer { - .inner { - background: #fff; - } - } - `}) - .then(() => deleteFile('src/app/app.component.css')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.scss' }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', './app.component.scss')) - .then(() => ng('build')) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/styles.css', /exports/))) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/main-es5.js', - /".*module\.exports.*\.outer.*background:/))); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/material-import.ts b/tests/legacy-cli/e2e/tests/build/styles/material-import.ts deleted file mode 100644 index 9f2772aaaade..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/material-import.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - writeMultipleFiles, - replaceInFile -} from '../../../utils/fs'; -import { ng, silentNpm } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - const extensions = ['css', 'scss', 'less', 'styl']; - let promise: Promise = Promise.resolve() - .then(() => silentNpm('install', '@angular/material@7.3.6')) - .then(() => silentNpm('install', '@angular/cdk@7.3.6')); - - extensions.forEach(ext => { - promise = promise.then(() => { - return writeMultipleFiles({ - [`src/styles.${ext}`]: stripIndents` - @import "~@angular/material/prebuilt-themes/indigo-pink.css"; - `, - [`src/app/app.component.${ext}`]: stripIndents` - @import "~@angular/material/prebuilt-themes/indigo-pink.css"; - `, - }) - // change files to use preprocessor - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: `src/styles.${ext}` }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', `./app.component.${ext}`)) - // run build app - .then(() => ng('build', '--extract-css', '--source-map')) - .then(() => writeMultipleFiles({ - [`src/styles.${ext}`]: stripIndents` - @import "@angular/material/prebuilt-themes/indigo-pink.css"; - `, - [`src/app/app.component.${ext}`]: stripIndents` - @import "@angular/material/prebuilt-themes/indigo-pink.css"; - `, - })) - .then(() => ng('build', '--extract-css')); - }); - }); - - return promise; -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/node-sass.ts b/tests/legacy-cli/e2e/tests/build/styles/node-sass.ts deleted file mode 100644 index e0a4b3fc2cdc..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/node-sass.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { - deleteFile, - expectFileToMatch, - replaceInFile, - writeMultipleFiles, -} from '../../../utils/fs'; -import { ng, silentExec, silentNpm } from '../../../utils/process'; -import { updateJsonFile } from '../../../utils/project'; -import { expectToFail } from '../../../utils/utils'; - - -export default async function () { - if (process.platform.startsWith('win')) { - return; - } - - await writeMultipleFiles({ - 'src/styles.scss': '@import \'./imported-styles.scss\';\nbody { background-color: blue; }', - 'src/imported-styles.scss': 'p { background-color: red; }', - 'src/app/app.component.scss': '.outer { .inner { background: #fff; } }', - }); - await deleteFile('src/app/app.component.css'); - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.scss' }, - ]; - }); - await replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.scss'); - - await silentExec('rm', '-rf', 'node_modules/node-sass'); - await silentExec('rm', '-rf', 'node_modules/sass'); - await expectToFail(() => ng('build', '--extract-css', '--source-map')); - - await silentNpm('install', 'node-sass'); - await silentExec('rm', '-rf', 'node_modules/sass'); - await ng('build', '--extract-css', '--source-map'); - - await expectFileToMatch('dist/test-project/styles.css', /body\s*{\s*background-color: blue;\s*}/); - await expectFileToMatch('dist/test-project/styles.css', /p\s*{\s*background-color: red;\s*}/); - await expectToFail(() => expectFileToMatch('dist/test-project/styles.css', '"mappings":""')); - await expectFileToMatch('dist/test-project/main-es5.js', /.outer.*.inner.*background:\s*#[fF]+/); - await expectFileToMatch('dist/test-project/main-es2015.js', /.outer.*.inner.*background:\s*#[fF]+/); - - await silentNpm('install', 'node-gyp'); - await silentNpm('install', 'fibers'); - await silentNpm('install', 'sass'); - await silentExec('rm', '-rf', 'node_modules/node-sass'); - await ng('build', '--extract-css', '--source-map'); - - await expectFileToMatch('dist/test-project/styles.css', /body\s*{\s*background-color: blue;\s*}/); - await expectFileToMatch('dist/test-project/styles.css', /p\s*{\s*background-color: red;\s*}/); - await expectToFail(() => expectFileToMatch('dist/test-project/styles.css', '"mappings":""')); - await expectFileToMatch('dist/test-project/main-es5.js', /.outer.*.inner.*background:\s*#[fF]+/); - await expectFileToMatch('dist/test-project/main-es2015.js', /.outer.*.inner.*background:\s*#[fF]+/); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/scss.ts b/tests/legacy-cli/e2e/tests/build/styles/scss.ts deleted file mode 100644 index 156ad85cd592..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/scss.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { - writeMultipleFiles, - deleteFile, - expectFileToMatch, - replaceInFile -} from '../../../utils/fs'; -import { expectToFail } from '../../../utils/utils'; -import { ng } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return writeMultipleFiles({ - 'src/styles.scss': stripIndents` - @import './imported-styles.scss'; - body { background-color: blue; } - `, - 'src/imported-styles.scss': stripIndents` - p { background-color: red; } - `, - 'src/app/app.component.scss': stripIndents` - .outer { - .inner { - background: #fff; - } - } - `}) - .then(() => deleteFile('src/app/app.component.css')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.scss' }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', './app.component.scss')) - .then(() => ng('build', '--extract-css', '--source-map')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /body\s*{\s*background-color: blue;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /p\s*{\s*background-color: red;\s*}/)) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/styles.css', '"mappings":""'))) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /.outer.*.inner.*background:\s*#[fF]+/)); - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /.outer.*.inner.*background:\s*#[fF]+/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/styles/stylus.ts b/tests/legacy-cli/e2e/tests/build/styles/stylus.ts deleted file mode 100644 index fef7ef380ec0..000000000000 --- a/tests/legacy-cli/e2e/tests/build/styles/stylus.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { - writeMultipleFiles, - deleteFile, - expectFileToMatch, - replaceInFile -} from '../../../utils/fs'; -import { expectToFail } from '../../../utils/utils'; -import { ng } from '../../../utils/process'; -import { stripIndents } from 'common-tags'; -import { updateJsonFile } from '../../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return writeMultipleFiles({ - 'src/styles.styl': stripIndents` - @import './imported-styles.styl'; - body { background-color: blue; } - `, - 'src/imported-styles.styl': stripIndents` - p { background-color: red; } - `, - 'src/app/app.component.styl': stripIndents` - .outer { - .inner { - background: #fff; - } - } - `}) - .then(() => deleteFile('src/app/app.component.css')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'src/styles.styl' }, - ]; - })) - .then(() => replaceInFile('src/app/app.component.ts', - './app.component.css', './app.component.styl')) - .then(() => ng('build', '--extract-css', '--source-map')) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /body\s*{\s*background-color: #00f;\s*}/)) - .then(() => expectFileToMatch('dist/test-project/styles.css', - /p\s*{\s*background-color: #f00;\s*}/)) - .then(() => expectToFail(() => expectFileToMatch('dist/test-project/styles.css', '"mappings":""'))) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /.outer.*.inner.*background:\s*#[fF]+/)); - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /.outer.*.inner.*background:\s*#[fF]+/)); -} diff --git a/tests/legacy-cli/e2e/tests/build/subresource-integrity.ts b/tests/legacy-cli/e2e/tests/build/subresource-integrity.ts deleted file mode 100644 index 6592fd373154..000000000000 --- a/tests/legacy-cli/e2e/tests/build/subresource-integrity.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -const integrityRe = /integrity="\w+-[A-Za-z0-9\/\+=]+"/; - -export default async function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - // WEBPACK4_DISABLED - disabled pending a webpack 4 version - return; - - return ng('build') - .then(() => expectToFail(() => - expectFileToMatch('dist/test-project/index.html', integrityRe))) - .then(() => ng('build', '--sri')) - .then(() => expectFileToMatch('dist/test-project/index.html', integrityRe)); -} diff --git a/tests/legacy-cli/e2e/tests/build/ts-paths.ts b/tests/legacy-cli/e2e/tests/build/ts-paths.ts deleted file mode 100644 index d36d5818c822..000000000000 --- a/tests/legacy-cli/e2e/tests/build/ts-paths.ts +++ /dev/null @@ -1,54 +0,0 @@ -import {updateTsConfig} from '../../utils/project'; -import {writeMultipleFiles, appendToFile, createDir, replaceInFile} from '../../utils/fs'; -import {ng} from '../../utils/process'; -import {stripIndents} from 'common-tags'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return updateTsConfig(json => { - json['compilerOptions']['baseUrl'] = './src'; - json['compilerOptions']['paths'] = { - '@shared': [ - 'app/shared' - ], - '@shared/*': [ - 'app/shared/*' - ], - '@root/*': [ - './*' - ] - }; - }) - .then(() => createDir('src/app/shared')) - .then(() => writeMultipleFiles({ - 'src/meaning-too.ts': 'export var meaning = 42;', - 'src/app/shared/meaning.ts': 'export var meaning = 42;', - 'src/app/shared/index.ts': `export * from './meaning'`, - })) - .then(() => replaceInFile('src/app/app.module.ts', './app.component', '@root/app/app.component')) - .then(() => ng('build')) - .then(() => updateTsConfig(json => { - json['compilerOptions']['paths']['*'] = [ - '*', - 'app/shared/*' - ]; - })) - .then(() => appendToFile('src/app/app.component.ts', stripIndents` - import { meaning } from 'app/shared/meaning'; - import { meaning as meaning2 } from '@shared'; - import { meaning as meaning3 } from '@shared/meaning'; - import { meaning as meaning4 } from 'meaning'; - import { meaning as meaning5 } from 'meaning-too'; - - // need to use imports otherwise they are ignored and - // no error is outputted, even if baseUrl/paths don't work - console.log(meaning) - console.log(meaning2) - console.log(meaning3) - console.log(meaning4) - console.log(meaning5) - `)) - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/build/typescript/typescript-2_7.ts b/tests/legacy-cli/e2e/tests/build/typescript/typescript-2_7.ts deleted file mode 100644 index 0afd67574d41..000000000000 --- a/tests/legacy-cli/e2e/tests/build/typescript/typescript-2_7.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ng, npm } from '../../../utils/process'; -import { updateJsonFile } from '../../../utils/project'; - -export default async function () { - // This test should only be active when the current version of Angular supports multiple - // TypeScript minor versions. - return; - - // Disable the strict TS version check for snapshots - await updateJsonFile('src/tsconfig.app.json', configJson => { - configJson.angularCompilerOptions = { - ...configJson.angularCompilerOptions, - disableTypeScriptVersionCheck: true, - }; - }); - - await npm('install', 'typescript@2.7'); - await ng('build'); - await ng('build', '--prod'); - await npm('install', 'typescript@2.6'); -} diff --git a/tests/legacy-cli/e2e/tests/build/vendor-chunk-symlink-node-module.ts b/tests/legacy-cli/e2e/tests/build/vendor-chunk-symlink-node-module.ts deleted file mode 100644 index 61eae952ea71..000000000000 --- a/tests/legacy-cli/e2e/tests/build/vendor-chunk-symlink-node-module.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {ng} from '../../utils/process'; -import {deleteFile, expectFileToExist, moveFile, symlinkFile} from '../../utils/fs'; - - -// THIS TEST REQUIRES TO MOVE NODE_MODULES AND MOVE IT BACK. -export default function() { - // E2E_DISABLED: temporarily disabled - return Promise.resolve(); - - return Promise.resolve() - .then(() => moveFile('node_modules', '../node_modules')) - .then(() => symlinkFile('../node_modules', 'node_modules', 'dir')) - .then(() => ng('build')) - .then(() => expectFileToExist('dist/test-project/vendor.js')) - // Cleanup - .then(() => { - return deleteFile('node_modules') - .then(() => moveFile('../node_modules', 'node_modules')); - }, (err: any) => { - return deleteFile('node_modules') - .then(() => moveFile('../node_modules', 'node_modules')) - .then(() => { throw err; }); - }) -} diff --git a/tests/legacy-cli/e2e/tests/build/vendor-chunk.ts b/tests/legacy-cli/e2e/tests/build/vendor-chunk.ts deleted file mode 100644 index d2fd20a855b1..000000000000 --- a/tests/legacy-cli/e2e/tests/build/vendor-chunk.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {ng} from '../../utils/process'; -import {expectFileToExist} from '../../utils/fs'; -import {expectToFail} from '../../utils/utils'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('build') - .then(() => expectFileToExist('dist/test-project/vendor-es5.js')) - .then(() => expectFileToExist('dist/test-project/vendor-es2015.js')) - .then(() => ng('build', '--vendor-chunk=false')) - .then(() => expectToFail(() => expectFileToExist('dist/test-project/vendor-es5.js'))) - .then(() => expectToFail(() => expectFileToExist('dist/test-project/vendor-es2015.js'))); -} diff --git a/tests/legacy-cli/e2e/tests/build/watch.ts b/tests/legacy-cli/e2e/tests/build/watch.ts deleted file mode 100644 index cb3bf7390bb9..000000000000 --- a/tests/legacy-cli/e2e/tests/build/watch.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - killAllProcesses, - exec, - waitForAnyProcessOutputToMatch, - execAndWaitForOutputToMatch -} from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - - -const webpackGoodRegEx = /: Compiled successfully./; - -export default function () { - // TODO(architect): This test is behaving oddly both here and in devkit/build-angular. - // It seems to be because of file watchers. - return; - - if (process.platform.startsWith('win')) { - return Promise.resolve(); - } - - return execAndWaitForOutputToMatch('ng', ['serve'], webpackGoodRegEx) - // Should trigger a rebuild. - .then(() => exec('touch', 'src/main.ts')) - .then(() => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000)) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }) - .then(() => execAndWaitForOutputToMatch('ng', ['serve', '--no-watch'], webpackGoodRegEx)) - // Should not trigger a rebuild when not watching files. - .then(() => exec('touch', 'src/main.ts')) - .then(() => expectToFail(() => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000))) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }) -} diff --git a/tests/legacy-cli/e2e/tests/build/worker.ts b/tests/legacy-cli/e2e/tests/build/worker.ts deleted file mode 100644 index 759bb57e36c8..000000000000 --- a/tests/legacy-cli/e2e/tests/build/worker.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ -import { join } from 'path'; -import { expectFileToExist, expectFileToMatch, replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function () { - - const workerPath = join('src', 'app', 'app.worker.ts'); - const snippetPath = join('src', 'app', 'app.component.ts'); - const projectTsConfig = 'tsconfig.json'; - const workerTsConfig = 'tsconfig.worker.json'; - - await ng('generate', 'web-worker', 'app'); - await expectFileToExist(workerPath); - await expectFileToExist(projectTsConfig); - await expectFileToExist(workerTsConfig); - await expectFileToMatch(snippetPath, `new Worker('./app.worker', { type: 'module' })`); - - // console.warn has to be used because chrome only captures warnings and errors by default - // https://github.com/angular/protractor/issues/2207 - await replaceInFile('src/app/app.component.ts', 'console.log', 'console.warn'); - - await writeFile('e2e/app.e2e-spec.ts', ` - import { AppPage } from './app.po'; - import { browser, logging } from 'protractor'; - describe('worker bundle', () => { - it('should log worker messages', async () => { - const page = new AppPage();; - page.navigateTo(); - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs.length).toEqual(1); - expect(logs[0].message).toContain('page got message: worker response to hello'); - }); - }); - `); - - await ng('e2e'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-material.ts b/tests/legacy-cli/e2e/tests/commands/add/add-material.ts deleted file mode 100644 index ad0c81629ef3..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/add-material.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { expectFileToMatch, rimraf } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - - -export default async function () { - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/material'); - - await ng('add', '@angular/material'); - await expectFileToMatch('package.json', /@angular\/material/); - - const output1 = await ng('add', '@angular/material'); - if (!output1.stdout.includes('Skipping installation: Package already installed')) { - throw new Error('Installation was not skipped'); - } - - const output2 = await ng('add', '@angular/material@latest'); - if (output2.stdout.includes('Skipping installation: Package already installed')) { - throw new Error('Installation should not have been skipped'); - } - - const output3 = await ng('add', '@angular/material@8.0.0'); - if (output3.stdout.includes('Skipping installation: Package already installed')) { - throw new Error('Installation should not have been skipped'); - } - - const output4 = await ng('add', '@angular/material@8'); - if (!output4.stdout.includes('Skipping installation: Package already installed')) { - throw new Error('Installation was not skipped'); - } -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-pwa-yarn.ts b/tests/legacy-cli/e2e/tests/commands/add/add-pwa-yarn.ts deleted file mode 100644 index 37f929954203..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/add-pwa-yarn.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { join } from 'path'; -import { expectFileToExist, readFile, rimraf } from '../../../utils/fs'; -import { ng, npm } from '../../../utils/process'; - -export default async function () { - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/pwa'); - - // set yarn as package manager - await ng('config', 'cli.packageManager', 'yarn'); - await ng('add', '@angular/pwa'); - await expectFileToExist(join(process.cwd(), 'src/manifest.webmanifest')); - - // Angular PWA doesn't install as a dependency - const { dependencies, devDependencies } = JSON.parse(await readFile(join(process.cwd(), 'package.json'))); - const hasPWADep = Object.keys({ ...dependencies, ...devDependencies }) - .some(d => d === '@angular/pwa'); - if (hasPWADep) { - throw new Error(`Expected 'package.json' not to contain a dependency on '@angular/pwa'.`); - } - - // 'yarn' will nuke the entire node_modules when it is triggered during the above tests. - // Let's restore the previous node_modules state by re-installing using 'npm' - // and run 'webdriver-update'. Otherwise, we will start seeing errors in CI like: - // Error: Could not find update-config.json. Run 'webdriver-manager update' to download binaries. - await npm('install'); - await npm('run', 'webdriver-update'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-pwa.ts b/tests/legacy-cli/e2e/tests/commands/add/add-pwa.ts deleted file mode 100644 index e4737cd71c36..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/add-pwa.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { join } from 'path'; -import { expectFileToExist, readFile, rimraf } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - -export default async function () { - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/pwa'); - await ng('add', '@angular/pwa'); - await expectFileToExist(join(process.cwd(), 'src/manifest.webmanifest')); - - // Angular PWA doesn't install as a dependency - const { dependencies, devDependencies } = JSON.parse(await readFile(join(process.cwd(), 'package.json'))); - const hasPWADep = Object.keys({ ...dependencies, ...devDependencies }) - .some(d => d === '@angular/pwa'); - if (hasPWADep) { - throw new Error(`Expected 'package.json' not to contain a dependency on '@angular/pwa'.`); - } -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add.ts b/tests/legacy-cli/e2e/tests/commands/add/add.ts deleted file mode 100644 index 87aee9c82441..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/add.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { expectFileToExist, expectFileToMatch, rimraf } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - - -export default async function () { - await ng('add', '@angular-devkit-tests/ng-add-simple'); - await expectFileToMatch('package.json', /@angular-devkit-tests\/ng-add-simple/); - await expectFileToExist('ng-add-test'); - await rimraf('node_modules/@angular-devkit-tests/ng-add-simple'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/base.ts b/tests/legacy-cli/e2e/tests/commands/add/base.ts deleted file mode 100644 index b22583909076..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/base.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { expectFileToExist, rimraf, symlinkFile } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - - -export default async function () { - await symlinkFile(assetDir('add-collection'), `./node_modules/add-collection`, 'dir'); - - await ng('add', 'add-collection'); - await expectFileToExist('empty-file'); - - await ng('add', 'add-collection', '--name=blah'); - await expectFileToExist('blah'); - - await expectToFail(() => ng('add', 'add-collection')); // File already exists. - - // Cleanup the package - await rimraf('node_modules/add-collection'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/dir.ts b/tests/legacy-cli/e2e/tests/commands/add/dir.ts deleted file mode 100644 index d3c4b01d82e7..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/dir.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { expectFileToExist } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - - -export default async function () { - await ng('add', assetDir('add-collection'), '--name=blah'); - await expectFileToExist('blah'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/file.ts b/tests/legacy-cli/e2e/tests/commands/add/file.ts deleted file mode 100644 index 7cd61da0374b..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/file.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { expectFileToExist } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - - -export default async function () { - await ng('add', assetDir('add-collection.tgz'), '--name=blah'); - await expectFileToExist('blah'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/peer.ts b/tests/legacy-cli/e2e/tests/commands/add/peer.ts deleted file mode 100644 index ee1ece6dab6a..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/peer.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { ng } from '../../../utils/process'; - -const warning = 'Adding the package may not succeed.'; - -export default async function () { - const { stderr: bad } = await ng('add', assetDir('add-collection-peer-bad')); - if (!bad.includes(warning)) { - throw new Error('peer warning not shown on bad package'); - } - - const { stderr: base } = await ng('add', assetDir('add-collection')); - if (base.includes(warning)) { - throw new Error('peer warning shown on base package'); - } - - const { stderr: good } = await ng('add', assetDir('add-collection-peer-good')); - if (good.includes(warning)) { - throw new Error('peer warning shown on good package'); - } -} diff --git a/tests/legacy-cli/e2e/tests/commands/additional-properties.ts b/tests/legacy-cli/e2e/tests/commands/additional-properties.ts deleted file mode 100644 index b9a477c7cff6..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/additional-properties.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { createDir, rimraf, writeMultipleFiles } from '../../utils/fs'; -import { execAndWaitForOutputToMatch } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function() { - await createDir('example-builder'); - await writeMultipleFiles({ - 'example-builder/package.json': '{ "builders": "./builders.json" }', - 'example-builder/schema.json': '{ "$schema": "http://json-schema.org/draft-07/schema", "type": "object", "additionalProperties": true }', - 'example-builder/builders.json': '{ "$schema": "@angular-devkit/architect/src/builders-schema.json", "builders": { "example": { "implementation": "./example", "schema": "./schema.json" } } }', - 'example-builder/example.js': 'module.exports.default = require("@angular-devkit/architect").createBuilder((options) => { console.log(options); return { success: true }; });', - }); - - await updateJsonFile('angular.json', json => { - const appArchitect = json.projects['test-project'].architect; - appArchitect.example = { - builder: './example-builder:example', - }; - }); - - await execAndWaitForOutputToMatch( - 'ng', - ['run', 'test-project:example', '--additional', 'property'], - /'{ '--': \[ '--additional', 'property' \] }'/, - ); - - await rimraf('example-builder'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/build/build-outdir.ts b/tests/legacy-cli/e2e/tests/commands/build/build-outdir.ts deleted file mode 100644 index e83b6b04552b..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/build/build-outdir.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {ng} from '../../../utils/process'; -import {updateJsonFile} from '../../../utils/project'; -import {expectToFail} from '../../../utils/utils'; - -export default function() { - // TODO(architect): This isn't working correctly in devkit/build-angular, due to module resolution. - return; - - return Promise.resolve() - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.outputPath = './'; - })) - .then(() => expectToFail(() => ng('build'))) - .then(() => expectToFail(() => ng('serve'))); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-get.ts b/tests/legacy-cli/e2e/tests/commands/config/config-get.ts deleted file mode 100644 index 4786838afefc..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/config-get.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle'))) - .then(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'false')) - .then(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle')) - .then(({ stdout }) => { - if (!stdout.match(/false\n?/)) { - throw new Error(`Expected "false", received "${JSON.stringify(stdout)}".`); - } - }) - .then(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'true')) - .then(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle')) - .then(({ stdout }) => { - if (!stdout.match(/true\n?/)) { - throw new Error(`Expected "true", received "${JSON.stringify(stdout)}".`); - } - }) - .then(() => ng('config', 'schematics.@schematics/angular.component.inlineStyle', 'false')) - .then(() => ng('config', `projects.test-project.architect.build.options.assets[0]`)) - .then(({ stdout }) => { - if (!stdout.includes('src/favicon.ico')) { - throw new Error(`Expected "src/favicon.ico", received "${JSON.stringify(stdout)}".`); - } - }) - .then(() => ng('config', `projects["test-project"].architect.build.options.assets[0]`)) - .then(({ stdout }) => { - if (!stdout.includes('src/favicon.ico')) { - throw new Error(`Expected "src/favicon.ico", received "${JSON.stringify(stdout)}".`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-global.ts b/tests/legacy-cli/e2e/tests/commands/config/config-global.ts deleted file mode 100644 index 8327836fc500..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/config-global.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { homedir } from 'os'; -import * as path from 'path'; -import { deleteFile, expectFileToExist } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - - -export default async function() { - await expectToFail(() => ng( - 'config', - '--global', - 'schematics.@schematics/angular.component.inlineStyle', - )); - - await ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle', 'false'); - let output = await ng( - 'config', - '--global', - 'schematics.@schematics/angular.component.inlineStyle', - ); - if (!output.stdout.match(/false\n?/)) { - throw new Error(`Expected "false", received "${JSON.stringify(output.stdout)}".`); - } - - // This test requires schema querying capabilities - // .then(() => expectToFail(() => { - // return ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle', 'INVALID_BOOLEAN'); - // })) - - const cwd = process.cwd(); - process.chdir('/'); - try { - await ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle', 'true'); - } finally { - process.chdir(cwd); - } - - output = await ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle'); - if (!output.stdout.match(/true\n?/)) { - throw new Error(`Expected "true", received "${JSON.stringify(output.stdout)}".`); - } - - await expectToFail(() => ng('config', '--global', 'cli.warnings.notreal', 'true')); - - await ng('config', '--global', 'cli.warnings.versionMismatch', 'false'); - await expectFileToExist(path.join(homedir(), '.angular-config.json')); - await deleteFile(path.join(homedir(), '.angular-config.json')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-enum-check.ts b/tests/legacy-cli/e2e/tests/commands/config/config-set-enum-check.ts deleted file mode 100644 index aabf758930a9..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/config-set-enum-check.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - -export default async function() { - - // These tests require schema querying capabilities - // .then(() => expectToFail( - // () => ng('config', 'schematics.@schematics/angular.component.aaa', 'bbb')), - // ) - // .then(() => expectToFail(() => ng( - // 'config', - // 'schematics.@schematics/angular.component.viewEncapsulation', - // 'bbb', - // ))) - - await ng( - 'config', - 'schematics.@schematics/angular.component.viewEncapsulation', - 'Emulated', - ); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-prefix.ts b/tests/legacy-cli/e2e/tests/commands/config/config-set-prefix.ts deleted file mode 100644 index 904050649129..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/config-set-prefix.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => ng('config', 'schematics.@schematics/angular.component.prefix'))) - .then(() => ng('config', 'schematics.@schematics/angular.component.prefix' , 'new-prefix')) - .then(() => ng('config', 'schematics.@schematics/angular.component.prefix')) - .then(({ stdout }) => { - if (!stdout.match(/new-prefix/)) { - throw new Error(`Expected "new-prefix", received "${JSON.stringify(stdout)}".`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set.ts b/tests/legacy-cli/e2e/tests/commands/config/config-set.ts deleted file mode 100644 index cabf4c1373a6..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/config-set.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => ng('config', 'cli.warnings.zzzz'))) - .then(() => ng('config', 'cli.warnings.versionMismatch' , 'false')) - .then(() => ng('config', 'cli.warnings.versionMismatch')) - .then(({ stdout }) => { - if (!stdout.match(/false/)) { - throw new Error(`Expected "false", received "${JSON.stringify(stdout)}".`); - } - }) - .then(() => ng('config', 'cli.packageManager' , 'yarn')) - .then(() => ng('config', 'cli.packageManager')) - .then(({ stdout }) => { - if (!stdout.match(/yarn/)) { - throw new Error(`Expected "yarn", received "${JSON.stringify(stdout)}".`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/config/get-set-deprecation.ts b/tests/legacy-cli/e2e/tests/commands/config/get-set-deprecation.ts deleted file mode 100644 index ad9d3f106d17..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/config/get-set-deprecation.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {ng} from '../../../utils/process'; - - -export default function() { - const depRegEx = /get\/set have been deprecated in favor of the config command\./; - return Promise.resolve() - .then(() => ng('get')) - .then(({ stderr }) => { - if (!stderr.match(depRegEx)) { - throw new Error(`Expected deprecation warning.`); - } - }) - .then(() => ng('set')) - .then(({ stderr }) => { - if (!stderr.match(depRegEx)) { - throw new Error(`Expected deprecation warning.`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-hidden.ts b/tests/legacy-cli/e2e/tests/commands/help/help-hidden.ts deleted file mode 100644 index 5f88a787257c..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/help/help-hidden.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { oneLine } from 'common-tags'; - -import { silentNg } from '../../../utils/process'; - - -export default function() { - return Promise.resolve() - .then(() => silentNg('--help')) - .then(({ stdout }) => { - if (stdout.match(/(easter-egg)|(ng make-this-awesome)|(ng init)/)) { - throw new Error(oneLine` - Expected to not match "(easter-egg)|(ng make-this-awesome)|(ng init)" - in help output. - `); - } - }) - .then(() => silentNg('--help', 'new')) - .then(({ stdout }) => { - if (stdout.match(/--link-cli/)) { - throw new Error(oneLine` - Expected to not match "--link-cli" - in help output. - `); - } - }) -} diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-json.ts b/tests/legacy-cli/e2e/tests/commands/help/help-json.ts deleted file mode 100644 index af4f18872990..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/help/help-json.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { silentNg } from '../../../utils/process'; - - -export default async function() { - const commands = require('@angular/cli/commands.json'); - for (const commandName of Object.keys(commands)) { - const { stdout } = await silentNg(commandName, '--help=json'); - - if (stdout.trim()) { - JSON.parse(stdout); - } else { - console.warn(`No JSON output for command [${commandName}].`); - } - } -} diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-option-command.ts b/tests/legacy-cli/e2e/tests/commands/help/help-option-command.ts deleted file mode 100644 index c6782765b839..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/help/help-option-command.ts +++ /dev/null @@ -1,7 +0,0 @@ -import {silentNg} from '../../../utils/process'; - - -export default function() { - return Promise.resolve() - .then(() => silentNg('--help', 'build')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-option.ts b/tests/legacy-cli/e2e/tests/commands/help/help-option.ts deleted file mode 100644 index 03b96b5758d9..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/help/help-option.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {silentNg} from '../../../utils/process'; - - -export default function() { - return Promise.resolve() - .then(() => silentNg('--help')) - .then(() => process.chdir('/')) - .then(() => silentNg('--help')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/help/help.ts b/tests/legacy-cli/e2e/tests/commands/help/help.ts deleted file mode 100644 index f326f6a81ff8..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/help/help.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {silentNg} from '../../../utils/process'; - - -export default function() { - return Promise.resolve() - .then(() => silentNg('help')) - .then(() => process.chdir('/')) - .then(() => silentNg('help')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/check-yarn.ts b/tests/legacy-cli/e2e/tests/commands/new/check-yarn.ts deleted file mode 100644 index 9dd3bf411b4d..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/check-yarn.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {ng} from '../../../utils/process'; -import {getGlobalVariable} from '../../../utils/env'; - -const yarnRegEx = /You can `ng config -g cli.packageManager yarn`./; - -export default function() { - return Promise.resolve() - .then(() => process.chdir(getGlobalVariable('tmp-root'))) - .then(() => ng('config', '--global', 'packageManager', 'default')) - .then(() => ng('new', 'foo', '--version=1.6.8')) - .then(({ stdout }) => { - // Assuming yarn is installed and checking for message with yarn. - if (!stdout.match(yarnRegEx)) { - throw new Error('Should display message to use yarn packageManager'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/existing-directory.ts b/tests/legacy-cli/e2e/tests/commands/new/existing-directory.ts deleted file mode 100644 index 232874ff5ae4..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/existing-directory.ts +++ /dev/null @@ -1,14 +0,0 @@ -import * as fs from 'fs'; -import { promisify } from 'util'; -import {ng} from '../../../utils/process'; -import {getGlobalVariable} from '../../../utils/env'; - -const mkdir = promisify(fs.mkdir); - - -export default function() { - return Promise.resolve() - .then(() => process.chdir(getGlobalVariable('tmp-root'))) - .then(() => mkdir('empty-directory')) - .then(() => ng('new', 'foo', '--directory=empty-directory', '--skip-install', '--skip-git')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/new-minimal.ts b/tests/legacy-cli/e2e/tests/commands/new/new-minimal.ts deleted file mode 100644 index 8134d2490179..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/new-minimal.ts +++ /dev/null @@ -1,31 +0,0 @@ -import {ng} from '../../../utils/process'; -import {createProject} from '../../../utils/project'; -import {expectFileNotToExist, expectFileToMatch} from '../../../utils/fs'; -import {expectToFail} from '../../../utils/utils'; - - -export default function() { - // TODO(architect): re-enable after figuring out how a new minimal project looks like. - return ( - Promise.resolve() - .then(() => createProject('minimal-project', '--minimal')) - .then(() => expectFileNotToExist('.editorconfig')) - .then(() => expectFileNotToExist('README.md')) - .then(() => expectFileNotToExist('karma.conf.js')) - .then(() => expectFileNotToExist('protractor.conf.js')) - .then(() => expectFileNotToExist('src/test.ts')) - .then(() => expectFileNotToExist('tsconfig.spec.json')) - .then(() => expectFileNotToExist('tslint.json')) - .then(() => expectFileNotToExist('src/app/app.component.html')) - .then(() => expectFileNotToExist('src/app/app.component.css')) - .then(() => expectFileNotToExist('src/app/app.component.spec.ts')) - .then(() => expectFileNotToExist('src/app/favicon.ico')) - - .then(() => expectToFail(() => expectFileToMatch('package.json', '"protractor":'))) - .then(() => expectToFail(() => expectFileToMatch('package.json', '"karma":'))) - .then(() => expectToFail(() => expectFileToMatch('package.json', '"jasmine-core":'))) - - // Try to run a build. - .then(() => ng('build')) - ); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/new-routing.ts b/tests/legacy-cli/e2e/tests/commands/new/new-routing.ts deleted file mode 100644 index 5addb021d8a0..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/new-routing.ts +++ /dev/null @@ -1,11 +0,0 @@ -import {ng} from '../../../utils/process'; -import {createProject} from '../../../utils/project'; - - -export default function() { - return Promise.resolve() - .then(() => createProject('routing-project', '--routing')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/new-skip-commit.ts b/tests/legacy-cli/e2e/tests/commands/new/new-skip-commit.ts deleted file mode 100644 index adedb9dc2ac4..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/new-skip-commit.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {ng} from '../../../utils/process'; -import {createProject} from '../../../utils/project'; -import {expectToFail} from '../../../utils/utils'; -import {expectGitToBeClean} from '../../../utils/git'; - - -export default function() { - return Promise.resolve() - .then(() => createProject('new-project', '--skip-commit')) - .then(() => expectToFail(() => expectGitToBeClean())) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/new-skip-tests.ts b/tests/legacy-cli/e2e/tests/commands/new/new-skip-tests.ts deleted file mode 100644 index 95dde0a38e88..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/new-skip-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {createProject} from '../../../utils/project'; -import {expectFileNotToExist} from '../../../utils/fs'; - - -export default function() { - return Promise.resolve() - .then(() => createProject('new-project-skip-tests', '--skip-tests')) - .then(() => expectFileNotToExist('src/app/app.component.spec.ts')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/new/new-style.ts b/tests/legacy-cli/e2e/tests/commands/new/new-style.ts deleted file mode 100644 index c0e2d9e2b894..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/new/new-style.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {ng} from '../../../utils/process'; -import {createProject} from '../../../utils/project'; -import {expectFileToExist} from '../../../utils/fs'; - - -export default function() { - return Promise.resolve() - .then(() => ng('config', 'defaults.style', 'scss', '--global')) - .then(() => createProject('style-project')) - .then(() => expectFileToExist('src/app/app.component.scss')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/commands/serve/serve-path.ts b/tests/legacy-cli/e2e/tests/commands/serve/serve-path.ts deleted file mode 100644 index 2075b1acd3c0..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/serve/serve-path.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { request } from '../../../utils/http'; -import { killAllProcesses } from '../../../utils/process'; -import { ngServe } from '../../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return Promise.resolve() - .then(() => ngServe('--serve-path', 'test/')) - .then(() => request('http://localhost:4200/test')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => request('http://localhost:4200/test/abc')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - // .then(() => ngServe('--base-href', 'test/')) - // .then(() => request('http://localhost:4200/test')) - // .then(body => { - // if (!body.match(/<\/app-root>/)) { - // throw new Error('Response does not match expected value.'); - // } - // }) - // .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }); -} diff --git a/tests/legacy-cli/e2e/tests/commands/unknown-configuration.ts b/tests/legacy-cli/e2e/tests/commands/unknown-configuration.ts deleted file mode 100644 index 98257ee86e70..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/unknown-configuration.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ng } from "../../utils/process"; - -export default async function () { - try { - await ng('build', '--configuration', 'invalid'); - throw new Error('should have failed.'); - } catch (error) { - if (!error.message.includes(`Configuration 'invalid' is not set in the workspace`)) { - throw error; - } - } -}; diff --git a/tests/legacy-cli/e2e/tests/commands/unknown-option.ts b/tests/legacy-cli/e2e/tests/commands/unknown-option.ts deleted file mode 100644 index 220d74bc1646..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/unknown-option.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { execAndWaitForOutputToMatch, ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - await expectToFail(() => ng('build', '--notanoption')); - - await execAndWaitForOutputToMatch( - 'ng', - [ 'build', '--notanoption' ], - /Unknown option: '--notanoption'/, - ); - - await expectToFail(() => execAndWaitForOutputToMatch( - 'ng', - [ 'build', '--notanoption' ], - /should NOT have additional properties\(notanoption\)./, - )); - - const ngGenerateArgs = [ 'generate', 'component', 'component-name', '--notanoption' ]; - await expectToFail(() => ng(...ngGenerateArgs)); - - await execAndWaitForOutputToMatch( - 'ng', - ngGenerateArgs, - /Unknown option: '--notanoption'/, - ); -} diff --git a/tests/legacy-cli/e2e/tests/experimental/bep.ts b/tests/legacy-cli/e2e/tests/experimental/bep.ts deleted file mode 100644 index 863b1cac9397..000000000000 --- a/tests/legacy-cli/e2e/tests/experimental/bep.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ng } from '../../utils/process'; -import { expectFileToMatch } from '../../utils/fs'; - - -export default async function() { - await ng('build', '--build-event-log', 'bep-log.txt'); - - await expectFileToMatch('bep-log.txt', '{"id":{"started":{}},"started":{"command":"build",'); - await expectFileToMatch('bep-log.txt', '{"id":{"finished":{}},"finished":{"finish_time_millis":'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts b/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts deleted file mode 100644 index e5459bb9e185..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expectFileToMatch } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { useCIChrome } from '../../../utils/project'; - - -export default function() { - return ng('generate', 'application', 'app2') - .then(() => expectFileToMatch('angular.json', /\"app2\":/)) - .then(() => useCIChrome('projects/app2')) - .then(() => ng('test', 'app2', '--watch=false', '--browsers=ChromeHeadlessCI')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/class.ts b/tests/legacy-cli/e2e/tests/generate/class.ts deleted file mode 100644 index aa3ba25b5899..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/class.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../utils/process'; -import {expectFileToExist} from '../../utils/fs'; - - -export default function() { - const projectDir = join('src', 'app'); - - return ng('generate', 'class', 'test-class') - .then(() => expectFileToExist(projectDir)) - .then(() => expectFileToExist(join(projectDir, 'test-class.ts'))) - .then(() => expectFileToExist(join(projectDir, 'test-class.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-basic.ts b/tests/legacy-cli/e2e/tests/generate/component/component-basic.ts deleted file mode 100644 index 7c39f144d00d..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-basic.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist, expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const projectDir = join('src', 'app'); - const componentDir = join(projectDir, 'test-component'); - - const importCheck = - `import { TestComponentComponent } from './test-component/test-component.component';`; - return ng('generate', 'component', 'test-component') - .then(() => expectFileToExist(componentDir)) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.css'))) - .then(() => expectFileToMatch(join(projectDir, 'app.module.ts'), importCheck)) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-child-dir.ts b/tests/legacy-cli/e2e/tests/generate/component/component-child-dir.ts deleted file mode 100644 index 660e1e119c8c..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-child-dir.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {createDir, expectFileToExist} from '../../../utils/fs'; - - -export default function() { - const subDir = 'sub-dir'; - const componentDir = join('src', 'app', subDir, 'test-component'); - - return Promise.resolve() - .then(() => process.chdir('src')) - .then(() => process.chdir('app')) - .then(() => createDir(subDir)) - .then(() => process.chdir(subDir)) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => process.chdir('../../..')) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-duplicate.ts b/tests/legacy-cli/e2e/tests/generate/component/component-duplicate.ts deleted file mode 100644 index 94d73a23fcb3..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-duplicate.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectToFail } from '../../../utils/utils'; -import { oneLine } from 'common-tags'; - -export default function () { - return ng('generate', 'component', 'test-component') - .then((output) => { - if (!output.stdout.match(/UPDATE src[\\|\/]app[\\|\/]app.module.ts/)) { - throw new Error(oneLine` - Expected to match - "UPDATE src/app.module.ts" - in ${output.stdout}.`); - } - }) - .then(() => expectToFail(() => ng('generate', 'component', 'test-component'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-flag-case.ts b/tests/legacy-cli/e2e/tests/generate/component/component-flag-case.ts deleted file mode 100644 index a759ae01832a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-flag-case.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - // TODO:BREAKING CHANGE... NO LONGER SUPPORTED - return Promise.resolve(); - const compDir = join('projects', 'test-project', 'src', 'test'); - - return Promise.resolve() - .then(() => ng('generate', 'component', 'test', - '--change-detection', 'onpush', - '--view-encapsulation', 'emulated')) - .then(() => expectFileToMatch(join(compDir, 'test.component.ts'), - /changeDetection: ChangeDetectionStrategy.OnPush/)) - .then(() => expectFileToMatch(join(compDir, 'test.component.ts'), - /encapsulation: ViewEncapsulation.Emulated/)); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-flat.ts b/tests/legacy-cli/e2e/tests/generate/component/component-flat.ts deleted file mode 100644 index 448a6aef4df3..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-flat.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; -import {updateJsonFile} from '../../../utils/project'; - - -export default function() { - const appDir = join('src', 'app'); - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - configJson.projects['test-project'].schematics = { - '@schematics/angular:component': { flat: true } - }; - })) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => expectFileToExist(appDir)) - .then(() => expectFileToExist(join(appDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(appDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(appDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(appDir, 'test-component.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-in-existing-module-dir.ts b/tests/legacy-cli/e2e/tests/generate/component/component-in-existing-module-dir.ts deleted file mode 100644 index bb98447bb4a1..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-in-existing-module-dir.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; - -export default function () { - const modulePath = join('src', 'app', 'foo', 'foo.module.ts'); - - return Promise.resolve() - .then(() => ng('generate', 'module', 'foo')) - .then(() => ng('generate', 'component', 'foo')) - .then(() => expectFileToMatch(modulePath, /import { FooComponent } from '.\/foo.component'/)); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-inline-template.ts b/tests/legacy-cli/e2e/tests/generate/component/component-inline-template.ts deleted file mode 100644 index f76409820a1a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-inline-template.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; -import {updateJsonFile} from '../../../utils/project'; -import { expectToFail } from '../../../utils/utils'; - - -// tslint:disable:max-line-length -export default function() { - const componentDir = join('src', 'app', 'test-component'); - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - configJson.projects['test-project'].schematics = { - '@schematics/angular:component': { inlineTemplate: true } - }; - })) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => expectFileToExist(componentDir)) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.spec.ts'))) - .then(() => expectToFail(() => expectFileToExist(join(componentDir, 'test-component.component.html')))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-module-2.ts b/tests/legacy-cli/e2e/tests/generate/component/component-module-2.ts deleted file mode 100644 index 3036083e9241..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-module-2.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const root = process.cwd(); - const modulePath = join(root, 'src', 'app', - 'admin', 'module', 'module.module.ts'); - - return Promise.resolve() - .then(() => ng('generate', 'module', 'admin/module')) - .then(() => ng('generate', 'component', 'other/test-component', '--module', 'admin/module')) - .then(() => expectFileToMatch(modulePath, - new RegExp(/import { TestComponentComponent } /.source + - /from '..\/..\/other\/test-component\/test-component.component'/.source))) - - // Try to run the unit tests. - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-module-export.ts b/tests/legacy-cli/e2e/tests/generate/component/component-module-export.ts deleted file mode 100644 index c17e7f051468..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-module-export.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'component', 'test-component', '--export') - .then(() => expectFileToMatch(modulePath, 'exports: [TestComponentComponent]')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-module-fail.ts b/tests/legacy-cli/e2e/tests/generate/component/component-module-fail.ts deleted file mode 100644 index f4efd1eb8ff6..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-module-fail.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {ng} from '../../../utils/process'; -import {expectToFail} from '../../../utils/utils'; - - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => - ng('generate', 'component', 'test-component', '--module', 'app.moduleXXX.ts'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-module.ts b/tests/legacy-cli/e2e/tests/generate/component/component-module.ts deleted file mode 100644 index 53f6c161532a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-module.ts +++ /dev/null @@ -1,23 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const root = process.cwd(); - // projects/ test-project/ src/ app.module.ts - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'component', 'test-component', '--module', 'app.module.ts') - .then(() => expectFileToMatch(modulePath, - /import { TestComponentComponent } from '.\/test-component\/test-component.component'/)) - - .then(() => process.chdir(join(root, 'src', 'app'))) - .then(() => ng('generate', 'component', 'test-component2', '--module', 'app.module.ts')) - .then(() => process.chdir('../..')) - .then(() => expectFileToMatch(modulePath, - /import { TestComponent2Component } from '.\/test-component2\/test-component2.component'/)) - - // Try to run the unit tests. - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-not-flat.ts b/tests/legacy-cli/e2e/tests/generate/component/component-not-flat.ts deleted file mode 100644 index d25936fb6e4f..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-not-flat.ts +++ /dev/null @@ -1,25 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; -import {updateJsonFile} from '../../../utils/project'; - - -export default function() { - const componentDir = join('src', 'app', 'test-component'); - - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - configJson.projects['test-project'].schematics = { - '@schematics/angular:component': { flat: false } - }; - })) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => expectFileToExist(componentDir)) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-path-case.ts b/tests/legacy-cli/e2e/tests/generate/component/component-path-case.ts deleted file mode 100644 index 2a53a3446847..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-path-case.ts +++ /dev/null @@ -1,27 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; - - -export default function() { - const upperDirs = join('non', 'existing', 'dir'); - const rootDir = join('src', 'app', upperDirs); - - const componentDir = join(rootDir, 'test-component'); - const componentTwoDir = join(rootDir, 'test-component-two'); - - return ng('generate', 'component', `${upperDirs}/test-component`) - .then(() => expectFileToExist(componentDir)) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(componentDir, 'test-component.component.css'))) - .then(() => ng('generate', 'component', `${upperDirs}/Test-Component-Two`)) - .then(() => expectFileToExist(join(componentTwoDir, 'test-component-two.component.ts'))) - .then(() => expectFileToExist(join(componentTwoDir, 'test-component-two.component.spec.ts'))) - .then(() => expectFileToExist(join(componentTwoDir, 'test-component-two.component.html'))) - .then(() => expectFileToExist(join(componentTwoDir, 'test-component-two.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-prefix.ts b/tests/legacy-cli/e2e/tests/generate/component/component-prefix.ts deleted file mode 100644 index f63dece7672a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/component/component-prefix.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; -import { updateJsonFile } from '../../../utils/project'; - - -export default function() { - const testCompDir = join('src', 'app', 'test-component'); - const aliasCompDir = join('src', 'app', 'alias'); - - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - configJson.projects['test-project'].schematics = { - '@schematics/angular:component': { prefix: 'pre' } - }; - })) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => expectFileToMatch(join(testCompDir, 'test-component.component.ts'), - /selector: 'pre-/)) - .then(() => ng('g', 'c', 'alias')) - .then(() => expectFileToMatch(join(aliasCompDir, 'alias.component.ts'), - /selector: 'pre-/)) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-basic.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-basic.ts deleted file mode 100644 index b76308f26da3..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-basic.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {ng} from '../../../utils/process'; -import {join} from 'path'; -import {expectFileToExist} from '../../../utils/fs'; - - -export default function() { - const directiveDir = join('src', 'app'); - return ng('generate', 'directive', 'test-directive') - .then(() => expectFileToExist(join(directiveDir, 'test-directive.directive.ts'))) - .then(() => expectFileToExist(join(directiveDir, 'test-directive.directive.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-in-existing-module-dir.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-in-existing-module-dir.ts deleted file mode 100644 index 7dd270fe81a1..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-in-existing-module-dir.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; - -export default function () { - const modulePath = join('src', 'app', 'foo', 'foo.module.ts'); - - return Promise.resolve() - .then(() => ng('generate', 'module', 'foo')) - .then(() => ng('generate', 'directive', 'foo', '--no-flat')) - .then(() => expectFileToMatch(modulePath, /import { FooDirective } from '.\/foo.directive'/)); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-module-export.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-module-export.ts deleted file mode 100644 index 2e1499f2d0e2..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-module-export.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'directive', 'test-directive', '--export') - .then(() => expectFileToMatch(modulePath, 'exports: [TestDirectiveDirective]')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-module-fail.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-module-fail.ts deleted file mode 100644 index 05ff8d98f1c9..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-module-fail.ts +++ /dev/null @@ -1,8 +0,0 @@ -import {ng} from '../../../utils/process'; -import {expectToFail} from '../../../utils/utils'; - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => - ng('generate', 'directive', 'test-directive', '--module', 'app.moduleXXX.ts'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-module.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-module.ts deleted file mode 100644 index 5585253c8fac..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-module.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'directive', 'test-directive', '--module', 'app.module.ts') - .then(() => expectFileToMatch(modulePath, - /import { TestDirectiveDirective } from '.\/test-directive.directive'/)) - - .then(() => process.chdir(join('src', 'app'))) - .then(() => ng('generate', 'directive', 'test-directive2', '--module', 'app.module.ts')) - .then(() => process.chdir('../..')) - .then(() => expectFileToMatch(modulePath, - /import { TestDirective2Directive } from '.\/test-directive2.directive'/)) - - // Try to run the unit tests. - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts b/tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts deleted file mode 100644 index 7667915c7af3..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts +++ /dev/null @@ -1,40 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; -import { updateJsonFile, useCIChrome, useCIDefaults } from '../../../utils/project'; - - -export default function() { - const directiveDir = join('src', 'app'); - - return Promise.resolve() - .then(() => updateJsonFile('angular.json', configJson => { - configJson.schematics = { - '@schematics/angular:directive': { prefix: 'preW' } - }; - })) - .then(() => ng('generate', 'directive', 'test2-directive')) - .then(() => expectFileToMatch(join(directiveDir, 'test2-directive.directive.ts'), - /selector: '\[preW/)) - .then(() => ng('generate', 'application', 'app-two', '--skip-install')) - .then(() => useCIDefaults('app-two')) - .then(() => useCIChrome('./projects/app-two')) - .then(() => updateJsonFile('angular.json', configJson => { - configJson.projects['test-project'].schematics = { - '@schematics/angular:directive': { prefix: 'preP' } - }; - })) - .then(() => process.chdir('projects/app-two')) - .then(() => ng('generate', 'directive', '--skip-import', 'test3-directive')) - .then(() => process.chdir('../..')) - .then(() => expectFileToMatch(join('projects', 'app-two', 'test3-directive.directive.ts'), - /selector: '\[preW/)) - .then(() => process.chdir('src/app')) - .then(() => ng('generate', 'directive', 'test-directive')) - .then(() => process.chdir('../..')) - .then(() => expectFileToMatch(join(directiveDir, 'test-directive.directive.ts'), - /selector: '\[preP/)) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/generate-error.ts b/tests/legacy-cli/e2e/tests/generate/generate-error.ts deleted file mode 100644 index 08d85cc02b43..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/generate-error.ts +++ /dev/null @@ -1,8 +0,0 @@ -import {ng} from '../../utils/process'; -import {deleteFile} from '../../utils/fs'; -import {expectToFail} from '../../utils/utils'; - -export default function() { - return deleteFile('angular.json') - .then(() => expectToFail(() => ng('generate', 'class', 'hello'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/generate-name-check.ts b/tests/legacy-cli/e2e/tests/generate/generate-name-check.ts deleted file mode 100644 index a42a5cd6ca9a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/generate-name-check.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../utils/process'; -import {expectFileToExist} from '../../utils/fs'; -import {updateJsonFile} from '../../utils/project'; - - -export default function() { - const compDir = join('src', 'app', 'test-component'); - - return Promise.resolve() - .then(() => updateJsonFile('package.json', configJson => { - delete configJson.name; - return configJson; - })) - .then(() => ng('generate', 'component', 'test-component')) - .then(() => expectFileToExist(compDir)) - .then(() => expectFileToExist(join(compDir, 'test-component.component.ts'))) - .then(() => expectFileToExist(join(compDir, 'test-component.component.spec.ts'))) - .then(() => expectFileToExist(join(compDir, 'test-component.component.html'))) - .then(() => expectFileToExist(join(compDir, 'test-component.component.css'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/generate-name-error.ts b/tests/legacy-cli/e2e/tests/generate/generate-name-error.ts deleted file mode 100644 index 2fb0583ca514..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/generate-name-error.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {ng} from '../../utils/process'; -import {expectToFail} from '../../utils/utils'; - - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => - ng('generate', 'component', '1my-component'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-basic.ts b/tests/legacy-cli/e2e/tests/generate/guard/guard-basic.ts deleted file mode 100644 index 7148fb0b5bf5..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/guard/guard-basic.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist, expectFileToMatch} from '../../../utils/fs'; - - -export default async function() { - // Does not create a sub directory. - const guardDir = join('src', 'app'); - - await ng('generate', 'guard', 'test-guard'); - await expectFileToExist(guardDir); - await expectFileToExist(join(guardDir, 'test-guard.guard.ts')); - await expectFileToMatch(join(guardDir, 'test-guard.guard.ts'), /implements CanActivate/); - await expectFileToExist(join(guardDir, 'test-guard.guard.spec.ts')); - await ng('test', '--watch=false'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-implements.ts b/tests/legacy-cli/e2e/tests/generate/guard/guard-implements.ts deleted file mode 100644 index 5dcf2a32d18c..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/guard/guard-implements.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist,expectFileToMatch} from '../../../utils/fs'; - - -export default async function() { - // Does not create a sub directory. - const guardDir = join('src', 'app'); - - await ng('generate', 'guard', 'load', '--implements=CanLoad'); - await expectFileToExist(guardDir); - await expectFileToExist(join(guardDir, 'load.guard.ts')); - await expectFileToMatch(join(guardDir, 'load.guard.ts'), /implements CanLoad/); - await expectFileToExist(join(guardDir, 'load.guard.spec.ts')); - await ng('test', '--watch=false'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-multiple-implements.ts b/tests/legacy-cli/e2e/tests/generate/guard/guard-multiple-implements.ts deleted file mode 100644 index a91bfd0ddde5..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/guard/guard-multiple-implements.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist,expectFileToMatch} from '../../../utils/fs'; - - -export default async function() { - // Does not create a sub directory. - const guardDir = join('src', 'app'); - - await ng('generate', 'guard', 'load', '--implements=CanLoad', '--implements=CanDeactivate'); - await expectFileToExist(guardDir); - await expectFileToExist(join(guardDir, 'load.guard.ts')); - await expectFileToMatch(join(guardDir, 'load.guard.ts'), /implements CanLoad, CanDeactivate/); - await expectFileToExist(join(guardDir, 'load.guard.spec.ts')); - await ng('test', '--watch=false'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/help-output.ts b/tests/legacy-cli/e2e/tests/generate/help-output.ts deleted file mode 100644 index 7fc079729562..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/help-output.ts +++ /dev/null @@ -1,126 +0,0 @@ -import {join} from 'path'; -import {ng, ProcessOutput} from '../../utils/process'; -import {writeMultipleFiles, createDir} from '../../utils/fs'; -import { updateJsonFile } from '../../utils/project'; - - -export default function() { - // setup temp collection - const genRoot = join('node_modules/fake-schematics/'); - - return Promise.resolve() - .then(() => createDir(genRoot)) - .then(() => writeMultipleFiles({ - [join(genRoot, 'package.json')]: ` - { - "schematics": "./collection.json" - }`, - [join(genRoot, 'collection.json')]: ` - { - "schematics": { - "fake": { - "factory": "./fake", - "description": "Fake schematic", - "schema": "./fake-schema.json" - }, - } - }`, - [join(genRoot, 'fake-schema.json')]: ` - { - "id": "FakeSchema", - "title": "Fake Schema", - "type": "object", - "properties": { - "b": { - "type": "string", - "description": "b.", - "$default": { - "$source": "argv", - "index": 1 - } - }, - "a": { - "type": "string", - "description": "a.", - "$default": { - "$source": "argv", - "index": 0 - } - }, - "optC": { - "type": "string", - "description": "optC" - }, - "optA": { - "type": "string", - "description": "optA" - }, - "optB": { - "type": "string", - "description": "optB" - } - }, - "required": [] - }`, - [join(genRoot, 'fake.js')]: ` - function def(options) { - return (host, context) => { - return host; - }; - } - exports.default = def; - `}, - )) - .then(() => ng('generate', 'fake-schematics:fake', '--help')) - .then(({stdout}) => { - if (!/ng generate fake-schematics:fake \[options\]/.test(stdout)) { - throw new Error('Help signature is wrong (1).'); - } - if (!/opt-a[\s\S]*opt-b[\s\S]*opt-c/.test(stdout)) { - throw new Error('Help signature options are incorrect.'); - } - }) - // set up default collection. - .then(() => updateJsonFile('angular.json', json => { - json.cli = json.cli || {} as any; - json.cli.defaultCollection = 'fake-schematics'; - })) - .then(() => ng('generate', 'fake', '--help')) - // verify same output - .then(({stdout}) => { - if (!/ng generate fake \[options\]/.test(stdout)) { - throw new Error('Help signature is wrong (2).'); - } - if (!/opt-a[\s\S]*opt-b[\s\S]*opt-c/.test(stdout)) { - throw new Error('Help signature options are incorrect.'); - } - }) - - // should print all the available schematics in a collection - // when a collection has more than 1 schematic - .then(() => writeMultipleFiles({ - [join(genRoot, 'collection.json')]: ` - { - "schematics": { - "fake": { - "factory": "./fake", - "description": "Fake schematic", - "schema": "./fake-schema.json" - }, - "fake-two": { - "factory": "./fake", - "description": "Fake schematic", - "schema": "./fake-schema.json" - }, - } - }`, - })) - .then(() => ng('generate', '--help')) - .then(({stdout}) => { - if (!/Collection \"fake-schematics\" \(default\):[\s\S]*fake[\s\S]*fake-two/.test(stdout)) { - throw new Error( - `Help result is wrong, it didn't contain all the schematics.`); - } - }); - -} diff --git a/tests/legacy-cli/e2e/tests/generate/interceptor/interceptor-basic.ts b/tests/legacy-cli/e2e/tests/generate/interceptor/interceptor-basic.ts deleted file mode 100755 index 19e27eeed5dc..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/interceptor/interceptor-basic.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; - - -export default function() { - // Does not create a sub directory. - const interceptorDir = join('src', 'app'); - - return ng('generate', 'interceptor', 'test-interceptor') - .then(() => expectFileToExist(interceptorDir)) - .then(() => expectFileToExist(join(interceptorDir, 'test-interceptor.interceptor.ts'))) - .then(() => expectFileToExist(join(interceptorDir, 'test-interceptor.interceptor.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/interface.ts b/tests/legacy-cli/e2e/tests/generate/interface.ts deleted file mode 100644 index e74f2570f4f1..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/interface.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../utils/process'; -import {expectFileToExist} from '../../utils/fs'; - - -export default function() { - const interfaceDir = join('src', 'app'); - - return ng('generate', 'interface', 'test-interface', 'model') - .then(() => expectFileToExist(interfaceDir)) - .then(() => expectFileToExist(join(interfaceDir, 'test-interface.model.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/library/library-basic.ts b/tests/legacy-cli/e2e/tests/generate/library/library-basic.ts deleted file mode 100644 index a4a29f2be493..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/library/library-basic.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ng } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; -import { useCIChrome } from '../../../utils/project'; - -export default function () { - return ng('generate', 'library', 'my-lib') - .then(() => expectFileToMatch('angular.json', /\"my-lib\":/)) - .then(() => useCIChrome('projects/my-lib')) - .then(() => ng('build', 'my-lib')) - .then(() => ng('test', 'my-lib', '--watch=false', '--browsers=ChromeHeadlessCI')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/library/library-consumption.ts b/tests/legacy-cli/e2e/tests/generate/library/library-consumption.ts deleted file mode 100644 index ff222d77cda4..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/library/library-consumption.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { writeFile } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - -export default async function () { - await ng('generate', 'library', 'my-lib'); - await writeFile('./src/app/app.module.ts', ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - import { MyLibModule } from 'my-lib'; - - import { AppComponent } from './app.component'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - MyLibModule, - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - `); - - await writeFile('./src/app/app.component.ts', ` - import { Component } from '@angular/core'; - import { MyLibService } from 'my-lib'; - - @Component({ - selector: 'app-root', - template: '' - }) - export class AppComponent { - title = 'app'; - - constructor(myLibService: MyLibService) { - console.log(myLibService); - } - } - `); - - await writeFile('e2e/src/app.e2e-spec.ts', ` - import { browser, logging, element, by } from 'protractor'; - import { AppPage } from './app.po'; - - describe('workspace-project App', () => { - let page: AppPage; - - beforeEach(() => { - page = new AppPage(); - }); - - it('should display text from library component', () => { - page.navigateTo(); - expect(element(by.css('lib-my-lib p')).getText()).toEqual('my-lib works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); - }); - `); - - await runLibraryTests(); - await runLibraryTests(true); -} - -async function runLibraryTests(prodMode = false): Promise { - const args = ['build', 'my-lib']; - if (prodMode) { - args.push('--prod'); - } - - await ng(...args); - - // Check that the tests succeeds both with named project, unnammed (should test app), and prod. - await ng('e2e'); - await ng('e2e', 'test-project', '--devServerTarget=test-project:serve:production'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/lint-fix.ts b/tests/legacy-cli/e2e/tests/generate/lint-fix.ts deleted file mode 100644 index 10394ca45561..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/lint-fix.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { expectToFail } from '../../utils/utils'; - -export default function () { - const nestedConfigContent = ` - { - "rules": { - "quotemark": [ - true, - "double", - "avoid-escape" - ] - } - }`; - - return Promise.resolve() - - // setup a double-quote tslint config - .then(() => writeFile('src/app/tslint.json', nestedConfigContent)) - - // Generate a fixed new component but don't fix rest of app - .then(() => ng('generate', 'component', 'test-component1', '--lint-fix')) - .then(() => expectToFail(() => ng('lint'))) - - // Fix rest of app and generate new component - .then(() => ng('lint', '--fix')) - .then(() => ng('generate', 'component', 'test-component2', '--lint-fix')) - .then(() => ng('lint')) - - // Enable default option and generate all other module related blueprints - .then(() => ng('config', 'schematics.@schematics/angular.directive.lintFix', 'true')) - .then(() => ng('config', 'schematics.@schematics/angular.service.lintFix', 'true')) - .then(() => ng('config', 'schematics.@schematics/angular.pipe.lintFix', 'true')) - .then(() => ng('config', 'schematics.@schematics/angular.guard.lintFix', 'true')) - .then(() => ng('generate', 'directive', 'test-directive')) - .then(() => ng('generate', 'service', 'test-service')) - .then(() => ng('generate', 'pipe', 'test-pipe')) - .then(() => ng('generate', 'guard', 'test-guard')) - .then(() => ng('lint')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-basic.ts b/tests/legacy-cli/e2e/tests/generate/module/module-basic.ts deleted file mode 100644 index b78c3c22a112..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/module/module-basic.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist, expectFileToMatch} from '../../../utils/fs'; -import {expectToFail} from '../../../utils/utils'; - - -export default function() { - const moduleDir = join('src', 'app', 'test'); - - return ng('generate', 'module', 'test') - .then(() => expectFileToExist(moduleDir)) - .then(() => expectFileToExist(join(moduleDir, 'test.module.ts'))) - .then(() => expectToFail(() => expectFileToExist(join(moduleDir, 'test-routing.module.ts')))) - .then(() => expectToFail(() => expectFileToExist(join(moduleDir, 'test.spec.ts')))) - .then(() => expectFileToMatch(join(moduleDir, 'test.module.ts'), 'TestModule')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-import.ts b/tests/legacy-cli/e2e/tests/generate/module/module-import.ts deleted file mode 100644 index 1e00993bc858..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/module/module-import.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; - -export default function () { - const root = process.cwd(); - const modulePath = join(root, 'src', 'app', 'app.module.ts'); - const subModulePath = join('src', 'app', 'sub', 'sub.module.ts'); - const deepSubModulePath = join('src', 'app', 'sub', 'deep', 'deep.module.ts'); - - return Promise.resolve() - .then(() => ng('generate', 'module', 'sub')) - .then(() => ng('generate', 'module', 'sub/deep')) - - .then(() => ng('generate', 'module', 'test1', '--module', 'app.module.ts')) - .then(() => expectFileToMatch(modulePath, - /import { Test1Module } from '.\/test1\/test1.module'/)) - .then(() => expectFileToMatch(modulePath, /imports: \[(.|\s)*Test1Module(.|\s)*\]/m)) - - .then(() => ng('generate', 'module', 'test2', '--module', 'app.module')) - .then(() => expectFileToMatch(modulePath, - /import { Test2Module } from '.\/test2\/test2.module'/)) - .then(() => expectFileToMatch(modulePath, /imports: \[(.|\s)*Test2Module(.|\s)*\]/m)) - - .then(() => ng('generate', 'module', 'test3', '--module', 'app')) - .then(() => expectFileToMatch(modulePath, - /import { Test3Module } from '.\/test3\/test3.module'/)) - .then(() => expectFileToMatch(modulePath, /imports: \[(.|\s)*Test3Module(.|\s)*\]/m)) - - .then(() => ng('generate', 'module', 'test4', '--routing', '--module', 'app')) - .then(() => expectFileToMatch(modulePath, /imports: \[(.|\s)*Test4Module(.|\s)*\]/m)) - .then(() => expectFileToMatch(join('src', 'app', 'test4', 'test4.module.ts'), - /import { Test4RoutingModule } from '.\/test4-routing.module'/)) - .then(() => expectFileToMatch(join('src', 'app', 'test4', 'test4.module.ts'), - /imports: \[(.|\s)*Test4RoutingModule(.|\s)*\]/m)) - - .then(() => ng('generate', 'module', 'test5', '--module', 'sub')) - .then(() => expectFileToMatch(subModulePath, - /import { Test5Module } from '..\/test5\/test5.module'/)) - .then(() => expectFileToMatch(subModulePath, /imports: \[(.|\s)*Test5Module(.|\s)*\]/m)) - - .then(() => ng('generate', 'module', 'test6', '--module', join('sub', 'deep')) - .then(() => expectFileToMatch(deepSubModulePath, - /import { Test6Module } from '..\/..\/test6\/test6.module'/)) - .then(() => expectFileToMatch(deepSubModulePath, /imports: \[(.|\s)*Test6Module(.|\s)*\]/m))); - - // E2E_DISABLE: temporarily disable pending investigation - // .then(() => process.chdir(join(root, 'src', 'app'))) - // .then(() => ng('generate', 'module', 'test7', '--module', 'app.module.ts')) - // .then(() => process.chdir('..')) - // .then(() => expectFileToMatch(modulePath, - // /import { Test7Module } from '.\/test7\/test7.module'/)) - // .then(() => expectFileToMatch(modulePath, /imports: \[(.|\s)*Test7Module(.|\s)*\]/m)); -} diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-routing-child-folder.ts b/tests/legacy-cli/e2e/tests/generate/module/module-routing-child-folder.ts deleted file mode 100644 index 240588a8967d..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/module/module-routing-child-folder.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../../utils/process'; -import { expectFileToExist } from '../../../utils/fs'; -import { expectToFail } from '../../../utils/utils'; - - -export default function () { - const root = process.cwd(); - const testPath = join(root, 'src', 'app'); - - process.chdir(testPath); - - return Promise.resolve() - .then(() => - ng('generate', 'module', 'sub-dir/child', '--routing') - .then(() => expectFileToExist(join(testPath, 'sub-dir/child'))) - .then(() => expectFileToExist(join(testPath, 'sub-dir/child', 'child.module.ts'))) - .then(() => expectFileToExist(join(testPath, 'sub-dir/child', 'child-routing.module.ts'))) - .then(() => expectToFail(() => - expectFileToExist(join(testPath, 'sub-dir/child', 'child.spec.ts')) - )) - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')) - ); -} diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-routing.ts b/tests/legacy-cli/e2e/tests/generate/module/module-routing.ts deleted file mode 100644 index cf6208b0a84c..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/module/module-routing.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; -import {expectToFail} from '../../../utils/utils'; - - -export default function() { - const moduleDir = join('src', 'app', 'test'); - - return ng('generate', 'module', 'test', '--routing') - .then(() => expectFileToExist(moduleDir)) - .then(() => expectFileToExist(join(moduleDir, 'test.module.ts'))) - .then(() => expectFileToExist(join(moduleDir, 'test-routing.module.ts'))) - .then(() => expectToFail(() => expectFileToExist(join(moduleDir, 'test.spec.ts')))) - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-basic.ts b/tests/legacy-cli/e2e/tests/generate/pipe/pipe-basic.ts deleted file mode 100644 index 0480c13cd2ff..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-basic.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; - -import {expectFileToExist} from '../../../utils/fs'; - -export default function() { - // Create the pipe in the same directory. - const pipeDir = join('src', 'app'); - - return ng('generate', 'pipe', 'test-pipe') - .then(() => expectFileToExist(pipeDir)) - .then(() => expectFileToExist(join(pipeDir, 'test-pipe.pipe.ts'))) - .then(() => expectFileToExist(join(pipeDir, 'test-pipe.pipe.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-in-existing-module-dir.ts b/tests/legacy-cli/e2e/tests/generate/pipe/pipe-in-existing-module-dir.ts deleted file mode 100644 index 2055643a1b5b..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-in-existing-module-dir.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; - -export default function () { - const modulePath = join('src', 'app', 'foo', 'foo.module.ts'); - - return Promise.resolve() - .then(() => ng('generate', 'module', 'foo')) - .then(() => ng('generate', 'pipe', 'foo', '--no-flat')) - .then(() => expectFileToMatch(modulePath, /import { FooPipe } from '.\/foo.pipe'/)); -} diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-export.ts b/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-export.ts deleted file mode 100644 index 570f7b339bcb..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-export.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'pipe', 'test-pipe', '--export') - .then(() => expectFileToMatch(modulePath, 'exports: [TestPipePipe]')) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-fail.ts b/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-fail.ts deleted file mode 100644 index e18d5e73d038..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module-fail.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {ng} from '../../../utils/process'; -import {expectToFail} from '../../../utils/utils'; - - -export default function() { - return Promise.resolve() - .then(() => expectToFail(() => - ng('generate', 'pipe', 'test-pipe', '--module', 'app.moduleXXX.ts'))); -} diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module.ts b/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module.ts deleted file mode 100644 index e5986f01ec57..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-module.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToMatch} from '../../../utils/fs'; - - -export default function() { - const modulePath = join('src', 'app', 'app.module.ts'); - - return ng('generate', 'pipe', 'test-pipe', '--module', 'app.module.ts') - .then(() => expectFileToMatch(modulePath, - /import { TestPipePipe } from '.\/test-pipe.pipe'/)) - - .then(() => process.chdir(join('src', 'app'))) - .then(() => ng('generate', 'pipe', 'test-pipe2', '--module', 'app.module.ts')) - .then(() => process.chdir('../..')) - .then(() => expectFileToMatch(modulePath, - /import { TestPipe2Pipe } from '.\/test-pipe2.pipe'/)) - - // Try to run the unit tests. - .then(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/service/service-basic.ts b/tests/legacy-cli/e2e/tests/generate/service/service-basic.ts deleted file mode 100644 index 3ebd58fc977c..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/service/service-basic.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../../utils/process'; -import {expectFileToExist} from '../../../utils/fs'; - - -export default function() { - // Does not create a sub directory. - const serviceDir = join('src', 'app'); - - return ng('generate', 'service', 'test-service') - .then(() => expectFileToExist(serviceDir)) - .then(() => expectFileToExist(join(serviceDir, 'test-service.service.ts'))) - .then(() => expectFileToExist(join(serviceDir, 'test-service.service.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/build-locale.ts b/tests/legacy-cli/e2e/tests/i18n/build-locale.ts deleted file mode 100644 index cfc3ef2120cc..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/build-locale.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { expectFileToMatch, rimraf } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function () { - const argv = getGlobalVariable('argv'); - const veEnabled = argv['ve']; - if (!veEnabled) { - return; - } - - // These tests should be moved to the default when we use ng5 in new projects. - return Promise.resolve() - // tests for register_locale_data transformer - .then(() => ng('build', '--aot', '--i18n-locale=fr')) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /registerLocaleData/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /angular_common_locales_fr/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /registerLocaleData/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /angular_common_locales_fr/)) - .then(() => expectFileToMatch('dist/test-project/index.html', /lang="fr"/)) - .then(() => rimraf('dist')) - .then(() => ng('build', '--aot', '--i18n-locale=fr_FR')) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /registerLocaleData/)) - .then(() => expectFileToMatch('dist/test-project/main-es2015.js', /angular_common_locales_fr/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /registerLocaleData/)) - .then(() => expectFileToMatch('dist/test-project/main-es5.js', /angular_common_locales_fr/)) - .then(() => expectFileToMatch('dist/test-project/index.html', /lang="fr_FR"/)) - .then(() => rimraf('dist')); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-default.ts b/tests/legacy-cli/e2e/tests/i18n/extract-default.ts deleted file mode 100644 index fb7a2d135993..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-default.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { join } from 'path'; -import { expectFileToExist, expectFileToMatch, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - await ng('generate', 'component', 'i18n-test'); - await writeFile( - join('src/app/i18n-test', 'i18n-test.component.html'), - '

Hello world

', - ); - await ng('xi18n'); - await expectFileToExist('messages.xlf'); - await expectFileToMatch('messages.xlf', /Hello world/); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-errors.ts b/tests/legacy-cli/e2e/tests/i18n/extract-errors.ts deleted file mode 100644 index a000ba27e404..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-errors.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { expectToFail } from '../../utils/utils'; -import { join } from 'path'; - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('generate', 'component', 'i18n-test') - .then(() => writeFile( - join('src/app/i18n-test', 'i18n-test.component.html'), - '

Hello world inner

')) - .then(() => expectToFail(() => ng('xi18n'))) - .then(({ message }) => { - if (!message.includes('Could not mark an element as' + - ' translatable inside a translatable section')) { - throw new Error(`Expected i18n extraction error, got this instead:\n${message}`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-locale.ts b/tests/legacy-cli/e2e/tests/i18n/extract-locale.ts deleted file mode 100644 index 5c1b5e05bc09..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-locale.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { join } from 'path'; -import { ng } from '../../utils/process'; -import { writeFile, expectFileToMatch } from '../../utils/fs'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('generate', 'component', 'i18n-test') - .then(() => writeFile( - join('src/app/i18n-test', 'i18n-test.component.html'), - '

Hello world

')) - .then(() => ng('xi18n', '--i18n-locale', 'fr')) - .then((output) => { - if (!output.stderr.match(/starting from Angular v4/)) { - return expectFileToMatch('messages.xlf', 'source-language="fr"'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-outfile.ts b/tests/legacy-cli/e2e/tests/i18n/extract-outfile.ts deleted file mode 100644 index 5daf48417c98..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-outfile.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../utils/process'; -import { writeFile, expectFileToMatch } from '../../utils/fs'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('generate', 'component', 'i18n-test') - .then(() => writeFile( - join('src/app/i18n-test', 'i18n-test.component.html'), - '

Hello world

')) - .then(() => ng('xi18n', '--out-file', 'messages.fr.xlf')) - .then((output) => { - if (!output.stdout.match(/starting from Angular v4/)) { - return expectFileToMatch('messages.fr.xlf', 'Hello world'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-output.ts b/tests/legacy-cli/e2e/tests/i18n/extract-output.ts deleted file mode 100644 index 8a82ff241450..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-output.ts +++ /dev/null @@ -1,18 +0,0 @@ -export default function temporarilyDisabledTest() { return Promise.resolve(); } -// import {join} from 'path'; -// import {ng} from '../../utils/process'; -// import { -// expectFileToExist, writeFile, -// expectFileToMatch -// } from '../../utils/fs'; - - -// export default function() { -// return ng('generate', 'component', 'i18n-test') -// .then(() => writeFile( -// join('src/app/i18n-test', 'i18n-test.component.html'), -// '

Hello world

')) -// .then(() => ng('xi18n', '--output-path', 'src/locale')) -// .then(() => expectFileToExist(join('src', 'locale', 'messages.xlf'))) -// .then(() => expectFileToMatch(join('src', 'locale', 'messages.xlf'), /Hello world/)); -// } diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-xmb.ts b/tests/legacy-cli/e2e/tests/i18n/extract-xmb.ts deleted file mode 100644 index c5dd1c5a85f2..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/extract-xmb.ts +++ /dev/null @@ -1,19 +0,0 @@ -import {join} from 'path'; -import {ng} from '../../utils/process'; -import { - expectFileToExist, writeFile, - expectFileToMatch -} from '../../utils/fs'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('generate', 'component', 'i18n-test') - .then(() => - writeFile(join('src/app/i18n-test', 'i18n-test.component.html'), '

Hello world

'), - ) - .then(() => ng('xi18n', '--format', 'xmb')) - .then(() => expectFileToExist('messages.xmb')) - .then(() => expectFileToMatch('messages.xmb', /Hello world/)); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts deleted file mode 100644 index f6be20dfca50..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { - appendToFile, - copyFile, - expectFileToExist, - expectFileToMatch, - replaceInFile, - writeFile, -} from '../../utils/fs'; -import { ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { readNgVersion } from '../../utils/version'; - -const snapshots = require('../../ng-snapshot/package.json'); - -export default async function () { - // TEMP: disable pending i18n updates - // TODO: when re-enabling, use setupI18nConfig and helpers like other i18n tests. - return; - - const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; - - await updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/localize'] = isSnapshotBuild - ? snapshots.dependencies['@angular/localize'] - : readNgVersion(); - }); - - await appendToFile('src/app/app.component.html', ''); - await ng('generate', 'appShell', '--client-project', 'test-project'); - - if (isSnapshotBuild) { - await updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; - dependencies['@angular/router'] = snapshots.dependencies['@angular/router']; - }); - } - - await silentNpm('install'); - - const browserBaseDir = 'dist/test-project/browser'; - - // Set configurations for each locale. - const langTranslations = [ - { lang: 'en-US', translation: 'Hello i18n!' }, - { lang: 'fr', translation: 'Bonjour i18n!' }, - ]; - - await updateJsonFile('angular.json', workspaceJson => { - const appProject = workspaceJson.projects['test-project']; - const appArchitect = appProject.architect || appProject.targets; - const buildOptions = appArchitect['build'].options; - const serverOptions = appArchitect['server'].options; - - // Make default builds prod. - buildOptions.optimization = true; - buildOptions.buildOptimizer = true; - buildOptions.aot = true; - buildOptions.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; - - serverOptions.optimization = true; - serverOptions.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; - - // Enable localization for all locales - buildOptions.localize = true; - serverOptions.localize = true; - - // Add locale definitions to the project - // tslint:disable-next-line: no-any - const i18n: Record = (appProject.i18n = { locales: {} }); - for (const { lang } of langTranslations) { - if (lang == 'en-US') { - i18n.sourceLocale = lang; - } else { - i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; - } - } - }); - - await writeFile( - 'src/app/app-shell/app-shell.component.html', - '

Hello i18n!

', - ); - - // Add a translatable element - // Extraction of i18n only works on browser targets. - // Let's add the same translation that there is in the app-shell - await writeFile( - 'src/app/app.component.html', - '

Hello i18n!

', - ); - - // Extract the translation messages and copy them for each language. - await ng('xi18n', '--output-path=src/locale'); - await expectFileToExist('src/locale/messages.xlf'); - await expectFileToMatch('src/locale/messages.xlf', `source-language="en-US"`); - await expectFileToMatch('src/locale/messages.xlf', `An introduction header for this sample`); - - // Clean up app.component.html so that we can easily - // find the translation text - await writeFile( - 'src/app/app.component.html', - '', - ); - - for (const { lang, translation } of langTranslations) { - if (lang != 'en-US') { - await copyFile('src/locale/messages.xlf', `src/locale/messages.${lang}.xlf`); - await replaceInFile( - `src/locale/messages.${lang}.xlf`, - 'source-language="en-US"', - `source-language="en-US" target-language="${lang}"`, - ); - await replaceInFile( - `src/locale/messages.${lang}.xlf`, - 'Hello i18n!', - `Hello i18n!\n${translation}`, - ); - } - } - - // Build each locale and verify the output. - await ng('run', 'test-project:app-shell'); - - for (const { lang, translation } of langTranslations) { - await expectFileToMatch(`${browserBaseDir}/${lang}/index.html`, translation); - } -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-dl.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-dl.ts deleted file mode 100644 index d0ac318f04d2..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-dl.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { appendToFile, expectFileToMatch } from '../../utils/fs'; -import { execAndWaitForOutputToMatch, killAllProcesses, ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { baseDir, externalServer, langTranslations, setupI18nConfig } from './legacy'; - -export default async function() { - // Setup i18n tests and config. - await setupI18nConfig(); - - // Ensure a DL build is used. - await updateJsonFile('tsconfig.json', config => { - config.compilerOptions.target = 'es2015'; - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - - // Build each locale and verify the output. - await ng('build'); - for (const { lang, outputPath, translation } of langTranslations) { - await expectFileToMatch(`${outputPath}/main-es5.js`, translation.helloPartial); - await expectFileToMatch(`${outputPath}/main-es2015.js`, translation.helloPartial); - await expectToFail(() => expectFileToMatch(`${outputPath}/main-es5.js`, '$localize`')); - await expectToFail(() => expectFileToMatch(`${outputPath}/main-es2015.js`, '$localize`')); - - // Verify the locale ID is present - await expectFileToMatch(`${outputPath}/vendor-es5.js`, lang); - await expectFileToMatch(`${outputPath}/vendor-es2015.js`, lang); - - // Verify the locale data is registered using the global files - await expectFileToMatch(`${outputPath}/vendor-es5.js`, '.ng.common.locales'); - await expectFileToMatch(`${outputPath}/vendor-es2015.js`, '.ng.common.locales'); - - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - - // Execute Application E2E tests for a production build without dev server - const server = externalServer(outputPath); - try { - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } - - // Verify deprecated locale data registration is not present - await ng('build', '--configuration=fr', '--optimization=false'); - await expectToFail(() => expectFileToMatch(`${baseDir}/fr/main-es5.js`, 'registerLocaleData(')); - await expectToFail(() => expectFileToMatch(`${baseDir}/fr/main-es2015.js`, 'registerLocaleData(')); - - // Verify missing translation behaviour. - await appendToFile('src/app/app.component.html', '

Other content

'); - await ng('build', '--i18n-missing-translation', 'ignore'); - await expectFileToMatch(`${baseDir}/fr/main-es5.js`, /Other content/); - await expectFileToMatch(`${baseDir}/fr/main-es2015.js`, /Other content/); - await expectToFail(() => ng('build')); - try { - await execAndWaitForOutputToMatch( - 'ng', - ['serve', '--configuration=fr', '--port=0'], - /No translation found for/, - ); - } finally { - killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts deleted file mode 100644 index f5fb2a8cc30a..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expectFileNotToExist, expectFileToMatch, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { externalServer, langTranslations, setupI18nConfig } from './legacy'; - -export default async function() { - // Setup i18n tests and config. - await setupI18nConfig(); - - // Ensure a ES2015 build is used. - await writeFile('browserslist', 'Chrome 65'); - await updateJsonFile('tsconfig.json', config => { - config.compilerOptions.target = 'es2015'; - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - - await ng('build'); - for (const { lang, outputPath, translation } of langTranslations) { - await expectFileToMatch(`${outputPath}/main.js`, translation.helloPartial); - await expectToFail(() => expectFileToMatch(`${outputPath}/main.js`, '$localize`')); - await expectFileNotToExist(`${outputPath}/main-es5.js`); - await expectFileToMatch(`${outputPath}/main.js`, lang); - - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - - // Execute Application E2E tests for a production build without dev server - const server = externalServer(outputPath); - try { - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es5.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es5.ts deleted file mode 100644 index 99c8a408357d..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es5.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expectFileNotToExist, expectFileToMatch } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { externalServer, langTranslations, setupI18nConfig } from './legacy'; - -export default async function() { - // Setup i18n tests and config. - await setupI18nConfig(); - - // Ensure a es5 build is used. - await updateJsonFile('tsconfig.json', config => { - config.compilerOptions.target = 'es5'; - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - - // Build each locale and verify the output. - await ng('build'); - for (const { lang, outputPath, translation } of langTranslations) { - await expectFileToMatch(`${outputPath}/main.js`, translation.helloPartial); - await expectToFail(() => expectFileToMatch(`${outputPath}/main.js`, '$localize`')); - await expectFileNotToExist(`${outputPath}/main-es2015.js`); - await expectFileToMatch(`${outputPath}/main.js`, lang); - - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - - // Execute Application E2E tests for a production build without dev server - const server = externalServer(outputPath); - try { - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-server.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-server.ts deleted file mode 100644 index 7350c23a9694..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-server.ts +++ /dev/null @@ -1,127 +0,0 @@ -import * as express from 'express'; -import { join } from 'path'; -import { getGlobalVariable } from '../../utils/env'; -import { appendToFile, expectFileToMatch, writeFile } from '../../utils/fs'; -import { ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { langTranslations, setupI18nConfig } from './legacy'; - -const snapshots = require('../../ng-snapshot/package.json'); - -export default async function () { - // TODO: Re-enable pending further Ivy/Universal/i18n work - return; - - // Setup i18n tests and config. - await setupI18nConfig(); - - // Add universal to the project - const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; - await ng('add', '@nguniversal/express-engine@9.0.0-next.6', '--skip-install'); - - if (isSnapshotBuild) { - await updateJsonFile('package.json', packageJson => { - const dependencies = packageJson['dependencies']; - dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; - }); - } - - await silentNpm('install'); - - const serverbaseDir = 'dist/test-project/server'; - const serverBuildArgs = ['run', 'test-project:server']; - - // Add server-specific config. - await updateJsonFile('angular.json', workspaceJson => { - const appProject = workspaceJson.projects['test-project']; - const appArchitect = appProject.architect || appProject.targets; - const serverOptions = appArchitect['server'].options; - - serverOptions.optimization = true; - serverOptions.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; - - // Enable localization for all locales - // TODO: re-enable all locales once localeData support is added. - // serverOptions.localize = true; - serverOptions.localize = ['fr']; - // Always error on missing translations. - serverOptions.i18nMissingTranslation = 'error'; - }); - - // Override 'main.ts' so that we never bootstrap the client side - // This is needed so that we can we can run E2E test against the server view - await writeFile( - 'src/main.ts', - ` - import { enableProdMode } from '@angular/core'; - - import { AppModule } from './app/app.module'; - import { environment } from './environments/environment'; - - if (environment.production) { - enableProdMode(); - } - `, - ); - - // By default the 'server.ts' doesn't support localized dist folders, - // so we create a copy of 'app' function with a locale parameter. - await appendToFile( - 'server.ts', - ` - export function i18nApp(locale: string) { - const server = express(); - const distFolder = join(process.cwd(), \`dist/test-project/browser/\${locale}\`); - - server.engine('html', ngExpressEngine({ - bootstrap: AppServerModule, - })); - - server.set('view engine', 'html'); - server.set('views', distFolder); - - server.get('*.*', express.static(distFolder, { - maxAge: '1y' - })); - - server.get('*', (req, res) => { - res.render('index', { req }); - }); - - return server; - } - `, - ); - - // Build each locale and verify the output. - await ng('build'); - await ng(...serverBuildArgs); - - for (const { lang, translation } of langTranslations) { - await expectFileToMatch(`${serverbaseDir}/${lang}/main.js`, translation.helloPartial); - await expectToFail(() => expectFileToMatch(`${serverbaseDir}/${lang}/main.js`, '$localize`')); - - // Run the server - const serverBundle = join(process.cwd(), `${serverbaseDir}/${lang}/main.js`); - const { i18nApp } = await import(serverBundle) as { i18nApp(locale: string): express.Express }; - const server = i18nApp(lang).listen(4200, 'localhost'); - try { - // Execute without a devserver. - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } - - // Verify missing translation behaviour. - await appendToFile('src/app/app.component.html', '

Other content

'); - await ng(...serverBuildArgs, '--i18n-missing-translation', 'ignore'); - await expectFileToMatch(`${serverbaseDir}/fr/main.js`, /Other content/); - await expectToFail(() => ng(...serverBuildArgs)); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-serviceworker.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-serviceworker.ts deleted file mode 100644 index 24536c5544c6..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-serviceworker.ts +++ /dev/null @@ -1,184 +0,0 @@ -import * as express from 'express'; -import { resolve } from 'path'; -import { getGlobalVariable } from '../../utils/env'; -import { - copyFile, - expectFileToExist, - expectFileToMatch, - replaceInFile, - writeFile, -} from '../../utils/fs'; -import { ng, npm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { readNgVersion } from '../../utils/version'; - -export default async function() { - // TEMP: disable pending i18n updates - // TODO: when re-enabling, use setupI18nConfig and helpers like other i18n tests. - return; - - let localizeVersion = '@angular/localize@' + readNgVersion(); - if (getGlobalVariable('argv')['ng-snapshots']) { - localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; - } - await npm('install', `${localizeVersion}`); - - let serviceWorkerVersion = '@angular/service-worker@' + readNgVersion(); - if (getGlobalVariable('argv')['ng-snapshots']) { - serviceWorkerVersion = require('../../ng-snapshot/package.json').dependencies[ - '@angular/service-worker' - ]; - } - await npm('install', `${serviceWorkerVersion}`); - - await updateJsonFile('tsconfig.json', config => { - config.compilerOptions.target = 'es2015'; - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - - const baseDir = 'dist/test-project'; - - // Set configurations for each locale. - const langTranslations = [ - { lang: 'en-US', translation: 'Hello i18n!' }, - { lang: 'fr', translation: 'Bonjour i18n!' }, - ]; - - await updateJsonFile('angular.json', workspaceJson => { - const appProject = workspaceJson.projects['test-project']; - const appArchitect = appProject.architect || appProject.targets; - const serveConfigs = appArchitect['serve'].configurations; - const e2eConfigs = appArchitect['e2e'].configurations; - - // Make default builds prod. - appArchitect['build'].options.optimization = true; - appArchitect['build'].options.buildOptimizer = true; - appArchitect['build'].options.aot = true; - appArchitect['build'].options.fileReplacements = [ - { - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }, - ]; - - // Enable service worker - appArchitect['build'].options.serviceWorker = true; - - // Enable localization for all locales - // appArchitect['build'].options.localize = true; - - // Add locale definitions to the project - // tslint:disable-next-line: no-any - const i18n: Record = (appProject.i18n = { locales: {} }); - for (const { lang } of langTranslations) { - if (lang == 'en-US') { - i18n.sourceLocale = lang; - } else { - i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; - } - serveConfigs[lang] = { browserTarget: `test-project:build:${lang}` }; - e2eConfigs[lang] = { - specs: [`./src/app.${lang}.e2e-spec.ts`], - devServerTarget: `test-project:serve:${lang}`, - }; - } - }); - - // Add service worker source configuration - const manifest = { - index: '/index.html', - assetGroups: [ - { - name: 'app', - installMode: 'prefetch', - resources: { - files: ['/favicon.ico', '/index.html', '/manifest.webmanifest', '/*.css', '/*.js'], - }, - }, - { - name: 'assets', - installMode: 'lazy', - updateMode: 'prefetch', - resources: { - files: ['/assets/**', '/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)'], - }, - }, - ], - }; - await writeFile('ngsw-config.json', JSON.stringify(manifest)); - - // Add a translatable element. - await writeFile( - 'src/app/app.component.html', - '

Hello i18n!

', - ); - - // Extract the translation messages and copy them for each language. - await ng('xi18n', '--output-path=src/locale'); - await expectFileToExist('src/locale/messages.xlf'); - await expectFileToMatch('src/locale/messages.xlf', `source-language="en-US"`); - await expectFileToMatch('src/locale/messages.xlf', `An introduction header for this sample`); - - for (const { lang, translation } of langTranslations) { - if (lang != 'en-US') { - await copyFile('src/locale/messages.xlf', `src/locale/messages.${lang}.xlf`); - await replaceInFile( - `src/locale/messages.${lang}.xlf`, - 'source-language="en-US"', - `source-language="en-US" target-language="${lang}"`, - ); - await replaceInFile( - `src/locale/messages.${lang}.xlf`, - 'Hello i18n!', - `Hello i18n!\n${translation}`, - ); - } - } - - // Build each locale and verify the output. - await ng('build', '--i18n-missing-translation', 'error'); - for (const { lang, translation } of langTranslations) { - await expectFileToMatch(`${baseDir}/${lang}/main-es5.js`, translation); - await expectFileToMatch(`${baseDir}/${lang}/main-es2015.js`, translation); - await expectToFail(() => expectFileToMatch(`${baseDir}/${lang}/main-es5.js`, '$localize`')); - await expectToFail(() => expectFileToMatch(`${baseDir}/${lang}/main-es2015.js`, '$localize`')); - await expectFileToMatch(`${baseDir}/${lang}/main-es5.js`, lang); - await expectFileToMatch(`${baseDir}/${lang}/main-es2015.js`, lang); - - // Expect service worker configuration to be present - await expectFileToExist(`${baseDir}/${lang}/ngsw.json`); - - // Ivy i18n doesn't yet work with `ng serve` so we must use a separate server. - const app = express(); - app.use(express.static(resolve(baseDir, lang))); - const server = app.listen(4200, 'localhost'); - try { - // Add E2E test for locale - await writeFile( - 'e2e/src/app.e2e-spec.ts', - ` - import { browser, logging, element, by } from 'protractor'; - describe('workspace-project App', () => { - it('should display welcome message', () => { - browser.get(browser.baseUrl); - expect(element(by.css('h1')).getText()).toEqual('${translation}'); - }); - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - } as logging.Entry)); - }); - }); - `, - ); - - // Execute without a devserver. - await ng('e2e', '--devServerTarget='); - } finally { - server.close(); - } - } -} diff --git a/tests/legacy-cli/e2e/tests/i18n/legacy.ts b/tests/legacy-cli/e2e/tests/i18n/legacy.ts deleted file mode 100644 index 90c60c6f302e..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/legacy.ts +++ /dev/null @@ -1,239 +0,0 @@ -import * as express from 'express'; -import { resolve } from 'path'; -import { getGlobalVariable } from '../../utils/env'; -import { appendToFile, copyFile, expectFileToExist, expectFileToMatch, replaceInFile, writeFile } from '../../utils/fs'; -import { ng, npm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { readNgVersion } from '../../utils/version'; - -// Configurations for each locale. -export const baseDir = 'dist/test-project'; -export const langTranslations = [ - { - lang: 'en-US', outputPath: `${baseDir}/en-US`, - translation: { - helloPartial: 'Hello', - hello: 'Hello i18n!', - plural: 'Updated 3 minutes ago', - date: 'January', - }, - }, - { - lang: 'fr', outputPath: `${baseDir}/fr`, - translation: { - helloPartial: 'Bonjour', - hello: 'Bonjour i18n!', - plural: 'Mis à jour il y a 3 minutes', - date: 'janvier', - }, - translationReplacements: [ - [/source/g, 'target'], - ['Hello', 'Bonjour'], - ['Updated', 'Mis à jour'], - ['just now', 'juste maintenant'], - ['one minute ago', 'il y a une minute'], - [/other {/g, 'other {il y a '], - ['minutes ago', 'minutes'], - ], - }, - { - lang: 'de', outputPath: `${baseDir}/de`, - translation: { - helloPartial: 'Hallo', - hello: 'Hallo i18n!', - plural: 'Aktualisiert vor 3 Minuten', - date: 'Januar', - }, - translationReplacements: [ - [/source/g, 'target'], - ['Hello', 'Hallo'], - ['Updated', 'Aktualisiert'], - ['just now', 'gerade jetzt'], - ['one minute ago', 'vor einer Minute'], - [/other {/g, 'other {vor '], - ['minutes ago', 'Minuten'], - ], - }, -]; -export const sourceLocale = langTranslations[0].lang; -export const externalServer = (outputPath: string) => { - const app = express(); - app.use(express.static(resolve(outputPath))); - - // call .close() on the return value to close the server. - return app.listen(4200, 'localhost'); -}; - -export async function setupI18nConfig(useLocalize = true) { - // Add component with i18n content, both translations and localeData (plural, dates). - await writeFile('src/app/app.component.ts', ` - import { Component, Inject, LOCALE_ID } from '@angular/core'; - @Component({ - selector: 'app-root', - templateUrl: './app.component.html' - }) - export class AppComponent { - constructor(@Inject(LOCALE_ID) public locale: string) { } - title = 'i18n'; - jan = new Date(2000, 0, 1); - minutes = 3; - } - `); - await writeFile(`src/app/app.component.html`, ` -

Hello {{ title }}!

-

{{ locale }}

-

{{ jan | date : 'LLLL' }}

-

Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}

- `); - - // Add e2e specs for each lang. - for (const { lang, translation } of langTranslations) { - await writeFile(`./e2e/src/app.${lang}.e2e-spec.ts`, ` - import { browser, logging, element, by } from 'protractor'; - - describe('workspace-project App', () => { - const getParagraph = (name: string) => element(by.css('app-root p#' + name)).getText(); - beforeEach(() => browser.get(browser.baseUrl)); - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - } as logging.Entry)); - }); - - it('should display welcome message', () => - expect(getParagraph('hello')).toEqual('${translation.hello}')); - - it('should display locale', () => - expect(getParagraph('locale')).toEqual('${lang}')); - - it('should display localized date', () => - expect(getParagraph('date')).toEqual('${translation.date}')); - - it('should display pluralized message', () => - expect(getParagraph('plural')).toEqual('${translation.plural}')); - }); - `); - } - - // Update angular.json to build, serve, and test each locale. - await updateJsonFile('angular.json', workspaceJson => { - const appProject = workspaceJson.projects['test-project']; - const appArchitect = workspaceJson.projects['test-project'].architect; - const buildConfigs = appArchitect['build'].configurations; - const serveConfigs = appArchitect['serve'].configurations; - const e2eConfigs = appArchitect['e2e'].configurations; - - // Make default builds prod. - appArchitect['build'].options.optimization = true; - appArchitect['build'].options.buildOptimizer = true; - appArchitect['build'].options.aot = true; - appArchitect['build'].options.fileReplacements = [{ - replace: 'src/environments/environment.ts', - with: 'src/environments/environment.prod.ts', - }]; - - // Always error on missing translations. - appArchitect['build'].options.i18nMissingTranslation = 'error'; - - if (useLocalize) { - // Enable localization for all locales - appArchitect['build'].options.localize = true; - } - - // Add i18n config items (app, build, serve, e2e). - // tslint:disable-next-line: no-any - const i18n: Record = (appProject.i18n = { locales: {} }); - for (const { lang, outputPath } of langTranslations) { - if (!useLocalize) { - if (lang == sourceLocale) { - buildConfigs[lang] = { outputPath }; - } else { - buildConfigs[lang] = { - outputPath, - i18nFile: `src/locale/messages.${lang}.xlf`, - i18nFormat: `xlf`, - i18nLocale: lang, - }; - } - } else { - if (lang == sourceLocale) { - i18n.sourceLocale = lang; - } else { - i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; - } - buildConfigs[lang] = { localize: [lang] }; - } - - serveConfigs[lang] = { browserTarget: `test-project:build:${lang}` }; - e2eConfigs[lang] = { - specs: [`./src/app.${lang}.e2e-spec.ts`], - devServerTarget: `test-project:serve:${lang}`, - }; - } - }); - - // Extract the translation messages. - await ng('xi18n', '--output-path=src/locale'); - await expectFileToExist('src/locale/messages.xlf'); - await expectFileToMatch('src/locale/messages.xlf', `source-language="en-US"`); - await expectFileToMatch('src/locale/messages.xlf', `An introduction header for this sample`); - - // Make translations for each language. - for (const { lang, translationReplacements } of langTranslations) { - if (lang != sourceLocale) { - await copyFile('src/locale/messages.xlf', `src/locale/messages.${lang}.xlf`); - for (const replacements of translationReplacements) { - await replaceInFile(`src/locale/messages.${lang}.xlf`, replacements[0], replacements[1] as string); - } - } - } - - // Install the localize package if using ivy - if (!getGlobalVariable('argv')['ve']) { - let localizeVersion = '@angular/localize@' + readNgVersion(); - if (getGlobalVariable('argv')['ng-snapshots']) { - localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; - } - await npm('install', `${localizeVersion}`); - } -} - -export default async function () { - // Setup i18n tests and config. - await setupI18nConfig(false); - - // Legacy option usage with the en-US locale needs $localize when using ivy - // Legacy usage did not need to process en-US and typically no i18nLocale options were present - // This will currently be the overwhelmingly common scenario for users updating existing projects - if (!getGlobalVariable('argv')['ve']) { - await appendToFile('src/polyfills.ts', `import '@angular/localize/init';`); - } - - // Build each locale and verify the output. - for (const { lang, translation, outputPath } of langTranslations) { - await ng('build', `--configuration=${lang}`); - await expectFileToMatch(`${outputPath}/main-es5.js`, translation.helloPartial); - await expectFileToMatch(`${outputPath}/main-es2015.js`, translation.helloPartial); - - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - - // Execute Application E2E tests for a production build without dev server - const server = externalServer(outputPath); - try { - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } - - // Verify missing translation behaviour. - await appendToFile('src/app/app.component.html', '

Other content

'); - await ng('build', '--configuration=fr', '--i18n-missing-translation', 'ignore'); - await expectFileToMatch(`${baseDir}/fr/main-es5.js`, /Other content/); - await expectFileToMatch(`${baseDir}/fr/main-es2015.js`, /Other content/); - await expectToFail(() => ng('build', '--configuration=fr')); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ve-localize-es2015.ts b/tests/legacy-cli/e2e/tests/i18n/ve-localize-es2015.ts deleted file mode 100644 index fa90c46997ba..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ve-localize-es2015.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { expectFileToMatch, writeFile } from '../../utils/fs'; -import { execAndWaitForOutputToMatch, ng, npm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { readNgVersion } from '../../utils/version'; -import { baseDir, externalServer, langTranslations, setupI18nConfig } from './legacy'; - -export default async function() { - if (!getGlobalVariable('argv')['ve']) { - return; - } - - // Setup i18n tests and config. - await setupI18nConfig(); - - // Using localize-based options requires the @angular/locale package - let localizeVersion = '@angular/localize@' + readNgVersion(); - if (getGlobalVariable('argv')['ng-snapshots']) { - localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; - } - await npm('install', `${localizeVersion}`); - - // Ensure a ES2015 build is used. - await writeFile('browserslist', 'Chrome 65'); - await updateJsonFile('tsconfig.json', config => { - config.compilerOptions.target = 'es2015'; - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - - // Attempts to build multiple locales with VE should fail - await expectToFail(() => ng('build')); - - for (const { lang, outputPath, translation } of langTranslations) { - await ng('build', `--configuration=${lang}`); - - await expectFileToMatch(`${outputPath}/main.js`, translation.helloPartial); - await expectToFail(() => expectFileToMatch(`${outputPath}/main.js`, '$localize`')); - - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - - // Execute Application E2E tests for a production build without dev server - const server = externalServer(outputPath); - try { - await ng('e2e', `--configuration=${lang}`, '--devServerTarget='); - } finally { - server.close(); - } - } - - await execAndWaitForOutputToMatch( - 'ng', - ['build', '--configuration=fr', '--i18n-locale=en-US'], - /Option 'localize' and deprecated 'i18nLocale' found. Using 'localize'./, - ); - await execAndWaitForOutputToMatch( - 'ng', - ['build', '--configuration=fr', '--i18n-format=xmb'], - /Option 'localize' and deprecated 'i18nFormat' found. Using 'localize'./, - ); - await execAndWaitForOutputToMatch( - 'ng', - ['build', '--configuration=fr', '--i18n-file=error.json'], - /Option 'localize' and deprecated 'i18nFile' found. Using 'localize'./, - ); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-no-config-section.ts b/tests/legacy-cli/e2e/tests/lint/lint-no-config-section.ts deleted file mode 100644 index 473a6fbb10f9..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-no-config-section.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ng } from '../../utils/process'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - return Promise.resolve() - .then(() => ng('config', 'lint', '[]')) - .then(() => ng('lint', 'app')) - .then(({ stdout }) => { - if (!stdout.match(/No lint configuration\(s\) found\./)) { - throw new Error(oneLine` - Expected to match "No lint configuration(s) found." - in ${stdout}. - `); - } - - return stdout; - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-no-project.ts b/tests/legacy-cli/e2e/tests/lint/lint-no-project.ts deleted file mode 100644 index 6253087a997c..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-no-project.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { expectToFail } from '../../utils/utils'; -import { oneLine } from 'common-tags'; -import { updateJsonFile } from '../../utils/project'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - return Promise.resolve() - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.lint.options.tsConfig = undefined; - })) - .then(() => ng('lint', 'app', '--type-check')) - .then(({ stdout }) => { - if (!stdout.match(/A "project" must be specified to enable type checking./)) { - throw new Error(oneLine` - Expected to match "A "project" must be specified to enable type checking." - in ${stdout}. - `); - } - - return stdout; - }) - .then(() => ng('config', 'lint.0.files', '"**/baz.ts"')) - .then(() => writeFile('src/app/foo.ts', 'const foo = "";\n')) - .then(() => writeFile('src/app/baz.ts', 'const baz = \'\';\n')) - .then(() => ng('lint', 'app')) - .then(() => ng('config', 'lint.0.files', '"**/foo.ts"')) - .then(() => expectToFail(() => ng('lint', 'app'))); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-exclude.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-exclude.ts deleted file mode 100644 index 887bd7a06542..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-exclude.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - - return Promise.resolve() - .then(() => ng('config', 'lint.0.exclude', '"**/foo.ts"')) - .then(() => writeFile(fileName, 'const foo = "";\n')) - .then(() => ng('lint', 'app')) - .then(({ stdout }) => { - if (!stdout.match(/All files pass linting\./)) { - throw new Error(oneLine` - Expected to match "All files pass linting." - in ${stdout}. - `); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-fix.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-fix.ts deleted file mode 100644 index 41bbdd6762dc..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-fix.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ng } from '../../utils/process'; -import { readFile, writeFile } from '../../utils/fs'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - - return Promise.resolve() - .then(() => writeFile(fileName, 'const foo = "";\n')) - .then(() => ng('lint', 'app', '--fix', '--force')) - .then(() => readFile(fileName)) - .then(content => { - if (!content.match(/const foo = '';/)) { - throw new Error(`Expected to match "const foo = '';" in ${content}.`); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-force.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-force.ts deleted file mode 100644 index 147941721a52..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-force.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - - return Promise.resolve() - .then(() => writeFile(fileName, 'const foo = "";\n')) - .then(() => ng('lint', 'app', '--force')) - .then(({ stdout }) => { - if (!stdout.match(/" should be '/)) { - throw new Error(`Expected to match "" should be '" in ${stdout}.`); - } - - return stdout; - }) - .then((output) => { - if (!output.match(/Lint errors found in the listed files\./)) { - throw new Error(oneLine` - Expected to match "Lint errors found in the listed files." - in ${output}. - `); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-format-by-aliases.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-format-by-aliases.ts deleted file mode 100644 index 8c1d983e9c18..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-format-by-aliases.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - - return Promise.resolve() - .then(() => writeFile(fileName, 'const foo = "";\n')) - .then(() => ng('lint', 'app', '-t=stylish', '--force')) - .then(({ stdout }) => { - if (!stdout.match(/1:13 quotemark " should be '/)) { - throw new Error(oneLine` - Expected to match "1:13 quotemark " should be '" - in ${stdout}. - `); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-format.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-format.ts deleted file mode 100644 index 5376986eb08c..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-format.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - - return Promise.resolve() - .then(() => writeFile(fileName, 'const foo = "";\n')) - .then(() => ng('lint', 'app', '--format=stylish', '--force')) - .then(({ stdout }) => { - if (!stdout.match(/1:13 quotemark " should be '/)) { - throw new Error(oneLine` - Expected to match "1:13 quotemark " should be '" - in ${stdout}. - `); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-nested-configs.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-nested-configs.ts deleted file mode 100644 index 5ba81188b981..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-nested-configs.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { createDir, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo/foo.ts'; - const nestedConfigContent = ` - { - "rules": { - "quotemark": [ - true, - "double", - "avoid-escape" - ] - } - }`; - - return Promise.resolve() - .then(() => createDir('src/app/foo')) - .then(() => writeFile(fileName, 'const foo = \'\';\n')) - .then(() => writeFile('src/app/foo/tslint.json', nestedConfigContent)) - .then(() => expectToFail(() => ng('lint', 'app'))); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-non-project.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-non-project.ts deleted file mode 100644 index ebe4c207181a..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-non-project.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - return Promise.resolve() - .then(() => ng('config', 'lint.0.files', '"src/app/**/*.ts"')) - .then(() => expectToFail(() => ng('lint', 'app'))); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-type-check-fail.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-type-check-fail.ts deleted file mode 100644 index 448c79822a3f..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-type-check-fail.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; -import { writeFile } from '../../utils/fs'; - - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - const fileContents = ` -const ANIMATION_CSS_VALUE_REGEX = 'asda'; -const a = ["asda", 'asda', 'asdasd', "ASDASDAS"]; -const b = "asdasd"; -const c = { - a: "sadas", - b: { - v: "asdasda", - s: ["asda", "asdas", 10, true, "asda"], - } -}; - -function check(val: any, fxState: any) { - if (typeof val === "string" && val.indexOf(" ") < 0) { - var r = val.match(ANIMATION_CSS_VALUE_REGEX); - var num = parseFloat(r[1]); - - if (!isNaN(num)) { - fxState.num = num + ""; - } - fxState.unit = (r[0] !== r[2] ? r[2] : ""); - - } else if (typeof val === "number") { - fxState.num = val + ""; - } -} - - `; - - return Promise.resolve() - .then(() => writeFile(fileName, fileContents)) - .then(() => expectToFail(() => ng('lint', 'app', '--fix', '--type-check'))); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint-with-type-check.ts b/tests/legacy-cli/e2e/tests/lint/lint-with-type-check.ts deleted file mode 100644 index 1c41f38e6a1d..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint-with-type-check.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; - - -export default function () { - // TODO(architect): Figure out how this test should look like post devkit/build-angular. - return; - - const fileName = 'src/app/foo.ts'; - const fileContents = ` -const ANIMATION_CSS_VALUE_REGEX = 'asda'; -const a = ["asda", 'asda', 'asdasd', "ASDASDAS"]; -const b = "asdasd"; -const c = { - a: "sadas", - b: { - v: "asdasda", - s: ["asda", "asdas", 10, true, "asda"], - } -}; - -function check(val: any, fxState: any) { - if (typeof val === "string" && val.indexOf(" ") < 0) { - let r = val.match(ANIMATION_CSS_VALUE_REGEX); - let num = parseFloat(r[1]); - - if (!isNaN(num)) { - fxState.num = num + ""; - } - fxState.unit = (r[0] !== r[2] ? r[2] : ""); - - } else if (typeof val === "number") { - fxState.num = val + ""; - } -} - - `; - - return Promise.resolve() - .then(() => writeFile(fileName, fileContents)) - .then(() => ng('lint', 'app', '--fix')) - .then(() => ng('lint', 'app')) - .then(({ stdout }) => { - if (!stdout.match(/All files pass linting./)) { - throw new Error('All files pass linting.'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/lint/lint.ts b/tests/legacy-cli/e2e/tests/lint/lint.ts deleted file mode 100644 index 49bd7aadae4b..000000000000 --- a/tests/legacy-cli/e2e/tests/lint/lint.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ng } from '../../utils/process'; -import { oneLine } from 'common-tags'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return ng('lint', 'test-project') - .then(({ stdout }) => { - if (!stdout.match(/All files pass linting\./)) { - throw new Error(oneLine` - Expected to match "All files pass linting." - in ${stdout}. - `); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/ask-analytics-command.ts b/tests/legacy-cli/e2e/tests/misc/ask-analytics-command.ts deleted file mode 100644 index d571b38cb671..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/ask-analytics-command.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { execWithEnv, killAllProcesses, waitForAnyProcessOutputToMatch } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - try { - // Execute a command with TTY force enabled - const execution = execWithEnv('ng', ['version'], { - ...process.env, - NG_FORCE_TTY: '1', - NG_CLI_ANALYTICS: 'ci', - }); - - // Check if the prompt is shown - await waitForAnyProcessOutputToMatch(/Would you like to share anonymous usage data/); - } finally { - killAllProcesses(); - } - - try { - // Execute a command with TTY force enabled - const execution = execWithEnv('ng', ['version'], { - ...process.env, - NG_FORCE_TTY: '1', - NG_CLI_ANALYTICS: 'false', - }); - - // Check if the prompt is shown - await expectToFail(() => - waitForAnyProcessOutputToMatch(/Would you like to share anonymous usage data/, 5), - ); - } finally { - killAllProcesses(); - } - - // Should not show a prompt when using update - try { - // Execute a command with TTY force enabled - const execution = execWithEnv('ng', ['update'], { - ...process.env, - NG_FORCE_TTY: '1', - NG_CLI_ANALYTICS: 'ci', - }); - - // Check if the prompt is shown - await expectToFail(() => - waitForAnyProcessOutputToMatch(/Would you like to share anonymous usage data/, 5), - ); - } finally { - killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/ask-analytics-install.ts b/tests/legacy-cli/e2e/tests/misc/ask-analytics-install.ts deleted file mode 100644 index 5ef8dc5a6953..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/ask-analytics-install.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { createDir, rimraf } from '../../utils/fs'; -import { - execWithEnv, - killAllProcesses, - waitForAnyProcessOutputToMatch, -} from '../../utils/process'; - -export default async function() { - // Create a temporary directory to install the CLI - await createDir('../ask-analytics'); - const cwd = process.cwd(); - process.chdir('../ask-analytics'); - - try { - // Install the CLI with TTY force enabled - const execution = execWithEnv( - 'npm', - ['install', '@angular/cli', '--registry=http://localhost:4873'], - { ...process.env, 'NG_FORCE_TTY': '1' }, - ); - - // Check if the prompt is shown - await waitForAnyProcessOutputToMatch(/Would you like to share anonymous usage data/); - - } finally { - killAllProcesses(); - - // Cleanup - process.chdir(cwd); - await rimraf('../ask-analytics'); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/assets.ts b/tests/legacy-cli/e2e/tests/misc/assets.ts deleted file mode 100644 index 181a07dac4a3..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/assets.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {writeFile, expectFileToExist, expectFileToMatch} from '../../utils/fs'; -import {ng} from '../../utils/process'; -import {expectToFail} from '../../utils/utils'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return writeFile('src/assets/.file', '') - .then(() => writeFile('src/assets/test.abc', 'hello world')) - .then(() => ng('build')) - .then(() => expectFileToExist('dist/test-project/favicon.ico')) - .then(() => expectFileToExist('dist/test-project/assets/.file')) - .then(() => expectFileToMatch('dist/test-project/assets/test.abc', 'hello world')) - .then(() => expectToFail(() => expectFileToExist('dist/test-project/assets/.gitkeep'))); -} diff --git a/tests/legacy-cli/e2e/tests/misc/browsers.ts b/tests/legacy-cli/e2e/tests/misc/browsers.ts deleted file mode 100644 index 50fa6d76edaa..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/browsers.ts +++ /dev/null @@ -1,79 +0,0 @@ -import * as express from 'express'; -import * as path from 'path'; -import { copyProjectAsset } from '../../utils/assets'; -import { getGlobalVariable } from '../../utils/env'; -import { replaceInFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function () { - if (!process.env['E2E_BROWSERS']) { - return; - } - - // Ensure SauceLabs configuration - if (!process.env['SAUCE_USERNAME'] || !process.env['SAUCE_ACCESS_KEY']) { - throw new Error('SauceLabs is not configured.'); - } - - await replaceInFile( - 'browserslist', - 'not IE 9-11', - 'Safari 9-10.1\nIE 9-11', - ); - - if (!getGlobalVariable('argv')['ve']) { - // Workaround for https://github.com/angular/angular/issues/32192 - await replaceInFile( - 'src/app/app.component.html', - /class="material-icons"/g, - '', - ); - } - - await ng('build', '--prod'); - - // Add Protractor configuration - await copyProjectAsset('protractor-saucelabs.conf.js', 'e2e/protractor-saucelabs.conf.js'); - - // Remove browser log checks as they are only supported with the chrome webdriver - await replaceInFile( - 'e2e/src/app.e2e-spec.ts', - 'await browser.manage().logs().get(logging.Type.BROWSER)', - '[] as any', - ); - - // Workaround defect in getText WebDriver implementation for Safari/Edge - // Leading and trailing space is not removed - await replaceInFile( - 'e2e/src/app.e2e-spec.ts', - '\'should display welcome message\',', - '\'should display welcome message\', async', - ); - await replaceInFile( - 'e2e/src/app.e2e-spec.ts', - 'page.navigateTo();', - 'await page.navigateTo();', - ); - await replaceInFile( - 'e2e/src/app.e2e-spec.ts', - 'page.getTitleText()', - '(await page.getTitleText()).trim()', - ); - - // Setup server - const app = express(); - app.use(express.static(path.resolve('dist/test-project'))); - const server = app.listen(2000, 'localhost'); - - try { - // Execute application's E2E tests with SauceLabs - await ng( - 'e2e', - 'test-project', - '--protractorConfig=e2e/protractor-saucelabs.conf.js', - '--devServerTarget=', - ); - } finally { - server.close(); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/circular-dependency.ts b/tests/legacy-cli/e2e/tests/misc/circular-dependency.ts deleted file mode 100644 index 4ff2e94759f6..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/circular-dependency.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { prependToFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - await prependToFile('src/app/app.component.ts', - `import { AppModule } from './app.module'; console.log(AppModule);`); - const { stderr } = await ng('build', '--show-circular-dependencies'); - if (!stderr.match(/WARNING in Circular dependency detected/)) { - throw new Error('Expected to have circular dependency warning in output.'); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/common-async.ts b/tests/legacy-cli/e2e/tests/misc/common-async.ts deleted file mode 100644 index 9c317e759694..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/common-async.ts +++ /dev/null @@ -1,78 +0,0 @@ -import {readdirSync} from 'fs'; -import {oneLine} from 'common-tags'; - -import {ng, silentNpm} from '../../utils/process'; -import {appendToFile, expectFileToExist, prependToFile, replaceInFile} from '../../utils/fs'; -import {expectToFail} from '../../utils/utils'; - - -export default function() { - // TODO(architect): The common chunk seems to have a different name in devkit/build-angular. - // Investigate, validate, then delete this test. - return; - - let oldNumberOfFiles = 0; - return Promise.resolve() - .then(() => ng('build')) - .then(() => oldNumberOfFiles = readdirSync('dist/test-project').length) - .then(() => ng('generate', 'module', 'lazyA', '--routing')) - .then(() => ng('generate', 'module', 'lazyB', '--routing')) - .then(() => prependToFile('src/app/app.module.ts', ` - import { RouterModule } from '@angular/router'; - `)) - .then(() => replaceInFile('src/app/app.module.ts', 'imports: [', `imports: [ - RouterModule.forRoot([{ path: "lazyA", loadChildren: "./lazy-a/lazy-a.module#LazyAModule" }]), - RouterModule.forRoot([{ path: "lazyB", loadChildren: "./lazy-b/lazy-b.module#LazyBModule" }]), - `)) - .then(() => ng('build')) - .then(() => readdirSync('dist').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles >= currentNumberOfDistFiles) { - throw new Error('A bundle for the lazy module was not created.'); - } - oldNumberOfFiles = currentNumberOfDistFiles; - }) - .then(() => silentNpm('install', 'moment')) - .then(() => appendToFile('src/app/lazy-a/lazy-a.module.ts', ` - import * as moment from 'moment'; - console.log(moment); - `)) - .then(() => ng('build')) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles != currentNumberOfDistFiles) { - throw new Error('The build contains a different number of files.'); - } - }) - .then(() => appendToFile('src/app/lazy-b/lazy-b.module.ts', ` - import * as moment from 'moment'; - console.log(moment); - `)) - .then(() => ng('build')) - .then(() => expectFileToExist('dist/test-project/common.chunk.js')) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles >= currentNumberOfDistFiles) { - throw new Error(oneLine`The build contains the wrong number of files. - The test for 'dist/test-project/common.chunk.js' to exist should have failed.`); - } - oldNumberOfFiles = currentNumberOfDistFiles; - }) - .then(() => ng('build', '--no-common-chunk')) - .then(() => expectToFail(() => expectFileToExist('dist/test-project/common.chunk.js'))) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles <= currentNumberOfDistFiles) { - throw new Error(oneLine`The build contains the wrong number of files. - The test for 'dist/test-project/common.chunk.js' not to exist should have failed.`); - } - }) - // Check for AoT and lazy routes. - .then(() => ng('build', '--aot')) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles != currentNumberOfDistFiles) { - throw new Error('AoT build contains a different number of files.'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/coverage.ts b/tests/legacy-cli/e2e/tests/misc/coverage.ts deleted file mode 100644 index af42921fbf76..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/coverage.ts +++ /dev/null @@ -1,29 +0,0 @@ -import {expectFileToExist, expectFileToMatch} from '../../utils/fs'; -import {updateJsonFile} from '../../utils/project'; -import {expectToFail} from '../../utils/utils'; -import {ng} from '../../utils/process'; - - -export default function () { - // TODO(architect): This test is broken in devkit/build-angular, istanbul and - // istanbul-instrumenter-loader are missing from the dependencies. - return; - - return ng('test', '--watch=false', '--code-coverage') - .then(output => expect(output.stdout).toContain('Coverage summary')) - .then(() => expectFileToExist('coverage/src/app')) - .then(() => expectFileToExist('coverage/lcov.info')) - // Verify code coverage exclude work - .then(() => expectFileToMatch('coverage/lcov.info', 'polyfills.ts')) - .then(() => expectFileToMatch('coverage/lcov.info', 'test.ts')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.test.options.codeCoverageExclude = [ - 'src/polyfills.ts', - '**/test.ts', - ]; - })) - .then(() => ng('test', '--watch=false', '--code-coverage')) - .then(() => expectToFail(() => expectFileToMatch('coverage/lcov.info', 'polyfills.ts'))) - .then(() => expectToFail(() => expectFileToMatch('coverage/lcov.info', 'test.ts'))); -} diff --git a/tests/legacy-cli/e2e/tests/misc/different-file-format.ts b/tests/legacy-cli/e2e/tests/misc/different-file-format.ts deleted file mode 100644 index 60b544bc97a6..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/different-file-format.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {ng} from '../../utils/process'; -import * as fs from '../../utils/fs'; - - -const options = { - encoding: 'utf8' -}; - - -export default function() { - return Promise.resolve() - .then(() => fs.prependToFile('./tsconfig.app.json', '\ufeff', options)) - .then(() => fs.prependToFile('angular.json', '\ufeff', options)) - .then(() => ng('build', '--environment=dev')); -} diff --git a/tests/legacy-cli/e2e/tests/misc/e2e-host.ts b/tests/legacy-cli/e2e/tests/misc/e2e-host.ts deleted file mode 100644 index 08d3a76712ae..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/e2e-host.ts +++ /dev/null @@ -1,28 +0,0 @@ -import * as os from 'os'; -import { killAllProcesses, ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - const interfaces = [].concat.apply([], Object.values(os.networkInterfaces())); - let host = ''; - for (const { family, address, internal } of interfaces) { - if (family === 'IPv4' && !internal) { - host = address; - break; - } - } - - try { - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.serve.options.port = 8888; - appArchitect.serve.options.host = host; - }); - - await ng('e2e'); - - await ng('e2e', '--host', host); - } finally { - await killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/es2015-nometa.ts b/tests/legacy-cli/e2e/tests/misc/es2015-nometa.ts deleted file mode 100644 index d283d03be9a7..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/es2015-nometa.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { prependToFile, replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function() { - // Ensure an ES2015 build is used in test - await writeFile('browserslist', 'Chrome 65'); - - await ng('generate', 'service', 'user'); - - // Update the application to use the new service - await prependToFile( - 'src/app/app.component.ts', - 'import { UserService } from \'./user.service\';', - ); - - await replaceInFile( - 'src/app/app.component.ts', - 'export class AppComponent {', - 'export class AppComponent {\n constructor(user: UserService) {}', - ); - - // Execute the application's tests with emitDecoratorMetadata disabled (default) - await ng('test', '--no-watch'); -} diff --git a/tests/legacy-cli/e2e/tests/misc/fallback.ts b/tests/legacy-cli/e2e/tests/misc/fallback.ts deleted file mode 100644 index 1c8d1ca56ea1..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/fallback.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { request } from '../../utils/http'; -import { killAllProcesses } from '../../utils/process'; -import { ngServe } from '../../utils/project'; -import { updateJsonFile } from '../../utils/project'; -import { moveFile } from '../../utils/fs'; - - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - // should fallback to config.app[0].index (index.html by default) - return Promise.resolve() - .then(() => ngServe()) - .then(() => request('http://localhost:4200/')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - // should correctly fallback to a changed index - .then(() => moveFile('src/index.html', 'src/not-index.html')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.index = 'src/not-index.html'; - })) - .then(() => ngServe()) - .then(() => request('http://localhost:4200/')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/forwardref-es2105.ts b/tests/legacy-cli/e2e/tests/misc/forwardref-es2105.ts deleted file mode 100644 index af0e32ee5c01..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/forwardref-es2105.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { appendToFile, replaceInFile, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - // Ensure an ES2015 build is used in test - await writeFile('browserslist', 'Chrome 65'); - - // Update the application to use a forward reference - await replaceInFile( - 'src/app/app.component.ts', - 'import { Component } from \'@angular/core\';', - 'import { Component, Inject, Injectable, forwardRef } from \'@angular/core\';', - ); - await appendToFile('src/app/app.component.ts', '\n@Injectable() export class Lock { }\n'); - await replaceInFile( - 'src/app/app.component.ts', - 'export class AppComponent {', - 'export class AppComponent {\n constructor(@Inject(forwardRef(() => Lock)) lock: Lock) {}', - ); - - // Update the application's unit tests to include the new injectable - await replaceInFile( - 'src/app/app.component.spec.ts', - 'import { AppComponent } from \'./app.component\';', - 'import { AppComponent, Lock } from \'./app.component\';', - ); - await replaceInFile( - 'src/app/app.component.spec.ts', - 'TestBed.configureTestingModule({', - 'TestBed.configureTestingModule({ providers: [Lock],', - ); - - // Execute the application's tests with emitDecoratorMetadata disabled (default) - await ng('test', '--no-watch'); - - // Turn on emitDecoratorMetadata - await replaceInFile( - 'tsconfig.json', - '"experimentalDecorators": true', - '"experimentalDecorators": true, "emitDecoratorMetadata": true', - ); - - // Execute the application's tests with emitDecoratorMetadata enabled - await expectToFail(() => ng('test', '--no-watch')); -} diff --git a/tests/legacy-cli/e2e/tests/misc/lazy-module.ts b/tests/legacy-cli/e2e/tests/misc/lazy-module.ts deleted file mode 100644 index 0256d2a82081..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/lazy-module.ts +++ /dev/null @@ -1,85 +0,0 @@ -import {readdirSync} from 'fs'; - -import {ng, silentNpm} from '../../utils/process'; -import {appendToFile, writeFile, prependToFile, replaceInFile} from '../../utils/fs'; - - -export default function() { - let oldNumberOfFiles = 0; - return Promise.resolve() - .then(() => ng('build')) - .then(() => oldNumberOfFiles = readdirSync('dist').length) - .then(() => ng('generate', 'module', 'lazy', '--routing')) - .then(() => ng('generate', 'module', 'too/lazy', '--routing')) - .then(() => prependToFile('src/app/app.module.ts', ` - import { RouterModule } from '@angular/router'; - `)) - .then(() => replaceInFile('src/app/app.module.ts', 'imports: [', `imports: [ - RouterModule.forRoot([{ path: "lazy", loadChildren: () => import('src/app/lazy/lazy.module').then(m => m.LazyModule) }]), - RouterModule.forRoot([{ path: "lazy1", loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }]), - RouterModule.forRoot([{ path: "lazy2", loadChildren: () => import('./too/lazy/lazy.module').then(m => m.LazyModule) }]), - `)) - .then(() => ng('build', '--named-chunks')) - .then(() => readdirSync('dist/test-project')) - .then((distFiles) => { - const currentNumberOfDistFiles = distFiles.length; - if (oldNumberOfFiles >= currentNumberOfDistFiles) { - throw new Error('A bundle for the lazy module was not created.'); - } - oldNumberOfFiles = currentNumberOfDistFiles; - - if (!distFiles.includes('too-lazy-lazy-module-es5.js')) { - throw new Error('The lazy module chunk did not use a unique name.'); - } - }) - // verify System.import still works - .then(() => writeFile('src/app/lazy-file.ts', '')) - .then(() => appendToFile('src/app/app.component.ts', ` - // verify other System.import still work - declare var System: any; - const lazyFile = 'file'; - System.import(/*webpackChunkName: '[request]'*/'./lazy-' + lazyFile); - `)) - .then(() => ng('build', '--named-chunks')) - .then(() => readdirSync('dist/test-project')) - .then((distFiles) => { - const currentNumberOfDistFiles = distFiles.length; - if (oldNumberOfFiles >= currentNumberOfDistFiles) { - throw new Error('A bundle for the lazy file was not created.'); - } - if (!distFiles.includes('lazy-file-es5.js')) { - throw new Error('The lazy file chunk did not have a name.'); - } - oldNumberOfFiles = currentNumberOfDistFiles; - }) - // verify 'import *' syntax doesn't break lazy modules - .then(() => silentNpm('install', 'moment')) - .then(() => appendToFile('src/app/app.component.ts', ` - import * as moment from 'moment'; - console.log(moment); - `)) - .then(() => ng('build')) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles != currentNumberOfDistFiles) { - throw new Error('Bundles were not created after adding \'import *\'.'); - } - }) - .then(() => ng('build', '--no-named-chunks')) - .then(() => readdirSync('dist/test-project')) - .then((distFiles) => { - if (distFiles.includes('lazy-lazy-module-es5.js') - || distFiles.includes('too-lazy-lazy-module-es5.js') - ) { - throw new Error('Lazy chunks shouldn\'t have a name but did.'); - } - }) - // Check for AoT and lazy routes. - .then(() => ng('build', '--aot')) - .then(() => readdirSync('dist/test-project').length) - .then(currentNumberOfDistFiles => { - if (oldNumberOfFiles != currentNumberOfDistFiles) { - throw new Error('AoT build contains a different number of files.'); - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/live-reload.ts b/tests/legacy-cli/e2e/tests/misc/live-reload.ts deleted file mode 100644 index c70ae92ab091..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/live-reload.ts +++ /dev/null @@ -1,172 +0,0 @@ -export default function temporarilyDisabledTest() { return Promise.resolve(); } -// import * as os from 'os'; -// import * as _ from 'lodash'; -// import * as express from 'express'; -// import * as http from 'http'; - -// import {appendToFile, writeMultipleFiles, writeFile} from '../../utils/fs'; -// import { -// killAllProcesses, -// execAndWaitForOutputToMatch, -// waitForAnyProcessOutputToMatch -// } from '../../utils/process'; -// import { wait } from '../../utils/utils'; - - -// export default function () { -// const protractorGoodRegEx = /Jasmine started/; -// const webpackGoodRegEx = /: Compiled successfully./; - -// // Create an express api for the Angular app to call. -// const app = express(); -// const server = http.createServer(app); -// let liveReloadCount = 0; -// function resetApiVars() { -// liveReloadCount = 0; -// } - -// server.listen(0); -// app.set('port', server.address().port); - -// const firstLocalIp = _(os.networkInterfaces()) -// .values() -// .flatten() -// .filter({ family: 'IPv4', internal: false }) -// .map('address') -// .first(); -// const publicHost = `${firstLocalIp}:4200`; - -// const apiUrl = `http://localhost:${server.address().port}`; - -// // This endpoint will be pinged by the main app on each reload. -// app.get('/live-reload-count', _ => liveReloadCount++); - -// const proxyConfigFile = 'proxy.config.json'; -// const proxyConfig = { -// '/live-reload-count': { -// target: apiUrl -// } -// }; - -// return Promise.resolve() -// .then(_ => writeMultipleFiles({ -// 'src/app/app.module.ts': ` -// import { BrowserModule } from '@angular/platform-browser'; -// import { NgModule } from '@angular/core'; -// import { FormsModule } from '@angular/forms'; -// import { HttpModule } from '@angular/http'; -// import { AppComponent } from './app.component'; -// @NgModule({ -// declarations: [ -// AppComponent -// ], -// imports: [ -// BrowserModule, -// FormsModule, -// HttpModule -// ], -// providers: [], -// bootstrap: [AppComponent] -// }) -// export class AppModule { } -// `, -// // e2e test that just opens the page and waits, so that the app runs. -// './e2e/app.e2e-spec.ts': ` -// import { browser } from 'protractor'; - -// describe('master-project App', function() { -// it('should wait', _ => { -// browser.get('/'); -// browser.sleep(30000); -// }); -// }); -// `, -// // App that calls the express server once. -// './src/app/app.component.ts': ` -// import { Component } from '@angular/core'; -// import { Http } from '@angular/http'; - -// @Component({ -// selector: 'app-root', -// template: '

Live reload test

' -// }) -// export class AppComponent { -// constructor(private http: Http) { -// http.get('${apiUrl + '/live-reload-count'}').subscribe(res => null); -// } -// } -// ` -// })) -// .then(_ => execAndWaitForOutputToMatch( -// 'ng', -// ['e2e', '--watch', '--live-reload'], -// protractorGoodRegEx -// )) -// // Let app run. -// .then(_ => wait(2000)) -// .then(_ => appendToFile('src/main.ts', 'console.log(1);')) -// .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000)) -// .then(_ => wait(2000)) -// .then(_ => { -// if (liveReloadCount != 2) { -// throw new Error( -// `Expected API to have been called 2 times but it was called ${liveReloadCount} times.` -// ); -// } -// }) -// .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) -// .then(_ => resetApiVars()) -// // Serve with live reload off should call api only once. -// .then(_ => execAndWaitForOutputToMatch( -// 'ng', -// ['e2e', '--watch', '--no-live-reload'], -// protractorGoodRegEx -// )) -// .then(_ => wait(2000)) -// .then(_ => appendToFile('src/main.ts', 'console.log(1);')) -// .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000)) -// .then(_ => wait(2000)) -// .then(_ => { -// if (liveReloadCount != 1) { -// throw new Error( -// `Expected API to have been called 1 time but it was called ${liveReloadCount} times.` -// ); -// } -// }) -// .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) -// .then(_ => resetApiVars()) -// // Serve with live reload client set to api should call api. -// .then(() => writeFile(proxyConfigFile, JSON.stringify(proxyConfig, null, 2))) -// // Update the component to call the webserver -// .then(() => writeFile('./src/app/app.component.ts', -// ` -// import { Component } from '@angular/core'; -// import { Http } from '@angular/http'; -// @Component({ -// selector: 'app-root', -// template: '

Live reload test

' -// }) -// export class AppComponent { -// constructor(private http: Http) { -// http.get('http://${publicHost + '/live-reload-count'}').subscribe(res => null); -// } -// }`)) -// .then(_ => execAndWaitForOutputToMatch( -// 'ng', -// ['e2e', '--watch', '--host=0.0.0.0', '--port=4200', `--public-host=${publicHost}`, '--proxy', proxyConfigFile], -// protractorGoodRegEx -// )) -// .then(_ => wait(2000)) -// .then(_ => appendToFile('src/main.ts', 'console.log(1);')) -// .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000)) -// .then(_ => wait(2000)) -// .then(_ => { -// if (liveReloadCount != 2) { -// throw new Error( -// `Expected API to have been called 2 times but it was called ${liveReloadCount} times.` -// ); -// } -// }) -// .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) -// .then(_ => server.close(), (err) => { server.close(); throw err; }); -// } diff --git a/tests/legacy-cli/e2e/tests/misc/loaders-resolution.ts b/tests/legacy-cli/e2e/tests/misc/loaders-resolution.ts deleted file mode 100644 index c3267d41a070..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/loaders-resolution.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createDir, moveFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function () { - await createDir('node_modules/@angular-devkit/build-angular/node_modules'); - await moveFile( - 'node_modules/@ngtools', - 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools' - ); - - await ng('build'); - - // Move it back. - await moveFile( - 'node_modules/@angular-devkit/build-angular/node_modules/@ngtools', - 'node_modules/@ngtools', - ); -} diff --git a/tests/legacy-cli/e2e/tests/misc/minimal-config.ts b/tests/legacy-cli/e2e/tests/misc/minimal-config.ts deleted file mode 100644 index a5ad29d11990..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/minimal-config.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { writeFile, writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default function () { - // TODO(architect): Figure out what a minimal config is for architect apps. - return; - - return Promise.resolve() - .then(() => writeFile('angular.json', JSON.stringify({ - apps: [{ - root: 'src', - main: 'main.ts', - scripts: [ - '../node_modules/core-js/client/shim.min.js', - '../node_modules/zone.js/dist/zone.js' - ] - }], - e2e: { protractor: { config: './protractor.conf.js' } } - }))) - .then(() => ng('e2e', 'test-project-e2e')) - .then(() => writeMultipleFiles({ - './src/script.js': ` - document.querySelector('app-root').innerHTML = '

app works!

'; - `, - './e2e/app.e2e-spec.ts': ` - import { browser, element, by } from 'protractor'; - - describe('minimal project App', function() { - it('should display message saying app works', () => { - browser.ignoreSynchronization = true; - browser.get('/'); - let el = element(by.css('app-root h1')).getText(); - expect(el).toEqual('app works!'); - }); - }); - `, - 'angular.json': JSON.stringify({ - apps: [{ - root: 'src', - scripts: ['./script.js'] - }], - e2e: { protractor: { config: './protractor.conf.js' } } - }), - })) - .then(() => ng('e2e', 'test-project-e2e')); -} diff --git a/tests/legacy-cli/e2e/tests/misc/module-resolution.ts b/tests/legacy-cli/e2e/tests/misc/module-resolution.ts deleted file mode 100644 index 0396650258c7..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/module-resolution.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { appendToFile, createDir, moveFile, prependToFile } from '../../utils/fs'; -import { ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - - -export default async function () { - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '*': ['./node_modules/*'], - }; - }); - await ng('build'); - - await createDir('xyz'); - await moveFile( - 'node_modules/@angular/common', - 'xyz/common', - ); - - await expectToFail(() => ng('build')); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '@angular/common': [ './xyz/common' ], - }; - }); - await ng('build'); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '*': ['./node_modules/*'], - '@angular/common': [ './xyz/common' ], - }; - }); - await ng('build'); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '@angular/common': [ './xyz/common' ], - '*': ['./node_modules/*'], - }; - }); - await ng('build'); - - await updateJsonFile('tsconfig.json', tsconfig => { - delete tsconfig.compilerOptions.paths; - }); - - await prependToFile('src/app/app.module.ts', 'import * as firebase from \'firebase\';'); - await appendToFile('src/app/app.module.ts', 'firebase.initializeApp({});'); - - await silentNpm('install', 'firebase@3.7.8'); - await ng('build', '--aot'); - await ng('test', '--watch=false'); - - await silentNpm('install', 'firebase@4.9.0'); - await ng('build', '--aot'); - await ng('test', '--watch=false'); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = {}; - }); - await ng('build'); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '@app/*': ['*'], - '@lib/*/test': ['*/test'], - }; - }); - await ng('build'); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '@firebase/polyfill': ['./node_modules/@firebase/polyfill/index.ts'], - }; - }); - await expectToFail(() => ng('build')); - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.paths = { - '@firebase/polyfill*': ['./node_modules/@firebase/polyfill/index.ts'], - }; - }); - await expectToFail(() => ng('build')); -} diff --git a/tests/legacy-cli/e2e/tests/misc/multiple-targets.ts b/tests/legacy-cli/e2e/tests/misc/multiple-targets.ts deleted file mode 100644 index 58c92dcfea7d..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/multiple-targets.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { expectFileToExist } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - await ng('generate', 'app', 'secondary-app'); - - await updateJsonFile('angular.json', workspaceJson => { - workspaceJson.defaultProject = undefined; - }); - - await ng('build', 'secondary-app'); - - expectFileToExist('dist/secondary-app/index.html'); - expectFileToExist('dist/secondary-app/main.js'); -} diff --git a/tests/legacy-cli/e2e/tests/misc/non-relative-module-resolution.ts b/tests/legacy-cli/e2e/tests/misc/non-relative-module-resolution.ts deleted file mode 100644 index 12c10f7d8ce1..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/non-relative-module-resolution.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { prependToFile, writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - await writeMultipleFiles({ - './src/app/foo.ts': ` - export const foo = 'fooo'; - `, - './src/app/bar.ts': ` - import { foo } from './foo'; - - console.log(foo); - ` - }), - - await prependToFile('src/app/app.module.ts', `import './bar';\n`); - - await ng('build'); - await ng('build', '--aot'); -} diff --git a/tests/legacy-cli/e2e/tests/misc/npm-audit.ts b/tests/legacy-cli/e2e/tests/misc/npm-audit.ts deleted file mode 100644 index c96e17132e80..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/npm-audit.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { npm } from '../../utils/process'; - - -export default async function() { - try { - await npm('audit'); - } catch {} -} diff --git a/tests/legacy-cli/e2e/tests/misc/proxy-config.ts b/tests/legacy-cli/e2e/tests/misc/proxy-config.ts deleted file mode 100644 index ec5ce3d7101e..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/proxy-config.ts +++ /dev/null @@ -1,71 +0,0 @@ -import * as express from 'express'; -import * as http from 'http'; - -import {writeFile} from '../../utils/fs'; -import {request} from '../../utils/http'; -import {killAllProcesses, ng} from '../../utils/process'; -import {ngServe} from '../../utils/project'; -import {updateJsonFile} from '../../utils/project'; -import {expectToFail} from "../../utils/utils"; - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - // Create an express app that serves as a proxy. - const app = express(); - const server = http.createServer(app); - server.listen(0); - - app.set('port', server.address().port); - app.get('/api/test', function (req, res) { - res.send('TEST_API_RETURN'); - }); - - const backendHost = 'localhost'; - const backendPort = server.address().port; - const proxyServerUrl = `http://${backendHost}:${backendPort}`; - const proxyConfigFile = 'proxy.config.json'; - const proxyConfig = { - '/api/*': { - target: proxyServerUrl - } - }; - - return Promise.resolve() - .then(() => writeFile(proxyConfigFile, JSON.stringify(proxyConfig, null, 2))) - .then(() => ngServe('--proxy-config', proxyConfigFile)) - .then(() => request('http://localhost:4200/api/test')) - .then(body => { - if (!body.match(/TEST_API_RETURN/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - - // .then(() => updateJsonFile('angular.json', configJson => { - // const app = configJson.defaults; - // app.serve = { - // proxyConfig: proxyConfigFile - // }; - // })) - // .then(() => ngServe()) - // .then(() => request('http://localhost:4200/api/test')) - // .then(body => { - // if (!body.match(/TEST_API_RETURN/)) { - // throw new Error('Response does not match expected value.'); - // } - // }) - // .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - - .then(() => server.close(), (err) => { server.close(); throw err; }) - - // // A non-existing proxy file should error. - // .then(() => expectToFail(() => ng('serve', '--proxy-config', 'proxy.non-existent.json'))) - // .then(() => updateJsonFile('angular.json', configJson => { - // const app = configJson.defaults; - // app.serve = { - // proxyConfig: 'proxy.non-existent.json' - // }; - // })) - // .then(() => expectToFail(() => ng('serve'))); -} diff --git a/tests/legacy-cli/e2e/tests/misc/public-host.ts b/tests/legacy-cli/e2e/tests/misc/public-host.ts deleted file mode 100644 index faf63bd82316..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/public-host.ts +++ /dev/null @@ -1,63 +0,0 @@ -import * as os from 'os'; -import * as _ from 'lodash'; - -import { request } from '../../utils/http'; -import { killAllProcesses } from '../../utils/process'; -import { ngServe } from '../../utils/project'; - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - const firstLocalIp = _(os.networkInterfaces()) - .values() - .flatten() - .filter({ family: 'IPv4', internal: false }) - .map('address') - .first(); - const publicHost = `${firstLocalIp}:4200`; - const localAddress = `http://${publicHost}`; - - return Promise.resolve() - // Disabling this test. Webpack Dev Server does not check the hots anymore when binding to - // numeric IP addresses. - // .then(() => ngServe('--host=0.0.0.0')) - // .then(() => request(localAddress)) - // .then(body => { - // if (!body.match(/Invalid Host header/)) { - // throw new Error('Response does not match expected value.'); - // } - // }) - // .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - .then(() => ngServe('--host=0.0.0.0', `--public-host=${publicHost}`)) - .then(() => request(localAddress)) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - .then(() => ngServe('--host=0.0.0.0', `--disable-host-check`)) - .then(() => request(localAddress)) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - .then(() => ngServe('--host=0.0.0.0', `--public-host=${localAddress}`)) - .then(() => request(localAddress)) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }) - .then(() => ngServe('--host=0.0.0.0', `--public-host=${firstLocalIp}`)) - .then(() => request(localAddress)) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/ssl-default.ts b/tests/legacy-cli/e2e/tests/misc/ssl-default.ts deleted file mode 100644 index e3b8cd2cfe4e..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/ssl-default.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { request } from '../../utils/http'; -import { killAllProcesses } from '../../utils/process'; -import { ngServe } from '../../utils/project'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return Promise.resolve() - .then(() => ngServe('--ssl', 'true')) - .then(() => request('https://localhost:4200/')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/ssl-with-cert.ts b/tests/legacy-cli/e2e/tests/misc/ssl-with-cert.ts deleted file mode 100644 index a905d17322bf..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/ssl-with-cert.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { request } from '../../utils/http'; -import { assetDir } from '../../utils/assets'; -import { killAllProcesses } from '../../utils/process'; -import { ngServe } from '../../utils/project'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return Promise.resolve() - .then(() => ngServe( - '--ssl', 'true', - '--ssl-key', assetDir('ssl/server.key'), - '--ssl-cert', assetDir('ssl/server.crt') - )) - .then(() => request('https://localhost:4200/')) - .then(body => { - if (!body.match(/<\/app-root>/)) { - throw new Error('Response does not match expected value.'); - } - }) - .then(() => killAllProcesses(), (err) => { killAllProcesses(); throw err; }); - -} diff --git a/tests/legacy-cli/e2e/tests/misc/support-ie.ts b/tests/legacy-cli/e2e/tests/misc/support-ie.ts deleted file mode 100644 index 8f174b7059e5..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/support-ie.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { oneLineTrim } from 'common-tags'; -import { expectFileNotToExist, expectFileToMatch, writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - await updateJsonFile('tsconfig.json', configJson => { - const compilerOptions = configJson['compilerOptions']; - compilerOptions['target'] = 'es5'; - }); - - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.es5BrowserSupport = false; - }); - - await writeFile('browserslist', 'last 2 Chrome versions'); - await ng('build'); - await expectFileNotToExist('dist/test-project/polyfills-es5.js'); - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - `); - - await ng('build', `--es5BrowserSupport`); - await expectFileToMatch('dist/test-project/polyfills-es5.js', 'core-js'); - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - - `); - - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.es5BrowserSupport = undefined; - }); - await writeFile('browserslist', 'IE 10'); - await ng('build'); - await expectFileToMatch('dist/test-project/polyfills-es5.js', 'core-js'); - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - - `); -} diff --git a/tests/legacy-cli/e2e/tests/misc/support-safari-10.1.ts b/tests/legacy-cli/e2e/tests/misc/support-safari-10.1.ts deleted file mode 100644 index f790ba83180e..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/support-safari-10.1.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { oneLineTrim } from 'common-tags'; -import { - expectFileNotToExist, - expectFileToExist, - expectFileToMatch, - writeFile, -} from '../../utils/fs'; -import { ng } from '../../utils/process'; - -export default async function () { - await writeFile('browserslist', 'Safari 10.1'); - await ng('build'); - await expectFileNotToExist('dist/test-project/polyfills-es5.js'); - await expectFileNotToExist('dist/test-project/polyfills-nomodule-es5.js'); - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - `); - - await writeFile('browserslist', ` - IE 9 - Safari 10.1 - `); - await ng('build'); - await expectFileToExist('dist/test-project/polyfills-nomodule-es5.js'); - - if (process.env['NG_BUILD_DIFFERENTIAL_FULL']) { - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - - - - - - - `); - } else { - await expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - - - - - - - - - - - `); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts b/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts deleted file mode 100644 index 1886318a051c..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/third-party-decorators.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { writeMultipleFiles } from '../../utils/fs'; -import { ng, npm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default function () { - return updateJsonFile('package.json', packageJson => { - // Install ngrx - packageJson['dependencies']['@ngrx/effects'] = '^6.1.0'; - packageJson['dependencies']['@ngrx/schematics'] = '^6.1.0'; - packageJson['dependencies']['@ngrx/store'] = '^6.1.0'; - packageJson['dependencies']['@ngrx/store-devtools'] = '^6.1.0'; - }) - .then(() => npm('install')) - // Create an app that uses ngrx decorators and has e2e tests. - .then(_ => writeMultipleFiles({ - './e2e/src/app.po.ts': ` - import { browser, by, element } from 'protractor'; - export class AppPage { - navigateTo() { return browser.get('/'); } - getIncrementButton() { return element(by.buttonText('Increment')); } - getDecrementButton() { return element(by.buttonText('Decrement')); } - getResetButton() { return element(by.buttonText('Reset Counter')); } - getCounter() { return element(by.xpath('/html/body/app-root/div/span')).getText(); } - } - `, - './e2e/src/app.e2e-spec.ts': ` - import { AppPage } from './app.po'; - - describe('workspace-project App', () => { - let page: AppPage; - - beforeEach(() => { - page = new AppPage(); - }); - - it('should operate counter', () => { - page.navigateTo(); - page.getIncrementButton().click(); - page.getIncrementButton().click(); - expect(page.getCounter()).toEqual('2'); - page.getDecrementButton().click(); - expect(page.getCounter()).toEqual('1'); - page.getResetButton().click(); - expect(page.getCounter()).toEqual('0'); - }); - }); - `, - './src/app/app.component.ts': ` - import { Component } from '@angular/core'; - import { Store, select } from '@ngrx/store'; - import { Observable } from 'rxjs'; - import { INCREMENT, DECREMENT, RESET } from './counter.reducer'; - - interface AppState { - count: number; - } - - @Component({ - selector: 'app-root', - template: \` - -
Current Count: {{ count$ | async }}
- - - - \`, - }) - export class AppComponent { - count$: Observable; - - constructor(private store: Store) { - this.count$ = store.pipe(select(state => state.count)); - } - - increment() { - this.store.dispatch({ type: INCREMENT }); - } - - decrement() { - this.store.dispatch({ type: DECREMENT }); - } - - reset() { - this.store.dispatch({ type: RESET }); - } - } - `, - './src/app/app.effects.ts': ` - import { Injectable } from '@angular/core'; - import { Actions, Effect } from '@ngrx/effects'; - import { filter, map, tap } from 'rxjs/operators'; - - @Injectable() - export class AppEffects { - - @Effect() - mapper$ = this.actions$.pipe(map(() => ({ type: 'ANOTHER'})), filter(() => false)); - - @Effect({ dispatch: false }) - logger$ = this.actions$.pipe(tap(console.log)); - - constructor(private actions$: Actions) {} - } - `, - './src/app/app.module.ts': ` - import { BrowserModule } from '@angular/platform-browser'; - import { NgModule } from '@angular/core'; - - import { AppComponent } from './app.component'; - import { StoreModule } from '@ngrx/store'; - import { StoreDevtoolsModule } from '@ngrx/store-devtools'; - import { environment } from '../environments/environment'; - import { EffectsModule } from '@ngrx/effects'; - import { AppEffects } from './app.effects'; - import { counterReducer } from './counter.reducer'; - - @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - StoreModule.forRoot({ count: counterReducer }), - !environment.production ? StoreDevtoolsModule.instrument() : [], - EffectsModule.forRoot([AppEffects]) - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - `, - './src/app/counter.reducer.ts': ` - import { Action } from '@ngrx/store'; - - export const INCREMENT = 'INCREMENT'; - export const DECREMENT = 'DECREMENT'; - export const RESET = 'RESET'; - - const initialState = 0; - - export function counterReducer(state: number = initialState, action: Action) { - switch (action.type) { - case INCREMENT: - return state + 1; - - case DECREMENT: - return state - 1; - - case RESET: - return 0; - - default: - return state; - } - } - `, - })) - // Run the e2e tests against a prod build. - .then(() => ng('e2e', '--prod')); -} diff --git a/tests/legacy-cli/e2e/tests/misc/title.ts b/tests/legacy-cli/e2e/tests/misc/title.ts deleted file mode 100644 index 748bc6297d49..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/title.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { execAndWaitForOutputToMatch, execWithEnv, killAllProcesses } from '../../utils/process'; - - -export default async function() { - if (process.platform.startsWith('win')) { - // "On Windows, process.title affects the console title, but not the name of the process in the task manager." - // https://stackoverflow.com/questions/44756196/how-to-change-the-node-js-process-name-on-windows-10#comment96259375_44756196 - return Promise.resolve(); - } - - try { - await execAndWaitForOutputToMatch('ng', ['build', '--watch'], /./); - - const output = await execWithEnv('ps', ['x'], { COLUMNS: '200' }); - - if (!output.stdout.match(/ng build --watch/)) { - throw new Error('Title of the process was not properly set.'); - } - } finally { - await killAllProcesses(); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/trace-resolution.ts b/tests/legacy-cli/e2e/tests/misc/trace-resolution.ts deleted file mode 100644 index 30c8113ce9ec..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/trace-resolution.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.traceResolution = true; - }); - - const { stdout: stdoutTraced } = await ng('build'); - if (!/Resolving module/.test(stdoutTraced)) { - throw new Error(`Modules resolutions must be printed when 'traceResolution' is enabled.`); - } - - await updateJsonFile('tsconfig.json', tsconfig => { - tsconfig.compilerOptions.traceResolution = false; - }); - - const { stdout: stdoutUnTraced } = await ng('build'); - if (/Resolving module/.test(stdoutUnTraced)) { - throw new Error(`Modules resolutions must not be printed when 'traceResolution' is disabled.`); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/universal-bundle-dependencies.ts b/tests/legacy-cli/e2e/tests/misc/universal-bundle-dependencies.ts deleted file mode 100644 index 5c34a295cc27..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/universal-bundle-dependencies.ts +++ /dev/null @@ -1,66 +0,0 @@ -import * as path from 'path'; -import { - createDir, - expectFileToMatch, - rimraf, - symlinkFile, - writeMultipleFiles, -} from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function() { - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect['server'] = { - builder: '@angular-devkit/build-angular:server', - options: { - bundleDependencies: 'none', - outputPath: 'dist/test-project-server', - main: 'src/main.server.ts', - tsConfig: 'tsconfig.server.json', - }, - }; - }); - - await createDir('./dummy-lib'); - - await writeMultipleFiles({ - './tsconfig.server.json': ` - { - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "../dist-server", - "baseUrl": "./", - "module": "commonjs", - "types": [] - }, - "include": [ - "src/main.server.ts" - ] - } - `, - './src/main.server.ts': ` - import { dummyVersion } from 'dummy-lib'; - console.log(dummyVersion); - `, - // create a dummy library - './dummy-lib/package.json': `{ - "name": "dummy-lib", - "version": "0.0.0", - "typings": "./main.d.ts", - "main": "./main.js" - }`, - './dummy-lib/main.js': 'export const dummyVersion = 1', - './dummy-lib/main.d.ts': 'export declare const dummyVersion = 1', - }); - - await symlinkFile(path.resolve('./dummy-lib'), path.resolve('./node_modules/dummy-lib'), 'dir'); - - await ng('run', 'test-project:server'); - // when preserve symlinks is true, it should not included node_modules in the bundle - await expectFileToMatch('dist/test-project-server/main.js', 'require("dummy-lib")'); - - // cleanup the package - await rimraf('node_modules/dummy-lib'); -} diff --git a/tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts b/tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts deleted file mode 100644 index 33dddb8d50a2..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { createDir, writeFile } from '../../utils/fs'; -import { ng, silentGit } from '../../utils/process'; -import { prepareProjectForE2e } from '../../utils/project'; - -export default async function() { - process.chdir(getGlobalVariable('tmp-root')); - - await createDir('./subdirectory'); - process.chdir('./subdirectory'); - - await silentGit('init', '.'); - - await ng('new', 'subdirectory-test-project', '--skip-install'); - process.chdir('./subdirectory-test-project'); - await prepareProjectForE2e('subdirectory-test-project'); - - await writeFile('../added.ts', 'console.log(\'created\');\n'); - await silentGit('add', '../added.ts'); - - const { stderr } = await ng('update', '--all', '--force'); - if (stderr && stderr.includes('Repository is not clean.')) { - throw new Error('Expected clean repository'); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/update-git-clean.ts b/tests/legacy-cli/e2e/tests/misc/update-git-clean.ts deleted file mode 100644 index 04345b4441ec..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/update-git-clean.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { appendToFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - await appendToFile('src/main.ts', 'console.log(\'changed\');\n'); - - const { message } = await expectToFail(() => ng('update', '--all')); - if (!message || !message.includes('Repository is not clean.')) { - throw new Error('Expected unclean repository'); - } -} diff --git a/tests/legacy-cli/e2e/tests/misc/update-help.ts b/tests/legacy-cli/e2e/tests/misc/update-help.ts deleted file mode 100644 index 2e98d9fd4a9d..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/update-help.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ng } from '../../utils/process'; - -export default function () { - return Promise.resolve() - .then(() => ng('update', '--help')) - .then(({ stdout }) => { - if (!/next/.test(stdout)) { - throw 'Update help should contain "next" option'; - } - }); -} diff --git a/tests/legacy-cli/e2e/tests/misc/version.ts b/tests/legacy-cli/e2e/tests/misc/version.ts deleted file mode 100644 index 121d1aa123e1..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/version.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { deleteFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; - - -export default async function() { - const { stdout: commandOutput } = await ng('version'); - const { stdout: optionOutput } = await ng('--version'); - if (!optionOutput.includes('Angular CLI:')) { - throw new Error('version not displayed'); - } - if (commandOutput !== optionOutput) { - throw new Error('version variants have differing output'); - } - - // doesn't fail on a project with missing angular.json - await deleteFile('angular.json'); - await ng('version'); - - // Doesn't fail outside a project. - await process.chdir('/'); - await ng('version'); -} diff --git a/tests/legacy-cli/e2e/tests/misc/workspace-verification.ts b/tests/legacy-cli/e2e/tests/misc/workspace-verification.ts deleted file mode 100644 index a9353edf7395..000000000000 --- a/tests/legacy-cli/e2e/tests/misc/workspace-verification.ts +++ /dev/null @@ -1,13 +0,0 @@ -import {deleteFile} from '../../utils/fs'; -import {ng} from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; - - -export default function() { - return ng('generate', 'component', 'foo', '--dry-run') - .then(() => deleteFile('angular.json')) - // fails because it needs to be inside a project - // without a workspace file - .then(() => expectToFail(() => ng('generate', 'component', 'foo', '--dry-run'))) - .then(() => ng('version')); -} diff --git a/tests/legacy-cli/e2e/tests/packages/webpack/server-app.ts b/tests/legacy-cli/e2e/tests/packages/webpack/server-app.ts deleted file mode 100644 index 992cbe4de699..000000000000 --- a/tests/legacy-cli/e2e/tests/packages/webpack/server-app.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { normalize } from 'path'; -import { createProjectFromAsset } from '../../../utils/assets'; -import { exec } from '../../../utils/process'; -import { expectFileToMatch } from '../../../utils/fs'; - - -export default function (skipCleaning: () => void) { - // This test was broken as it was a copy of the ng2 server test - // and did not actually test ng5 - return; - - return Promise.resolve() - .then(() => createProjectFromAsset('webpack/test-server-app')) - .then(() => exec(normalize('node_modules/.bin/webpack-cli'))) - .then(() => expectFileToMatch('dist/app.main.js', - new RegExp('MyInjectable.ctorParameters = .*' - + 'type: undefined, decorators.*Inject.*args: .*DOCUMENT.*'))) - .then(() => expectFileToMatch('dist/app.main.js', - new RegExp('AppComponent.ctorParameters = .*MyInjectable'))) - .then(() => expectFileToMatch('dist/app.main.js', - /AppModule \*\/\].*\.testProp = \'testing\'/)) - .then(() => expectFileToMatch('dist/app.main.js', - /platformServer \*\/\]\)\(\)\.bootstrapModuleFactory\(.*\/\* AppModuleNgFactory \*\/\]/)) - .then(() => expectFileToMatch('dist/app.main.js', - /renderModuleFactory \*\/\].*\/\* AppModuleNgFactory \*\/\]/)) - .then(() => skipCleaning()); -} diff --git a/tests/legacy-cli/e2e/tests/packages/webpack/test-app.ts b/tests/legacy-cli/e2e/tests/packages/webpack/test-app.ts deleted file mode 100644 index ab38d87e462c..000000000000 --- a/tests/legacy-cli/e2e/tests/packages/webpack/test-app.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { normalize } from 'path'; -import { createProjectFromAsset } from '../../../utils/assets'; -import { getGlobalVariable } from '../../../utils/env'; -import { expectFileSizeToBeUnder, expectFileToMatch, replaceInFile } from '../../../utils/fs'; -import { exec } from '../../../utils/process'; -import { updateJsonFile } from '../../../utils/project'; - - -export default async function (skipCleaning: () => void) { - const webpackCLIBin = normalize('node_modules/.bin/webpack-cli'); - const isVe = getGlobalVariable('argv')['ve']; - - await createProjectFromAsset('webpack/test-app'); - if (isVe) { - await updateJsonFile('tsconfig.json', config => { - config.angularCompilerOptions.enableIvy = false; - }); - } - - await exec(webpackCLIBin); - - // Note: these sizes are without Build Optimizer or any advanced optimizations in the CLI. - await expectFileSizeToBeUnder('dist/app.main.js', (isVe ? 483 : 565) * 1024); - await expectFileSizeToBeUnder('dist/0.app.main.js', 1 * 1024); - await expectFileSizeToBeUnder('dist/1.app.main.js', 2 * 1024); - - // test resource urls without ./ - await replaceInFile('app/app.component.ts', './app.component.html', 'app.component.html'); - await replaceInFile('app/app.component.ts', './app.component.scss', 'app.component.scss'); - - // test the inclusion of metadata - // This build also test resource URLs without ./ - await exec(webpackCLIBin, '--mode=development'); - await expectFileToMatch('dist/app.main.js', `AppModule${isVe ? 'NgFactory' : ''}`); - - skipCleaning(); -} diff --git a/tests/legacy-cli/e2e/tests/packages/webpack/weird-app.ts b/tests/legacy-cli/e2e/tests/packages/webpack/weird-app.ts deleted file mode 100644 index 99b012c98d0a..000000000000 --- a/tests/legacy-cli/e2e/tests/packages/webpack/weird-app.ts +++ /dev/null @@ -1,37 +0,0 @@ -import {normalize} from 'path'; - -import {createProjectFromAsset} from '../../../utils/assets'; -import {exec} from '../../../utils/process'; -import {updateJsonFile} from '../../../utils/project'; -import {expectFileSizeToBeUnder, expectFileToExist, expectFileToMatch} from '../../../utils/fs'; -import {expectToFail} from '../../../utils/utils'; - - -export default function(skipCleaning: () => void) { - // This test was broken in angular 8 - return; - - return Promise.resolve() - .then(() => createProjectFromAsset('webpack/test-app-weird')) - .then(() => exec(normalize('node_modules/.bin/webpack-cli'))) - .then(() => expectFileToExist('dist/app.main.js')) - .then(() => expectFileToExist('dist/0.app.main.js')) - .then(() => expectFileToExist('dist/1.app.main.js')) - .then(() => expectFileToExist('dist/2.app.main.js')) - .then(() => expectFileSizeToBeUnder('dist/app.main.js', 410000)) - .then(() => expectFileSizeToBeUnder('dist/0.app.main.js', 40000)) - - // Verify that we're using the production environment. - .then(() => expectFileToMatch('dist/app.main.js', /PRODUCTION_ONLY/)) - .then(() => expectToFail(() => expectFileToMatch('dist/app.main.js', /DEBUG_ONLY/))) - - // Verify that we're using the debug environment now. - .then(() => updateJsonFile('webpack.flags.json', json => { - json['DEBUG'] = true; - })) - .then(() => exec(normalize('node_modules/.bin/webpack-cli'))) - .then(() => expectFileToMatch('dist/app.main.js', /DEBUG_ONLY/)) - .then(() => expectToFail(() => expectFileToMatch('dist/app.main.js', /PRODUCTION_ONLY/))) - - .then(() => skipCleaning()); -} diff --git a/tests/legacy-cli/e2e/tests/schematics_cli/basic.ts b/tests/legacy-cli/e2e/tests/schematics_cli/basic.ts deleted file mode 100644 index a160f5d703b7..000000000000 --- a/tests/legacy-cli/e2e/tests/schematics_cli/basic.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as path from 'path'; -import { getGlobalVariable } from '../../utils/env'; -import { exec, execAndWaitForOutputToMatch, silentNpm } from '../../utils/process'; - -export default async function () { - // setup - const argv = getGlobalVariable('argv'); - if (argv.noglobal) { - return; - } - - const startCwd = process.cwd(); - await silentNpm( - 'install', - '-g', - '@angular-devkit/schematics-cli', - '--registry=http://localhost:4873', - ); - await exec(process.platform.startsWith('win') ? 'where' : 'which', 'schematics'); - - // create blank schematic - await exec('schematics', 'schematic', '--name', 'test-schematic'); - - process.chdir(path.join(startCwd, 'test-schematic')); - await execAndWaitForOutputToMatch( - 'schematics', - ['.:', '--list-schematics'], - /my-full-schematic/, - ); - - // restore path - process.chdir(startCwd); - -} diff --git a/tests/legacy-cli/e2e/tests/test/e2e-baseurl.ts b/tests/legacy-cli/e2e/tests/test/e2e-baseurl.ts deleted file mode 100644 index c7abf7c66d97..000000000000 --- a/tests/legacy-cli/e2e/tests/test/e2e-baseurl.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ng, killAllProcesses } from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; -import { ngServe } from '../../utils/project'; -import { updateJsonFile } from '../../utils/project'; - - -export default function () { - // TODO(architect): Figure out why this test is not working. - return; - - return Promise.resolve() - .then(() => expectToFail(() => ng('e2e', 'test-project-e2e', '--devServerTarget='))) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.serve.options.port = 4400; - })) - .then(() => ngServe()) - .then(() => ng('e2e', 'test-project-e2e', '--devServerTarget=', '--base-url=http://localhost:4400')) - .then(() => ng('e2e', 'test-project-e2e', '--devServerTarget=', '--port=4400')) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }); -} diff --git a/tests/legacy-cli/e2e/tests/test/test-assets.ts b/tests/legacy-cli/e2e/tests/test/test-assets.ts deleted file mode 100644 index d647d07f8d0e..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-assets.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { stripIndent } from 'common-tags'; - -// Make sure asset files are served -export default function () { - // TODO(architect): Figure out why this test is not working. - return; - - return Promise.resolve() - .then(() => writeMultipleFiles({ - 'src/assets/file.txt': 'assets-folder-content', - 'src/file.txt': 'file-content', - // Not using `async()` in tests as it seemed to swallow `fetch()` errors - 'src/app/app.component.spec.ts': stripIndent` - describe('Test Runner', () => { - const fetch = global['fetch']; - it('should serve files in assets folder', (done) => { - fetch('/assets/file.txt') - .then(response => response.text()) - .then(fileText => { - expect(fileText).toMatch('assets-folder-content'); - done(); - }); - }); - it('should serve files explicitly added to assets array', (done) => { - fetch('/file.txt') - .then(response => response.text()) - .then(fileText => { - expect(fileText).toMatch('file-content'); - done(); - }); - }); - }); - ` - })) - // Test failure condition (no assets in angular.json) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project']; - appArchitect.build.options.assets = []; - })) - .then(() => expectToFail(() => ng('test', '--watch=false'), - 'Should fail because the assets to serve were not in the Angular CLI config')) - // Test passing condition (assets are included) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.assets = [ - { 'glob': '**/*', 'input': 'src/assets' }, - { 'glob': 'file.txt' }, - ]; - })) - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/test/test-environment.ts b/tests/legacy-cli/e2e/tests/test/test-environment.ts deleted file mode 100644 index 09152caee409..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-environment.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { updateJsonFile } from '../../utils/project'; - -export default function () { - // Tests run in 'dev' environment by default. - return writeFile('src/app/environment.spec.ts', ` - import { environment } from '../environments/environment'; - - describe('Test environment', () => { - it('should have production disabled', () => { - expect(environment.production).toBe(false); - }); - }); - `) - .then(() => ng('test', '--watch=false')) - .then(() => updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.test.configurations = { - production: { - fileReplacements: [ - { - src: 'src/environments/environment.ts', - replaceWith: 'src/environments/environment.prod.ts', - } - ], - } - }; - })) - - // Tests can run in different environment. - .then(() => writeFile('src/app/environment.spec.ts', ` - import { environment } from '../environments/environment'; - - describe('Test environment', () => { - it('should have production enabled', () => { - expect(environment.production).toBe(true); - }); - }); - `)) - .then(() => ng('test', '--prod', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/test/test-fail-single-run.ts b/tests/legacy-cli/e2e/tests/test/test-fail-single-run.ts deleted file mode 100644 index 62ac51d0199a..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-fail-single-run.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile } from '../../utils/fs'; -import { expectToFail } from '../../utils/utils'; - - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - // Fails on single run with broken compilation. - return writeFile('src/app.component.spec.ts', '

definitely not typescript

') - .then(() => expectToFail(() => ng('test', '--watch=false'))); -} diff --git a/tests/legacy-cli/e2e/tests/test/test-fail-watch.ts b/tests/legacy-cli/e2e/tests/test/test-fail-watch.ts deleted file mode 100644 index 69b28fabaeea..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-fail-watch.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { - killAllProcesses, - waitForAnyProcessOutputToMatch, - execAndWaitForOutputToMatch, -} from '../../utils/process'; -import { expectToFail } from '../../utils/utils'; -import { readFile, writeFile } from '../../utils/fs'; - - -// Karma is only really finished with a run when it shows a non-zero total time in the first slot. -const karmaGoodRegEx = /Executed 3 of 3 SUCCESS \(\d+\.\d+ secs/; - -export default function () { - // TODO(architect): This test is behaving oddly both here and in devkit/build-angular. - // It seems to be because of file watchers. - return; - - let originalSpec: string; - return execAndWaitForOutputToMatch('ng', ['test'], karmaGoodRegEx) - .then(() => readFile('src/app/app.component.spec.ts')) - .then((data) => originalSpec = data) - // Trigger a failed rebuild, which shouldn't run tests again. - .then(() => writeFile('src/app/app.component.spec.ts', '

definitely not typescript

')) - .then(() => expectToFail(() => waitForAnyProcessOutputToMatch(karmaGoodRegEx, 10000))) - // Restore working spec. - .then(() => writeFile('src/app/app.component.spec.ts', originalSpec)) - .then(() => waitForAnyProcessOutputToMatch(karmaGoodRegEx, 20000)) - .then(() => killAllProcesses(), (err: any) => { - killAllProcesses(); - throw err; - }); -} diff --git a/tests/legacy-cli/e2e/tests/test/test-scripts.ts b/tests/legacy-cli/e2e/tests/test/test-scripts.ts deleted file mode 100644 index bf5299647efd..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-scripts.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { writeMultipleFiles } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; -import { stripIndent } from 'common-tags'; - - -export default function () { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return Promise.resolve() - .then(() => ng('test', '--watch=false')) - // prepare global scripts test files - .then(() => writeMultipleFiles({ - 'src/string-script.js': `stringScriptGlobal = 'string-scripts.js';`, - 'src/input-script.js': `inputScriptGlobal = 'input-scripts.js';`, - 'src/typings.d.ts': stripIndent` - declare var stringScriptGlobal: any; - declare var inputScriptGlobal: any; - `, - 'src/app/app.component.ts': stripIndent` - import { Component } from '@angular/core'; - - @Component({ selector: 'app-root', template: '' }) - export class AppComponent { - stringScriptGlobalProp = stringScriptGlobal; - inputScriptGlobalProp = inputScriptGlobal; - } - `, - 'src/app/app.component.spec.ts': stripIndent` - import { TestBed, async } from '@angular/core/testing'; - import { AppComponent } from './app.component'; - - describe('AppComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [ AppComponent ] - }).compileComponents(); - })); - - it('should have access to string-script.js', async(() => { - let app = TestBed.createComponent(AppComponent).debugElement.componentInstance; - expect(app.stringScriptGlobalProp).toEqual('string-scripts.js'); - })); - - it('should have access to input-script.js', async(() => { - let app = TestBed.createComponent(AppComponent).debugElement.componentInstance; - expect(app.inputScriptGlobalProp).toEqual('input-scripts.js'); - })); - }); - - describe('Spec', () => { - it('should have access to string-script.js', async(() => { - expect(stringScriptGlobal).toBe('string-scripts.js'); - })); - - it('should have access to input-script.js', async(() => { - expect(inputScriptGlobal).toBe('input-scripts.js'); - })); - }); - ` - })) - // should fail because the global scripts were not added to scripts array - .then(() => expectToFail(() => ng('test', '--watch=false'))) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.test.options.scripts = [ - { input: 'src/string-script.js' }, - { input: 'src/input-script.js' }, - ]; - })) - // should pass now - .then(() => ng('test', '--watch=false')); -} - diff --git a/tests/legacy-cli/e2e/tests/test/test-sourcemap.ts b/tests/legacy-cli/e2e/tests/test/test-sourcemap.ts deleted file mode 100644 index 7bf102e0820a..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-sourcemap.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { writeFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function () { - await writeFile('src/app/app.component.spec.ts', ` - it('show fail', () => { - expect(undefined).toBeTruthy(); - }); - `); - - await updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.test.options.sourceMap = { - scripts: true, - }; - }); - - // when sourcemaps are 'on' the stacktrace will point to the spec.ts file. - try { - await ng('test', '--watch', 'false'); - throw new Error('ng test should have failed.'); - } catch (error) { - if (!error.message.includes('app.component.spec.ts')) { - throw error; - }; - } - - await updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.test.options.sourceMap = true; - }); - - // when sourcemaps are 'on' the stacktrace will point to the spec.ts file. - try { - await ng('test', '--watch', 'false'); - throw new Error('ng test should have failed.'); - } catch (error) { - if (!error.message.includes('app.component.spec.ts')) { - throw error; - }; - } - - await updateJsonFile('angular.json', configJson => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.test.options.sourceMap = false; - }); - - // when sourcemaps are 'off' the stacktrace won't point to the spec.ts file. - try { - await ng('test', '--watch', 'false'); - throw new Error('ng test should have failed.'); - } catch (error) { - if (!error.message.includes('main.js')) { - throw error; - }; - } -} diff --git a/tests/legacy-cli/e2e/tests/test/test-target.ts b/tests/legacy-cli/e2e/tests/test/test-target.ts deleted file mode 100644 index ba1afd13d1c2..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-target.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { ng } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default function () { - // TODO(architect): This is giving odd errors in devkit/build-angular. - // TypeError: Assignment to constant variable. - return; - - return updateJsonFile('tsconfig.json', configJson => { - const compilerOptions = configJson['compilerOptions']; - compilerOptions['target'] = 'es2015'; - }) - .then(() => updateJsonFile('src/tsconfig.spec.json', configJson => { - const compilerOptions = configJson['compilerOptions']; - compilerOptions['target'] = 'es2015'; - })) - .then(() => ng('test', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/third-party/bootstrap.ts b/tests/legacy-cli/e2e/tests/third-party/bootstrap.ts deleted file mode 100644 index 91ff0215ce57..000000000000 --- a/tests/legacy-cli/e2e/tests/third-party/bootstrap.ts +++ /dev/null @@ -1,39 +0,0 @@ -import {silentNpm, ng} from '../../utils/process'; -import {updateJsonFile} from '../../utils/project'; -import {expectFileToMatch} from '../../utils/fs'; -import {oneLineTrim} from 'common-tags'; - - -export default function() { - // TODO(architect): Delete this test. It is now in devkit/build-angular. - - return Promise.resolve() - .then(() => silentNpm('install', 'bootstrap@4.0.0-beta.3')) - .then(() => updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'node_modules/bootstrap/dist/css/bootstrap.css' }, - ]; - appArchitect.build.options.scripts = [ - { input: 'node_modules/bootstrap/dist/js/bootstrap.js' }, - ]; - })) - .then(() => ng('build', '--extract-css')) - .then(() => expectFileToMatch('dist/test-project/scripts.js', '* Bootstrap')) - .then(() => expectFileToMatch('dist/test-project/styles.css', '* Bootstrap')) - .then(() => expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - `)) - .then(() => ng( - 'build', - '--optimization', - '--extract-css', - '--output-hashing=none', - '--vendor-chunk=false', - )) - .then(() => expectFileToMatch('dist/test-project/scripts.js', 'jQuery')) - .then(() => expectFileToMatch('dist/test-project/styles.css', '* Bootstrap')) - .then(() => expectFileToMatch('dist/test-project/index.html', oneLineTrim` - - `)); -} diff --git a/tests/legacy-cli/e2e/tests/third-party/material-icons.ts b/tests/legacy-cli/e2e/tests/third-party/material-icons.ts deleted file mode 100644 index 4ced68fbaca8..000000000000 --- a/tests/legacy-cli/e2e/tests/third-party/material-icons.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { expectFileToMatch } from '../../utils/fs'; -import { ng, silentNpm } from '../../utils/process'; -import { updateJsonFile } from '../../utils/project'; - -export default async function() { - // Install material design icons - await silentNpm('install', 'material-design-icons@3.0.1'); - - // Add icon stylesheet to application - await updateJsonFile('angular.json', workspaceJson => { - const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.build.options.styles = [ - { input: 'node_modules/material-design-icons/iconfont/material-icons.css' }, - ]; - }); - - // Build dev application - await ng('build', '--extract-css'); - - // Ensure icons are included - await expectFileToMatch('dist/test-project/styles.css', 'Material Icons') - - // Build prod application - await ng('build', '--prod', '--extract-css', '--output-hashing=none'); - - // Ensure icons are included - await expectFileToMatch('dist/test-project/styles.css', 'Material Icons') -} diff --git a/tests/legacy-cli/e2e/tests/update/update-1.0.ts b/tests/legacy-cli/e2e/tests/update/update-1.0.ts deleted file mode 100644 index 6d24c8ffeb4d..000000000000 --- a/tests/legacy-cli/e2e/tests/update/update-1.0.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createProjectFromAsset } from '../../utils/assets'; -import { ng, silentNpm } from '../../utils/process'; -import { isPrereleaseCli, useBuiltPackages, useCIChrome, useCIDefaults } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - const extraUpdateArgs = (await isPrereleaseCli()) ? ['--next', '--force'] : []; - - await createProjectFromAsset('1.0-project'); - - await useCIChrome('.'); - await expectToFail(() => ng('build')); - await ng('update', '@angular/cli'); - await useBuiltPackages(); - await silentNpm('install'); - await ng('update', '@angular/core', ...extraUpdateArgs); - await useCIDefaults('one-oh-project'); - await ng('generate', 'component', 'my-comp'); - await ng('test', '--watch=false'); - await ng('lint'); - await ng('build'); - await ng('build', '--prod'); - await ng('e2e'); -} diff --git a/tests/legacy-cli/e2e/tests/update/update-1.7-longhand.ts b/tests/legacy-cli/e2e/tests/update/update-1.7-longhand.ts deleted file mode 100644 index adec63d719ac..000000000000 --- a/tests/legacy-cli/e2e/tests/update/update-1.7-longhand.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createProjectFromAsset } from '../../utils/assets'; -import { ng, silentNpm } from '../../utils/process'; -import { isPrereleaseCli, useBuiltPackages } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - const extraUpdateArgs = (await isPrereleaseCli()) ? ['--next', '--force'] : []; - - await createProjectFromAsset('1.7-project'); - - await expectToFail(() => ng('build')); - await ng('update', '@angular/cli', '--migrate-only', '--from=1.7.1'); - await useBuiltPackages(); - await silentNpm('install'); - await ng('update', '@angular/core', ...extraUpdateArgs); - await ng('build'); -} diff --git a/tests/legacy-cli/e2e/tests/update/update-1.7.ts b/tests/legacy-cli/e2e/tests/update/update-1.7.ts deleted file mode 100644 index 335368638446..000000000000 --- a/tests/legacy-cli/e2e/tests/update/update-1.7.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as fs from 'fs'; -import { createProjectFromAsset } from '../../utils/assets'; -import { ng, silentNpm } from '../../utils/process'; -import { isPrereleaseCli, useBuiltPackages, useCIChrome, useCIDefaults } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - const extraUpdateArgs = (await isPrereleaseCli()) ? ['--next', '--force'] : []; - - await createProjectFromAsset('1.7-project'); - fs.writeFileSync('.npmrc', 'registry = http://localhost:4873', 'utf8'); - - await useCIChrome('.'); - await expectToFail(() => ng('build')); - await ng('update', '@angular/cli'); - await useBuiltPackages(); - await silentNpm('install'); - await ng('update', '@angular/core', ...extraUpdateArgs); - await useCIDefaults('latest-project'); - await ng('generate', 'component', 'my-comp'); - await ng('test', '--watch=false'); - await ng('lint'); - await ng('build', '--prod'); - await ng('e2e'); -} diff --git a/tests/legacy-cli/e2e/tests/update/update-7.0.ts b/tests/legacy-cli/e2e/tests/update/update-7.0.ts deleted file mode 100644 index a7cd7e169dd2..000000000000 --- a/tests/legacy-cli/e2e/tests/update/update-7.0.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as fs from 'fs'; -import { createProjectFromAsset } from '../../utils/assets'; -import { expectFileMatchToExist, expectFileToExist, expectFileToMatch } from '../../utils/fs'; -import { ng, noSilentNg, silentNpm } from '../../utils/process'; -import { isPrereleaseCli, useBuiltPackages, useCIChrome, useCIDefaults } from '../../utils/project'; -import { expectToFail } from '../../utils/utils'; - -export default async function() { - const extraUpdateArgs = (await isPrereleaseCli()) ? ['--next', '--force'] : []; - - // Create new project from previous version files. - // We must use the original NPM packages to force a real update. - await createProjectFromAsset('7.0-project', true); - fs.writeFileSync('.npmrc', 'registry = http://localhost:4873', 'utf8'); - - // Update the CLI. - // Users of CLI <7.2 will see the following warnings: - // packageGroup metadata of package @angular/cli is malformed. Ignoring. - // This is expected since the format changed in 7.2. - await ng('update', '@angular/cli', ...extraUpdateArgs); - - // Test CLI migrations. - // Should update the lazy route syntax via update-lazy-module-paths. - await expectFileToMatch( - 'src/app/app-routing.module.ts', - `loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)`, - ); - // Should update tsconfig and src/browserslist via differential-loading. - await expectFileToMatch('tsconfig.json', `"target": "es2015",`); - await expectToFail(() => expectFileToExist('e2e/browserlist')); - // Should rename codelyzer rules. - await expectFileToMatch('tslint.json', `use-lifecycle-interface`); - // Unnecessary es6 polyfills should be removed via drop-es6-polyfills. - await expectToFail(() => expectFileToMatch('src/polyfills.ts', `import 'core-js/es6/symbol';`)); - await expectToFail(() => expectFileToMatch('src/polyfills.ts', `import 'core-js/es6/set';`)); - - // Use the packages we are building in this commit, and CI Chrome. - await useBuiltPackages(); - await useCIChrome('src/'); - await useCIChrome('e2e/'); - await useCIDefaults('seven-oh-project'); - await silentNpm('install'); - - // Update Angular. - await ng('update', '@angular/core', ...extraUpdateArgs); - - // Run CLI commands. - await ng('generate', 'component', 'my-comp'); - await ng('test', '--watch=false'); - await ng('lint'); - await ng('e2e'); - await ng('e2e', '--prod'); - - // Verify project now creates bundles for differential loading. - await noSilentNg('build', '--prod'); - await expectFileMatchToExist('dist/seven-oh-project/', /main-es5\.[0-9a-f]{20}\.js/); - await expectFileMatchToExist('dist/seven-oh-project/', /main-es2015\.[0-9a-f]{20}\.js/); -} diff --git a/tests/legacy-cli/e2e/tests/update/update.ts b/tests/legacy-cli/e2e/tests/update/update.ts deleted file mode 100644 index 2ed02ee65856..000000000000 --- a/tests/legacy-cli/e2e/tests/update/update.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { ng, silentNpm } from '../../utils/process'; -import { readFile, writeFile } from '../../utils/fs'; -import { updateJsonFile } from '../../utils/project'; - - -export default function () { - // Disable this e2e as it takes about 10 minutes on a good computer and is flaky. - if (!process.env['E2E_UPDATE']) { - return Promise.resolve(); - } - - let origPackageJson: string; - let origCoreVersion: string; - let origCliVersion: string; - let origTypeScriptVersion: string; - - function updateVersions(obj: any) { - const keys = Object.keys(obj); - keys.forEach(key => { - if (key.startsWith('@angular/')) { - obj[key] = '2.1.0'; - } - }); - } - - return readFile('package.json') - .then((content) => origPackageJson = content) - .then(() => updateJsonFile('package.json', obj => { - origCoreVersion = obj.dependencies['@angular/core']; - origCliVersion = obj.devDependencies['@angular/cli']; - origTypeScriptVersion = obj.devDependencies['typescript']; - obj.devDependencies['@angular/cli'] = '1.6.5'; - obj.devDependencies['typescript'] = '2.0.2'; - obj.dependencies['rxjs'] = '5.0.0-beta.12'; - })) - .then(() => ng('update', '@angular/cli', 'typescript')) - .then(() => readFile('package.json')) - .then(s => { - const obj = JSON.parse(s); - if (origCliVersion === obj.devDependencies['@angular/cli']) { - throw new Error('CLI version not updated'); - } - if (origTypeScriptVersion === obj.devDependencies['typescript']) { - throw new Error('TypeScript version not updated'); - } - }) - .then(() => writeFile('package.json', origPackageJson)) - .then(() => silentNpm('install')); -} diff --git a/tests/legacy-cli/e2e/utils/assets.ts b/tests/legacy-cli/e2e/utils/assets.ts deleted file mode 100644 index b8c0c2736c42..000000000000 --- a/tests/legacy-cli/e2e/utils/assets.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {join} from 'path'; -import * as glob from 'glob'; -import {getGlobalVariable} from './env'; -import {relative} from 'path'; -import {copyFile, writeFile} from './fs'; -import {useBuiltPackages} from './project'; -import { git, silentNpm } from './process'; - - -export function assetDir(assetName: string) { - return join(__dirname, '../assets', assetName); -} - -export function copyProjectAsset(assetName: string, to?: string) { - const tempRoot = join(getGlobalVariable('tmp-root'), 'test-project'); - const sourcePath = assetDir(assetName); - const targetPath = join(tempRoot, to || assetName); - - return copyFile(sourcePath, targetPath); -} - -export function copyAssets(assetName: string) { - const seed = +Date.now(); - const tempRoot = join(getGlobalVariable('tmp-root'), 'assets', assetName + '-' + seed); - const root = assetDir(assetName); - - return Promise.resolve() - .then(() => { - const allFiles = glob.sync(join(root, '**/*'), { dot: true, nodir: true }); - - return allFiles.reduce((promise, filePath) => { - const relPath = relative(root, filePath); - const toPath = join(tempRoot, relPath); - - return promise.then(() => copyFile(filePath, toPath)); - }, Promise.resolve()); - }) - .then(() => tempRoot); -} - - -export async function createProjectFromAsset(assetName: string, useNpmPackages = false) { - const dir = await copyAssets(assetName); - process.chdir(dir); - if (!useNpmPackages) { - await useBuiltPackages(); - await writeFile('.npmrc', 'registry = http://localhost:4873', 'utf8'); - } - await silentNpm('install'); -} diff --git a/tests/legacy-cli/e2e/utils/env.ts b/tests/legacy-cli/e2e/utils/env.ts deleted file mode 100644 index dd80596f0698..000000000000 --- a/tests/legacy-cli/e2e/utils/env.ts +++ /dev/null @@ -1,13 +0,0 @@ -const global: {[name: string]: any} = Object.create(null); - - -export function setGlobalVariable(name: string, value: any) { - global[name] = value; -} - -export function getGlobalVariable(name: string): any { - if (!(name in global)) { - throw new Error(`Trying to access variable "${name}" but it's not defined.`); - } - return global[name]; -} diff --git a/tests/legacy-cli/e2e/utils/fs.ts b/tests/legacy-cli/e2e/utils/fs.ts deleted file mode 100644 index 6b696065b829..000000000000 --- a/tests/legacy-cli/e2e/utils/fs.ts +++ /dev/null @@ -1,207 +0,0 @@ -import * as fs from 'fs-extra'; -import {dirname} from 'path'; -import {stripIndents} from 'common-tags'; - - -export function readFile(fileName: string) { - return new Promise((resolve, reject) => { - fs.readFile(fileName, 'utf-8', (err: any, data: string) => { - if (err) { - reject(err); - } else { - resolve(data); - } - }); - }); -} - -export function writeFile(fileName: string, content: string, options?: any) { - return new Promise((resolve, reject) => { - fs.writeFile(fileName, content, options, (err: any) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); -} - - -export function deleteFile(path: string) { - return new Promise((resolve, reject) => { - fs.unlink(path, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); -} - - -export function rimraf(path: string) { - return new Promise((resolve, reject) => { - fs.remove(path, (err?: any) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); -} - - -export function moveFile(from: string, to: string) { - return new Promise((resolve, reject) => { - fs.rename(from, to, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); -} - - -export function symlinkFile(from: string, to: string, type?: string) { - return new Promise((resolve, reject) => { - fs.symlink(from, to, type, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); -} - -export function createDir(path: string) { - return _recursiveMkDir(path); -} - - -function _recursiveMkDir(path: string): Promise { - if (fs.existsSync(path)) { - return Promise.resolve(); - } else { - return _recursiveMkDir(dirname(path)) - .then(() => fs.mkdirSync(path)); - } -} - -export function copyFile(from: string, to: string) { - return _recursiveMkDir(dirname(to)) - .then(() => new Promise((resolve, reject) => { - const rd = fs.createReadStream(from); - rd.on('error', (err: Error) => reject(err)); - - const wr = fs.createWriteStream(to); - wr.on('error', (err: Error) => reject(err)); - wr.on('close', () => resolve()); - - rd.pipe(wr); - })); -} - -export function moveDirectory(from: string, to: string) { - return fs.move(from, to, { overwrite: true }); -} - - -export function writeMultipleFiles(fs: { [path: string]: string }) { - return Promise.all(Object.keys(fs).map(fileName => writeFile(fileName, fs[fileName]))); -} - - -export function replaceInFile(filePath: string, match: RegExp | string, replacement: string) { - return readFile(filePath) - .then((content: string) => writeFile(filePath, content.replace(match, replacement))); -} - - -export function appendToFile(filePath: string, text: string, options?: any) { - return readFile(filePath) - .then((content: string) => writeFile(filePath, content.concat(text), options)); -} - - -export function prependToFile(filePath: string, text: string, options?: any) { - return readFile(filePath) - .then((content: string) => writeFile(filePath, text.concat(content), options)); -} - - -export function expectFileMatchToExist(dir: string, regex: RegExp) { - return new Promise((resolve, reject) => { - const [fileName] = fs.readdirSync(dir).filter(name => name.match(regex)); - if (!fileName) { - reject(new Error(`File ${regex} was expected to exist but not found...`)); - } - resolve(fileName); - }); -} - -export function expectFileNotToExist(fileName: string) { - return new Promise((resolve, reject) => { - fs.exists(fileName, (exist) => { - if (exist) { - reject(new Error(`File ${fileName} was expected not to exist but found...`)); - } else { - resolve(); - } - }); - }); -} - -export function expectFileToExist(fileName: string) { - return new Promise((resolve, reject) => { - fs.exists(fileName, (exist) => { - if (exist) { - resolve(); - } else { - reject(new Error(`File ${fileName} was expected to exist but not found...`)); - } - }); - }); -} - -export function expectFileToMatch(fileName: string, regEx: RegExp | string) { - return readFile(fileName) - .then(content => { - if (typeof regEx == 'string') { - if (content.indexOf(regEx) == -1) { - throw new Error(stripIndents`File "${fileName}" did not contain "${regEx}"... - Content: - ${content} - ------ - `); - } - } else { - if (!content.match(regEx)) { - throw new Error(stripIndents`File "${fileName}" did not contain "${regEx}"... - Content: - ${content} - ------ - `); - } - } - }); -} - -export async function getFileSize(fileName: string) { - const stats = await fs.stat(fileName); - - return stats.size; -} - -export async function expectFileSizeToBeUnder(fileName: string, sizeInBytes: number) { - const fileSize = await getFileSize(fileName); - - if (fileSize > sizeInBytes) { - throw new Error(`File "${fileName}" exceeded file size of "${sizeInBytes}". Size is ${fileSize}.`); - } -} diff --git a/tests/legacy-cli/e2e/utils/git.ts b/tests/legacy-cli/e2e/utils/git.ts deleted file mode 100644 index 7da09d308c01..000000000000 --- a/tests/legacy-cli/e2e/utils/git.ts +++ /dev/null @@ -1,37 +0,0 @@ -import {git, silentGit} from './process'; - - -export function gitClean() { - console.log(' Cleaning git...'); - return silentGit('clean', '-df') - .then(() => silentGit('reset', '--hard')) - .then(() => { - // Checkout missing files - return silentGit('status', '--porcelain') - .then(({ stdout }) => stdout - .split(/[\n\r]+/g) - .filter(line => line.match(/^ D/)) - .map(line => line.replace(/^\s*\S+\s+/, ''))) - .then(files => silentGit('checkout', ...files)); - }) - .then(() => expectGitToBeClean()); -} - -export function expectGitToBeClean() { - return silentGit('status', '--porcelain') - .then(({ stdout }) => { - if (stdout != '') { - throw new Error('Git repo is not clean...\n' + stdout); - } - }); -} - -export function gitCommit(message: string) { - return git('add', '-A') - .then(() => silentGit('status', '--porcelain')) - .then(({ stdout }) => { - if (stdout != '') { - return git('commit', '-am', message); - } - }); -} diff --git a/tests/legacy-cli/e2e/utils/http.ts b/tests/legacy-cli/e2e/utils/http.ts deleted file mode 100644 index fa0fbc32c3c5..000000000000 --- a/tests/legacy-cli/e2e/utils/http.ts +++ /dev/null @@ -1,22 +0,0 @@ -import {IncomingMessage} from 'http'; -import * as _request from 'request'; - - -export function request(url: string): Promise { - return new Promise((resolve, reject) => { - let options = { - url: url, - headers: { 'Accept': 'text/html' }, - agentOptions: { rejectUnauthorized: false } - }; - _request(options, (error: any, response: IncomingMessage, body: string) => { - if (error) { - reject(error); - } else if (response.statusCode >= 400) { - reject(new Error(`Requesting "${url}" returned status code ${response.statusCode}.`)); - } else { - resolve(body); - } - }); - }); -} diff --git a/tests/legacy-cli/e2e/utils/process.ts b/tests/legacy-cli/e2e/utils/process.ts deleted file mode 100644 index 0864042796f1..000000000000 --- a/tests/legacy-cli/e2e/utils/process.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { SpawnOptions } from "child_process"; -import * as child_process from 'child_process'; -import { terminal } from '@angular-devkit/core'; -import { Observable, concat, defer, EMPTY, from} from 'rxjs'; -import {repeat, takeLast} from 'rxjs/operators'; -import {getGlobalVariable} from './env'; -import {rimraf} from './fs'; -import {catchError} from 'rxjs/operators'; -const treeKill = require('tree-kill'); - - -interface ExecOptions { - silent?: boolean; - waitForMatch?: RegExp; - env?: { [varname: string]: string }; -} - - -let _processes: child_process.ChildProcess[] = []; - -export type ProcessOutput = { - stdout: string; - stderr: string; -}; - - -function _exec(options: ExecOptions, cmd: string, args: string[]): Promise { - let stdout = ''; - let stderr = ''; - const cwd = process.cwd(); - const env = options.env; - console.log( - `==========================================================================================` - ); - - args = args.filter(x => x !== undefined); - const flags = [ - options.silent && 'silent', - options.waitForMatch && `matching(${options.waitForMatch})` - ] - .filter(x => !!x) // Remove false and undefined. - .join(', ') - .replace(/^(.+)$/, ' [$1]'); // Proper formatting. - - console.log(terminal.blue(`Running \`${cmd} ${args.map(x => `"${x}"`).join(' ')}\`${flags}...`)); - console.log(terminal.blue(`CWD: ${cwd}`)); - console.log(terminal.blue(`ENV: ${JSON.stringify(env)}`)); - const spawnOptions: SpawnOptions = { - cwd, - ...env ? { env } : {}, - }; - - if (process.platform.startsWith('win')) { - args.unshift('/c', cmd); - cmd = 'cmd.exe'; - spawnOptions['stdio'] = 'pipe'; - } - - const childProcess = child_process.spawn(cmd, args, spawnOptions); - childProcess.stdout.on('data', (data: Buffer) => { - stdout += data.toString('utf-8'); - if (options.silent) { - return; - } - data.toString('utf-8') - .split(/[\n\r]+/) - .filter(line => line !== '') - .forEach(line => console.log(' ' + line)); - }); - childProcess.stderr.on('data', (data: Buffer) => { - stderr += data.toString('utf-8'); - if (options.silent) { - return; - } - data.toString('utf-8') - .split(/[\n\r]+/) - .filter(line => line !== '') - .forEach(line => console.error(terminal.yellow(' ' + line))); - }); - - _processes.push(childProcess); - - // Create the error here so the stack shows who called this function. - const err = new Error(`Running "${cmd} ${args.join(' ')}" returned error code `); - return new Promise((resolve, reject) => { - childProcess.on('exit', (error: any) => { - _processes = _processes.filter(p => p !== childProcess); - - if (!error) { - resolve({ stdout, stderr }); - } else { - err.message += `${error}...\n\nSTDOUT:\n${stdout}\n\nSTDERR:\n${stderr}\n`; - reject(err); - } - }); - - if (options.waitForMatch) { - const match = options.waitForMatch; - childProcess.stdout.on('data', (data: Buffer) => { - if (data.toString().match(match)) { - resolve({ stdout, stderr }); - } - }); - childProcess.stderr.on('data', (data: Buffer) => { - if (data.toString().match(match)) { - resolve({ stdout, stderr }); - } - }); - } - }); -} - -export function waitForAnyProcessOutputToMatch(match: RegExp, - timeout = 30000): Promise { - // Race between _all_ processes, and the timeout. First one to resolve/reject wins. - const timeoutPromise: Promise = new Promise((_resolve, reject) => { - // Wait for 30 seconds and timeout. - setTimeout(() => { - reject(new Error(`Waiting for ${match} timed out (timeout: ${timeout}msec)...`)); - }, timeout); - }); - - const matchPromises: Promise[] = _processes.map( - childProcess => new Promise(resolve => { - let stdout = ''; - let stderr = ''; - childProcess.stdout.on('data', (data: Buffer) => { - stdout += data.toString(); - if (data.toString().match(match)) { - resolve({ stdout, stderr }); - } - }); - childProcess.stderr.on('data', (data: Buffer) => { - stderr += data.toString(); - if (data.toString().match(match)) { - resolve({ stdout, stderr }); - } - }); - })); - - return Promise.race(matchPromises.concat([timeoutPromise])); -} - -export function killAllProcesses(signal = 'SIGTERM') { - _processes.forEach(process => treeKill(process.pid, signal)); - _processes = []; -} - -export function exec(cmd: string, ...args: string[]) { - return _exec({}, cmd, args); -} - -export function silentExec(cmd: string, ...args: string[]) { - return _exec({ silent: true }, cmd, args); -} - -export function execWithEnv(cmd: string, args: string[], env: { [varname: string]: string }) { - return _exec({ env }, cmd, args); -} - -export function execAndWaitForOutputToMatch(cmd: string, args: string[], match: RegExp) { - if (cmd === 'ng' && args[0] === 'serve') { - // Accept matches up to 20 times after the initial match. - // Useful because the Webpack watcher can rebuild a few times due to files changes that - // happened just before the build (e.g. `git clean`). - // This seems to be due to host file system differences, see - // https://nodejs.org/docs/latest/api/fs.html#fs_caveats - return concat( - from( - _exec({ waitForMatch: match }, cmd, args) - ), - defer(() => waitForAnyProcessOutputToMatch(match, 2500)).pipe( - repeat(20), - catchError(() => EMPTY), - ), - ).pipe( - takeLast(1), - ).toPromise(); - } else { - return _exec({ waitForMatch: match }, cmd, args); - } -} - -export function ng(...args: string[]) { - const argv = getGlobalVariable('argv'); - const maybeSilentNg = argv['nosilent'] ? noSilentNg : silentNg; - if (['build', 'serve', 'test', 'e2e', 'xi18n'].indexOf(args[0]) != -1) { - if (args[0] == 'e2e') { - // Wait 1 second before running any end-to-end test. - return new Promise(resolve => setTimeout(resolve, 1000)) - .then(() => maybeSilentNg(...args)); - } - - return maybeSilentNg(...args); - } else { - return noSilentNg(...args); - } -} - -export function noSilentNg(...args: string[]) { - return _exec({}, 'ng', args); -} - -export function silentNg(...args: string[]) { - return _exec({silent: true}, 'ng', args); -} - -export function silentNpm(...args: string[]) { - return _exec({silent: true}, 'npm', args); -} - -export function npm(...args: string[]) { - return _exec({}, 'npm', args); -} - -export function node(...args: string[]) { - return _exec({}, 'node', args); -} - -export function git(...args: string[]) { - return _exec({}, 'git', args); -} - -export function silentGit(...args: string[]) { - return _exec({silent: true}, 'git', args); -} diff --git a/tests/legacy-cli/e2e/utils/project.ts b/tests/legacy-cli/e2e/utils/project.ts deleted file mode 100644 index 276b6adea7d0..000000000000 --- a/tests/legacy-cli/e2e/utils/project.ts +++ /dev/null @@ -1,305 +0,0 @@ -import * as fs from 'fs'; -import { prerelease } from 'semver'; -import { packages } from '../../../../lib/packages'; -import { getGlobalVariable } from './env'; -import { prependToFile, readFile, replaceInFile, writeFile } from './fs'; -import { gitCommit } from './git'; -import { execAndWaitForOutputToMatch, git, ng, npm, silentNpm } from './process'; - -const tsConfigPath = 'tsconfig.json'; - - -export function updateJsonFile(filePath: string, fn: (json: any) => any | void) { - return readFile(filePath) - .then(tsConfigJson => { - const tsConfig = JSON.parse(tsConfigJson); - const result = fn(tsConfig) || tsConfig; - - return writeFile(filePath, JSON.stringify(result, null, 2)); - }); -} - - -export function updateTsConfig(fn: (json: any) => any | void) { - return updateJsonFile(tsConfigPath, fn); -} - - -export function ngServe(...args: string[]) { - return execAndWaitForOutputToMatch('ng', - ['serve', ...args], - /: Compiled successfully./); -} - - -export async function createProject(name: string, ...args: string[]) { - const extraArgs = []; - - process.chdir(getGlobalVariable('tmp-root')); - await ng('new', name, '--skip-install', ...extraArgs, ...args); - process.chdir(name); - - if (fs.existsSync('tsconfig.json')) { - // Disable the TS version check to make TS updates easier. - // Only VE does it, but on Ivy the i18n extraction uses VE. - await updateJsonFile('tsconfig.json', config => { - config.angularCompilerOptions.disableTypeScriptVersionCheck = true; - }); - } - - await prepareProjectForE2e(name); -} - -export async function prepareProjectForE2e(name) { - const argv: string[] = getGlobalVariable('argv'); - - await git( - 'config', - 'user.email', - 'angular-core+e2e@google.com', - ); - await git( - 'config', - 'user.name', - 'Angular CLI E2e', - ); - await git( - 'config', - 'commit.gpgSign', - 'false', - ); - - await useCIChrome( - 'e2e', - ); - await useCIChrome( - '', - ); - - // legacy projects - await useCIChrome( - 'src', - ); - - if (argv['ng-snapshots'] || argv['ng-tag']) { - await useSha(); - } - - await writeFile('.npmrc', 'registry=http://localhost:4873'); - - console.log( - `Project ${name} created... Installing npm.`, - ); - await silentNpm( - 'install', - ); - await useCIDefaults( - name, - ); - // Force sourcemaps to be from the root of the filesystem. - await updateJsonFile( - 'tsconfig.json', - json => { - json[ - 'compilerOptions' - ][ - 'sourceRoot' - ] = - '/'; - }, - ); - await gitCommit( - 'prepare-project-for-e2e', - ); -} - -export function useBuiltPackages() { - return Promise.resolve() - .then(() => updateJsonFile('package.json', json => { - if (!json['dependencies']) { - json['dependencies'] = {}; - } - if (!json['devDependencies']) { - json['devDependencies'] = {}; - } - - for (const packageName of Object.keys(packages)) { - if (json['dependencies'].hasOwnProperty(packageName) - ) { - json['dependencies'][packageName] = packages[packageName].tar; - } else if (json['devDependencies'].hasOwnProperty(packageName)) { - json['devDependencies'][packageName] = packages[packageName].tar; - } - } - })); -} - -export function useSha() { - const argv = getGlobalVariable('argv'); - if (argv['ng-snapshots'] || argv['ng-tag']) { - // We need more than the sha here, version is also needed. Examples of latest tags: - // 7.0.0-beta.4+dd2a650 - // 6.1.6+4a8d56a - const label = argv['ng-tag'] ? argv['ng-tag'] : ''; - const ngSnapshotVersions = require('../ng-snapshot/package.json'); - return updateJsonFile('package.json', json => { - // Install over the project with snapshot builds. - function replaceDependencies(key: string) { - const missingSnapshots = []; - Object.keys(json[key] || {}) - .filter(name => name.match(/^@angular\//)) - .forEach(name => { - const pkgName = name.split(/\//)[1]; - if (pkgName == 'cli') { - return; - } - if (label) { - json[key][`@angular/${pkgName}`] - = `github:angular/${pkgName}-builds${label}`; - } else { - const replacement = ngSnapshotVersions.dependencies[`@angular/${pkgName}`]; - if (!replacement) { - missingSnapshots.push(`missing @angular/${pkgName}`); - } - json[key][`@angular/${pkgName}`] = replacement; - } - }); - if (missingSnapshots.length > 0) { - throw new Error('e2e test with --ng-snapshots requires all angular packages be ' + - 'listed in tests/legacy-cli/e2e/ng-snapshot/package.json.\nErrors:\n' + missingSnapshots.join('\n ')); - } - } - try { - replaceDependencies('dependencies'); - replaceDependencies('devDependencies'); - } catch (e) { - return Promise.reject(e); - } - }); - } else { - return Promise.resolve(); - } -} - -export function useNgVersion(version: string) { - return updateJsonFile('package.json', json => { - // Install over the project with specific versions. - Object.keys(json['dependencies'] || {}) - .filter(name => name.match(/^@angular\//)) - .forEach(name => { - const pkgName = name.split(/\//)[1]; - if (pkgName == 'cli') { - return; - } - json['dependencies'][`@angular/${pkgName}`] = version; - }); - - Object.keys(json['devDependencies'] || {}) - .filter(name => name.match(/^@angular\//)) - .forEach(name => { - const pkgName = name.split(/\//)[1]; - if (pkgName == 'cli') { - return; - } - json['devDependencies'][`@angular/${pkgName}`] = version; - }); - // Set the correct peer dependencies for @angular/core and @angular/compiler-cli. - // This list should be kept up to date with each major release. - if (version.startsWith('^5')) { - json['devDependencies']['typescript'] = '>=2.4.2 <2.5'; - json['dependencies']['rxjs'] = '^5.5.0'; - json['dependencies']['zone.js'] = '~0.8.4'; - } else if (version.startsWith('^6')) { - json['devDependencies']['typescript'] = '>=2.7.2 <2.8'; - json['dependencies']['rxjs'] = '^6.0.0'; - json['dependencies']['zone.js'] = '~0.8.26'; - } else if (version.startsWith('^7')) { - json['devDependencies']['typescript'] = '>=3.1.1 <3.2'; - json['dependencies']['rxjs'] = '^6.0.0'; - json['dependencies']['zone.js'] = '~0.8.26'; - } - }); -} - -export function useCIDefaults(projectName = 'test-project') { - return updateJsonFile('angular.json', workspaceJson => { - // Disable progress reporting on CI to reduce spam. - const project = workspaceJson.projects[projectName]; - const appTargets = project.targets || project.architect; - appTargets.build.options.progress = false; - appTargets.test.options.progress = false; - // Use the CI chrome setup in karma. - appTargets.test.options.browsers = 'ChromeHeadlessCI'; - // Disable auto-updating webdriver in e2e. - if (appTargets.e2e) { - appTargets.e2e.options.webdriverUpdate = false; - } - - // legacy project structure - const e2eProject = workspaceJson.projects[projectName + '-e2e']; - if (e2eProject) { - const e2eTargets = e2eProject.targets || e2eProject.architect; - e2eTargets.e2e.options.webdriverUpdate = false; - } - }) - .then(() => updateJsonFile('package.json', json => { - // Use matching versions of Chromium and ChromeDriver. - // https://github.com/GoogleChrome/puppeteer/releases - // http://chromedriver.chromium.org/downloads - json['scripts']['webdriver-update'] = 'webdriver-manager update' + - ` --standalone false --gecko false --versions.chrome 79.0.3945.16`; // Supports Chrome 79 - - })) - .then(() => npm('run', 'webdriver-update')); -} - -export function useCIChrome(projectDir: string) { - const dir = projectDir ? projectDir + '/' : ''; - const protractorConf = `${dir}protractor.conf.js`; - const karmaConf = `${dir}karma.conf.js`; - - return Promise.resolve() - .then(() => updateJsonFile('package.json', json => { - // Use matching versions of Chromium (via puppeteer) and ChromeDriver. - // https://github.com/GoogleChrome/puppeteer/releases - // http://chromedriver.chromium.org/downloads - json['devDependencies']['puppeteer'] = '2.0.0'; // Chromium 79.0.3942.0 (r706915) - json['devDependencies']['karma-chrome-launcher'] = '~2.2.0'; // Minimum for ChromeHeadless. - })) - // Use Pupeteer in protractor if a config is found on the project. - .then(() => { - if (fs.existsSync(protractorConf)) { - return replaceInFile(protractorConf, - `browserName: 'chrome'`, - `browserName: 'chrome', - chromeOptions: { - args: ['--headless'], - binary: require('puppeteer').executablePath() - } - `); - } - }) - // Use Pupeteer in karma if a config is found on the project. - .then(() => { - if (fs.existsSync(karmaConf)) { - return prependToFile(karmaConf, - `process.env.CHROME_BIN = require('puppeteer').executablePath();`) - .then(() => replaceInFile(karmaConf, - `browsers: ['Chrome']`, - `browsers: ['Chrome'], - customLaunchers: { - ChromeHeadlessCI: { - base: 'ChromeHeadless', - } - } - `)); - } - }); -} - -export async function isPrereleaseCli() { - const angularCliPkgJson = JSON.parse(await readFile('node_modules/@angular/cli/package.json')); - const pre = prerelease(angularCliPkgJson.version); - - return pre && pre.length > 0; -} diff --git a/tests/legacy-cli/e2e/utils/utils.ts b/tests/legacy-cli/e2e/utils/utils.ts deleted file mode 100644 index 3f73ec59ba94..000000000000 --- a/tests/legacy-cli/e2e/utils/utils.ts +++ /dev/null @@ -1,16 +0,0 @@ - -export function expectToFail(fn: () => Promise, errorMessage?: string): Promise { - return fn() - .then(() => { - const functionSource = fn.name || (fn).source || fn.toString(); - const errorDetails = errorMessage ? `\n\tDetails:\n\t${errorMessage}` : ''; - throw new Error( - `Function ${functionSource} was expected to fail, but succeeded.${errorDetails}`); - }, (err) => { return err; }); -} - -export function wait(msecs: number): Promise { - return new Promise((resolve) => { - setTimeout(resolve, msecs); - }); -} diff --git a/tests/legacy-cli/e2e/utils/version.ts b/tests/legacy-cli/e2e/utils/version.ts deleted file mode 100644 index 0be47e2216e3..000000000000 --- a/tests/legacy-cli/e2e/utils/version.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as fs from 'fs'; -import * as semver from 'semver'; - - -export function readNgVersion(): string { - const packageJson: any = JSON.parse(fs.readFileSync('./node_modules/@angular/core/package.json', 'utf8')); - return packageJson['version']; -} - -export function ngVersionMatches(range: string): boolean { - return semver.satisfies(readNgVersion(), range); -} diff --git a/tests/legacy-cli/e2e_runner.ts b/tests/legacy-cli/e2e_runner.ts deleted file mode 100644 index 19ac155152f1..000000000000 --- a/tests/legacy-cli/e2e_runner.ts +++ /dev/null @@ -1,274 +0,0 @@ -// This may seem awkward but we're using Logger in our e2e. At this point the unit tests -// have run already so it should be "safe", teehee. -import { logging, terminal } from '@angular-devkit/core'; -import { createConsoleLogger } from '@angular-devkit/core/node'; -import { spawn } from 'child_process'; -import * as fs from 'fs'; -import * as glob from 'glob'; -import * as minimist from 'minimist'; -import * as os from 'os'; -import * as path from 'path'; -import { setGlobalVariable } from './e2e/utils/env'; -import { gitClean } from './e2e/utils/git'; - -const { blue, bold, green, red, yellow, white } = terminal; - -Error.stackTraceLimit = Infinity; - -// tslint:disable:no-global-tslint-disable no-console - -/** - * Here's a short description of those flags: - * --debug If a test fails, block the thread so the temporary directory isn't deleted. - * --noproject Skip creating a project or using one. - * --nobuild Skip building the packages. Use with --noglobal and --reuse to quickly - * rerun tests. - * --noglobal Skip linking your local @angular/cli directory. Can save a few seconds. - * --nosilent Never silence ng commands. - * --ng-tag=TAG Use a specific tag for build snapshots. Similar to ng-snapshots but point to a - * tag instead of using the latest master. - * --ng-snapshots Install angular snapshot builds in the test project. - * --ve Use the View Engine compiler. - * --glob Run tests matching this glob pattern (relative to tests/e2e/). - * --ignore Ignore tests matching this glob pattern. - * --reuse=/path Use a path instead of create a new project. That project should have been - * created, and npm installed. Ideally you want a project created by a previous - * run of e2e. - * --nb-shards Total number of shards that this is part of. Default is 2 if --shard is - * passed in. - * --shard Index of this processes' shard. - * --devkit=path Path to the devkit to use. The devkit will be built prior to running. - * --tmpdir=path Override temporary directory to use for new projects. - * If unnamed flags are passed in, the list of tests will be filtered to include only those passed. - */ -const argv = minimist(process.argv.slice(2), { - boolean: ['debug', 'ng-snapshots', 'noglobal', 'nosilent', 'noproject', 'verbose', 've'], - string: ['devkit', 'glob', 'ignore', 'reuse', 'ng-tag', 'tmpdir', 'ng-version'], -}); - -/** - * Set the error code of the process to 255. This is to ensure that if something forces node - * to exit without finishing properly, the error code will be 255. Right now that code is not used. - * - * - 1 When tests succeed we already call `process.exit(0)`, so this doesn't change any correct - * behaviour. - * - * One such case that would force node <= v6 to exit with code 0, is a Promise that doesn't resolve. - */ -process.exitCode = 255; - -const logger = createConsoleLogger(argv.verbose); -const logStack = [logger]; -function lastLogger() { - return logStack[logStack.length - 1]; -} - -const testGlob = argv.glob || 'tests/**/*.ts'; -let currentFileName = null; - -const e2eRoot = path.join(__dirname, 'e2e'); -const allSetups = glob - .sync(path.join(e2eRoot, 'setup/**/*.ts'), { nodir: true }) - .map(name => path.relative(e2eRoot, name)) - .sort(); -let allTests = glob - .sync(path.join(e2eRoot, testGlob), { nodir: true, ignore: argv.ignore }) - .map(name => path.relative(e2eRoot, name)) - // Replace windows slashes. - .map(name => name.replace(/\\/g, '/')) - .sort(); - -// TODO: either update or remove these tests. -allTests = allTests - // IS this test still valid? \/ - .filter(name => !name.endsWith('/module-id.ts')) - // Do we want to support this? - .filter(name => !name.endsWith('different-file-format.ts')) - // Not sure what this test is meant to test, but with depedency changes it is not valid anymore. - .filter(name => !name.endsWith('loaders-resolution.ts')) - // NEW COMMAND - .filter(name => !name.includes('tests/commands/new/')) - // NEEDS devkit change - .filter(name => !name.endsWith('/existing-directory.ts')) - // Disabled on rc.0 due to needed sync with devkit for changes. - .filter(name => !name.endsWith('/service-worker.ts')); - -if (argv.ve) { - // Remove Ivy specific tests - allTests = allTests - .filter(name => !name.includes('tests/i18n/ivy-localize-')); -} - -const shardId = 'shard' in argv ? argv['shard'] : null; -const nbShards = (shardId === null ? 1 : argv['nb-shards']) || 2; -const tests = allTests.filter(name => { - // Check for naming tests on command line. - if (argv._.length == 0) { - return true; - } - - return argv._.some(argName => { - return ( - path.join(process.cwd(), argName) == path.join(__dirname, 'e2e', name) || - argName == name || - argName == name.replace(/\.ts$/, '') - ); - }); -}); - -// Remove tests that are not part of this shard. -const shardedTests = tests.filter((name, i) => shardId === null || i % nbShards == shardId); -const testsToRun = allSetups.concat(shardedTests); - -if (shardedTests.length === 0) { - console.log(`No tests would be ran, aborting.`); - process.exit(1); -} - -console.log(testsToRun.join('\n')); -/** - * Load all the files from the e2e, filter and sort them and build a promise of their default - * export. - */ -if (testsToRun.length == allTests.length) { - console.log(`Running ${testsToRun.length} tests`); -} else { - console.log(`Running ${testsToRun.length} tests (${allTests.length + allSetups.length} total)`); -} - -setGlobalVariable('argv', argv); - -// Setup local package registry -const registryPath = - fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-e2e-registry-')); -fs.copyFileSync( - path.join(__dirname, 'verdaccio.yaml'), - path.join(registryPath, 'verdaccio.yaml'), -); -const registryProcess = spawn( - 'node', - [require.resolve('verdaccio/bin/verdaccio'), '-c', './verdaccio.yaml'], - { cwd: registryPath, stdio: 'inherit' }, -); - -testsToRun - .reduce((previous, relativeName, testIndex) => { - // Make sure this is a windows compatible path. - let absoluteName = path.join(e2eRoot, relativeName); - if (/^win/.test(process.platform)) { - absoluteName = absoluteName.replace(/\\/g, path.posix.sep); - } - - return previous.then(() => { - currentFileName = relativeName.replace(/\.ts$/, ''); - const start = +new Date(); - - const module = require(absoluteName); - const fn: (skipClean?: () => void) => Promise | void = - typeof module == 'function' - ? module - : typeof module.default == 'function' - ? module.default - : () => { - throw new Error('Invalid test module.'); - }; - - let clean = true; - let previousDir = null; - - return Promise.resolve() - .then(() => printHeader(currentFileName, testIndex)) - .then(() => (previousDir = process.cwd())) - .then(() => logStack.push(lastLogger().createChild(currentFileName))) - .then(() => fn(() => (clean = false))) - .then( - () => logStack.pop(), - err => { - logStack.pop(); - throw err; - }, - ) - .then(() => console.log('----')) - .then(() => { - // If we're not in a setup, change the directory back to where it was before the test. - // This allows tests to chdir without worrying about keeping the original directory. - if (allSetups.indexOf(relativeName) == -1 && previousDir) { - process.chdir(previousDir); - } - }) - .then(() => { - // Only clean after a real test, not a setup step. Also skip cleaning if the test - // requested an exception. - if (allSetups.indexOf(relativeName) == -1 && clean) { - logStack.push(new logging.NullLogger()); - - return gitClean().then( - () => logStack.pop(), - err => { - logStack.pop(); - throw err; - }, - ); - } - }) - .then( - () => printFooter(currentFileName, start), - err => { - printFooter(currentFileName, start); - console.error(err); - throw err; - }, - ); - }); - }, Promise.resolve()) - .then( - () => { - if (registryProcess) { - registryProcess.kill(); - } - - console.log(green('Done.')); - process.exit(0); - }, - err => { - console.log('\n'); - console.error(red(`Test "${currentFileName}" failed...`)); - console.error(red(err.message)); - console.error(red(err.stack)); - - if (registryProcess) { - registryProcess.kill(); - } - - if (argv.debug) { - console.log(`Current Directory: ${process.cwd()}`); - console.log('Will loop forever while you debug... CTRL-C to quit.'); - - /* eslint-disable no-constant-condition */ - while (1) { - // That's right! - } - } - - process.exit(1); - }, - ); - -function printHeader(testName: string, testIndex: number) { - const text = `${testIndex + 1} of ${testsToRun.length}`; - const fullIndex = - (testIndex < allSetups.length - ? testIndex - : (testIndex - allSetups.length) * nbShards + shardId + allSetups.length) + 1; - const length = tests.length + allSetups.length; - const shard = - shardId === null ? '' : yellow(` [${shardId}:${nbShards}]` + bold(` (${fullIndex}/${length})`)); - console.log(green(`Running "${bold(blue(testName))}" (${bold(white(text))}${shard})...`)); -} - -function printFooter(testName: string, startTime: number) { - // Round to hundredth of a second. - const t = Math.round((Date.now() - startTime) / 10) / 100; - console.log(green('Last step took ') + bold(blue(t)) + green('s...')); - console.log(''); -} diff --git a/tests/legacy-cli/run_e2e.js b/tests/legacy-cli/run_e2e.js deleted file mode 100644 index fb004c88a042..000000000000 --- a/tests/legacy-cli/run_e2e.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; -require('../../lib/bootstrap-local'); -require('./e2e_runner.ts'); diff --git a/tests/legacy-cli/verdaccio.yaml b/tests/legacy-cli/verdaccio.yaml deleted file mode 100644 index 75ca0c10e257..000000000000 --- a/tests/legacy-cli/verdaccio.yaml +++ /dev/null @@ -1,38 +0,0 @@ -storage: ./storage - -auth: - htpasswd: - file: ./htpasswd - max_users: -1 - -uplinks: - npmjs: - url: https://registry.npmjs.org/ - -packages: - '@angular/{cli,pwa}': - access: $all - publish: $all - - '@angular-devkit/*': - access: $all - publish: $all - - '@ngtools/webpack': - access: $all - publish: $all - - '@schematics/{angular,schematics,update}': - access: $all - publish: $all - - '**': - access: $all - proxy: npmjs - -logs: - - {type: stdout, format: pretty, level: warn} - -# https://github.com/verdaccio/verdaccio/issues/301 -server: - keepAliveTimeout: 0 \ No newline at end of file diff --git a/tests/package.json b/tests/package.json new file mode 100644 index 000000000000..6191b2f070d6 --- /dev/null +++ b/tests/package.json @@ -0,0 +1,6 @@ +{ + "devDependencies": { + "@types/tar-stream": "3.1.5", + "tar-stream": "3.2.2" + } +} diff --git a/tests/rollup.config.mjs b/tests/rollup.config.mjs new file mode 100644 index 000000000000..c48299094fef --- /dev/null +++ b/tests/rollup.config.mjs @@ -0,0 +1,45 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ +import { nodeResolve } from '@rollup/plugin-node-resolve'; +import commonjs from '@rollup/plugin-commonjs'; +import json from '@rollup/plugin-json'; +import glob from 'fast-glob'; + +const testFiles = [ + 'e2e_runner.js', + 'e2e/utils/test_process.js', + ...glob.sync('e2e/(initialize|setup|tests)/**/*.js'), +]; + +// Generate chunks to keep the original folder structure. +// Needed as we dynamically load these files. +const chunks = {}; +for (const file of testFiles) { + chunks[file.slice(0, -'.js'.length)] = file; +} + +export default { + input: chunks, + external: ['undici', 'puppeteer'], // This cannot be bundled as `node:sqlite` is experimental in node.js 22. Remove once this feature is no longer behind a flag + plugins: [ + nodeResolve({ + preferBuiltins: true, + browser: false, + }), + json(), + commonjs({ + // Test runner uses dynamic requires, and those are fine. + // Rollup should not try to process them. + ignoreDynamicRequires: true, + }), + ], + output: { + dir: './runner_bundled_out', + exports: 'auto', + }, +}; diff --git a/tests/schematics/update/packages/update-migrations/v1_5.js b/tests/schematics/update/packages/update-migrations/v1_5.js index 7e79eda93d49..becf300fecdf 100644 --- a/tests/schematics/update/packages/update-migrations/v1_5.js +++ b/tests/schematics/update/packages/update-migrations/v1_5.js @@ -1,12 +1,13 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ -exports.default = function() { - return function(tree) { - tree.create('/version1_5', ''); - }; + +exports.default = function () { + return function (tree) { + tree.create('/version1_5', ''); + }; }; diff --git a/tests/tsconfig.json b/tests/tsconfig.json new file mode 100644 index 000000000000..5070cc5b6927 --- /dev/null +++ b/tests/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig-test.json", + "compilerOptions": { "paths": {} }, + "exclude": ["e2e/assets/**"] +} diff --git a/tests/verdaccio.yaml b/tests/verdaccio.yaml new file mode 100644 index 000000000000..a398f671b43e --- /dev/null +++ b/tests/verdaccio.yaml @@ -0,0 +1,51 @@ +storage: ./storage + +auth: + auth-memory: + users: {} +listen: localhost:${HTTP_PORT} +uplinks: + npmjs: + url: https://registry.npmjs.org/ + cache: false + maxage: 20m + max_fails: 32 + timeout: 60s + agent_options: + keepAlive: true + maxSockets: 32 + maxFreeSockets: 8 + +packages: + '@angular/{build,create,cli,pwa,ssr}': + access: $all + publish: $all + + '@angular-devkit/*': + access: $all + publish: $all + + '@ngtools/webpack': + access: $all + publish: $all + + '@schematics/{angular,schematics,update}': + access: $all + publish: $all + + '@*/*': + access: $all + proxy: npmjs + + '**': + access: $all + proxy: npmjs + +log: + type: stdout + format: pretty + level: warn + +# https://github.com/verdaccio/verdaccio/issues/301 +server: + keepAliveTimeout: 0 diff --git a/tests/verdaccio_auth.yaml b/tests/verdaccio_auth.yaml new file mode 100644 index 000000000000..1cb53f5d8b5f --- /dev/null +++ b/tests/verdaccio_auth.yaml @@ -0,0 +1,33 @@ +storage: ./storage +auth: + auth-memory: + users: + testing: + name: testing + password: s3cret +listen: localhost:${HTTPS_PORT} +uplinks: + local: + url: http://localhost:${HTTP_PORT} + cache: false + maxage: 20m + max_fails: 32 + timeout: 60s + agent_options: + keepAlive: true + maxSockets: 32 + maxFreeSockets: 8 + +packages: + '**': + access: $authenticated + proxy: local + +log: + type: stdout + format: pretty + level: warn + +# https://github.com/verdaccio/verdaccio/issues/301 +server: + keepAliveTimeout: 0 diff --git a/third_party/README.md b/third_party/README.md deleted file mode 100644 index b154dd489c2a..000000000000 --- a/third_party/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# third_party vendored sources in Angular CLI - -Note, other third_party directories under subpackages currently exist to support the legacy pre-bazel build system. - -For example, `/packages/angular_devkit/core/third_party` - -## TL;DR: don't copy sources into this repo - -All sources in this repo should be authored from scratch by the committer. -Don't copy sources you've found in any other location. - -For more info, see the longer version of this README: -https://github.com/angular/angular/blob/master/third_party/README.md diff --git a/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/BUILD b/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/BUILD deleted file mode 100644 index bac38c77f52e..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/BUILD +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -package(default_visibility = ["//:__subpackages__"]) - -licenses(["notice"]) # Apache 2.0 - -proto_library( - name = "proto", - srcs = glob(["*.proto"]), - deps = ["//third_party/github.com/bazelbuild/bazel/src/main/protobuf"], -) diff --git a/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto b/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto deleted file mode 100644 index b8556bc9b30f..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto +++ /dev/null @@ -1,700 +0,0 @@ -// Copyright 2016 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package build_event_stream; - -option java_package = "com.google.devtools.build.lib.buildeventstream"; -option java_outer_classname = "BuildEventStreamProtos"; - -// LOCAL MOD: change import path -import "third_party/github.com/bazelbuild/bazel/src/main/protobuf/invocation_policy.proto"; -import "third_party/github.com/bazelbuild/bazel/src/main/protobuf/command_line.proto"; - -// Identifier for a build event. It is deliberately structured to also provide -// information about which build target etc the event is related to. -// -// Events are chained via the event id as follows: each event has an id and a -// set of ids of children events such that apart from the initial event each -// event has an id that is mentioned as child id in an earlier event and a build -// invocation is complete if and only if all direct and indirect children of the -// initial event have been posted. -message BuildEventId { - // Generic identifier for a build event. This is the default type of - // BuildEventId, but should not be used outside testing; nevertheless, - // tools should handle build events with this kind of id gracefully. - message UnknownBuildEventId { - string details = 1; - } - - // Identifier of an event reporting progress. Those events are also used to - // chain in events that come early. - message ProgressId { - // Unique identifier. No assumption should be made about how the ids are - // assigned; the only meaningful operation on this field is test for - // equality. - int32 opaque_count = 1; - } - - // Identifier of an event indicating the beginning of a build; this will - // normally be the first event. - message BuildStartedId { - } - - // Identifier on an event indicating the original commandline received by - // the bazel server. - message UnstructuredCommandLineId { - } - - // Identifier on an event describing the commandline received by Bazel. - message StructuredCommandLineId { - // A title for this command line value, as there may be multiple. - // For example, a single invocation may wish to report both the literal and - // canonical command lines, and this label would be used to differentiate - // between both versions. - string command_line_label = 1; - } - - // Identifier of an event indicating the workspace status. - message WorkspaceStatusId { - } - - // Identifier on an event reporting on the options included in the command - // line, both explicitly and implicitly. - message OptionsParsedId { - } - - // Identifier of an event reporting that an external resource was fetched - // from. - message FetchId { - // The external resource that was fetched from. - string url = 1; - } - - // Identifier of an event indicating that a target pattern has been expanded - // further. - // Messages of this shape are also used to describe parts of a pattern that - // have been skipped for some reason, if the actual expansion was still - // carried out (e.g., if keep_going is set). In this case, the - // pattern_skipped choice in the id field is to be made. - message PatternExpandedId { - repeated string pattern = 1; - } - - // Identifier of an event indicating that a target has been expanded by - // identifying for which configurations it should be build. - message TargetConfiguredId { - string label = 1; - - // If not empty, the id refers to the expansion of the target for a given - // aspect. - string aspect = 2; - } - - // Identifier of an event introducing a named set of files (usually artifacts) - // to be referred to in later messages. - message NamedSetOfFilesId { - // Identifier of the file set; this is an opaque string valid only for the - // particular instance of the event stream. - string id = 1; - } - - // Identifier of an event introducing a configuration. - message ConfigurationId { - // Identifier of the configuration; users of the protocol should not make - // any assumptions about it having any structure, or equality of the - // identifier between different streams. - string id = 1; - } - - // Identifier of an event indicating that a target was built completely; this - // does not include running the test if the target is a test target. - message TargetCompletedId { - string label = 1; - - // The configuration for which the target was built. - ConfigurationId configuration = 3; - - // If not empty, the id refers to the completion of the target for a given - // aspect. - string aspect = 2; - } - - // Identifier of an event reporting that an action was completed (not all - // actions are reported, only the ones that can be considered important; - // this includes all failed actions). - message ActionCompletedId { - string primary_output = 1; - // Optional, the label of the owner of the action, for reference. - string label = 2; - // Optional, the id of the configuration of the action owner. - ConfigurationId configuration = 3; - } - - // Identifier of an event reporting an event associated with an unconfigured - // label. Usually, this indicates a failure due to a missing input file. In - // any case, it will report some form of error (i.e., the payload will be an - // Aborted event); there are no regular events using this identifier. The - // purpose of those events is to serve as the root cause of a failed target. - message UnconfiguredLabelId { - string label = 1; - } - - // Identifier of an event reporting an event associated with a configured - // label, usually a visibility error. In any case, an event with such an - // id will always report some form of error (i.e., the payload will be an - // Aborted event); there are no regular events using this identifier. - message ConfiguredLabelId { - string label = 1; - ConfigurationId configuration = 2; - } - - // Identifier of an event reporting on an individual test run. The label - // identifies the test that is reported about, the remaining fields are - // in such a way as to uniquely identify the action within a build. In fact, - // attempts for the same test, run, shard triple are counted sequentially, - // starting with 1. - message TestResultId { - string label = 1; - ConfigurationId configuration = 5; - int32 run = 2; - int32 shard = 3; - int32 attempt = 4; - } - - // Identifier of an event reporting the summary of a test. - message TestSummaryId { - string label = 1; - ConfigurationId configuration = 2; - } - - // Identifier of the BuildFinished event, indicating the end of a build. - message BuildFinishedId { - } - - // Identifier of an event providing additional logs/statistics after - // completion of the build. - message BuildToolLogsId { - } - - // Identifier of an event providing build metrics after completion - // of the build. - message BuildMetricsId { - } - - oneof id { - UnknownBuildEventId unknown = 1; - ProgressId progress = 2; - BuildStartedId started = 3; - UnstructuredCommandLineId unstructured_command_line = 11; - StructuredCommandLineId structured_command_line = 18; - WorkspaceStatusId workspace_status = 14; - OptionsParsedId options_parsed = 12; - FetchId fetch = 17; - ConfigurationId configuration = 15; - TargetConfiguredId target_configured = 16; - PatternExpandedId pattern = 4; - PatternExpandedId pattern_skipped = 10; - NamedSetOfFilesId named_set = 13; - TargetCompletedId target_completed = 5; - ActionCompletedId action_completed = 6; - UnconfiguredLabelId unconfigured_label = 19; - ConfiguredLabelId configured_label = 21; - TestResultId test_result = 8; - TestSummaryId test_summary = 7; - BuildFinishedId build_finished = 9; - BuildToolLogsId build_tool_logs = 20; - BuildMetricsId build_metrics = 22; - } -} - -// Payload of an event summarizing the progress of the build so far. Those -// events are also used to be parents of events where the more logical parent -// event cannot be posted yet as the needed information is not yet complete. -message Progress { - // The next chunk of stdout that bazel produced since the last progress event - // or the beginning of the build. - string stdout = 1; - - // The next chunk of stderr that bazel produced since the last progress event - // or the beginning of the build. - string stderr = 2; -} - -// Payload of an event indicating that an expected event will not come, as -// the build is aborted prematurely for some reason. -message Aborted { - enum AbortReason { - UNKNOWN = 0; - - // The user requested the build to be aborted (e.g., by hitting Ctl-C). - USER_INTERRUPTED = 1; - - // The user requested that no analysis be performed. - NO_ANALYZE = 8; - - // The user requested that no build be carried out. - NO_BUILD = 9; - - // The build or target was aborted as a timeout was exceeded. - TIME_OUT = 2; - - // The build or target was aborted as some remote environment (e.g., for - // remote execution of actions) was not available in the expected way. - REMOTE_ENVIRONMENT_FAILURE = 3; - - // Failure due to reasons entirely internal to the build tool, e.g., - // running out of memory. - INTERNAL = 4; - - // A Failure occurred in the loading phase of a target. - LOADING_FAILURE = 5; - - // A Failure occurred in the analysis phase of a target. - ANALYSIS_FAILURE = 6; - - // Target build was skipped (e.g. due to incompatible CPU constraints). - SKIPPED = 7; - } - AbortReason reason = 1; - - // A human readable description with more details about there reason, where - // available and useful. - string description = 2; -} - -// Payload of an event indicating the beginning of a new build. Usually, events -// of those type start a new build-event stream. The target pattern requested -// to be build is contained in one of the announced child events; it is an -// invariant that precisely one of the announced child events has a non-empty -// target pattern. -message BuildStarted { - string uuid = 1; - - // Start of the build in ms since the epoch. - // TODO(buchgr): Use google.protobuf.TimeStamp once bazel's protoc supports - // it. - int64 start_time_millis = 2; - - // Version of the build tool that is running. - string build_tool_version = 3; - - // A human-readable description of all the non-default option settings - string options_description = 4; - - // The name of the command that the user invoked. - string command = 5; - - // The working directory from which the build tool was invoked. - string working_directory = 6; - - // The directory of the workspace. - string workspace_directory = 7; - - // The process ID of the Bazel server. - int64 server_pid = 8; -} - -// Payload of an event reporting the command-line of the invocation as -// originally received by the server. Note that this is not the command-line -// given by the user, as the client adds information about the invocation, -// like name and relevant entries of rc-files and client environment variables. -// However, it does contain enough information to reproduce the build -// invocation. -message UnstructuredCommandLine { - repeated string args = 1; -} - -// Payload of an event reporting on the parsed options, grouped in various ways. -message OptionsParsed { - repeated string startup_options = 1; - repeated string explicit_startup_options = 2; - repeated string cmd_line = 3; - repeated string explicit_cmd_line = 4; - blaze.invocation_policy.InvocationPolicy invocation_policy = 5; - string tool_tag = 6; -} - -// Payload of an event indicating that an external resource was fetched. This -// event will only occur in streams where an actual fetch happened, not in ones -// where a cached copy of the entity to be fetched was used. -message Fetch { - bool success = 1; -} - -// Payload of an event reporting the workspace status. Key-value pairs can be -// provided by specifying the workspace_status_command to an executable that -// returns one key-value pair per line of output (key and value separated by a -// space). -message WorkspaceStatus { - message Item { - string key = 1; - string value = 2; - } - repeated Item item = 1; -} - -// Payload of an event reporting details of a given configuration. -message Configuration { - string mnemonic = 1; - string platform_name = 2; - string cpu = 3; - map make_variable = 4; -} - -// Payload of the event indicating the expansion of a target pattern. -// The main information is in the chaining part: the id will contain the -// target pattern that was expanded and the children id will contain the -// target or target pattern it was expanded to. -message PatternExpanded { -} - -// Enumeration type characterizing the size of a test, as specified by the -// test rule. -enum TestSize { - UNKNOWN = 0; - SMALL = 1; - MEDIUM = 2; - LARGE = 3; - ENORMOUS = 4; -} - -// Payload of the event indicating that the configurations for a target have -// been identified. As with pattern expansion the main information is in the -// chaining part: the id will contain the target that was configured and the -// children id will contain the configured targets it was configured to. -message TargetConfigured { - // The kind of target (e.g., e.g. "cc_library rule", "source file", - // "generated file") where the completion is reported. - string target_kind = 1; - - // The size of the test, if the target is a test target. Unset otherwise. - TestSize test_size = 2; - - // List of all tags associated with this target (for all possible - // configurations). - repeated string tag = 3; -} - -message File { - // identifier indicating the nature of the file (e.g., "stdout", "stderr") - string name = 1; - - oneof file { - // A location where the contents of the file can be found. The string is - // encoded according to RFC2396. - string uri = 2; - // The contents of the file, if they are guaranteed to be short. - bytes contents = 3; - } -} - -// Payload of a message to describe a set of files, usually build artifacts, to -// be referred to later by their name. In this way, files that occur identically -// as outputs of several targets have to be named only once. -message NamedSetOfFiles { - // Files that belong to this named set of files. - repeated File files = 1; - - // Other named sets whose members also belong to this set. - repeated BuildEventId.NamedSetOfFilesId file_sets = 2; -} - -// Payload of the event indicating the completion of an action. The main purpose -// of posting those events is to provide details on the root cause for a target -// failing; however, consumers of the build-event protocol must not assume -// that only failed actions are posted. -message ActionExecuted { - bool success = 1; - - // The mnemonic of the action that was executed - string type = 8; - - // The exit code of the action, if it is available. - int32 exit_code = 2; - - // Location where to find the standard output of the action - // (e.g., a file path). - File stdout = 3; - - // Location where to find the standard error of the action - // (e.g., a file path). - File stderr = 4; - - // Deprecated. This field is now present on ActionCompletedId. - string label = 5 [deprecated = true]; - - // Deprecated. This field is now present on ActionCompletedId. - BuildEventId.ConfigurationId configuration = 7 [deprecated = true]; - - // Primary output; only provided for successful actions. - File primary_output = 6; - - // The command-line of the action, if the action is a command. - repeated string command_line = 9; -} - -// Collection of all output files belonging to that output group. -message OutputGroup { - // Ids of fields that have been removed. - reserved 2; - - // Name of the output group - string name = 1; - - // List of file sets that belong to this output group as well. - repeated BuildEventId.NamedSetOfFilesId file_sets = 3; -} - -// Payload of the event indicating the completion of a target. The target is -// specified in the id. If the target failed the root causes are provided as -// children events. -message TargetComplete { - bool success = 1; - - // The kind of target (e.g., e.g. "cc_library rule", "source file", - // "generated file") where the completion is reported. - // Deprecated: use the target_kind field in TargetConfigured instead. - string target_kind = 5 [deprecated = true]; - - // The size of the test, if the target is a test target. Unset otherwise. - // Deprecated: use the test_size field in TargetConfigured instead. - TestSize test_size = 6 [deprecated = true]; - - // The output files are arranged by their output group. If an output file - // is part of multiple output groups, it appears once in each output - // group. - repeated OutputGroup output_group = 2; - - // Temporarily, also report the important outputs directly. This is only to - // allow existing clients help transition to the deduplicated representation; - // new clients should not use it. - repeated File important_output = 4 [deprecated = true]; - - // List of tags associated with this configured target. - repeated string tag = 3; - - // The timeout specified for test actions under this configured target. - int64 test_timeout_seconds = 7; -} - -enum TestStatus { - NO_STATUS = 0; - PASSED = 1; - FLAKY = 2; - TIMEOUT = 3; - FAILED = 4; - INCOMPLETE = 5; - REMOTE_FAILURE = 6; - FAILED_TO_BUILD = 7; - TOOL_HALTED_BEFORE_TESTING = 8; -}; - -// Payload on events reporting about individual test action. -message TestResult { - reserved 1; - - // The status of this test. - TestStatus status = 5; - - // Additional details about the status of the test. This is intended for - // user display and must not be parsed. - string status_details = 9; - - // True, if the reported attempt is taken from the tool's local cache. - bool cached_locally = 4; - - // Time in milliseconds since the epoch at which the test attempt was started. - // Note: for cached test results, this is time can be before the start of the - // build. - int64 test_attempt_start_millis_epoch = 6; - - // Time the test took to run. For locally cached results, this is the time - // the cached invocation took when it was invoked. - int64 test_attempt_duration_millis = 3; - - // Files (logs, test.xml, undeclared outputs, etc) generated by that test - // action. - repeated File test_action_output = 2; - - // Warnings generated by that test action. - repeated string warning = 7; - - // Message providing optional meta data on the execution of the test action, - // if available. - message ExecutionInfo { - // Deprecated, use TargetComplete.test_timeout_seconds instead. - int32 timeout_seconds = 1 [deprecated = true]; - - // Name of the strategy to execute this test action (e.g., "local", - // "remote") - string strategy = 2; - - // True, if the reported attempt was a cache hit in a remote cache. - bool cached_remotely = 6; - - // The exit code of the test action. - int32 exit_code = 7; - - // The hostname of the machine where the test action was executed (in case - // of remote execution), if known. - string hostname = 3; - - // Represents a hierarchical timing breakdown of an activity. - // The top level time should be the total time of the activity. - // Invariant: time_millis >= sum of time_millis of all direct children. - message TimingBreakdown { - repeated TimingBreakdown child = 1; - string name = 2; - int64 time_millis = 3; - } - TimingBreakdown timing_breakdown = 4; - - message ResourceUsage { - string name = 1; - int64 value = 2; - } - repeated ResourceUsage resource_usage = 5; - } - ExecutionInfo execution_info = 8; -} - -// Payload of the event summarizing a test. -// TODO(aehlig): extend event with additional information as soon as we known -// which additional information we need for test summaries. -message TestSummary { - // Wrapper around BlazeTestStatus to support importing that enum to proto3. - // Overall status of test, accumulated over all runs, shards, and attempts. - TestStatus overall_status = 5; - - // Total number of runs - int32 total_run_count = 1; - - // Path to logs of passed runs. - repeated File passed = 3; - - // Path to logs of failed runs; - repeated File failed = 4; - - // Total number of cached test actions - int32 total_num_cached = 6; -} - -// Event indicating the end of a build. -message BuildFinished { - // Exit code of a build. The possible values correspond to the predefined - // codes in bazel's lib.ExitCode class, as well as any custom exit code a - // module might define. The predefined exit codes are subject to change (but - // rarely do) and are not part of the public API. - // - // A build was successful iff ExitCode.code equals 0. - message ExitCode { - // The name of the exit code. - string name = 1; - - // The exit code. - int32 code = 2; - } - - // If the build succeeded or failed. - bool overall_success = 1 [deprecated = true]; - - // The overall status of the build. A build was successful iff - // ExitCode.code equals 0. - ExitCode exit_code = 3; - - // Time in milliseconds since the epoch. - // TODO(buchgr): Use google.protobuf.Timestamp once bazel's protoc supports - // it. - int64 finish_time_millis = 2; -} - -message BuildMetrics { - message ActionSummary { - // The total number of actions created and registered during the build. - // This includes unused actions that were constructed but - // not executed during this build. - int64 actions_created = 1; - - // The total number of actions executed during the build. - // This includes any remote cache hits, but excludes - // local action cache hits. - int64 actions_executed = 2; - } - ActionSummary action_summary = 1; - - message MemoryMetrics { - // Size of the JVM heap post build in bytes. This is only collected if - // --bep_publish_used_heap_size_post_build is set, - // since it forces a full GC. - int64 used_heap_size_post_build = 1; - } - MemoryMetrics memory_metrics = 2; - - message TargetMetrics { - // Number of targets loaded during this build. - int64 targets_loaded = 1; - - // Number of targets configured during this build. This can - // be greater than targets_loaded if the same target is configured - // multiple times. - int64 targets_configured = 2; - } - TargetMetrics target_metrics = 3; - - message PackageMetrics { - // Number of BUILD files (aka packages) loaded during this build. - int64 packages_loaded = 1; - } - PackageMetrics package_metrics = 4; -} - -// Event providing additional statistics/logs after completion of the build. -message BuildToolLogs { - repeated File log = 1; -} - -// Message describing a build event. Events will have an identifier that -// is unique within a given build invocation; they also announce follow-up -// events as children. More details, which are specific to the kind of event -// that is observed, is provided in the payload. More options for the payload -// might be added in the future. -message BuildEvent { - reserved 11, 19; - BuildEventId id = 1; - repeated BuildEventId children = 2; - bool last_message = 20; - oneof payload { - Progress progress = 3; - Aborted aborted = 4; - BuildStarted started = 5; - UnstructuredCommandLine unstructured_command_line = 12; - command_line.CommandLine structured_command_line = 22; - OptionsParsed options_parsed = 13; - WorkspaceStatus workspace_status = 16; - Fetch fetch = 21; - Configuration configuration = 17; - PatternExpanded expanded = 6; - TargetConfigured configured = 18; - ActionExecuted action = 7; - NamedSetOfFiles named_set_of_files = 15; - TargetComplete completed = 8; - TestResult test_result = 10; - TestSummary test_summary = 9; - BuildFinished finished = 14; - BuildToolLogs build_tool_logs = 23; - BuildMetrics build_metrics = 24; - }; -} diff --git a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/BUILD b/third_party/github.com/bazelbuild/bazel/src/main/protobuf/BUILD deleted file mode 100644 index 55e90267ea77..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/BUILD +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -package(default_visibility = ["//:__subpackages__"]) - -licenses(["notice"]) # Apache 2.0 - -proto_library( - name = "protobuf", - srcs = glob(["*.proto"]), -) diff --git a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/command_line.proto b/third_party/github.com/bazelbuild/bazel/src/main/protobuf/command_line.proto deleted file mode 100644 index fd09cd7c0aed..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/command_line.proto +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2017 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; -package command_line; - -// option java_api_version = 2; -option java_package = "com.google.devtools.build.lib.runtime.proto"; - -// LOCAL MOD: change import path -import "third_party/github.com/bazelbuild/bazel/src/main/protobuf/option_filters.proto"; - -// Representation of a Bazel command line. -message CommandLine { - // A title for this command line value, to differentiate it from others. - // In particular, a single invocation may wish to report both the literal and - // canonical command lines, and this label would be used to differentiate - // between both versions. This is a string for flexibility. - string command_line_label = 1; - - // A Bazel command line is made of distinct parts. For example, - // `bazel --nomaster_bazelrc test --nocache_test_results //foo:aTest` - // has the executable "bazel", a startup flag, a command "test", a command - // flag, and a test target. There could be many more flags and targets, or - // none (`bazel info` for example), but the basic structure is there. The - // command line should be broken down into these logical sections here. - repeated CommandLineSection sections = 2; -} - -// A section of the Bazel command line. -message CommandLineSection { - // The name of this section, such as "startup_option" or "command". - string section_label = 1; - - oneof section_type { - // Sections with non-options, such as the list of targets or the command, - // should use simple string chunks. - ChunkList chunk_list = 2; - - // Startup and command options are lists of options and belong here. - OptionList option_list = 3; - } -} - -// Wrapper to allow a list of strings in the "oneof" section_type. -message ChunkList { - repeated string chunk = 1; -} - -// Wrapper to allow a list of options in the "oneof" section_type. -message OptionList { - repeated Option option = 1; -} - -// A single command line option. -// -// This represents the option itself, but does not take into account the type of -// option or how the parser interpreted it. If this option is part of a command -// line that represents the actual input that Bazel received, it would, for -// example, include expansion flags as they are. However, if this option -// represents the canonical form of the command line, with the values as Bazel -// understands them, then the expansion flag, which has no value, would not -// appear, and the flags it expands to would. -message Option { - // How the option looks with the option and its value combined. Depending on - // the purpose of this command line report, this could be the canonical - // form, or the way that the flag was set. - // - // Some examples: this might be `--foo=bar` form, or `--foo bar` with a space; - // for boolean flags, `--nobaz` is accepted on top of `--baz=false` and other - // negating values, or for a positive value, the unqualified `--baz` form - // is also accepted. This could also be a short `-b`, if the flag has an - // abbreviated form. - string combined_form = 1; - - // The canonical name of the option, without the preceding dashes. - string option_name = 2; - - // The value of the flag, or unset for flags that do not take values. - // Especially for boolean flags, this should be in canonical form, the - // combined_form field above gives room for showing the flag as it was set - // if that is preferred. - string option_value = 3; - - // This flag's tagged effects. See OptionEffectTag's java documentation for - // details. - repeated options.OptionEffectTag effect_tags = 4; - - // Metadata about the flag. See OptionMetadataTag's java documentation for - // details. - repeated options.OptionMetadataTag metadata_tags = 5; -} diff --git a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/invocation_policy.proto b/third_party/github.com/bazelbuild/bazel/src/main/protobuf/invocation_policy.proto deleted file mode 100644 index 53572ac12011..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/invocation_policy.proto +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2015 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; -package blaze.invocation_policy; - -// option java_api_version = 2; -option java_package = "com.google.devtools.build.lib.runtime.proto"; - -// The --invocation_policy flag takes a base64-encoded binary-serialized or text -// formatted InvocationPolicy message. -message InvocationPolicy { - // Order matters. - // After expanding policies on expansion flags or flags with implicit - // requirements, only the final policy on a specific flag will be enforced - // onto the user's command line. - repeated FlagPolicy flag_policies = 1; -} - -// A policy for controlling the value of a flag. -message FlagPolicy { - // The name of the flag to enforce this policy on. - // - // Note that this should be the full name of the flag, not the abbreviated - // name of the flag. If the user specifies the abbreviated name of a flag, - // that flag will be matched using its full name. - // - // The "no" prefix will not be parsed, so for boolean flags, use - // the flag's full name and explicitly set it to true or false. - optional string flag_name = 1; - - // If set, this flag policy is applied only if one of the given commands or a - // command that inherits from one of the given commands is being run. For - // instance, if "build" is one of the commands here, then this policy will - // apply to any command that inherits from build, such as info, coverage, or - // test. If empty, this flag policy is applied for all commands. This allows - // the policy setter to add all policies to the proto without having to - // determine which Bazel command the user is actually running. Additionally, - // Bazel allows multiple flags to be defined by the same name, and the - // specific flag definition is determined by the command. - repeated string commands = 2; - - oneof operation { - SetValue set_value = 3; - UseDefault use_default = 4; - DisallowValues disallow_values = 5; - AllowValues allow_values = 6; - } -} - -message SetValue { - // Use this value for the specified flag, overriding any default or user-set - // value (unless append is set to true for repeatable flags). - // - // This field is repeated for repeatable flags. It is an error to set - // multiple values for a flag that is not actually a repeatable flag. - // This requires at least 1 value, if even the empty string. - // - // If the flag allows multiple values, all of its values are replaced with the - // value or values from the policy (i.e., no diffing or merging is performed), - // unless the append field (see below) is set to true. - // - // Note that some flags are tricky. For example, some flags look like boolean - // flags, but are actually Void expansion flags that expand into other flags. - // The Bazel flag parser will accept "--void_flag=false", but because - // the flag is Void, the "=false" is ignored. It can get even trickier, like - // "--novoid_flag" which is also an expansion flag with the type Void whose - // name is explicitly "novoid_flag" and which expands into other flags that - // are the opposite of "--void_flag". For expansion flags, it's best to - // explicitly override the flags they expand into. - // - // Other flags may be differently tricky: A flag could have a converter that - // converts some string to a list of values, but that flag may not itself have - // allowMultiple set to true. - // - // An example is "--test_tag_filters": this flag sets its converter to - // CommaSeparatedOptionListConverter, but does not set allowMultiple to true. - // So "--test_tag_filters=foo,bar" results in ["foo", "bar"], however - // "--test_tag_filters=foo --test_tag_filters=bar" results in just ["bar"] - // since the 2nd value overrides the 1st. - // - // Similarly, "--test_tag_filters=foo,bar --test_tag_filters=baz,qux" results - // in ["baz", "qux"]. For flags like these, the policy should specify - // "foo,bar" instead of separately specifying "foo" and "bar" so that the - // converter is appropriately invoked. - // - // Note that the opposite is not necessarily - // true: for a flag that specifies allowMultiple=true, "--flag=foo,bar" - // may fail to parse or result in an unexpected value. - repeated string flag_value = 1; - - // Whether to allow this policy to be overridden by user-specified values. - // When set, if the user specified a value for this flag, use the value - // from the user, otherwise use the value specified in this policy. - optional bool overridable = 2; - - // If true, and if the flag named in the policy is a repeatable flag, then - // the values listed in flag_value do not replace all the user-set or default - // values of the flag, but instead append to them. If the flag is not - // repeatable, then this has no effect. - optional bool append = 3; -} - -message UseDefault { - // Use the default value of the flag, as defined by Bazel (or equivalently, do - // not allow the user to set this flag). - // - // Note on implementation: UseDefault sets the default by clearing the flag, - // so that when the value is requested and no flag is found, the flag parser - // returns the default. This is mostly relevant for expansion flags: it will - // erase user values in *all* flags that the expansion flag expands to. Only - // use this on expansion flags if this is acceptable behavior. Since the last - // policy wins, later policies on this same flag will still remove the - // expanded UseDefault, so there is a way around, but it's really best not to - // use this on expansion flags at all. -} - -message DisallowValues { - // Obsolete new_default_value field. - reserved 2; - - // It is an error for the user to use any of these values (that is, the Bazel - // command will fail), unless new_value or use_default is set. - // - // For repeatable flags, if any one of the values in the flag matches a value - // in the list of disallowed values, an error is thrown. - // - // Care must be taken for flags with complicated converters. For example, - // it's possible for a repeated flag to be of type List>, so that - // "--foo=a,b --foo=c,d" results in foo=[["a","b"], ["c", "d"]]. In this case, - // it is not possible to disallow just "b", nor will ["b", "a"] match, nor - // will ["b", "c"] (but ["a", "b"] will still match). - repeated string disallowed_values = 1; - - oneof replacement_value { - // If set and if the value of the flag is disallowed (including the default - // value of the flag if the user doesn't specify a value), use this value as - // the value of the flag instead of raising an error. This does not apply to - // repeatable flags and is ignored if the flag is a repeatable flag. - string new_value = 3; - - // If set and if the value of the flag is disallowed, use the default value - // of the flag instead of raising an error. Unlike new_value, this works for - // repeatable flags, but note that the default value for repeatable flags is - // always empty. - // - // Note that it is an error to disallow the default value of the flag and - // to set use_default, unless the flag is a repeatable flag where the - // default value is always the empty list. - UseDefault use_default = 4; - } -} - -message AllowValues { - // Obsolete new_default_value field. - reserved 2; - - // It is an error for the user to use any value not in this list, unless - // new_value or use_default is set. - repeated string allowed_values = 1; - - oneof replacement_value { - // If set and if the value of the flag is disallowed (including the default - // value of the flag if the user doesn't specify a value), use this value as - // the value of the flag instead of raising an error. This does not apply to - // repeatable flags and is ignored if the flag is a repeatable flag. - string new_value = 3; - - // If set and if the value of the flag is disallowed, use the default value - // of the flag instead of raising an error. Unlike new_value, this works for - // repeatable flags, but note that the default value for repeatable flags is - // always empty. - // - // Note that it is an error to disallow the default value of the flag and - // to set use_default, unless the flag is a repeatable flag where the - // default value is always the empty list. - UseDefault use_default = 4; - } -} diff --git a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/option_filters.proto b/third_party/github.com/bazelbuild/bazel/src/main/protobuf/option_filters.proto deleted file mode 100644 index 782620d05371..000000000000 --- a/third_party/github.com/bazelbuild/bazel/src/main/protobuf/option_filters.proto +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2017 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -syntax = "proto3"; -package options; - -// option java_api_version = 2; -option java_package = "com.google.devtools.common.options.proto"; - -// IMPORTANT NOTE: These two enums must be kept in sync with their Java -// equivalents in src/main/java/com/google/devtools/common/options. -// Changing this proto has specific compatibility requirements, please see the -// Java documentation for details. - -// Docs in java enum. -enum OptionEffectTag { - // This option's effect or intent is unknown. - UNKNOWN = 0; - - // This flag has literally no effect. - NO_OP = 1; - - LOSES_INCREMENTAL_STATE = 2; - CHANGES_INPUTS = 3; - AFFECTS_OUTPUTS = 4; - BUILD_FILE_SEMANTICS = 5; - BAZEL_INTERNAL_CONFIGURATION = 6; - LOADING_AND_ANALYSIS = 7; - EXECUTION = 8; - HOST_MACHINE_RESOURCE_OPTIMIZATIONS = 9; - EAGERNESS_TO_EXIT = 10; - BAZEL_MONITORING = 11; - TERMINAL_OUTPUT = 12; - ACTION_COMMAND_LINES = 13; - TEST_RUNNER = 14; -} - -// Docs in java enum. -enum OptionMetadataTag { - EXPERIMENTAL = 0; - INCOMPATIBLE_CHANGE = 1; - DEPRECATED = 2; - HIDDEN = 3; - INTERNAL = 4; - TRIGGERED_BY_ALL_INCOMPATIBLE_CHANGES = 5; -} diff --git a/tools/BUILD b/tools/BUILD deleted file mode 100644 index 56865b097dbc..000000000000 --- a/tools/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -# @external_begin -package(default_visibility = ["//visibility:public"]) - -load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") - -nodejs_binary( - name = "quicktype_runner", - data = [ - "quicktype_runner.js", - "@npm//quicktype-core", - ], - entry_point = "quicktype_runner.js", - install_source_map_support = False, -) - -platform( - name = "rbe_ubuntu1604-angular", - parents = ["@rbe_ubuntu1604_angular//config:platform"], - remote_execution_properties = """ - {PARENT_REMOTE_EXECUTION_PROPERTIES} - properties: { - name: "dockerAddCapabilities" - value: "SYS_ADMIN" - } - """, -) - -# @external_end diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel new file mode 100644 index 000000000000..4804a9ee59a6 --- /dev/null +++ b/tools/BUILD.bazel @@ -0,0 +1,32 @@ +load("//tools:defaults.bzl", "js_binary") + +package(default_visibility = ["//visibility:public"]) + +platform( + name = "windows_x64", + constraint_values = [ + "@platforms//os:windows", + "@platforms//cpu:x86_64", + ], +) + +exports_files([ + "package_json_release_filter.jq", +]) + +js_binary( + name = "ng_cli_schema", + data = [ + "ng_cli_schema_generator.js", + ], + entry_point = "ng_cli_schema_generator.js", +) + +js_binary( + name = "quicktype_runner", + data = [ + "quicktype_runner.js", + "//:node_modules/quicktype-core", + ], + entry_point = "quicktype_runner.js", +) diff --git a/tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.css b/tools/bazel/BUILD.bazel similarity index 100% rename from tests/legacy-cli/e2e/assets/1.0-project/src/app/app.component.css rename to tools/bazel/BUILD.bazel diff --git a/tools/bazel/npm_package.bzl b/tools/bazel/npm_package.bzl new file mode 100644 index 000000000000..3e2843f37946 --- /dev/null +++ b/tools/bazel/npm_package.bzl @@ -0,0 +1,125 @@ +load("@aspect_rules_js//npm:defs.bzl", _npm_package = "npm_package") +load("@bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin") +load("@bazel_lib//lib:expand_template.bzl", "expand_template") +load("@bazel_lib//lib:utils.bzl", "to_label") +load("@jq.bzl//jq:jq.bzl", "jq") +load("@rules_pkg//:pkg.bzl", "pkg_tar") +load("//tools:link_package_json_to_tarballs.bzl", "link_package_json_to_tarballs") +load("//tools:snapshot_repo_filter.bzl", "SNAPSHOT_REPO_JQ_FILTER") +load("//tools:substitutions.bzl", "substitutions") + +def npm_package( + name, + deps = [], + visibility = None, + pkg_deps = [], + stamp_files = [], + pkg_json = "package.json", + extra_substitutions = {}, + replace_prefixes = {}, + **kwargs): + if name != "pkg": + fail("Expected npm_package to be named `pkg`. " + + "This is needed for pnpm workspace integration.") + + # Merge package.json with root package.json and perform various substitutions to + # prepare it for release. For jq docs, see https://stedolan.github.io/jq/manual/. + jq( + name = "basic_substitutions", + # Note: this jq filter relies on the order of the inputs + # buildifier: do not sort + srcs = ["//:package.json", pkg_json], + filter_file = "//tools:package_json_release_filter.jq", + args = ["--slurp"], + out = "substituted/package.json", + ) + + # Copy package.json files to bazel-out so we can use their bazel-out paths to determine + # the corresponding package npm package tgz path for substitutions. + copy_to_bin( + name = "package_json_copy", + srcs = [pkg_json], + ) + pkg_deps_copies = [] + for pkg_dep in pkg_deps: + pkg_label = to_label(pkg_dep) + if pkg_label.name != "package.json": + fail("ERROR: only package.json files allowed in pkg_deps of pkg_npm macro") + pkg_deps_copies.append("@@%s//%s:package_json_copy" % (pkg_label.repo_name, pkg_label.package)) + + # Substitute dependencies on other packages in this repo with tarballs. + link_package_json_to_tarballs( + name = "tar_substitutions", + src = "substituted/package.json", + pkg_deps = [":package_json_copy"] + pkg_deps_copies, + out = "substituted_with_tars/package.json", + ) + + # Substitute dependencies on other packages in this repo with snapshot repos. + jq( + name = "snapshot_repo_substitutions", + srcs = ["substituted/package.json"], + filter = SNAPSHOT_REPO_JQ_FILTER, + out = "substituted_with_snapshot_repos/package.json", + ) + + nostamp_subs = dict(substitutions["nostamp"], **extra_substitutions) + stamp_subs = dict(substitutions["stamp"], **extra_substitutions) + + expand_template( + name = "final_package_json", + template = select({ + # Do local tar substitution if config_setting is true. + "//:package_json_use_tar_deps": "substituted_with_tars/package.json", + # Do snapshot repo substitution if config_setting is true. + "//:package_json_use_snapshot_repo_deps": "substituted_with_snapshot_repos/package.json", + "//conditions:default": "substituted/package.json", + }), + out = "substituted_final/package.json", + substitutions = nostamp_subs, + stamp_substitutions = stamp_subs, + ) + + stamp_targets = [] + for f in stamp_files: + expand_template( + name = "stamp_file_%s" % f, + template = f, + out = "substituted/%s" % f, + substitutions = nostamp_subs, + stamp_substitutions = stamp_subs, + ) + + stamp_targets.append("stamp_file_%s" % f) + + _npm_package( + name = "npm_package", + visibility = visibility, + # Note: Order matters here! Last file takes precedence after replaced prefixes. + srcs = deps + stamp_targets + [":final_package_json"], + replace_prefixes = dict({ + "substituted_final/": "", + "substituted_with_tars/": "", + "substituted_with_snapshot_repos/": "", + "substituted/": "", + }, **replace_prefixes), + allow_overwrites = True, + **kwargs + ) + + # Note: For now, in hybrid mode with RNJS and RJS, we ensure + # both `:pkg` and `:npm_package` work. + native.alias( + name = "pkg", + actual = ":npm_package", + ) + + if pkg_json: + pkg_tar( + name = "npm_package_archive", + srcs = [":pkg"], + extension = "tgz", + # should not be built unless it is a dependency of another rule + tags = ["manual"], + visibility = visibility, + ) diff --git a/tools/build_event_protocol/BUILD b/tools/build_event_protocol/BUILD deleted file mode 100644 index e0984ab762a9..000000000000 --- a/tools/build_event_protocol/BUILD +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license -load("@npm_bazel_labs//:index.bzl", "ts_proto_library") -load("@npm_bazel_typescript//:index.bzl", "ts_library") -load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary") - -ts_proto_library( - name = "build_event_stream", - deps = ["//third_party/github.com/bazelbuild/bazel/src/main/java/com/google/devtools/build/lib/buildeventstream/proto"], -) - -ts_library( - name = "parse_bep", - srcs = ["parse_bep.ts"], - deps = [ - ":build_event_stream", - "@npm//@types/node", - "@npm//rxjs", - ], -) - -nodejs_binary( - name = "parse", - data = [":parse_bep"], - entry_point = "angular_devkit/tools/build_event_protocol/parse_bep", -) diff --git a/tools/build_event_protocol/README.md b/tools/build_event_protocol/README.md deleted file mode 100644 index 3eaf87961b67..000000000000 --- a/tools/build_event_protocol/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# build_event_protocol - -This protocol is used to make streaming build results available for machines to -read and process. - -See https://docs.bazel.build/versions/master/build-event-protocol.html - -This directory contains an example program that parses a streaming JSON file -containing build events. It's useful for manually testing a program that emits -the build event protocol. - -## Try it - -First build the tool: - -```sh -$ bazel build //tools/build_event_protocol:parse -``` - -Then produce a build event json file: - -$ bazel test //... --build_event_json_file=bep.json - -as soon as that process has started, you should be able to run in another window - -$ bazel-bin/tools/build_event_protocol/parse bep.json diff --git a/tools/build_event_protocol/parse_bep.ts b/tools/build_event_protocol/parse_bep.ts deleted file mode 100644 index 4884318406ca..000000000000 --- a/tools/build_event_protocol/parse_bep.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -/** - * @fileoverview simple program to read the build event protocol and convert to - * UI quasi-events. - * - * See the README.md in this directory for usage - */ - -/// -import * as fs from 'fs'; -import { Observable, Subject } from 'rxjs'; -import { filter } from 'rxjs/operators'; -import { build_event_stream as bes } from './build_event_stream'; - -function updateUi(s: string, ...more: Array<{}>) { - console.error('-->', s, ...more); -} - -// typeof bes.BuildEventId.id -type payloadType = 'unknown'|'progress'|'started'|'unstructuredCommandLine'| - 'structuredCommandLine'|'workspaceStatus'|'optionsParsed'|'fetch'| - 'configuration'|'targetConfigured'|'pattern'|'patternSkipped'|'namedSet'| - 'targetCompleted'|'actionCompleted'|'unconfiguredLabel'|'configuredLabel'| - 'testResult'|'testSummary'|'buildFinished'|'buildToolLogs'|'buildMetrics'; - -function filterType(s: payloadType) { - return filter((evt: bes.BuildEvent) => { - if (!evt.id) { - throw new Error(`expected BuildEvent to contain id - ${JSON.stringify(evt)}`); - } - return Object.keys(evt.id)[0] === s; - }); -} - -async function main(argv: string[]): Promise<0|1> { - const s = new Subject(); - const o: Observable = s.asObservable(); - o.pipe(filterType('testSummary')).subscribe({ - next: (evt: bes.BuildEvent) => { - if (!evt.id || !evt.id.testSummary || !evt.testSummary) { - throw new Error( - `expected BuildEvent to contain id, testSummary, id.testSummary - ${JSON.stringify(evt)}`); - } - updateUi('Test result', { - label: evt.id.testSummary.label, - overallStatus: evt.testSummary.overallStatus, - }); - } - }); - - o.pipe(filterType('buildFinished')).subscribe({ - next: (evt: bes.BuildEvent) => { - if (!evt.finished || !evt.finished.exitCode) { - throw new Error( - `expected BuildEvent to contain finished, finished.exitCode - ${JSON.stringify(evt)}`); - } - const exitName = evt.finished.exitCode.name; - switch (exitName) { - case 'SUCCESS': - updateUi('Thumbs up'); - break; - case 'TESTS_FAILED': - updateUi('Some tests failed'); - break; - case 'INTERRUPTED': - updateUi('Cancelled'); - break; - case 'PARSING_FAILURE': - updateUi('Error in build configuration file, report to expert', { - someDebugThatsUsefulToTheExpert: 'a-file-path', - }); - break; - default: - throw new Error(`Unhandled exitName ${exitName}`); - } - }, - error: (e) => console.error('Unrecoverable error ', e) - }); - - // Push values into the subject - // TODO: should be streaming from file - // const stream = fs.createReadStream(argv[0]); - // stream.on('data') - // stream.on('end) - // etc. - const content = fs.readFileSync(argv[0], {'encoding': 'utf-8'}); - content.split(/[\r\n]+/).filter(l => !!l).forEach( - evt => s.next(JSON.parse(evt))); - s.complete(); - - await o.toPromise(); - return 0; -} - - -if (require.main === module) { - // Allow this program to run under bazel run - const wd = process.env['BUILD_WORKING_DIRECTORY']; - if (wd) { - process.chdir(wd); - } - - main(process.argv.slice(2)) - .then(exitCode => process.exitCode = exitCode, e => { - throw new Error(e); - }); -} diff --git a/tools/defaults.bzl b/tools/defaults.bzl new file mode 100644 index 000000000000..20153614ac80 --- /dev/null +++ b/tools/defaults.bzl @@ -0,0 +1,98 @@ +load("@aspect_rules_jasmine//jasmine:defs.bzl", _jasmine_test = "jasmine_test") +load("@aspect_rules_js//js:defs.bzl", _js_binary = "js_binary") +load("@bazel_lib//lib:copy_to_bin.bzl", _copy_to_bin = "copy_to_bin") +load("@devinfra//bazel/ts_project:index.bzl", "strict_deps_test") +load("@rules_angular//src/ng_package:index.bzl", _ng_package = "ng_package") +load("@rules_angular//src/ts_project:index.bzl", _ts_project = "ts_project") +load("//tools:substitutions.bzl", "substitutions") +load("//tools/bazel:npm_package.bzl", _npm_package = "npm_package") + +def ts_project( + name, + deps = [], + tsconfig = None, + testonly = False, + source_map = True, + visibility = None, + **kwargs): + if tsconfig == None: + tsconfig = "//:test-tsconfig" if testonly else "//:build-tsconfig" + + package_json = kwargs.pop("package_json", None) + if not package_json and native.glob(["package.json"], allow_empty = True): + package_json = "package.json" + + _ts_project( + name = name, + testonly = testonly, + declaration = True, + source_map = source_map, + tsconfig = tsconfig, + visibility = visibility, + deps = deps, + **kwargs + ) + + strict_deps_test( + name = "%s_strict_deps_test" % name, + srcs = kwargs.get("srcs", []), + data = kwargs.get("data", []), + package_json = package_json, + tsconfig = tsconfig, + deps = deps, + ) + +def npm_package(**kwargs): + _npm_package(**kwargs) + +def copy_to_bin(**kwargs): + _copy_to_bin(**kwargs) + +def js_binary(**kwargs): + _js_binary(**kwargs) + +def ng_package(deps = [], extra_substitutions = {}, **kwargs): + nostamp_subs = dict(substitutions["nostamp"], **extra_substitutions) + stamp_subs = dict(substitutions["stamp"], **extra_substitutions) + + _ng_package( + deps = deps, + license = "//:LICENSE", + substitutions = select({ + "//:stamp": stamp_subs, + "//conditions:default": nostamp_subs, + }), + **kwargs + ) + +def jasmine_test(data = [], args = [], **kwargs): + # Create relative path to root, from current package dir. Necessary as + # we change the `chdir` below to the package directory. + relative_to_root = "/".join([".."] * len(native.package_name().split("/"))) + + # Chromium browser toolchain + env = kwargs.pop("env", {}) + env.update({ + "CHROME_BIN": "$(CHROME-HEADLESS-SHELL)", + "CHROME_PATH": "$(CHROME-HEADLESS-SHELL)", + "CHROMEDRIVER_BIN": "$(CHROMEDRIVER)", + }) + toolchains = kwargs.pop("toolchains", []) + toolchains = toolchains + ["@rules_browsers//browsers/chromium:toolchain_alias"] + data = data + ["@rules_browsers//browsers/chromium"] + + _jasmine_test( + node_modules = "//:node_modules", + chdir = native.package_name(), + env = env, + toolchains = toolchains, + args = [ + "--require=%s/node_modules/source-map-support/register.js" % relative_to_root, + # Escape so that the `js_binary` launcher triggers Bash expansion. + "'**/*+(.|_)spec.js'", + "'**/*+(.|_)spec.mjs'", + "'**/*+(.|_)spec.cjs'", + ] + args, + data = data + ["//:node_modules/source-map-support"], + **kwargs + ) diff --git a/tools/link_package_json_to_tarballs.bzl b/tools/link_package_json_to_tarballs.bzl new file mode 100644 index 000000000000..4a31cd194bf7 --- /dev/null +++ b/tools/link_package_json_to_tarballs.bzl @@ -0,0 +1,87 @@ +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license +load("@bazel_lib//lib:utils.bzl", "to_label") +load("@jq.bzl//jq:jq.bzl", "jq") + +def link_package_json_to_tarballs(name, src, pkg_deps, out): + """Substitute tar paths into a package.json file for the packages it depends on. + + src and pkg_deps must be labels in the bazel-out tree for the derived path to the npm_package_archive.tgz to be correct. + + Args: + name: Name of the rule + src: package.json file to perform substitions on + pkg_deps: package.json files of dependencies to substitute + out: Output package.json file + """ + + src_pkg = to_label(src).package + + # Generate partial jq filters for each dependent package that, when run + # against a package.json file, can replace its dependency with a tar path. + filter_files = [] + for i, pkg_dep in enumerate(pkg_deps): + pkg_dep_name = "%s_%s.name" % (name, i) + pkg_dep_filter = "%s_%s.filter" % (name, i) + jq( + name = "%s_%s_name" % (name, i), + srcs = [pkg_dep], + filter = ".name", + out = pkg_dep_name, + ) + + srcs = [ + pkg_dep_name, + pkg_dep, + ] + + # Add dependent tars as srcs to include them in the dependency graph, except + # for the tar for this package as that would create a circular dependency. + pkg_label = to_label(pkg_dep) + if pkg_label.package != src_pkg: + pkg_tar = "@@%s//%s:npm_package_archive.tgz" % (pkg_label.repo_name, pkg_label.package) + srcs.append(pkg_tar) + + # Deriving the absolute path to the tar in the execroot requries different + # commands depending on whether or not the action is sandboxed. + abs_path_sandbox = "readlink $(execpath {pkg_dep})".format(pkg_dep = pkg_dep) + abs_path_nosandbox = "(cd $$(dirname $(execpath {pkg_dep})) && pwd)".format(pkg_dep = pkg_dep) + + native.genrule( + name = "%s_%s_filter" % (name, i), + srcs = srcs, + cmd = """ + TAR=$$(dirname $$({abs_path_sandbox} || {abs_path_nosandbox}))/npm_package_archive.tgz + PKGNAME=$$(cat $(execpath {pkg_name})) + if [[ "$$TAR" != *bazel-out* ]]; then + echo "ERROR: package.json passed to substitute_tar_deps must be in the output tree. You can use copy_to_bin to copy a source file to the output tree." + exit 1 + fi + echo "(..|objects|select(has($${{PKGNAME}})))[$${{PKGNAME}}] |= \\"file:$${{TAR}}\\"" > $@ + """.format( + pkg_name = pkg_dep_name, + abs_path_sandbox = abs_path_sandbox, + abs_path_nosandbox = abs_path_nosandbox, + ), + outs = [pkg_dep_filter], + ) + filter_files.append(pkg_dep_filter) + + # Combine all of the filter files into a single filter by joining with | + filter = "%s.filter" % name + native.genrule( + name = "%s_filter" % name, + srcs = filter_files, + cmd = "cat $(SRCS) | sed '$$!s#$$# |#' > $@", + outs = [filter], + ) + + # Generate final package.json with tar substitutions using the above filter + jq( + name = name, + srcs = [src], + filter_file = filter, + out = out, + ) diff --git a/tools/ng_cli_schema_generator.bzl b/tools/ng_cli_schema_generator.bzl new file mode 100644 index 000000000000..86d9552dd70c --- /dev/null +++ b/tools/ng_cli_schema_generator.bzl @@ -0,0 +1,13 @@ +load("@aspect_rules_js//js:defs.bzl", "js_run_binary") + +def cli_json_schema(name, src, out, data = []): + js_run_binary( + name = name, + outs = [out], + tags = ["schema"], + srcs = [src] + data, + tool = "//tools:ng_cli_schema", + progress_message = "Generating CLI interface from %s" % src, + mnemonic = "NgCliJsonSchema", + args = ["$(rootpath %s)" % src, "$(rootpath %s)" % out], + ) diff --git a/tools/ng_cli_schema_generator.js b/tools/ng_cli_schema_generator.js new file mode 100644 index 000000000000..88ea5531c41c --- /dev/null +++ b/tools/ng_cli_schema_generator.js @@ -0,0 +1,109 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use 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 { readFileSync, writeFileSync, mkdirSync } = require('fs'); +const { resolve, dirname } = require('path'); + +/** + * Generator the Angular CLI workspace schema file. + */ +function generate(inPath, outPath) { + // While on paper we could use quicktype for this. + // Quicktype doesn't handle `patternProperties` and `oneOf` that well. + + const jsonSchema = readFileSync(inPath, 'utf8'); + const nestedDefinitions = {}; + const schemaParsed = JSON.parse(jsonSchema, (key, value) => { + if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) { + // Resolve $ref and camelize key + const definitionKey = value + .replace(/(\.json|src)/g, '') + .split(/\\|\/|_|-|\./) + .filter((p) => !!p) + .map((s) => s.charAt(0).toUpperCase() + s.slice(1)) + .join(''); + + const nestedSchemaPath = resolve(dirname(inPath), value); + const nestedSchema = readFileSync(nestedSchemaPath, 'utf8'); + const nestedSchemaJson = JSON.parse(nestedSchema, (key, value) => { + switch (key) { + case '$ref': + if (value.startsWith('#/definitions/')) { + return value.replace('#/definitions/', `#/definitions/${definitionKey}/definitions/`); + } else { + throw new Error(`Error while resolving $ref ${value} in ${nestedSchemaPath}.`); + } + case '$id': + case 'id': + case '$schema': + case 'required': + case 'x-prompt': + case 'x-user-analytics': + return undefined; + default: + return value; + } + }); + + nestedDefinitions[definitionKey] = nestedSchemaJson; + + return `#/definitions/${definitionKey}`; + } + + return key === '' + ? { + ...value, + definitions: { + ...value.definitions, + ...nestedDefinitions, + }, + } + : value; + }); + + const buildWorkspaceDirectory = process.env['BUILD_WORKSPACE_DIRECTORY'] || '.'; + outPath = resolve(buildWorkspaceDirectory, outPath); + + mkdirSync(dirname(outPath), { recursive: true }); + writeFileSync( + outPath, + JSON.stringify( + schemaParsed, + (key, value) => { + if (key === 'x-deprecated') { + // Needed for IDEs, and will be replaced to 'deprecated' later on. This must be a boolean. + // https://json-schema.org/draft/2020-12/json-schema-validation.html#name-deprecated + return !!value; + } + + return value; + }, + 2, + ).replace(/"x-deprecated"/g, '"deprecated"'), + ); +} + +if (require.main === module) { + const argv = process.argv.slice(2); + if (argv.length !== 2) { + console.error('Must include 2 arguments.'); + process.exit(1); + } + + const [inPath, outPath] = argv; + + try { + generate(inPath, outPath); + } catch (error) { + console.error('An error happened:'); + console.error(error); + process.exit(127); + } +} + +exports.generate = generate; diff --git a/tools/package_json_release_filter.jq b/tools/package_json_release_filter.jq new file mode 100644 index 000000000000..4e7c3c639c67 --- /dev/null +++ b/tools/package_json_release_filter.jq @@ -0,0 +1,37 @@ +# Copyright Google LLC. All Rights Reserved. +# +# Use 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 filter combines a subproject package.json with the root package.json +# and performs substitutions to prepare it for release. It should be called +# with the --slurp argument and be passed the root pacakge.json followed by +# the subproject package.json. +# +# See jq docs for filter syntax: https://stedolan.github.io/jq/manual/. + +.[0] as $root +| .[1] as $proj + +# Get the fields from root package.json that should override the project +# package.json, i.e., every field except the following +| ($root + | del(.bin, .description, .dependencies, .name, .main, .peerDependencies, .optionalDependencies, .typings, .version, .private, .workspaces, .resolutions, .scripts, .["ng-update"], .pnpm, .dependenciesMeta, .packageManager) +) as $root_overrides + +# Use the project package.json as a base and override other fields from root +| $proj + $root_overrides + +# Combine keywords from both +| .keywords = ($root.keywords + $proj.keywords | unique) + +# Remove devDependencies +| del(.devDependencies) + +# Add engines; versions substituted via pkg_npm ++ {"engines": {"node": "0.0.0-ENGINES-NODE", "npm": "0.0.0-ENGINES-NPM", "yarn": "0.0.0-ENGINES-YARN"}} + +# Remove all `workspace:` pnpm prefixes. Afterwards we can conveniently rely on +# substitutions from the stamp values. Note that we are doing it this way because +# substitutions can apply to multiple files, and `workspace:` can't be reliably replaced. +| walk(if type == "string" and startswith("workspace:") then sub("workspace:"; "") else . end) diff --git a/tools/quicktype_runner.js b/tools/quicktype_runner.js index d2e37b6fe48d..4fb99a56874e 100644 --- a/tools/quicktype_runner.js +++ b/tools/quicktype_runner.js @@ -1,10 +1,11 @@ /** * @license - * Copyright Google Inc. All Rights Reserved. + * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ + const fs = require('fs'); const path = require('path'); const { @@ -35,9 +36,6 @@ const header = ` // THIS FILE IS AUTOMATICALLY GENERATED. TO UPDATE THIS FILE YOU NEED TO CHANGE THE // CORRESPONDING JSON SCHEMA FILE, THEN RUN devkit-admin build (or bazel build ...). -// tslint:disable:no-global-tslint-disable -// tslint:disable - `; // Footer to add to all files. @@ -54,7 +52,7 @@ class FetchingJSONSchemaStore extends JSONSchemaStore { } async fetch(address) { - const URL = require("url"); + const URL = require('url'); const url = URL.parse(address); let content = null; if (url.protocol === 'ng-cli:') { @@ -62,7 +60,6 @@ class FetchingJSONSchemaStore extends JSONSchemaStore { content = fs.readFileSync(filePath, 'utf-8').trim(); } else if (url.hostname) { try { - const fetch = require("node-fetch"); const response = await fetch(address); content = response.text(); } catch (e) { @@ -89,15 +86,14 @@ class FetchingJSONSchemaStore extends JSONSchemaStore { content = appendDeprecatedDescription(content); - return parseJSON(content, "JSON Schema", address); + return parseJSON(content, 'JSON Schema', address); } } - /** * Create the TS file from the schema, and overwrite the outPath (or log). - * @param {string} inPath - * @param {string} outPath + * @param {string} inPath + * @param {string} outPath */ async function main(inPath, outPath) { const content = await generate(inPath); @@ -112,7 +108,6 @@ async function main(inPath, outPath) { fs.writeFileSync(outPath, content, 'utf-8'); } - async function generate(inPath) { // Best description of how to use the API was found at // https://blog.quicktype.io/customizing-quicktype/ @@ -131,9 +126,12 @@ async function generate(inPath) { inputData, alphabetizeProperties: true, rendererOptions: { - 'just-types': 'true', - 'explicit-unions': 'true', + 'prefer-types': true, + 'just-types': true, + 'prefer-unions': false, + 'explicit-unions': true, 'acronym-style': 'camel', + 'prefer-unknown': false, }, }); @@ -146,6 +144,14 @@ async function generate(inPath) { */ function appendDeprecatedDescription(schema) { const content = JSON.parse(schema); + const rootDeprecated = content['x-deprecated'] ?? content['deprecated']; + if (rootDeprecated) { + content.description = + (content.description ? content.description + '\n' : '') + + '@deprecated' + + (typeof rootDeprecated === 'string' ? ` ${rootDeprecated}` : ''); + } + const props = content.properties; for (const key in props) { @@ -171,7 +177,7 @@ if (require.main === module) { main(argv[0], argv[1]) .then(() => process.exit(0)) - .catch(err => { + .catch((err) => { console.error('An error happened:'); console.error(err); process.exit(127); diff --git a/tools/rebase-pr.js b/tools/rebase-pr.js deleted file mode 100644 index e74b6156d9c0..000000000000 --- a/tools/rebase-pr.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - - // tslint:disable:no-console -// ** IMPORTANT ** -// This script cannot use external dependencies because it needs to run before they are installed. - -const util = require('util'); -const https = require('https'); -const child_process = require('child_process'); -const exec = util.promisify(child_process.exec); - -function determineTargetBranch(repository, prNumber) { - const pullsUrl = `https://api.github.com/repos/${repository}/pulls/${prNumber}`; - // GitHub requires a user agent: https://developer.github.com/v3/#user-agent-required - const options = { headers: { 'User-Agent': repository } }; - - return new Promise((resolve, reject) => { - https.get(pullsUrl, options, (res) => { - const { statusCode } = res; - const contentType = res.headers['content-type']; - - let error; - if (statusCode !== 200) { - error = new Error(`Request Failed.\nStatus Code: ${statusCode}.\nResponse: ${res}.\n' +`); - } else if (!/^application\/json/.test(contentType)) { - error = new Error('Invalid content-type.\n' + - `Expected application/json but received ${contentType}`); - } - if (error) { - reject(error); - res.resume(); - return; - } - - res.setEncoding('utf8'); - let rawData = ''; - res.on('data', (chunk) => { rawData += chunk; }); - res.on('end', () => { - try { - const parsedData = JSON.parse(rawData); - resolve(parsedData['base']['ref']); - } catch (e) { - reject(e); - } - }); - }).on('error', (e) => { - reject(e); - }); - }); -} - -if (process.argv.length != 4) { - console.error(`This script requires the GitHub repository and PR number as arguments.`); - console.error(`Example: node scripts/rebase-pr.js angular/angular 123`); - process.exitCode = 1; - return; -} - -const repository = process.argv[2]; -const prNumber = process.argv[3]; -let targetBranch; - - -return Promise.resolve() - .then(() => { - console.log(`Determining target branch for PR ${prNumber} on ${repository}.`); - return determineTargetBranch(repository, prNumber); - }) - .then(target => { - targetBranch = target; - console.log(`Target branch is ${targetBranch}.`); - }) - .then(() => { - console.log(`Fetching ${targetBranch} from origin.`); - return exec(`git fetch origin ${targetBranch}`); - }) - .then(target => { - console.log(`Rebasing current branch on ${targetBranch}.`); - return exec(`git rebase origin/${targetBranch}`); - }) - .then(() => console.log('Rebase successfull.')) - .catch(err => { - console.log('Failed to rebase on top or target branch.\n'); - console.error(err); - process.exitCode = 1; - }); \ No newline at end of file diff --git a/tools/snapshot_repo_filter.bzl b/tools/snapshot_repo_filter.bzl new file mode 100644 index 000000000000..fbd9672c07a9 --- /dev/null +++ b/tools/snapshot_repo_filter.bzl @@ -0,0 +1,28 @@ +# Copyright Google LLC. All Rights Reserved. +# +# Use of this source code is governed by an MIT-style license that can be +# found in the LICENSE file at https://angular.dev/license + +load("//:constants.bzl", "SNAPSHOT_REPOS") + +def _generate_snapshot_repo_filter(): + individual_pkg_filters = [] + for pkg_name, snapshot_repo in SNAPSHOT_REPOS.items(): + individual_pkg_filters.append( + """ + . as $root + | [paths(..)] + | [(.[] | select( + contains(["{pkg_name}"]) and + contains(["peerDependenciesMeta"]) != true))] as $paths + | $paths | reduce $paths[] as $path ($root; setpath($path; "github:{snapshot_repo}#BUILD_SCM_HASH-PLACEHOLDER")) | . + """.format( + pkg_name = pkg_name, + snapshot_repo = snapshot_repo, + ), + ) + + return " | ".join(individual_pkg_filters) + +# jq filter that replaces package.json dependencies with snapshot repos +SNAPSHOT_REPO_JQ_FILTER = _generate_snapshot_repo_filter() diff --git a/tools/substitutions.bzl b/tools/substitutions.bzl new file mode 100644 index 000000000000..dc40701971ff --- /dev/null +++ b/tools/substitutions.bzl @@ -0,0 +1,37 @@ +load( + "//:constants.bzl", + "ANGULAR_FW_PEER_DEP", + "ANGULAR_FW_VERSION", + "BASELINE_DATE", + "NG_PACKAGR_PEER_DEP", + "NG_PACKAGR_VERSION", + "RELEASE_ENGINES_NODE", + "RELEASE_ENGINES_NPM", + "RELEASE_ENGINES_YARN", +) + +_stamp_substitutions = { + # Version of the local package being built, generated via the `--workspace_status_command` flag. + "0.0.0-PLACEHOLDER": "{{STABLE_PROJECT_VERSION}}", + "0.0.0-EXPERIMENTAL-PLACEHOLDER": "{{STABLE_PROJECT_EXPERIMENTAL_VERSION}}", + # --- + "BUILD_SCM_HASH-PLACEHOLDER": "{{BUILD_SCM_ABBREV_HASH}}", + "BASELINE-DATE-PLACEHOLDER": BASELINE_DATE, + "0.0.0-ENGINES-NODE": RELEASE_ENGINES_NODE, + "0.0.0-ENGINES-NPM": RELEASE_ENGINES_NPM, + "0.0.0-ENGINES-YARN": RELEASE_ENGINES_YARN, + "0.0.0-NG-PACKAGR-VERSION": NG_PACKAGR_VERSION, + "0.0.0-NG-PACKAGR-PEER-DEP": NG_PACKAGR_PEER_DEP, + "0.0.0-ANGULAR-FW-VERSION": ANGULAR_FW_VERSION, + "0.0.0-ANGULAR-FW-PEER-DEP": ANGULAR_FW_PEER_DEP, +} + +_no_stamp_substitutions = dict(_stamp_substitutions, **{ + "0.0.0-PLACEHOLDER": "0.0.0", + "0.0.0-EXPERIMENTAL-PLACEHOLDER": "0.0.0", +}) + +substitutions = { + "stamp": _stamp_substitutions, + "nostamp": _no_stamp_substitutions, +} diff --git a/tools/test/BUILD.bazel b/tools/test/BUILD.bazel new file mode 100644 index 000000000000..71ef3e3c2794 --- /dev/null +++ b/tools/test/BUILD.bazel @@ -0,0 +1,32 @@ +load("@bazel_skylib//rules:diff_test.bzl", "diff_test") +load("@jq.bzl//jq:jq.bzl", "jq") + +jq( + name = "final_package_json", + # This jq filter relies on the order of the inputs + # buildifier: do not sort + srcs = [ + "root_package.json", + "project_package.json", + ], + args = [ + "--slurp", + ], + filter_file = "//tools:package_json_release_filter.jq", +) + +# jq outputs CR on windows https://github.com/stedolan/jq/issues/92 +# strip the CRs to do a correct comparison on all platforms +genrule( + name = "final_package_json_cr_stripped", + srcs = [":final_package_json"], + outs = ["final_package_json_cr_stripped.json"], + cmd = "cat $(execpath :final_package_json) | sed \"s#\\r##\" > $@", +) + +# Test correctness of the filter that prepares each project's package.json file for release +diff_test( + name = "package_json_filter_test", + file1 = "expected_package.json", + file2 = ":final_package_json_cr_stripped", +) diff --git a/tools/test/expected_package.json b/tools/test/expected_package.json new file mode 100644 index 000000000000..6630c9062f8a --- /dev/null +++ b/tools/test/expected_package.json @@ -0,0 +1,42 @@ +{ + "name": "project", + "version": "0.0.0-SNAPSHOT", + "description": "Project package.json", + "main": "project/index.js", + "bin": { + "projectfoo": "./bin/project-foo.js" + }, + "keywords": [ + "a", + "b", + "c" + ], + "scripts": { + "build": "node project-build-script" + }, + "repository": { + "type": "git", + "url": "https://github.com/angular/angular-cli.git" + }, + "author": "Angular Authors", + "license": "MIT", + "bugs": { + "url": "https://github.com/angular/angular-cli/issues" + }, + "homepage": "https://github.com/angular/angular-cli", + "dependencies": { + "@project/foo": "1.0.0", + "@project/bar": "2.0.0" + }, + "ng-update": { + "migrations": "@project/migration-collection.json", + "packageGroup": { + "@project/abc": "0.0.0" + } + }, + "engines": { + "node": "0.0.0-ENGINES-NODE", + "npm": "0.0.0-ENGINES-NPM", + "yarn": "0.0.0-ENGINES-YARN" + } +} diff --git a/tools/test/project_package.json b/tools/test/project_package.json new file mode 100644 index 000000000000..894c9f4cf3f2 --- /dev/null +++ b/tools/test/project_package.json @@ -0,0 +1,39 @@ +{ + "name": "project", + "version": "0.0.0-SNAPSHOT", + "description": "Project package.json", + "main": "project/index.js", + "bin": { + "projectfoo": "./bin/project-foo.js" + }, + "keywords": [ + "b", + "c" + ], + "scripts": { + "build": "node project-build-script" + }, + "repository": { + "type": "git", + "url": "https://github.com/angular/angular-cli.git" + }, + "author": "Angular Authors", + "license": "MIT", + "bugs": { + "url": "https://github.com/angular/angular-cli/issues" + }, + "homepage": "https://github.com/angular/angular-cli", + "dependencies": { + "@project/foo": "1.0.0", + "@project/bar": "2.0.0" + }, + "devDependencies": { + "@project/devdep": "1.2.3" + }, + "ng-update": { + "migrations": "@project/migration-collection.json", + "packageGroup": { + "@project/abc": "0.0.0" + } + } +} diff --git a/tools/test/root_package.json b/tools/test/root_package.json new file mode 100644 index 000000000000..e0b263aef042 --- /dev/null +++ b/tools/test/root_package.json @@ -0,0 +1,37 @@ +{ + "name": "root", + "version": "1.0.0-next.1", + "private": true, + "description": "Root package.json", + "bin": { + "root-foo": "./bin/root-foo.js", + "root-bar": "./bin/root-bar.js" + }, + "keywords": [ + "a", + "b" + ], + "scripts": { + "build": "node root-build-script" + }, + "repository": { + "type": "git", + "url": "https://github.com/angular/angular-cli.git" + }, + "author": "Angular Authors", + "license": "MIT", + "bugs": { + "url": "https://github.com/angular/angular-cli/issues" + }, + "homepage": "https://github.com/angular/angular-cli", + "workspaces": { + "packages": ["packages/root/foo/*", "packages/root/bar/*"] + }, + "resolutions": { + "root/foo/bar": "1.0.0" + }, + "devDependencies": { + "@root/foo": "1.0.0", + "@root/bar": "2.0.0" + } +} diff --git a/tools/toolchain_info.bzl b/tools/toolchain_info.bzl new file mode 100644 index 000000000000..b920c8a8f88a --- /dev/null +++ b/tools/toolchain_info.bzl @@ -0,0 +1,31 @@ +# look at the toolchains registered in the workspace file with nodejs_register_toolchains + +# the name can be anything the user wants this is just added to the target to create unique names +# the order will match against the order in the TOOLCHAIN_VERSION list. +TOOLCHAINS_NAMES = [ + "node22", + "node24", + "node26", +] + +# this is the list of toolchains that should be used and are registered with nodejs_register_toolchains in the WORKSPACE file +TOOLCHAINS_VERSIONS = [ + select({ + "@bazel_tools//src/conditions:linux_x86_64": "@node22_linux_amd64//:node_toolchain", + "@bazel_tools//src/conditions:darwin": "@node22_darwin_amd64//:node_toolchain", + "@bazel_tools//src/conditions:windows": "@node22_windows_amd64//:node_toolchain", + }), + select({ + "@bazel_tools//src/conditions:linux_x86_64": "@node24_linux_amd64//:node_toolchain", + "@bazel_tools//src/conditions:darwin": "@node24_darwin_amd64//:node_toolchain", + "@bazel_tools//src/conditions:windows": "@node24_windows_amd64//:node_toolchain", + }), + select({ + "@bazel_tools//src/conditions:linux_x86_64": "@node26_linux_amd64//:node_toolchain", + "@bazel_tools//src/conditions:darwin": "@node26_darwin_amd64//:node_toolchain", + "@bazel_tools//src/conditions:windows": "@node26_windows_amd64//:node_toolchain", + }), +] + +# A default toolchain for use when only one is necessary +DEFAULT_TOOLCHAIN_VERSION = TOOLCHAINS_VERSIONS[len(TOOLCHAINS_VERSIONS) - 1] diff --git a/tools/toolchains/BUILD.bazel b/tools/toolchains/BUILD.bazel new file mode 100644 index 000000000000..09bb94865046 --- /dev/null +++ b/tools/toolchains/BUILD.bazel @@ -0,0 +1,32 @@ +load("@rules_cc//cc:defs.bzl", "cc_toolchain") +load(":dummy_cc_toolchain.bzl", "dummy_cc_toolchain_config") + +# This defines a dummy C++ toolchain for Windows. +# Without this, the build fails with "Unable to find a CC toolchain using toolchain resolution". +dummy_cc_toolchain_config(name = "dummy_cc_toolchain_config") + +filegroup(name = "empty") + +cc_toolchain( + name = "dummy_cc_toolchain", + all_files = ":empty", + compiler_files = ":empty", + dwp_files = ":empty", + linker_files = ":empty", + objcopy_files = ":empty", + strip_files = ":empty", + supports_param_files = 0, + toolchain_config = ":dummy_cc_toolchain_config", + toolchain_identifier = "dummy_cc_toolchain", +) + +toolchain( + name = "dummy_cc_windows_no_exec_toolchain", + exec_compatible_with = [], + target_compatible_with = [ + "@platforms//os:windows", + "@platforms//cpu:x86_64", + ], + toolchain = ":dummy_cc_toolchain", + toolchain_type = "@rules_cc//cc:toolchain_type", +) diff --git a/tools/toolchains/dummy_cc_toolchain.bzl b/tools/toolchains/dummy_cc_toolchain.bzl new file mode 100644 index 000000000000..a18a9c780915 --- /dev/null +++ b/tools/toolchains/dummy_cc_toolchain.bzl @@ -0,0 +1,28 @@ +""" +This file defines a dummy C++ toolchain for Windows. +It is needed to satisfy Bazel's toolchain resolution when cross-compiling for Windows on Linux. +Some rules (e.g. rules_nodejs, js_test) or their dependencies may trigger C++ toolchain resolution +even if no actual C++ compilation is performed for the target platform. +Without this, the build fails with "Unable to find a CC toolchain using toolchain resolution". +""" + +load("@rules_cc//cc:defs.bzl", "cc_common") + +def _impl(ctx): + return cc_common.create_cc_toolchain_config_info( + ctx = ctx, + toolchain_identifier = "dummy-toolchain", + host_system_name = "local", + target_system_name = "local", + target_cpu = "x64_windows", + target_libc = "unknown", + compiler = "dummy", + abi_version = "unknown", + abi_libc_version = "unknown", + ) + +dummy_cc_toolchain_config = rule( + implementation = _impl, + attrs = {}, + provides = [CcToolchainConfigInfo], +) diff --git a/tools/ts_json_schema.bzl b/tools/ts_json_schema.bzl index b74d27f12a6f..dab651d0d7e0 100644 --- a/tools/ts_json_schema.bzl +++ b/tools/ts_json_schema.bzl @@ -1,77 +1,20 @@ -# Copyright Google Inc. All Rights Reserved. -# -# Use of this source code is governed by an MIT-style license that can be -# found in the LICENSE file at https://angular.io/license +load("@aspect_rules_js//js:defs.bzl", "js_run_binary") -load("@npm_bazel_typescript//:index.bzl", "ts_library") - -# @external_begin -def _ts_json_schema_interface_impl(ctx): - args = [ - ctx.files.src[0].path, - ctx.outputs.ts.path, - ] - - ctx.actions.run( - inputs = ctx.files.src + ctx.files.data, - executable = ctx.executable._binary, - outputs = [ctx.outputs.ts], - arguments = args, - ) - - return [DefaultInfo()] - -_ts_json_schema_interface = rule( - _ts_json_schema_interface_impl, - attrs = { - "src": attr.label( - allow_files = [".json"], - mandatory = True, - ), - "out": attr.string( - mandatory = True, - ), - "data": attr.label_list( - allow_files = [".json"], - ), - "_binary": attr.label( - default = Label("//tools:quicktype_runner"), - executable = True, - cfg = "host", - ), - }, - outputs = { - "ts": "%{out}", - }, -) -# @external_end - -# Generates a library that contains the interface for a JSON Schema file. Takes a single `src` -# argument as input, an optional data field for reference files, and produces a ts_library() -# rule containing the typescript interface. +# Generates a TS file that contains the interface for a JSON Schema file. Takes a single `src` +# argument as input, an optional data field for reference files, and produces a +# _ts_json_schema_interface() rule containing the typescript interface. # The file produced will have the same name, with the extension replaced from `.json` to `.ts`. # Any filename collision will be an error thrown by Bazel. def ts_json_schema(name, src, data = []): out = src.replace(".json", ".ts") - # @external_begin - _ts_json_schema_interface( + js_run_binary( name = name + ".interface", - src = src, - out = out, - data = data, - ) - # @external_end - - ts_library( - name = name, - deps = [ - "@npm//@types/node", - ], - # Remove these to empty the rule, since those files are also compiled elsewhere. - # @external_begin - srcs = [ - out, - ], - # @external_end + outs = [out], + srcs = [src] + data, + tags = ["schema"], + tool = "//tools:quicktype_runner", + progress_message = "Generating TS interface for %s" % src, + mnemonic = "TsJsonSchema", + args = ["$(rootpath %s)" % src, "$(rootpath %s)" % out], ) diff --git a/tools/yarn/check-yarn.js b/tools/yarn/check-yarn.js deleted file mode 100644 index 2e7d66ef63c4..000000000000 --- a/tools/yarn/check-yarn.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @license - * Copyright Google Inc. All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -'use strict'; - -if (process.env.npm_execpath.indexOf('yarn') === -1) { - throw new Error( - 'Please use Yarn instead of NPM to install dependencies. See: https://yarnpkg.com/lang/en/docs/install/'); -} diff --git a/tsconfig-build-esm.json b/tsconfig-build-esm.json new file mode 100644 index 000000000000..5d44015a9631 --- /dev/null +++ b/tsconfig-build-esm.json @@ -0,0 +1,18 @@ +/** + * Root tsconfig file for use building all Angular packages. Note there is no rootDir + * and therefore any tsconfig in the package directory will need to define its own + * rootDir. + */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "target": "es2022", + "moduleResolution": "bundler", + // don't auto-discover @types/node, it results in a ///=2.2.7 <3" - -abab@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/abab/-/abab-2.0.2.tgz#a2fba1b122c69a85caa02d10f9270c7219709a9d" - integrity sha512-2scffjvioEmNz0OyDSLGWDfKCVwaKc6l9Pm9kOIREU13ClXZvHpg/nRL5xyjSSSLhOnXqft2HpsAzNEEA8cFFg== - -abbrev@1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" - integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== - -abstract-leveldown@^6.2.1, abstract-leveldown@~6.2.1: - version "6.2.2" - resolved "https://registry.yarnpkg.com/abstract-leveldown/-/abstract-leveldown-6.2.2.tgz#677425beeb28204367c7639e264e93ea4b49971a" - integrity sha512-/a+Iwj0rn//CX0EJOasNyZJd2o8xur8Ce9C57Sznti/Ilt/cb6Qd8/k98A4ZOklXgTG+iAYYUs1OTG0s1eH+zQ== - dependencies: - level-concat-iterator "~2.0.0" - level-supports "~1.0.0" - xtend "~4.0.0" - -abstract-leveldown@~6.0.1: - version "6.0.3" - resolved "https://registry.yarnpkg.com/abstract-leveldown/-/abstract-leveldown-6.0.3.tgz#b4b6159343c74b0c5197b2817854782d8f748c4a" - integrity sha512-jzewKKpZbaYUa6HTThnrl+GrJhzjEAeuc7hTVpZdzg7kupXZFoqQDFwyOwLNbmJKJlmzw8yiipMPkDiuKkT06Q== - dependencies: - level-concat-iterator "~2.0.0" - xtend "~4.0.0" - -accepts@~1.3.4, accepts@~1.3.5, accepts@~1.3.7: - version "1.3.7" - resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.7.tgz#531bc726517a3b2b41f850021c6cc15eaab507cd" - integrity sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA== - dependencies: - mime-types "~2.1.24" - negotiator "0.6.2" - -acorn-globals@^4.3.2: - version "4.3.4" - resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-4.3.4.tgz#9fa1926addc11c97308c4e66d7add0d40c3272e7" - integrity sha512-clfQEh21R+D0leSbUdWf3OcfqyaCSAQ8Ryq00bofSekfr9W8u1jyYZo6ir0xu9Gtcf7BjcHJpnbZH7JOCpP60A== - dependencies: - acorn "^6.0.1" - acorn-walk "^6.0.1" - -acorn-walk@^6.0.1: - version "6.2.0" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-6.2.0.tgz#123cb8f3b84c2171f1f7fb252615b1c78a6b1a8c" - integrity sha512-7evsyfH1cLOCdAzZAd43Cic04yKydNx0cF+7tiA19p1XnLLPU4dpCQOqpjqwokFe//vS0QqfqqjCS2JkiIs0cA== - -acorn@^5.0.0: - version "5.7.3" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.7.3.tgz#67aa231bf8812974b85235a96771eb6bd07ea279" - integrity sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw== - -acorn@^6.0.1, acorn@^6.2.1: - version "6.3.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.3.0.tgz#0087509119ffa4fc0a0041d1e93a417e68cb856e" - integrity sha512-/czfa8BwS88b9gWQVhc8eknunSA2DoJpJyTQkhheIf5E48u1N0R4q/YxxsAeqRrmK9TQ/uYfgLDfZo91UlANIA== - -acorn@^7.1.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.1.0.tgz#949d36f2c292535da602283586c2477c57eb2d6c" - integrity sha512-kL5CuoXA/dgxlBbVrflsflzQ3PAas7RYZB52NOm/6839iVYJgKMJ3cQJD+t2i5+qFa8h3MDpEOJiS64E8JLnSQ== - -adm-zip@^0.4.9, adm-zip@~0.4.3: - version "0.4.13" - resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.4.13.tgz#597e2f8cc3672151e1307d3e95cddbc75672314a" - integrity sha512-fERNJX8sOXfel6qCBCMPvZLzENBEhZTzKqg6vrOW5pvoEaQuJhRU4ndTAh6lHOxn1I6jnz2NHra56ZODM751uw== - -after@0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/after/-/after-0.8.2.tgz#fedb394f9f0e02aa9768e702bda23b505fae7e1f" - integrity sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8= - -agent-base@4, agent-base@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.3.0.tgz#8165f01c436009bccad0b1d122f05ed770efc6ee" - integrity sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg== - dependencies: - es6-promisify "^5.0.0" - -agent-base@~4.2.1: - version "4.2.1" - resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.2.1.tgz#d89e5999f797875674c07d87f260fc41e83e8ca9" - integrity sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg== - dependencies: - es6-promisify "^5.0.0" - -agentkeepalive@^3.4.1: - version "3.5.2" - resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-3.5.2.tgz#a113924dd3fa24a0bc3b78108c450c2abee00f67" - integrity sha512-e0L/HNe6qkQ7H19kTlRRqUibEAwDK5AFk6y3PtMsuut2VAH6+Q4xZml1tNDJD7kSAyqmbG/K08K5WEJYtUrSlQ== - dependencies: - humanize-ms "^1.2.1" - -aggregate-error@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.0.1.tgz#db2fe7246e536f40d9b5442a39e117d7dd6a24e0" - integrity sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA== - dependencies: - clean-stack "^2.0.0" - indent-string "^4.0.0" - -ajv-errors@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/ajv-errors/-/ajv-errors-1.0.1.tgz#f35986aceb91afadec4102fbd85014950cefa64d" - integrity sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ== - -ajv-keywords@^3.1.0, ajv-keywords@^3.4.1: - version "3.4.1" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" - integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== - -ajv@6.10.2, ajv@^6.1.0, ajv@^6.10.2, ajv@^6.5.5: - version "6.10.2" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.10.2.tgz#d3cea04d6b017b2894ad69040fec8b623eb4bd52" - integrity sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw== - dependencies: - fast-deep-equal "^2.0.1" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.4.1" - uri-js "^4.2.2" - -ajv@^5.0.0, ajv@^5.1.0: - version "5.5.2" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965" - integrity sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU= - dependencies: - co "^4.6.0" - fast-deep-equal "^1.0.0" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.3.0" - -ansi-align@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/ansi-align/-/ansi-align-3.0.0.tgz#b536b371cf687caaef236c18d3e21fe3797467cb" - integrity sha512-ZpClVKqXN3RGBmKibdfWzqCY4lnjEuoNzU5T0oEFpfd/z5qJHVarukridD4juLO2FXMiwUQxr9WqQtaYa8XRYw== - dependencies: - string-width "^3.0.0" - -ansi-colors@3.2.4, ansi-colors@^3.0.0: - version "3.2.4" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.4.tgz#e3a3da4bfbae6c86a9c285625de124a234026fbf" - integrity sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA== - -ansi-colors@4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" - integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== - -ansi-escapes@^4.2.1: - version "4.2.1" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.2.1.tgz#4dccdb846c3eee10f6d64dea66273eab90c37228" - integrity sha512-Cg3ymMAdN10wOk/VYfLV7KCQyv7EDirJ64500sU7n9UlmioEtDuU5Gd+hj73hXSU/ex7tHJSssmyftDdkMLO8Q== - dependencies: - type-fest "^0.5.2" - -ansi-html@0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/ansi-html/-/ansi-html-0.0.7.tgz#813584021962a9e9e6fd039f940d12f56ca7859e" - integrity sha1-gTWEAhliqenm/QOflA0S9WynhZ4= - -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= - -ansi-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" - integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= - -ansi-regex@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997" - integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== - -ansi-regex@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75" - integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg== - -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4= - -ansi-styles@^3.2.0, ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" - integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== - dependencies: - color-convert "^1.9.0" - -ansi-styles@^4.1.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.0.tgz#5681f0dcf7ae5880a7841d8831c4724ed9cc0172" - integrity sha512-7kFQgnEaMdRtwf6uSfUnVr9gSGC7faurn+J/Mv90/W+iTtN0405/nLdopfMWwchyxhbGYl6TC4Sccn9TUkGAgg== - dependencies: - "@types/color-name" "^1.1.1" - color-convert "^2.0.1" - -anymatch@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb" - integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw== - dependencies: - micromatch "^3.1.4" - normalize-path "^2.1.1" - -anymatch@~3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" - integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - -apache-md5@1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/apache-md5/-/apache-md5-1.1.2.tgz#ee49736b639b4f108b6e9e626c6da99306b41692" - integrity sha1-7klza2ObTxCLbp5ibG2pkwa0FpI= - -app-root-path@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/app-root-path/-/app-root-path-2.2.1.tgz#d0df4a682ee408273583d43f6f79e9892624bc9a" - integrity sha512-91IFKeKk7FjfmezPKkwtaRvSpnUc4gDwPAjA1YZ9Gn0q0PPeW+vbeUsZuyDwjI7+QTHhcLen2v25fi/AmhvbJA== - -append-transform@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/append-transform/-/append-transform-1.0.0.tgz#046a52ae582a228bd72f58acfbe2967c678759ab" - integrity sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw== - dependencies: - default-require-extensions "^2.0.0" - -aproba@^1.0.3, aproba@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" - integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw== - -are-we-there-yet@~1.1.2: - version "1.1.5" - resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz#4b35c2944f062a8bfcda66410760350fe9ddfc21" - integrity sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w== - dependencies: - delegates "^1.0.0" - readable-stream "^2.0.6" - -argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" - integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== - dependencies: - sprintf-js "~1.0.2" - -aria-query@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-3.0.0.tgz#65b3fcc1ca1155a8c9ae64d6eee297f15d5133cc" - integrity sha1-ZbP8wcoRVajJrmTW7uKX8V1RM8w= - dependencies: - ast-types-flow "0.0.7" - commander "^2.11.0" - -arr-diff@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" - integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= - -arr-flatten@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" - integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== - -arr-union@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" - integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= - -array-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/array-equal/-/array-equal-1.0.0.tgz#8c2a5ef2472fd9ea742b04c77a75093ba2757c93" - integrity sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM= - -array-find-index@^1.0.1, array-find-index@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1" - integrity sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E= - -array-flatten@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" - integrity sha1-ml9pkFGx5wczKPKgCJaLZOopVdI= - -array-flatten@^2.1.0: - version "2.1.2" - resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-2.1.2.tgz#24ef80a28c1a893617e2149b0c6d0d788293b099" - integrity sha512-hNfzcOV8W4NdualtqBFPyVO+54DSJuZGY9qT4pRroB6S9e3iiido2ISIC5h9R2sPJ8H3FHCIiEnsv1lPXO3KtQ== - -array-ify@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/array-ify/-/array-ify-1.0.0.tgz#9e528762b4a9066ad163a6962a364418e9626ece" - integrity sha1-nlKHYrSpBmrRY6aWKjZEGOlibs4= - -array-union@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" - integrity sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk= - dependencies: - array-uniq "^1.0.1" - -array-uniq@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" - integrity sha1-r2rId6Jcx/dOBYiUdThY39sk/bY= - -array-unique@^0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" - integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= - -arraybuffer.slice@~0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz#3bbc4275dd584cc1b10809b89d4e8b63a69e7675" - integrity sha512-wGUIVQXuehL5TCqQun8OW81jGzAWycqzFF8lFp+GOM5BXLYj3bKNsYC4daB7n6XjCqxQA/qgTJ+8ANR3acjrog== - -arrify@^1.0.0, arrify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" - integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= - -asap@^2.0.0, asap@~2.0.3: - version "2.0.6" - resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" - integrity sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY= - -asn1.js@^4.0.0: - version "4.10.1" - resolved "https://registry.yarnpkg.com/asn1.js/-/asn1.js-4.10.1.tgz#b9c2bf5805f1e64aadeed6df3a2bfafb5a73f5a0" - integrity sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw== - dependencies: - bn.js "^4.0.0" - inherits "^2.0.1" - minimalistic-assert "^1.0.0" - -asn1@~0.2.3: - version "0.2.4" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.4.tgz#8d2475dfab553bb33e77b54e59e880bb8ce23136" - integrity sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg== - dependencies: - safer-buffer "~2.1.0" - -assert-plus@1.0.0, assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU= - -assert@^1.1.1: - version "1.5.0" - resolved "https://registry.yarnpkg.com/assert/-/assert-1.5.0.tgz#55c109aaf6e0aefdb3dc4b71240c70bf574b18eb" - integrity sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA== - dependencies: - object-assign "^4.1.1" - util "0.10.3" - -assign-symbols@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" - integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= - -ast-types-flow@0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/ast-types-flow/-/ast-types-flow-0.0.7.tgz#f70b735c6bca1a5c9c22d982c3e39e7feba3bdad" - integrity sha1-9wtzXGvKGlycItmCw+Oef+ujva0= - -async-each@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" - integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== - -async-limiter@^1.0.0, async-limiter@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.1.tgz#dd379e94f0db8310b08291f9d64c3209766617fd" - integrity sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ== - -async@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/async/-/async-3.1.0.tgz#42b3b12ae1b74927b5217d8c0016baaf62463772" - integrity sha512-4vx/aaY6j/j3Lw3fbCHNWP0pPaTCew3F6F3hYyl/tHs/ndmV1q7NW9T5yuJ2XAGwdQrP+6Wu20x06U4APo/iQQ== - -async@^2.1.2, async@^2.5.0, async@^2.6.2: - version "2.6.3" - resolved "https://registry.yarnpkg.com/async/-/async-2.6.3.tgz#d72625e2344a3656e3a3ad4fa749fa83299d82ff" - integrity sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg== - dependencies: - lodash "^4.17.14" - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= - -atob@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" - integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== - -autoprefixer@9.7.1, autoprefixer@^9.6.5: - version "9.7.1" - resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-9.7.1.tgz#9ffc44c55f5ca89253d9bb7186cefb01ef57747f" - integrity sha512-w3b5y1PXWlhYulevrTJ0lizkQ5CyqfeU6BIRDbuhsMupstHQOeb1Ur80tcB1zxSu7AwyY/qCQ7Vvqklh31ZBFw== - dependencies: - browserslist "^4.7.2" - caniuse-lite "^1.0.30001006" - chalk "^2.4.2" - normalize-range "^0.1.2" - num2fraction "^1.2.2" - postcss "^7.0.21" - postcss-value-parser "^4.0.2" - -aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - integrity sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg= - -aws4@^1.6.0, aws4@^1.8.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f" - integrity sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ== - -axobject-query@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/axobject-query/-/axobject-query-2.0.2.tgz#ea187abe5b9002b377f925d8bf7d1c561adf38f9" - integrity sha512-MCeek8ZH7hKyO1rWUbKNQBbl4l2eY0ntk7OGi+q0RlafrCnfPxC06WZA+uebCfmYp4mNU9jRBP1AhGyf8+W3ww== - dependencies: - ast-types-flow "0.0.7" - -babel-code-frame@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" - integrity sha1-Y/1D99weO7fONZR9uP42mj9Yx0s= - dependencies: - chalk "^1.1.3" - esutils "^2.0.2" - js-tokens "^3.0.2" - -babel-generator@^6.18.0: - version "6.26.1" - resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.1.tgz#1844408d3b8f0d35a404ea7ac180f087a601bd90" - integrity sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA== - dependencies: - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - detect-indent "^4.0.0" - jsesc "^1.3.0" - lodash "^4.17.4" - source-map "^0.5.7" - trim-right "^1.0.1" - -babel-loader@8.0.6: - version "8.0.6" - resolved "https://registry.yarnpkg.com/babel-loader/-/babel-loader-8.0.6.tgz#e33bdb6f362b03f4bb141a0c21ab87c501b70dfb" - integrity sha512-4BmWKtBOBm13uoUwd08UwjZlaw3O9GWf456R9j+5YykFZ6LUIjIKLc0zEZf+hauxPOJs96C8k6FvYD09vWzhYw== - dependencies: - find-cache-dir "^2.0.0" - loader-utils "^1.0.2" - mkdirp "^0.5.1" - pify "^4.0.1" - -babel-messages@^6.23.0: - version "6.23.0" - resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" - integrity sha1-8830cDhYA1sqKVHG7F7fbGLyYw4= - dependencies: - babel-runtime "^6.22.0" - -babel-plugin-dynamic-import-node@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.0.tgz#f00f507bdaa3c3e3ff6e7e5e98d90a7acab96f7f" - integrity sha512-o6qFkpeQEBxcqt0XYlWzAVxNCSCZdUgcR8IRlhD/8DylxjjO4foPcvTW0GGKa/cVt3rvxZ7o5ippJ+/0nvLhlQ== - dependencies: - object.assign "^4.1.0" - -babel-runtime@^6.22.0, babel-runtime@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" - integrity sha1-llxwWGaOgrVde/4E/yM3vItWR/4= - dependencies: - core-js "^2.4.0" - regenerator-runtime "^0.11.0" - -babel-template@^6.16.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02" - integrity sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI= - dependencies: - babel-runtime "^6.26.0" - babel-traverse "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - lodash "^4.17.4" - -babel-traverse@^6.18.0, babel-traverse@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" - integrity sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4= - dependencies: - babel-code-frame "^6.26.0" - babel-messages "^6.23.0" - babel-runtime "^6.26.0" - babel-types "^6.26.0" - babylon "^6.18.0" - debug "^2.6.8" - globals "^9.18.0" - invariant "^2.2.2" - lodash "^4.17.4" - -babel-types@^6.18.0, babel-types@^6.26.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" - integrity sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc= - dependencies: - babel-runtime "^6.26.0" - esutils "^2.0.2" - lodash "^4.17.4" - to-fast-properties "^1.0.3" - -babylon@^6.18.0: - version "6.18.0" - resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" - integrity sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ== - -backo2@1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/backo2/-/backo2-1.0.2.tgz#31ab1ac8b129363463e35b3ebb69f4dfcfba7947" - integrity sha1-MasayLEpNjRj41s+u2n038+6eUc= - -balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= - -base64-arraybuffer@0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz#73926771923b5a19747ad666aa5cd4bf9c6e9ce8" - integrity sha1-c5JncZI7Whl0etZmqlzUv5xunOg= - -base64-js@^1.0.2: - version "1.3.1" - resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.1.tgz#58ece8cb75dd07e71ed08c736abc5fac4dbf8df1" - integrity sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g== - -base64id@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/base64id/-/base64id-1.0.0.tgz#47688cb99bb6804f0e06d3e763b1c32e57d8e6b6" - integrity sha1-R2iMuZu2gE8OBtPnY7HDLlfY5rY= - -base@^0.11.1: - version "0.11.2" - resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" - integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== - dependencies: - cache-base "^1.0.1" - class-utils "^0.3.5" - component-emitter "^1.2.1" - define-property "^1.0.0" - isobject "^3.0.1" - mixin-deep "^1.2.0" - pascalcase "^0.1.1" - -batch@0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" - integrity sha1-3DQxT05nkxgJP8dgJyUl+UvyXBY= - -bcrypt-pbkdf@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz#a4301d389b6a43f9b67ff3ca11a3f6637e360e9e" - integrity sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4= - dependencies: - tweetnacl "^0.14.3" - -bcryptjs@2.4.3: - version "2.4.3" - resolved "https://registry.yarnpkg.com/bcryptjs/-/bcryptjs-2.4.3.tgz#9ab5627b93e60621ff7cdac5da9733027df1d0cb" - integrity sha1-mrVie5PmBiH/fNrF2pczAn3x0Ms= - -better-assert@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/better-assert/-/better-assert-1.0.2.tgz#40866b9e1b9e0b55b481894311e68faffaebc522" - integrity sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI= - dependencies: - callsite "1.0.0" - -big.js@^5.2.2: - version "5.2.2" - resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" - integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== - -binary-extensions@^1.0.0: - version "1.13.1" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" - integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== - -binary-extensions@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.0.0.tgz#23c0df14f6a88077f5f986c0d167ec03c3d5537c" - integrity sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow== - -blob@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683" - integrity sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig== - -blocking-proxy@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/blocking-proxy/-/blocking-proxy-1.0.1.tgz#81d6fd1fe13a4c0d6957df7f91b75e98dac40cb2" - integrity sha512-KE8NFMZr3mN2E0HcvCgRtX7DjhiIQrwle+nSVJVC/yqFb9+xznHl2ZcoBp2L9qzkI4t4cBFJ1efXF8Dwi132RA== - dependencies: - minimist "^1.2.0" - -bluebird@^3.3.0, bluebird@^3.5.1, bluebird@^3.5.5: - version "3.7.1" - resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.1.tgz#df70e302b471d7473489acf26a93d63b53f874de" - integrity sha512-DdmyoGCleJnkbp3nkbxTLJ18rjDsE4yCggEwKNXkeV123sPNfOCYeDoeuOY+F2FrSjO1YXcTU+dsy96KMy+gcg== - -bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.1.1, bn.js@^4.4.0: - version "4.11.8" - resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.11.8.tgz#2cde09eb5ee341f484746bb0309b3253b1b1442f" - integrity sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA== - -body-parser@1.19.0, body-parser@^1.16.1: - version "1.19.0" - resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.0.tgz#96b2709e57c9c4e09a6fd66a8fd979844f69f08a" - integrity sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw== - dependencies: - bytes "3.1.0" - content-type "~1.0.4" - debug "2.6.9" - depd "~1.1.2" - http-errors "1.7.2" - iconv-lite "0.4.24" - on-finished "~2.3.0" - qs "6.7.0" - raw-body "2.4.0" - type-is "~1.6.17" - -bonjour@^3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/bonjour/-/bonjour-3.5.0.tgz#8e890a183d8ee9a2393b3844c691a42bcf7bc9f5" - integrity sha1-jokKGD2O6aI5OzhExpGkK897yfU= - dependencies: - array-flatten "^2.1.0" - deep-equal "^1.0.1" - dns-equal "^1.0.0" - dns-txt "^2.0.2" - multicast-dns "^6.0.1" - multicast-dns-service-types "^1.1.0" - -bootstrap@^4.0.0: - version "4.3.1" - resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-4.3.1.tgz#280ca8f610504d99d7b6b4bfc4b68cec601704ac" - integrity sha512-rXqOmH1VilAt2DyPzluTi2blhk17bO7ef+zLLPlWvG494pDxcM234pJ8wTc/6R40UWizAIIMgxjvxZg5kmsbag== - -boxen@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/boxen/-/boxen-3.2.0.tgz#fbdff0de93636ab4450886b6ff45b92d098f45eb" - integrity sha512-cU4J/+NodM3IHdSL2yN8bqYqnmlBTidDR4RC7nJs61ZmtGz8VZzM3HLQX0zY5mrSmPtR3xWwsq2jOUQqFZN8+A== - dependencies: - ansi-align "^3.0.0" - camelcase "^5.3.1" - chalk "^2.4.2" - cli-boxes "^2.2.0" - string-width "^3.0.0" - term-size "^1.2.0" - type-fest "^0.3.0" - widest-line "^2.0.0" - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -braces@^2.3.1, braces@^2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" - integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== - dependencies: - arr-flatten "^1.1.0" - array-unique "^0.3.2" - extend-shallow "^2.0.1" - fill-range "^4.0.0" - isobject "^3.0.1" - repeat-element "^1.1.2" - snapdragon "^0.8.1" - snapdragon-node "^2.0.1" - split-string "^3.0.2" - to-regex "^3.0.1" - -braces@^3.0.2, braces@~3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" - integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== - dependencies: - fill-range "^7.0.1" - -brfs@^1.4.0: - version "1.6.1" - resolved "https://registry.yarnpkg.com/brfs/-/brfs-1.6.1.tgz#b78ce2336d818e25eea04a0947cba6d4fb8849c3" - integrity sha512-OfZpABRQQf+Xsmju8XE9bDjs+uU4vLREGolP7bDgcpsI17QREyZ4Bl+2KLxxx1kCgA0fAIhKQBaBYh+PEcCqYQ== - dependencies: - quote-stream "^1.0.1" - resolve "^1.1.5" - static-module "^2.2.0" - through2 "^2.0.0" - -brorand@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" - integrity sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8= - -browser-process-hrtime@^0.1.2: - version "0.1.3" - resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz#616f00faef1df7ec1b5bf9cfe2bdc3170f26c7b4" - integrity sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw== - -browserify-aes@^1.0.0, browserify-aes@^1.0.4: - version "1.2.0" - resolved "https://registry.yarnpkg.com/browserify-aes/-/browserify-aes-1.2.0.tgz#326734642f403dabc3003209853bb70ad428ef48" - integrity sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA== - dependencies: - buffer-xor "^1.0.3" - cipher-base "^1.0.0" - create-hash "^1.1.0" - evp_bytestokey "^1.0.3" - inherits "^2.0.1" - safe-buffer "^5.0.1" - -browserify-cipher@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/browserify-cipher/-/browserify-cipher-1.0.1.tgz#8d6474c1b870bfdabcd3bcfcc1934a10e94f15f0" - integrity sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w== - dependencies: - browserify-aes "^1.0.4" - browserify-des "^1.0.0" - evp_bytestokey "^1.0.0" - -browserify-des@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/browserify-des/-/browserify-des-1.0.2.tgz#3af4f1f59839403572f1c66204375f7a7f703e9c" - integrity sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A== - dependencies: - cipher-base "^1.0.1" - des.js "^1.0.0" - inherits "^2.0.1" - safe-buffer "^5.1.2" - -browserify-rsa@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/browserify-rsa/-/browserify-rsa-4.0.1.tgz#21e0abfaf6f2029cf2fafb133567a701d4135524" - integrity sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ= - dependencies: - bn.js "^4.1.0" - randombytes "^2.0.1" - -browserify-sign@^4.0.0: - version "4.0.4" - resolved "https://registry.yarnpkg.com/browserify-sign/-/browserify-sign-4.0.4.tgz#aa4eb68e5d7b658baa6bf6a57e630cbd7a93d298" - integrity sha1-qk62jl17ZYuqa/alfmMMvXqT0pg= - dependencies: - bn.js "^4.1.1" - browserify-rsa "^4.0.0" - create-hash "^1.1.0" - create-hmac "^1.1.2" - elliptic "^6.0.0" - inherits "^2.0.1" - parse-asn1 "^5.0.0" - -browserify-zlib@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/browserify-zlib/-/browserify-zlib-0.2.0.tgz#2869459d9aa3be245fe8fe2ca1f46e2e7f54d73f" - integrity sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA== - dependencies: - pako "~1.0.5" - -browserslist@4.7.2, browserslist@^4.6.0, browserslist@^4.7.0, browserslist@^4.7.2: - version "4.7.2" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.7.2.tgz#1bb984531a476b5d389cedecb195b2cd69fb1348" - integrity sha512-uZavT/gZXJd2UTi9Ov7/Z340WOSQ3+m1iBVRUknf+okKxonL9P83S3ctiBDtuRmRu8PiCHjqyueqQ9HYlJhxiw== - dependencies: - caniuse-lite "^1.0.30001004" - electron-to-chromium "^1.3.295" - node-releases "^1.1.38" - -browserstack@^1.5.1: - version "1.5.3" - resolved "https://registry.yarnpkg.com/browserstack/-/browserstack-1.5.3.tgz#93ab48799a12ef99dbd074dd595410ddb196a7ac" - integrity sha512-AO+mECXsW4QcqC9bxwM29O7qWa7bJT94uBFzeb5brylIQwawuEziwq20dPYbins95GlWzOawgyDNdjYAo32EKg== - dependencies: - https-proxy-agent "^2.2.1" - -buffer-alloc-unsafe@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz#bd7dc26ae2972d0eda253be061dba992349c19f0" - integrity sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg== - -buffer-alloc@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/buffer-alloc/-/buffer-alloc-1.2.0.tgz#890dd90d923a873e08e10e5fd51a57e5b7cce0ec" - integrity sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow== - dependencies: - buffer-alloc-unsafe "^1.1.0" - buffer-fill "^1.0.0" - -buffer-equal-constant-time@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" - integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk= - -buffer-equal@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-0.0.1.tgz#91bc74b11ea405bc916bc6aa908faafa5b4aac4b" - integrity sha1-kbx0sR6kBbyRa8aqkI+q+ltKrEs= - -buffer-fill@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/buffer-fill/-/buffer-fill-1.0.0.tgz#f8f78b76789888ef39f205cd637f68e702122b2c" - integrity sha1-+PeLdniYiO858gXNY39o5wISKyw= - -buffer-from@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" - integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== - -buffer-indexof@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-indexof/-/buffer-indexof-1.1.1.tgz#52fabcc6a606d1a00302802648ef68f639da268c" - integrity sha512-4/rOEg86jivtPTeOUUT61jJO1Ya1TrR/OkqCSZDyq84WJh3LuuiphBYJN+fm5xufIk4XAFcEwte/8WzC8If/1g== - -buffer-xor@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/buffer-xor/-/buffer-xor-1.0.3.tgz#26e61ed1422fb70dd42e6e36729ed51d855fe8d9" - integrity sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk= - -buffer@^4.3.0: - version "4.9.2" - resolved "https://registry.yarnpkg.com/buffer/-/buffer-4.9.2.tgz#230ead344002988644841ab0244af8c44bbe3ef8" - integrity sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg== - dependencies: - base64-js "^1.0.2" - ieee754 "^1.1.4" - isarray "^1.0.0" - -builtin-modules@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" - integrity sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8= - -builtin-modules@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-3.1.0.tgz#aad97c15131eb76b65b50ef208e7584cd76a7484" - integrity sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw== - -builtin-status-codes@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz#85982878e21b98e1c66425e03d0174788f569ee8" - integrity sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug= - -builtins@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/builtins/-/builtins-1.0.3.tgz#cb94faeb61c8696451db36534e1422f94f0aee88" - integrity sha1-y5T662HIaWRR2zZTThQi+U8K7og= - -bunyan@1.8.12: - version "1.8.12" - resolved "https://registry.yarnpkg.com/bunyan/-/bunyan-1.8.12.tgz#f150f0f6748abdd72aeae84f04403be2ef113797" - integrity sha1-8VDw9nSKvdcq6uhPBEA74u8RN5c= - optionalDependencies: - dtrace-provider "~0.8" - moment "^2.10.6" - mv "~2" - safe-json-stringify "~1" - -bytes@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048" - integrity sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg= - -bytes@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6" - integrity sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg== - -cacache@13.0.1, cacache@^13.0.1: - version "13.0.1" - resolved "https://registry.yarnpkg.com/cacache/-/cacache-13.0.1.tgz#a8000c21697089082f85287a1aec6e382024a71c" - integrity sha512-5ZvAxd05HDDU+y9BVvcqYu2LLXmPnQ0hW62h32g4xBTgL/MppR4/04NHfj/ycM2y6lmTnbw6HVi+1eN0Psba6w== - dependencies: - chownr "^1.1.2" - figgy-pudding "^3.5.1" - fs-minipass "^2.0.0" - glob "^7.1.4" - graceful-fs "^4.2.2" - infer-owner "^1.0.4" - lru-cache "^5.1.1" - minipass "^3.0.0" - minipass-collect "^1.0.2" - minipass-flush "^1.0.5" - minipass-pipeline "^1.2.2" - mkdirp "^0.5.1" - move-concurrently "^1.0.1" - p-map "^3.0.0" - promise-inflight "^1.0.1" - rimraf "^2.7.1" - ssri "^7.0.0" - unique-filename "^1.1.1" - -cacache@^12.0.2, cacache@^12.0.3: - version "12.0.3" - resolved "https://registry.yarnpkg.com/cacache/-/cacache-12.0.3.tgz#be99abba4e1bf5df461cd5a2c1071fc432573390" - integrity sha512-kqdmfXEGFepesTuROHMs3MpFLWrPkSSpRqOw80RCflZXy/khxaArvFrQ7uJxSUduzAufc6G0g1VUCOZXxWavPw== - dependencies: - bluebird "^3.5.5" - chownr "^1.1.1" - figgy-pudding "^3.5.1" - glob "^7.1.4" - graceful-fs "^4.1.15" - infer-owner "^1.0.3" - lru-cache "^5.1.1" - mississippi "^3.0.0" - mkdirp "^0.5.1" - move-concurrently "^1.0.1" - promise-inflight "^1.0.1" - rimraf "^2.6.3" - ssri "^6.0.1" - unique-filename "^1.1.1" - y18n "^4.0.0" - -cache-base@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" - integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== - dependencies: - collection-visit "^1.0.0" - component-emitter "^1.2.1" - get-value "^2.0.6" - has-value "^1.0.0" - isobject "^3.0.1" - set-value "^2.0.0" - to-object-path "^0.3.0" - union-value "^1.0.0" - unset-value "^1.0.0" - -cacheable-request@^6.0.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-6.1.0.tgz#20ffb8bd162ba4be11e9567d823db651052ca912" - integrity sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg== - dependencies: - clone-response "^1.0.2" - get-stream "^5.1.0" - http-cache-semantics "^4.0.0" - keyv "^3.0.0" - lowercase-keys "^2.0.0" - normalize-url "^4.1.0" - responselike "^1.0.2" - -caller-callsite@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/caller-callsite/-/caller-callsite-2.0.0.tgz#847e0fce0a223750a9a027c54b33731ad3154134" - integrity sha1-hH4PzgoiN1CpoCfFSzNzGtMVQTQ= - dependencies: - callsites "^2.0.0" - -caller-path@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-2.0.0.tgz#468f83044e369ab2010fac5f06ceee15bb2cb1f4" - integrity sha1-Ro+DBE42mrIBD6xfBs7uFbsssfQ= - dependencies: - caller-callsite "^2.0.0" - -callsite@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/callsite/-/callsite-1.0.0.tgz#280398e5d664bd74038b6f0905153e6e8af1bc20" - integrity sha1-KAOY5dZkvXQDi28JBRU+borxvCA= - -callsites@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-2.0.0.tgz#06eb84f00eea413da86affefacbffb36093b3c50" - integrity sha1-BuuE8A7qQT2oav/vrL/7Ngk7PFA= - -camelcase-keys@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7" - integrity sha1-MIvur/3ygRkFHvodkyITyRuPkuc= - dependencies: - camelcase "^2.0.0" - map-obj "^1.0.0" - -camelcase-keys@^4.0.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-4.2.0.tgz#a2aa5fb1af688758259c32c141426d78923b9b77" - integrity sha1-oqpfsa9oh1glnDLBQUJteJI7m3c= - dependencies: - camelcase "^4.1.0" - map-obj "^2.0.0" - quick-lru "^1.0.0" - -camelcase@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f" - integrity sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8= - -camelcase@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd" - integrity sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0= - -camelcase@^5.0.0, camelcase@^5.3.1: - version "5.3.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" - integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== - -caniuse-lite@1.0.30001010: - version "1.0.30001010" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001010.tgz#397a14034d384260453cc81994f494626d34b938" - integrity sha512-RA5GH9YjFNea4ZQszdWgh2SC+dpLiRAg4VDQS2b5JRI45OxmbGrYocYHTa9x0bKMQUE7uvHkNPNffUr+pCxSGw== - -caniuse-lite@^1.0.30001004, caniuse-lite@^1.0.30001006: - version "1.0.30001008" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001008.tgz#b8841b1df78a9f5ed9702537ef592f1f8772c0d9" - integrity sha512-b8DJyb+VVXZGRgJUa30cbk8gKHZ3LOZTBLaUEEVr2P4xpmFigOCc62CO4uzquW641Ouq1Rm9N+rWLWdSYDaDIw== - -canonical-path@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/canonical-path/-/canonical-path-1.0.0.tgz#fcb470c23958def85081856be7a86e904f180d1d" - integrity sha512-feylzsbDxi1gPZ1IjystzIQZagYYLvfKrSuygUCgf7z6x790VEzze5QEkdSV1U58RA7Hi0+v6fv4K54atOzATg== - -caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw= - -chalk@^1.1.1, chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg= - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - -chalk@^2.0.0, chalk@^2.0.1, chalk@^2.3.0, chalk@^2.3.1, chalk@^2.4.1, chalk@^2.4.2: - version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - -chalk@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" - integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== - dependencies: - ansi-styles "^4.1.0" - supports-color "^7.1.0" - -chardet@^0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" - integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== - -"chokidar@>=2.0.0 <4.0.0", chokidar@^3.0.0, chokidar@^3.2.1: - version "3.3.0" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.3.0.tgz#12c0714668c55800f659e262d4962a97faf554a6" - integrity sha512-dGmKLDdT3Gdl7fBUe8XK+gAtGmzy5Fn0XkkWQuYxGIgWVPPse2CxFA5mtrlD0TOHaHjEUqkWNyP1XdHoJES/4A== - dependencies: - anymatch "~3.1.1" - braces "~3.0.2" - glob-parent "~5.1.0" - is-binary-path "~2.1.0" - is-glob "~4.0.1" - normalize-path "~3.0.0" - readdirp "~3.2.0" - optionalDependencies: - fsevents "~2.1.1" - -chokidar@^2.0.2, chokidar@^2.0.3, chokidar@^2.1.1, chokidar@^2.1.8: - version "2.1.8" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz#804b3a7b6a99358c3c5c61e71d8728f041cff917" - integrity sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg== - dependencies: - anymatch "^2.0.0" - async-each "^1.0.1" - braces "^2.3.2" - glob-parent "^3.1.0" - inherits "^2.0.3" - is-binary-path "^1.0.0" - is-glob "^4.0.0" - normalize-path "^3.0.0" - path-is-absolute "^1.0.0" - readdirp "^2.2.1" - upath "^1.1.1" - optionalDependencies: - fsevents "^1.2.7" - -chownr@^1.1.1, chownr@^1.1.2, chownr@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.3.tgz#42d837d5239688d55f303003a508230fa6727142" - integrity sha512-i70fVHhmV3DtTl6nqvZOnIjbY0Pe4kAUjwHj8z0zAdgBtYrJyYwLKCCuRBQ5ppkyL0AkN7HKRnETdmdp1zqNXw== - -chrome-trace-event@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" - integrity sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ== - dependencies: - tslib "^1.9.0" - -ci-info@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46" - integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ== - -cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de" - integrity sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q== - dependencies: - inherits "^2.0.1" - safe-buffer "^5.0.1" - -circular-dependency-plugin@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/circular-dependency-plugin/-/circular-dependency-plugin-5.2.0.tgz#e09dbc2dd3e2928442403e2d45b41cea06bc0a93" - integrity sha512-7p4Kn/gffhQaavNfyDFg7LS5S/UT1JAjyGd4UqR2+jzoYF02eDkj0Ec3+48TsIa4zghjLY87nQHIh/ecK9qLdw== - -circular-json@^0.5.5: - version "0.5.9" - resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.5.9.tgz#932763ae88f4f7dead7a0d09c8a51a4743a53b1d" - integrity sha512-4ivwqHpIFJZBuhN3g/pEcdbnGUywkBblloGbkglyloVjjR3uT6tieI89MVOfbP2tHX5sgb01FuLgAOzebNlJNQ== - -class-utils@^0.3.5: - version "0.3.6" - resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" - integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== - dependencies: - arr-union "^3.1.0" - define-property "^0.2.5" - isobject "^3.0.0" - static-extend "^0.1.1" - -clean-css@4.2.1, clean-css@^4.1.11: - version "4.2.1" - resolved "https://registry.yarnpkg.com/clean-css/-/clean-css-4.2.1.tgz#2d411ef76b8569b6d0c84068dabe85b0aa5e5c17" - integrity sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g== - dependencies: - source-map "~0.6.0" - -clean-stack@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" - integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== - -cli-boxes@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-boxes/-/cli-boxes-2.2.0.tgz#538ecae8f9c6ca508e3c3c95b453fe93cb4c168d" - integrity sha512-gpaBrMAizVEANOpfZp/EEUixTXDyGt7DFzdK5hU+UbWt/J0lB0w20ncZj59Z9a93xHb9u12zF5BS6i9RKbtg4w== - -cli-cursor@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" - integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== - dependencies: - restore-cursor "^3.1.0" - -cli-spinners@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" - integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== - -cli-width@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.0.tgz#ff19ede8a9a5e579324147b0c11f0fbcbabed639" - integrity sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk= - -cliui@^4.0.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-4.1.0.tgz#348422dbe82d800b3022eef4f6ac10bf2e4d1b49" - integrity sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ== - dependencies: - string-width "^2.1.1" - strip-ansi "^4.0.0" - wrap-ansi "^2.0.0" - -cliui@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-5.0.0.tgz#deefcfdb2e800784aa34f46fa08e06851c7bbbc5" - integrity sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA== - dependencies: - string-width "^3.1.0" - strip-ansi "^5.2.0" - wrap-ansi "^5.1.0" - -clone-deep@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" - integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== - dependencies: - is-plain-object "^2.0.4" - kind-of "^6.0.2" - shallow-clone "^3.0.0" - -clone-response@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.2.tgz#d1dc973920314df67fbeb94223b4ee350239e96b" - integrity sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws= - dependencies: - mimic-response "^1.0.0" - -clone@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" - integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4= - -clone@^2.1.1, clone@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f" - integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= - -co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ= - -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" - integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= - -codelyzer@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/codelyzer/-/codelyzer-5.2.0.tgz#b0ee573a12779c996090e596c5c1755479d83758" - integrity sha512-izfUfhEOOgAizszPlEDxo71DK/C4wprZw0vkY6UWcOSTQvN1JyfXf9DXwaV7WX+/JC+hH0ShXfdtGLA9Rca7LA== - dependencies: - app-root-path "^2.2.1" - aria-query "^3.0.0" - axobject-query "^2.0.2" - css-selector-tokenizer "^0.7.1" - cssauron "^1.4.0" - damerau-levenshtein "^1.0.4" - semver-dsl "^1.0.1" - source-map "^0.5.7" - sprintf-js "^1.1.2" - -collection-utils@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/collection-utils/-/collection-utils-1.0.1.tgz#31d14336488674f27aefc0a7c5eccacf6df78044" - integrity sha512-LA2YTIlR7biSpXkKYwwuzGjwL5rjWEZVOSnvdUc7gObvWe4WkjxOpfrdhoP7Hs09YWDVfg0Mal9BpAqLfVEzQg== - -collection-visit@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" - integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= - dependencies: - map-visit "^1.0.0" - object-visit "^1.0.0" - -color-convert@^1.9.0: - version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" - integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== - dependencies: - color-name "1.1.3" - -color-convert@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" - integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== - dependencies: - color-name "~1.1.4" - -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" - integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= - -color-name@~1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" - integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== - -colors@1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63" - integrity sha1-FopHAXVran9RoSzgyXv6KMCE7WM= - -colors@^1.1.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" - integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== - -combined-stream@^1.0.6, combined-stream@~1.0.5, combined-stream@~1.0.6: - version "1.0.8" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" - integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== - dependencies: - delayed-stream "~1.0.0" - -commander@3.0.2, commander@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/commander/-/commander-3.0.2.tgz#6837c3fb677ad9933d1cfba42dd14d5117d6b39e" - integrity sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow== - -commander@^2.11.0, commander@^2.12.1, commander@^2.20.0, commander@~2.20.3: - version "2.20.3" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" - integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== - -common-tags@^1.8.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/common-tags/-/common-tags-1.8.0.tgz#8e3153e542d4a39e9b10554434afaaf98956a937" - integrity sha512-6P6g0uetGpW/sdyUy/iQQCbFF0kWVMSIVSyYz7Zgjcgh8mgw8PQzDNZeyZ5DQ2gM7LBoZPHmnjz8rUthkBG5tw== - -commondir@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" - integrity sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs= - -compare-func@^1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/compare-func/-/compare-func-1.3.2.tgz#99dd0ba457e1f9bc722b12c08ec33eeab31fa648" - integrity sha1-md0LpFfh+bxyKxLAjsM+6rMfpkg= - dependencies: - array-ify "^1.0.0" - dot-prop "^3.0.0" - -compare-versions@^3.4.0: - version "3.5.1" - resolved "https://registry.yarnpkg.com/compare-versions/-/compare-versions-3.5.1.tgz#26e1f5cf0d48a77eced5046b9f67b6b61075a393" - integrity sha512-9fGPIB7C6AyM18CJJBHt5EnCZDG3oiTJYy0NjfIAGjKpzv0tkxWko7TNQHF5ymqm7IH03tqmeuBxtvD+Izh6mg== - -component-bind@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/component-bind/-/component-bind-1.0.0.tgz#00c608ab7dcd93897c0009651b1d3a8e1e73bbd1" - integrity sha1-AMYIq33Nk4l8AAllGx06jh5zu9E= - -component-emitter@1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6" - integrity sha1-E3kY1teCg/ffemt8WmPhQOaUJeY= - -component-emitter@^1.2.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" - integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== - -component-inherit@0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/component-inherit/-/component-inherit-0.0.3.tgz#645fc4adf58b72b649d5cae65135619db26ff143" - integrity sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM= - -compressible@~2.0.16: - version "2.0.17" - resolved "https://registry.yarnpkg.com/compressible/-/compressible-2.0.17.tgz#6e8c108a16ad58384a977f3a482ca20bff2f38c1" - integrity sha512-BGHeLCK1GV7j1bSmQQAi26X+GgWcTjLr/0tzSvMCl3LH1w1IJ4PFSPoV5316b30cneTziC+B1a+3OjoSUcQYmw== - dependencies: - mime-db ">= 1.40.0 < 2" - -compression@1.7.4, compression@^1.7.4: - version "1.7.4" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.7.4.tgz#95523eff170ca57c29a0ca41e6fe131f41e5bb8f" - integrity sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ== - dependencies: - accepts "~1.3.5" - bytes "3.0.0" - compressible "~2.0.16" - debug "2.6.9" - on-headers "~1.0.2" - safe-buffer "5.1.2" - vary "~1.1.2" - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= - -concat-stream@1.6.2, concat-stream@^1.5.0, concat-stream@^1.5.2, concat-stream@~1.6.0: - version "1.6.2" - resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" - integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== - dependencies: - buffer-from "^1.0.0" - inherits "^2.0.3" - readable-stream "^2.2.2" - typedarray "^0.0.6" - -configstore@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/configstore/-/configstore-4.0.0.tgz#5933311e95d3687efb592c528b922d9262d227e7" - integrity sha512-CmquAXFBocrzaSM8mtGPMM/HiWmyIpr4CcJl/rgY2uCObZ/S7cKU0silxslqJejl+t/T9HS8E0PUNQD81JGUEQ== - dependencies: - dot-prop "^4.1.0" - graceful-fs "^4.1.2" - make-dir "^1.0.0" - unique-string "^1.0.0" - write-file-atomic "^2.0.0" - xdg-basedir "^3.0.0" - -connect-history-api-fallback@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/connect-history-api-fallback/-/connect-history-api-fallback-1.6.0.tgz#8b32089359308d111115d81cad3fceab888f97bc" - integrity sha512-e54B99q/OUoH64zYYRf3HBP5z24G38h5D3qXu23JGRoigpX5Ss4r9ZnDk3g0Z8uQC2x2lPaJ+UlWBc1ZWBWdLg== - -connect@^3.6.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/connect/-/connect-3.7.0.tgz#5d49348910caa5e07a01800b030d0c35f20484f8" - integrity sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ== - dependencies: - debug "2.6.9" - finalhandler "1.1.2" - parseurl "~1.3.3" - utils-merge "1.0.1" - -console-browserify@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.2.0.tgz#67063cef57ceb6cf4993a2ab3a55840ae8c49336" - integrity sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA== - -console-control-strings@^1.0.0, console-control-strings@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" - integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4= - -constants-browserify@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/constants-browserify/-/constants-browserify-1.0.0.tgz#c20b96d8c617748aaf1c16021760cd27fcb8cb75" - integrity sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U= - -content-disposition@0.5.3: - version "0.5.3" - resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.3.tgz#e130caf7e7279087c5616c2007d0485698984fbd" - integrity sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g== - dependencies: - safe-buffer "5.1.2" - -content-type@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" - integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA== - -conventional-changelog-angular@^1.6.6: - version "1.6.6" - resolved "https://registry.yarnpkg.com/conventional-changelog-angular/-/conventional-changelog-angular-1.6.6.tgz#b27f2b315c16d0a1f23eb181309d0e6a4698ea0f" - integrity sha512-suQnFSqCxRwyBxY68pYTsFkG0taIdinHLNEAX5ivtw8bCRnIgnpvcHmlR/yjUyZIrNPYAoXlY1WiEKWgSE4BNg== - dependencies: - compare-func "^1.3.1" - q "^1.5.1" - -conventional-changelog-atom@^0.2.8: - version "0.2.8" - resolved "https://registry.yarnpkg.com/conventional-changelog-atom/-/conventional-changelog-atom-0.2.8.tgz#8037693455990e3256f297320a45fa47ee553a14" - integrity sha512-8pPZqhMbrnltNBizjoDCb/Sz85KyUXNDQxuAEYAU5V/eHn0okMBVjqc8aHWYpHrytyZWvMGbayOlDv7i8kEf6g== - dependencies: - q "^1.5.1" - -conventional-changelog-codemirror@^0.3.8: - version "0.3.8" - resolved "https://registry.yarnpkg.com/conventional-changelog-codemirror/-/conventional-changelog-codemirror-0.3.8.tgz#a1982c8291f4ee4d6f2f62817c6b2ecd2c4b7b47" - integrity sha512-3HFZKtBXTaUCHvz7ai6nk2+psRIkldDoNzCsom0egDtVmPsvvHZkzjynhdQyULfacRSsBTaiQ0ol6nBOL4dDiQ== - dependencies: - q "^1.5.1" - -conventional-changelog-core@^2.0.11: - version "2.0.11" - resolved "https://registry.yarnpkg.com/conventional-changelog-core/-/conventional-changelog-core-2.0.11.tgz#19b5fbd55a9697773ed6661f4e32030ed7e30287" - integrity sha512-HvTE6RlqeEZ/NFPtQeFLsIDOLrGP3bXYr7lFLMhCVsbduF1MXIe8OODkwMFyo1i9ku9NWBwVnVn0jDmIFXjDRg== - dependencies: - conventional-changelog-writer "^3.0.9" - conventional-commits-parser "^2.1.7" - dateformat "^3.0.0" - get-pkg-repo "^1.0.0" - git-raw-commits "^1.3.6" - git-remote-origin-url "^2.0.0" - git-semver-tags "^1.3.6" - lodash "^4.2.1" - normalize-package-data "^2.3.5" - q "^1.5.1" - read-pkg "^1.1.0" - read-pkg-up "^1.0.1" - through2 "^2.0.0" - -conventional-changelog-ember@^0.3.12: - version "0.3.12" - resolved "https://registry.yarnpkg.com/conventional-changelog-ember/-/conventional-changelog-ember-0.3.12.tgz#b7d31851756d0fcb49b031dffeb6afa93b202400" - integrity sha512-mmJzA7uzbrOqeF89dMMi6z17O07ORTXlTMArnLG9ZTX4oLaKNolUlxFUFlFm9JUoVWajVpaHQWjxH1EOQ+ARoQ== - dependencies: - q "^1.5.1" - -conventional-changelog-eslint@^1.0.9: - version "1.0.9" - resolved "https://registry.yarnpkg.com/conventional-changelog-eslint/-/conventional-changelog-eslint-1.0.9.tgz#b13cc7e4b472c819450ede031ff1a75c0e3d07d3" - integrity sha512-h87nfVh2fdk9fJIvz26wCBsbDC/KxqCc5wSlNMZbXcARtbgNbNDIF7Y7ctokFdnxkzVdaHsbINkh548T9eBA7Q== - dependencies: - q "^1.5.1" - -conventional-changelog-express@^0.3.6: - version "0.3.6" - resolved "https://registry.yarnpkg.com/conventional-changelog-express/-/conventional-changelog-express-0.3.6.tgz#4a6295cb11785059fb09202180d0e59c358b9c2c" - integrity sha512-3iWVtBJZ9RnRnZveNDzOD8QRn6g6vUif0qVTWWyi5nUIAbuN1FfPVyKdAlJJfp5Im+dE8Kiy/d2SpaX/0X678Q== - dependencies: - q "^1.5.1" - -conventional-changelog-jquery@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/conventional-changelog-jquery/-/conventional-changelog-jquery-0.1.0.tgz#0208397162e3846986e71273b6c79c5b5f80f510" - integrity sha1-Agg5cWLjhGmG5xJztsecW1+A9RA= - dependencies: - q "^1.4.1" - -conventional-changelog-jscs@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/conventional-changelog-jscs/-/conventional-changelog-jscs-0.1.0.tgz#0479eb443cc7d72c58bf0bcf0ef1d444a92f0e5c" - integrity sha1-BHnrRDzH1yxYvwvPDvHURKkvDlw= - dependencies: - q "^1.4.1" - -conventional-changelog-jshint@^0.3.8: - version "0.3.8" - resolved "https://registry.yarnpkg.com/conventional-changelog-jshint/-/conventional-changelog-jshint-0.3.8.tgz#9051c1ac0767abaf62a31f74d2fe8790e8acc6c8" - integrity sha512-hn9QU4ZI/5V50wKPJNPGT4gEWgiBFpV6adieILW4MaUFynuDYOvQ71EMSj3EznJyKi/KzuXpc9dGmX8njZMjig== - dependencies: - compare-func "^1.3.1" - q "^1.5.1" - -conventional-changelog-preset-loader@^1.1.8: - version "1.1.8" - resolved "https://registry.yarnpkg.com/conventional-changelog-preset-loader/-/conventional-changelog-preset-loader-1.1.8.tgz#40bb0f142cd27d16839ec6c74ee8db418099b373" - integrity sha512-MkksM4G4YdrMlT2MbTsV2F6LXu/hZR0Tc/yenRrDIKRwBl/SP7ER4ZDlglqJsCzLJi4UonBc52Bkm5hzrOVCcw== - -conventional-changelog-writer@^3.0.9: - version "3.0.9" - resolved "https://registry.yarnpkg.com/conventional-changelog-writer/-/conventional-changelog-writer-3.0.9.tgz#4aecdfef33ff2a53bb0cf3b8071ce21f0e994634" - integrity sha512-n9KbsxlJxRQsUnK6wIBRnARacvNnN4C/nxnxCkH+B/R1JS2Fa+DiP1dU4I59mEDEjgnFaN2+9wr1P1s7GYB5/Q== - dependencies: - compare-func "^1.3.1" - conventional-commits-filter "^1.1.6" - dateformat "^3.0.0" - handlebars "^4.0.2" - json-stringify-safe "^5.0.1" - lodash "^4.2.1" - meow "^4.0.0" - semver "^5.5.0" - split "^1.0.0" - through2 "^2.0.0" - -conventional-changelog@^1.1.0: - version "1.1.24" - resolved "https://registry.yarnpkg.com/conventional-changelog/-/conventional-changelog-1.1.24.tgz#3d94c29c960f5261c002678315b756cdd3d7d1f0" - integrity sha512-2WcSUst4Y3Z4hHvoMTWXMJr/DmgVdLiMOVY1Kak2LfFz+GIz2KDp5naqbFesYbfXPmaZ5p491dO0FWZIJoJw1Q== - dependencies: - conventional-changelog-angular "^1.6.6" - conventional-changelog-atom "^0.2.8" - conventional-changelog-codemirror "^0.3.8" - conventional-changelog-core "^2.0.11" - conventional-changelog-ember "^0.3.12" - conventional-changelog-eslint "^1.0.9" - conventional-changelog-express "^0.3.6" - conventional-changelog-jquery "^0.1.0" - conventional-changelog-jscs "^0.1.0" - conventional-changelog-jshint "^0.3.8" - conventional-changelog-preset-loader "^1.1.8" - -conventional-commits-filter@^1.1.6: - version "1.1.6" - resolved "https://registry.yarnpkg.com/conventional-commits-filter/-/conventional-commits-filter-1.1.6.tgz#4389cd8e58fe89750c0b5fb58f1d7f0cc8ad3831" - integrity sha512-KcDgtCRKJCQhyk6VLT7zR+ZOyCnerfemE/CsR3iQpzRRFbLEs0Y6rwk3mpDvtOh04X223z+1xyJ582Stfct/0Q== - dependencies: - is-subset "^0.1.1" - modify-values "^1.0.0" - -conventional-commits-parser@^2.1.7: - version "2.1.7" - resolved "https://registry.yarnpkg.com/conventional-commits-parser/-/conventional-commits-parser-2.1.7.tgz#eca45ed6140d72ba9722ee4132674d639e644e8e" - integrity sha512-BoMaddIEJ6B4QVMSDu9IkVImlGOSGA1I2BQyOZHeLQ6qVOJLcLKn97+fL6dGbzWEiqDzfH4OkcveULmeq2MHFQ== - dependencies: - JSONStream "^1.0.4" - is-text-path "^1.0.0" - lodash "^4.2.1" - meow "^4.0.0" - split2 "^2.0.0" - through2 "^2.0.0" - trim-off-newlines "^1.0.0" - -conventional-commits-parser@^3.0.0: - version "3.0.7" - resolved "https://registry.yarnpkg.com/conventional-commits-parser/-/conventional-commits-parser-3.0.7.tgz#55b6cde6a2d0b4a7ab399392777d527134a8d05c" - integrity sha512-4mx/FRC92z0yIiXGyRVYQFhn0jWDwvxnj2UuLaUi3hJSG4Thall6GXA8YOPHQK2qvotciJandJIVmuSvLgDLbQ== - dependencies: - JSONStream "^1.0.4" - is-text-path "^1.0.1" - lodash "^4.17.15" - meow "^4.0.0" - split2 "^2.0.0" - through2 "^3.0.0" - trim-off-newlines "^1.0.0" - -convert-source-map@^1.5.0, convert-source-map@^1.5.1, convert-source-map@^1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" - integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== - dependencies: - safe-buffer "~5.1.1" - -cookie-signature@1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" - integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw= - -cookie@0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb" - integrity sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s= - -cookie@0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba" - integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg== - -cookies@0.7.3: - version "0.7.3" - resolved "https://registry.yarnpkg.com/cookies/-/cookies-0.7.3.tgz#7912ce21fbf2e8c2da70cf1c3f351aecf59dadfa" - integrity sha512-+gixgxYSgQLTaTIilDHAdlNPZDENDQernEMiIcZpYYP14zgHsCt4Ce1FEjFtcp6GefhozebB6orvhAAWx/IS0A== - dependencies: - depd "~1.1.2" - keygrip "~1.0.3" - -copy-concurrently@^1.0.0: - version "1.0.5" - resolved "https://registry.yarnpkg.com/copy-concurrently/-/copy-concurrently-1.0.5.tgz#92297398cae34937fcafd6ec8139c18051f0b5e0" - integrity sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A== - dependencies: - aproba "^1.1.1" - fs-write-stream-atomic "^1.0.8" - iferr "^0.1.5" - mkdirp "^0.5.1" - rimraf "^2.5.4" - run-queue "^1.0.0" - -copy-descriptor@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" - integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= - -copy-webpack-plugin@5.0.5: - version "5.0.5" - resolved "https://registry.yarnpkg.com/copy-webpack-plugin/-/copy-webpack-plugin-5.0.5.tgz#731df6a837a2ef0f8f8e2345bdfe9b7c62a2da68" - integrity sha512-7N68eIoQTyudAuxkfPT7HzGoQ+TsmArN/I3HFwG+lVE3FNzqvZKIiaxtYh4o3BIznioxUvx9j26+Rtsc9htQUQ== - dependencies: - cacache "^12.0.3" - find-cache-dir "^2.1.0" - glob-parent "^3.1.0" - globby "^7.1.1" - is-glob "^4.0.1" - loader-utils "^1.2.3" - minimatch "^3.0.4" - normalize-path "^3.0.0" - p-limit "^2.2.1" - schema-utils "^1.0.0" - serialize-javascript "^2.1.0" - webpack-log "^2.0.0" - -core-js-compat@^3.1.1: - version "3.4.0" - resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.4.0.tgz#2a47c51d3dc026d290018cacd987495f68a47c75" - integrity sha512-pgQUcgT2+v9/yxHgMynYjNj7nmxLRXv3UC39rjCjDwpe63ev2rioQTju1PKLYUBbPCQQvZNWvQC8tBJd65q11g== - dependencies: - browserslist "^4.7.2" - semver "^6.3.0" - -core-js@3.4.1: - version "3.4.1" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.4.1.tgz#76dd6828412900ab27c8ce0b22e6114d7ce21b18" - integrity sha512-KX/dnuY/J8FtEwbnrzmAjUYgLqtk+cxM86hfG60LGiW3MmltIc2yAmDgBgEkfm0blZhUrdr1Zd84J2Y14mLxzg== - -core-js@^2.2.0, core-js@^2.4.0: - version "2.6.10" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.10.tgz#8a5b8391f8cc7013da703411ce5b585706300d7f" - integrity sha512-I39t74+4t+zau64EN1fE5v2W31Adtc/REhzWN+gWRRXg6WH5qAsZm62DHpQ1+Yhe4047T55jvzz7MUqF/dBBlA== - -core-util-is@1.0.2, core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= - -cors@2.8.5: - version "2.8.5" - resolved "https://registry.yarnpkg.com/cors/-/cors-2.8.5.tgz#eac11da51592dd86b9f06f6e7ac293b3df875d29" - integrity sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g== - dependencies: - object-assign "^4" - vary "^1" - -cosmiconfig@^5.0.0, cosmiconfig@^5.0.7: - version "5.2.1" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-5.2.1.tgz#040f726809c591e77a17c0a3626ca45b4f168b1a" - integrity sha512-H65gsXo1SKjf8zmrJ67eJk8aIRKV5ff2D4uKZIBZShbhGSpEmsQOPW/SKMKYhSTrqR7ufy6RP69rPogdaPh/kA== - dependencies: - import-fresh "^2.0.0" - is-directory "^0.3.1" - js-yaml "^3.13.1" - parse-json "^4.0.0" - -create-ecdh@^4.0.0: - version "4.0.3" - resolved "https://registry.yarnpkg.com/create-ecdh/-/create-ecdh-4.0.3.tgz#c9111b6f33045c4697f144787f9254cdc77c45ff" - integrity sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw== - dependencies: - bn.js "^4.1.0" - elliptic "^6.0.0" - -create-hash@^1.1.0, create-hash@^1.1.2: - version "1.2.0" - resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.2.0.tgz#889078af11a63756bcfb59bd221996be3a9ef196" - integrity sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg== - dependencies: - cipher-base "^1.0.1" - inherits "^2.0.1" - md5.js "^1.3.4" - ripemd160 "^2.0.1" - sha.js "^2.4.0" - -create-hmac@^1.1.0, create-hmac@^1.1.2, create-hmac@^1.1.4: - version "1.1.7" - resolved "https://registry.yarnpkg.com/create-hmac/-/create-hmac-1.1.7.tgz#69170c78b3ab957147b2b8b04572e47ead2243ff" - integrity sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg== - dependencies: - cipher-base "^1.0.3" - create-hash "^1.1.0" - inherits "^2.0.1" - ripemd160 "^2.0.0" - safe-buffer "^5.0.1" - sha.js "^2.4.8" - -cross-spawn@^4: - version "4.0.2" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-4.0.2.tgz#7b9247621c23adfdd3856004a823cbe397424d41" - integrity sha1-e5JHYhwjrf3ThWAEqCPL45dCTUE= - dependencies: - lru-cache "^4.0.1" - which "^1.2.9" - -cross-spawn@^5.0.1: - version "5.1.0" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" - integrity sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk= - dependencies: - lru-cache "^4.0.1" - shebang-command "^1.2.0" - which "^1.2.9" - -cross-spawn@^6.0.0: - version "6.0.5" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" - integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== - dependencies: - nice-try "^1.0.4" - path-key "^2.0.1" - semver "^5.5.0" - shebang-command "^1.2.0" - which "^1.2.9" - -crypto-browserify@^3.11.0: - version "3.12.0" - resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-3.12.0.tgz#396cf9f3137f03e4b8e532c58f698254e00f80ec" - integrity sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg== - dependencies: - browserify-cipher "^1.0.0" - browserify-sign "^4.0.0" - create-ecdh "^4.0.0" - create-hash "^1.1.0" - create-hmac "^1.1.0" - diffie-hellman "^5.0.0" - inherits "^2.0.1" - pbkdf2 "^3.0.3" - public-encrypt "^4.0.0" - randombytes "^2.0.0" - randomfill "^1.0.3" - -crypto-random-string@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-1.0.0.tgz#a230f64f568310e1498009940790ec99545bca7e" - integrity sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4= - -css-parse@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/css-parse/-/css-parse-2.0.0.tgz#a468ee667c16d81ccf05c58c38d2a97c780dbfd4" - integrity sha1-pGjuZnwW2BzPBcWMONKpfHgNv9Q= - dependencies: - css "^2.0.0" - -css-selector-tokenizer@^0.7.1: - version "0.7.1" - resolved "https://registry.yarnpkg.com/css-selector-tokenizer/-/css-selector-tokenizer-0.7.1.tgz#a177271a8bca5019172f4f891fc6eed9cbf68d5d" - integrity sha512-xYL0AMZJ4gFzJQsHUKa5jiWWi2vH77WVNg7JYRyewwj6oPh4yb/y6Y9ZCw9dsj/9UauMhtuxR+ogQd//EdEVNA== - dependencies: - cssesc "^0.1.0" - fastparse "^1.1.1" - regexpu-core "^1.0.0" - -css@^2.0.0: - version "2.2.4" - resolved "https://registry.yarnpkg.com/css/-/css-2.2.4.tgz#c646755c73971f2bba6a601e2cf2fd71b1298929" - integrity sha512-oUnjmWpy0niI3x/mPL8dVEI1l7MnG3+HHyRPHf+YFSbK+svOhXpmSOcDURUh2aOCgl2grzrOPt1nHLuCVFULLw== - dependencies: - inherits "^2.0.3" - source-map "^0.6.1" - source-map-resolve "^0.5.2" - urix "^0.1.0" - -cssauron@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/cssauron/-/cssauron-1.4.0.tgz#a6602dff7e04a8306dc0db9a551e92e8b5662ad8" - integrity sha1-pmAt/34EqDBtwNuaVR6S6LVmKtg= - dependencies: - through X.X.X - -cssesc@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-0.1.0.tgz#c814903e45623371a0477b40109aaafbeeaddbb4" - integrity sha1-yBSQPkViM3GgR3tAEJqq++6t27Q= - -cssom@^0.4.1: - version "0.4.2" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.4.2.tgz#e2abd06e1267a7f2e5eccd7770c9ebe1bd88648b" - integrity sha512-fVXFVBr7JPDcgqa92UNr6HIpeMypyG/XVloB+512KH43Z2aum8ZNVzRapWR4mZ/f2UlRMymIoDO3aFJmQ6Y3RA== - -cssom@~0.3.6: - version "0.3.8" - resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.3.8.tgz#9f1276f5b2b463f2114d3f2c75250af8c1a36f4a" - integrity sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg== - -cssstyle@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/cssstyle/-/cssstyle-2.0.0.tgz#911f0fe25532db4f5d44afc83f89cc4b82c97fe3" - integrity sha512-QXSAu2WBsSRXCPjvI43Y40m6fMevvyRm8JVAuF9ksQz5jha4pWP1wpaK7Yu5oLFc6+XAY+hj8YhefyXcBB53gg== - dependencies: - cssom "~0.3.6" - -cuint@^0.2.2: - version "0.2.2" - resolved "https://registry.yarnpkg.com/cuint/-/cuint-0.2.2.tgz#408086d409550c2631155619e9fa7bcadc3b991b" - integrity sha1-QICG1AlVDCYxFVYZ6fp7ytw7mRs= - -currently-unhandled@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea" - integrity sha1-mI3zP+qxke95mmE2nddsF635V+o= - dependencies: - array-find-index "^1.0.1" - -custom-event@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/custom-event/-/custom-event-1.0.1.tgz#5d02a46850adf1b4a317946a3928fccb5bfd0425" - integrity sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU= - -cyclist@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/cyclist/-/cyclist-1.0.1.tgz#596e9698fd0c80e12038c2b82d6eb1b35b6224d9" - integrity sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk= - -damerau-levenshtein@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/damerau-levenshtein/-/damerau-levenshtein-1.0.5.tgz#780cf7144eb2e8dbd1c3bb83ae31100ccc31a414" - integrity sha512-CBCRqFnpu715iPmw1KrdOrzRqbdFwQTwAWyyyYS42+iAgHCuXZ+/TdMgQkUENPomxEz9z1BEzuQU2Xw0kUuAgA== - -dargs@^4.0.1: - version "4.1.0" - resolved "https://registry.yarnpkg.com/dargs/-/dargs-4.1.0.tgz#03a9dbb4b5c2f139bf14ae53f0b8a2a6a86f4e17" - integrity sha1-A6nbtLXC8Tm/FK5T8LiipqhvThc= - dependencies: - number-is-nan "^1.0.0" - -dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - integrity sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA= - dependencies: - assert-plus "^1.0.0" - -data-urls@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-1.1.0.tgz#15ee0582baa5e22bb59c77140da8f9c76963bbfe" - integrity sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ== - dependencies: - abab "^2.0.0" - whatwg-mimetype "^2.2.0" - whatwg-url "^7.0.0" - -date-format@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/date-format/-/date-format-1.2.0.tgz#615e828e233dd1ab9bb9ae0950e0ceccfa6ecad8" - integrity sha1-YV6CjiM90aubua4JUODOzPpuytg= - -date-format@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/date-format/-/date-format-2.1.0.tgz#31d5b5ea211cf5fd764cd38baf9d033df7e125cf" - integrity sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA== - -dateformat@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae" - integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q== - -dayjs@1.8.16: - version "1.8.16" - resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.8.16.tgz#2a3771de537255191b947957af2fd90012e71e64" - integrity sha512-XPmqzWz/EJiaRHjBqSJ2s6hE/BUoCIHKgdS2QPtTQtKcS9E4/Qn0WomoH1lXanWCzri+g7zPcuNV4aTZ8PMORQ== - -debug@2.6.9, debug@^2.2.0, debug@^2.3.3, debug@^2.6.8: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== - dependencies: - ms "2.0.0" - -debug@3.1.0, debug@~3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" - integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g== - dependencies: - ms "2.0.0" - -debug@^3.0.0, debug@^3.1.0, debug@^3.1.1, debug@^3.2.5, debug@^3.2.6: - version "3.2.6" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" - integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== - dependencies: - ms "^2.1.1" - -debug@^4.1.0, debug@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" - integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== - dependencies: - ms "^2.1.1" - -debuglog@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/debuglog/-/debuglog-1.0.1.tgz#aa24ffb9ac3df9a2351837cfb2d279360cd78492" - integrity sha1-qiT/uaw9+aI1GDfPstJ5NgzXhJI= - -decamelize-keys@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.0.tgz#d171a87933252807eb3cb61dc1c1445d078df2d9" - integrity sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk= - dependencies: - decamelize "^1.1.0" - map-obj "^1.0.0" - -decamelize@^1.1.0, decamelize@^1.1.1, decamelize@^1.1.2, decamelize@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" - integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= - -decode-uri-component@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" - integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= - -decompress-response@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-3.3.0.tgz#80a4dd323748384bfa248083622aedec982adff3" - integrity sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M= - dependencies: - mimic-response "^1.0.0" - -deep-equal@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-1.1.0.tgz#3103cdf8ab6d32cf4a8df7865458f2b8d33f3745" - integrity sha512-ZbfWJq/wN1Z273o7mUSjILYqehAktR2NVoSrOukDkU9kg2v/Uv89yU4Cvz8seJeAmtN5oqiefKq8FPuXOboqLw== - dependencies: - is-arguments "^1.0.4" - is-date-object "^1.0.1" - is-regex "^1.0.4" - object-is "^1.0.1" - object-keys "^1.1.1" - regexp.prototype.flags "^1.2.0" - -deep-extend@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" - integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== - -deep-is@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" - integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= - -default-gateway@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/default-gateway/-/default-gateway-4.2.0.tgz#167104c7500c2115f6dd69b0a536bb8ed720552b" - integrity sha512-h6sMrVB1VMWVrW13mSc6ia/DwYYw5MN6+exNu1OaJeFac5aSAvwM7lZ0NVfTABuSkQelr4h5oebg3KB1XPdjgA== - dependencies: - execa "^1.0.0" - ip-regex "^2.1.0" - -default-require-extensions@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/default-require-extensions/-/default-require-extensions-2.0.0.tgz#f5f8fbb18a7d6d50b21f641f649ebb522cfe24f7" - integrity sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc= - dependencies: - strip-bom "^3.0.0" - -defaults@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.3.tgz#c656051e9817d9ff08ed881477f3fe4019f3ef7d" - integrity sha1-xlYFHpgX2f8I7YgUd/P+QBnz730= - dependencies: - clone "^1.0.2" - -defer-to-connect@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-1.1.0.tgz#b41bd7efa8508cef13f8456975f7a278c72833fd" - integrity sha512-WE2sZoctWm/v4smfCAdjYbrfS55JiMRdlY9ZubFhsYbteCK9+BvAx4YV7nPjYM6ZnX5BcoVKwfmyx9sIFTgQMQ== - -deferred-leveldown@~5.3.0: - version "5.3.0" - resolved "https://registry.yarnpkg.com/deferred-leveldown/-/deferred-leveldown-5.3.0.tgz#27a997ad95408b61161aa69bd489b86c71b78058" - integrity sha512-a59VOT+oDy7vtAbLRCZwWgxu2BaCfd5Hk7wxJd48ei7I+nsg8Orlb9CLG0PMZienk9BSUKgeAqkO2+Lw+1+Ukw== - dependencies: - abstract-leveldown "~6.2.1" - inherits "^2.0.3" - -define-properties@^1.1.2, define-properties@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" - integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== - dependencies: - object-keys "^1.0.12" - -define-property@^0.2.5: - version "0.2.5" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" - integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= - dependencies: - is-descriptor "^0.1.0" - -define-property@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" - integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= - dependencies: - is-descriptor "^1.0.0" - -define-property@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" - integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== - dependencies: - is-descriptor "^1.0.2" - isobject "^3.0.1" - -del@^2.2.0: - version "2.2.2" - resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" - integrity sha1-wSyYHQZ4RshLyvhiz/kw2Qf/0ag= - dependencies: - globby "^5.0.0" - is-path-cwd "^1.0.0" - is-path-in-cwd "^1.0.0" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - rimraf "^2.2.8" - -del@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/del/-/del-4.1.1.tgz#9e8f117222ea44a31ff3a156c049b99052a9f0b4" - integrity sha512-QwGuEUouP2kVwQenAsOof5Fv8K9t3D8Ca8NxcXKrIpEHjTXK5J2nXLdP+ALI1cgv8wj7KuwBhTwBkOZSJKM5XQ== - dependencies: - "@types/glob" "^7.1.1" - globby "^6.1.0" - is-path-cwd "^2.0.0" - is-path-in-cwd "^2.0.0" - p-map "^2.0.0" - pify "^4.0.1" - rimraf "^2.6.3" - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= - -delegates@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" - integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o= - -depd@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" - integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak= - -dependency-graph@^0.7.2: - version "0.7.2" - resolved "https://registry.yarnpkg.com/dependency-graph/-/dependency-graph-0.7.2.tgz#91db9de6eb72699209d88aea4c1fd5221cac1c49" - integrity sha512-KqtH4/EZdtdfWX0p6MGP9jljvxSY6msy/pRUD4jgNwVpv3v1QmNLlsB3LDSSUg79BRVSn7jI1QPRtArGABovAQ== - -des.js@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/des.js/-/des.js-1.0.0.tgz#c074d2e2aa6a8a9a07dbd61f9a15c2cd83ec8ecc" - integrity sha1-wHTS4qpqipoH29YfmhXCzYPsjsw= - dependencies: - inherits "^2.0.1" - minimalistic-assert "^1.0.0" - -destroy@~1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.0.4.tgz#978857442c44749e4206613e37946205826abd80" - integrity sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA= - -detect-indent@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" - integrity sha1-920GQ1LN9Docts5hnE7jqUdd4gg= - dependencies: - repeating "^2.0.0" - -detect-libc@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" - integrity sha1-+hN8S9aY7fVc1c0CrFWfkaTEups= - -detect-node@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.0.4.tgz#014ee8f8f669c5c58023da64b8179c083a28c46c" - integrity sha512-ZIzRpLJrOj7jjP2miAtgqIfmzbxa4ZOr5jJc601zklsfEx9oTzmmj2nVpIPRpNlRTIh8lc1kyViIY7BWSGNmKw== - -dezalgo@^1.0.0: - version "1.0.3" - resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.3.tgz#7f742de066fc748bc8db820569dddce49bf0d456" - integrity sha1-f3Qt4Gb8dIvI24IFad3c5Jvw1FY= - dependencies: - asap "^2.0.0" - wrappy "1" - -di@^0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/di/-/di-0.0.1.tgz#806649326ceaa7caa3306d75d985ea2748ba913c" - integrity sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw= - -diff@^3.1.0, diff@^3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" - integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== - -diff@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.1.tgz#0c667cb467ebbb5cea7f14f135cc2dba7780a8ff" - integrity sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q== - -diffie-hellman@^5.0.0: - version "5.0.3" - resolved "https://registry.yarnpkg.com/diffie-hellman/-/diffie-hellman-5.0.3.tgz#40e8ee98f55a2149607146921c63e1ae5f3d2875" - integrity sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg== - dependencies: - bn.js "^4.1.0" - miller-rabin "^4.0.0" - randombytes "^2.0.0" - -dir-glob@^2.0.0: - version "2.2.2" - resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-2.2.2.tgz#fa09f0694153c8918b18ba0deafae94769fc50c4" - integrity sha512-f9LBi5QWzIW3I6e//uxZoLBlUt9kcp66qo0sSCxL6YZKc75R1c4MFCoe/LaZiBGmgujvQdxc5Bn3QhfyvK5Hsw== - dependencies: - path-type "^3.0.0" - -dns-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/dns-equal/-/dns-equal-1.0.0.tgz#b39e7f1da6eb0a75ba9c17324b34753c47e0654d" - integrity sha1-s55/HabrCnW6nBcySzR1PEfgZU0= - -dns-packet@^1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/dns-packet/-/dns-packet-1.3.1.tgz#12aa426981075be500b910eedcd0b47dd7deda5a" - integrity sha512-0UxfQkMhYAUaZI+xrNZOz/as5KgDU0M/fQ9b6SpkyLbk3GEswDi6PADJVaYJradtRVsRIlF1zLyOodbcTCDzUg== - dependencies: - ip "^1.1.0" - safe-buffer "^5.0.1" - -dns-txt@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/dns-txt/-/dns-txt-2.0.2.tgz#b91d806f5d27188e4ab3e7d107d881a1cc4642b6" - integrity sha1-uR2Ab10nGI5Ks+fRB9iBocxGQrY= - dependencies: - buffer-indexof "^1.0.0" - -dom-serialize@^2.2.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/dom-serialize/-/dom-serialize-2.2.1.tgz#562ae8999f44be5ea3076f5419dcd59eb43ac95b" - integrity sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs= - dependencies: - custom-event "~1.0.0" - ent "~2.2.0" - extend "^3.0.0" - void-elements "^2.0.0" - -domain-browser@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/domain-browser/-/domain-browser-1.2.0.tgz#3d31f50191a6749dd1375a7f522e823d42e54eda" - integrity sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA== - -domexception@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/domexception/-/domexception-1.0.1.tgz#937442644ca6a31261ef36e3ec677fe805582c90" - integrity sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug== - dependencies: - webidl-conversions "^4.0.2" - -domino@^2.1.2: - version "2.1.3" - resolved "https://registry.yarnpkg.com/domino/-/domino-2.1.3.tgz#0ca1ad02cbd316ebe2e99e0ac9fb0010407d4601" - integrity sha512-EwjTbUv1Q/RLQOdn9k7ClHutrQcWGsfXaRQNOnM/KgK4xDBoLFEcIRFuBSxAx13Vfa63X029gXYrNFrSy+DOSg== - -dompurify@2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-2.0.7.tgz#f8266ad38fe1602fb5b3222f31eedbf5c16c4fd5" - integrity sha512-S3O0lk6rFJtO01ZTzMollCOGg+WAtCwS3U5E2WSDY/x/sy7q70RjEC4Dmrih5/UqzLLB9XoKJ8KqwBxaNvBu4A== - -dot-prop@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/dot-prop/-/dot-prop-3.0.0.tgz#1b708af094a49c9a0e7dbcad790aba539dac1177" - integrity sha1-G3CK8JSknJoOfbyteQq6U52sEXc= - dependencies: - is-obj "^1.0.0" - -dot-prop@^4.1.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/dot-prop/-/dot-prop-4.2.0.tgz#1f19e0c2e1aa0e32797c49799f2837ac6af69c57" - integrity sha512-tUMXrxlExSW6U2EXiiKGSBVdYgtV8qlHL+C10TsW4PURY/ic+eaysnSkwB4kA/mBlCyy/IKDJ+Lc3wbWeaXtuQ== - dependencies: - is-obj "^1.0.0" - -dtrace-provider@~0.8: - version "0.8.8" - resolved "https://registry.yarnpkg.com/dtrace-provider/-/dtrace-provider-0.8.8.tgz#2996d5490c37e1347be263b423ed7b297fb0d97e" - integrity sha512-b7Z7cNtHPhH9EJhNNbbeqTcXB8LGFFZhq1PGgEvpeHlzd36bhbdTWoE/Ba/YguqpBSlAPKnARWhVlhunCMwfxg== - dependencies: - nan "^2.14.0" - -duplexer2@~0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.1.4.tgz#8b12dab878c0d69e3e7891051662a32fc6bddcc1" - integrity sha1-ixLauHjA1p4+eJEFFmKjL8a93ME= - dependencies: - readable-stream "^2.0.2" - -duplexer3@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2" - integrity sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI= - -duplexify@^3.4.2, duplexify@^3.6.0: - version "3.7.1" - resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.7.1.tgz#2a4df5317f6ccfd91f86d6fd25d8d8a103b88309" - integrity sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g== - dependencies: - end-of-stream "^1.0.0" - inherits "^2.0.1" - readable-stream "^2.0.0" - stream-shift "^1.0.0" - -ecc-jsbn@~0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz#3a83a904e54353287874c564b7549386849a98c9" - integrity sha1-OoOpBOVDUyh4dMVkt1SThoSamMk= - dependencies: - jsbn "~0.1.0" - safer-buffer "^2.1.0" - -ecdsa-sig-formatter@1.0.11: - version "1.0.11" - resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf" - integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ== - dependencies: - safe-buffer "^5.0.1" - -ee-first@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" - integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= - -electron-to-chromium@^1.3.295: - version "1.3.306" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.306.tgz#e8265301d053d5f74e36cb876486830261fbe946" - integrity sha512-frDqXvrIROoYvikSKTIKbHbzO6M3/qC6kCIt/1FOa9kALe++c4VAJnwjSFvf1tYLEUsP2n9XZ4XSCyqc3l7A/A== - -elliptic@^6.0.0: - version "6.5.1" - resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.1.tgz#c380f5f909bf1b9b4428d028cd18d3b0efd6b52b" - integrity sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg== - dependencies: - bn.js "^4.4.0" - brorand "^1.0.1" - hash.js "^1.0.0" - hmac-drbg "^1.0.0" - inherits "^2.0.1" - minimalistic-assert "^1.0.0" - minimalistic-crypto-utils "^1.0.0" - -emoji-regex@^7.0.1: - version "7.0.3" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" - integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== - -emoji-regex@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" - integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== - -emojis-list@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-2.1.0.tgz#4daa4d9db00f9819880c79fa457ae5b09a1fd389" - integrity sha1-TapNnbAPmBmIDHn6RXrlsJof04k= - -encodeurl@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" - integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= - -encoding-down@^6.3.0: - version "6.3.0" - resolved "https://registry.yarnpkg.com/encoding-down/-/encoding-down-6.3.0.tgz#b1c4eb0e1728c146ecaef8e32963c549e76d082b" - integrity sha512-QKrV0iKR6MZVJV08QY0wp1e7vF6QbhnbQhb07bwpEyuz4uZiZgPlEGdkCROuFkUwdxlFaiPIhjyarH1ee/3vhw== - dependencies: - abstract-leveldown "^6.2.1" - inherits "^2.0.3" - level-codec "^9.0.0" - level-errors "^2.0.0" - -encoding@^0.1.12: - version "0.1.12" - resolved "https://registry.yarnpkg.com/encoding/-/encoding-0.1.12.tgz#538b66f3ee62cd1ab51ec323829d1f9480c74beb" - integrity sha1-U4tm8+5izRq1HsMjgp0flIDHS+s= - dependencies: - iconv-lite "~0.4.13" - -end-of-stream@^1.0.0, end-of-stream@^1.1.0: - version "1.4.4" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" - integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== - dependencies: - once "^1.4.0" - -engine.io-client@~3.2.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/engine.io-client/-/engine.io-client-3.2.1.tgz#6f54c0475de487158a1a7c77d10178708b6add36" - integrity sha512-y5AbkytWeM4jQr7m/koQLc5AxpRKC1hEVUb/s1FUAWEJq5AzJJ4NLvzuKPuxtDi5Mq755WuDvZ6Iv2rXj4PTzw== - dependencies: - component-emitter "1.2.1" - component-inherit "0.0.3" - debug "~3.1.0" - engine.io-parser "~2.1.1" - has-cors "1.1.0" - indexof "0.0.1" - parseqs "0.0.5" - parseuri "0.0.5" - ws "~3.3.1" - xmlhttprequest-ssl "~1.5.4" - yeast "0.1.2" - -engine.io-parser@~2.1.0, engine.io-parser@~2.1.1: - version "2.1.3" - resolved "https://registry.yarnpkg.com/engine.io-parser/-/engine.io-parser-2.1.3.tgz#757ab970fbf2dfb32c7b74b033216d5739ef79a6" - integrity sha512-6HXPre2O4Houl7c4g7Ic/XzPnHBvaEmN90vtRO9uLmwtRqQmTOw0QMevL1TOfL2Cpu1VzsaTmMotQgMdkzGkVA== - dependencies: - after "0.8.2" - arraybuffer.slice "~0.0.7" - base64-arraybuffer "0.1.5" - blob "0.0.5" - has-binary2 "~1.0.2" - -engine.io@~3.2.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/engine.io/-/engine.io-3.2.1.tgz#b60281c35484a70ee0351ea0ebff83ec8c9522a2" - integrity sha512-+VlKzHzMhaU+GsCIg4AoXF1UdDFjHHwMmMKqMJNDNLlUlejz58FCy4LBqB2YVJskHGYl06BatYWKP2TVdVXE5w== - dependencies: - accepts "~1.3.4" - base64id "1.0.0" - cookie "0.3.1" - debug "~3.1.0" - engine.io-parser "~2.1.0" - ws "~3.3.1" - -enhanced-resolve@4.1.1, enhanced-resolve@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.1.tgz#2937e2b8066cd0fe7ce0990a98f0d71a35189f66" - integrity sha512-98p2zE+rL7/g/DzMHMTF4zZlCgeVdJ7yr6xzEpJRYwFYrGi9ANdn5DnJURg6RpBkyk60XYDnWIv51VfIhfNGuA== - dependencies: - graceful-fs "^4.1.2" - memory-fs "^0.5.0" - tapable "^1.0.0" - -ent@~2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/ent/-/ent-2.2.0.tgz#e964219325a21d05f44466a2f686ed6ce5f5dd1d" - integrity sha1-6WQhkyWiHQX0RGai9obtbOX13R0= - -envinfo@7.4.0: - version "7.4.0" - resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.4.0.tgz#bef4ece9e717423aaf0c3584651430b735ad6630" - integrity sha512-FdDfnWnCVjxTTpWE3d6Jgh5JDIA3Cw7LCgpM/pI7kK1ORkjaqI2r6NqQ+ln2j0dfpgxY00AWieSvtkiZQKIItA== - -err-code@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/err-code/-/err-code-1.1.2.tgz#06e0116d3028f6aef4806849eb0ea6a748ae6960" - integrity sha1-BuARbTAo9q70gGhJ6w6mp0iuaWA= - -errno@^0.1.1, errno@^0.1.3, errno@~0.1.1, errno@~0.1.7: - version "0.1.7" - resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" - integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== - dependencies: - prr "~1.0.1" - -error-ex@^1.2.0, error-ex@^1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" - integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== - dependencies: - is-arrayish "^0.2.1" - -es-abstract@^1.5.1: - version "1.16.0" - resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.16.0.tgz#d3a26dc9c3283ac9750dca569586e976d9dcc06d" - integrity sha512-xdQnfykZ9JMEiasTAJZJdMWCQ1Vm00NBw79/AWi7ELfZuuPCSOMDZbT9mkOfSctVtfhb+sAAzrm+j//GjjLHLg== - dependencies: - es-to-primitive "^1.2.0" - function-bind "^1.1.1" - has "^1.0.3" - has-symbols "^1.0.0" - is-callable "^1.1.4" - is-regex "^1.0.4" - object-inspect "^1.6.0" - object-keys "^1.1.1" - string.prototype.trimleft "^2.1.0" - string.prototype.trimright "^2.1.0" - -es-to-primitive@^1.2.0: - version "1.2.1" - resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" - integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== - dependencies: - is-callable "^1.1.4" - is-date-object "^1.0.1" - is-symbol "^1.0.2" - -es6-promise@^4.0.3: - version "4.2.8" - resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.8.tgz#4eb21594c972bc40553d276e510539143db53e0a" - integrity sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w== - -es6-promisify@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/es6-promisify/-/es6-promisify-5.0.0.tgz#5109d62f3e56ea967c4b63505aef08291c8a5203" - integrity sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM= - dependencies: - es6-promise "^4.0.3" - -escape-html@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" - integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= - -escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= - -escodegen@^1.11.1, escodegen@^1.8.1: - version "1.12.0" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.12.0.tgz#f763daf840af172bb3a2b6dd7219c0e17f7ff541" - integrity sha512-TuA+EhsanGcme5T3R0L80u4t8CpbXQjegRmf7+FPTJrtCTErXFeelblRgHQa1FofEzqYYJmJ/OqjTwREp9qgmg== - dependencies: - esprima "^3.1.3" - estraverse "^4.2.0" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.6.1" - -escodegen@~1.9.0: - version "1.9.1" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.9.1.tgz#dbae17ef96c8e4bedb1356f4504fa4cc2f7cb7e2" - integrity sha512-6hTjO1NAWkHnDk3OqQ4YrCuwwmGHL9S3nPlzBOUG/R44rda3wLNrfvQ5fkSGjyhHFKM7ALPKcKGrwvCLe0lC7Q== - dependencies: - esprima "^3.1.3" - estraverse "^4.2.0" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.6.1" - -eslint-scope@^4.0.3: - version "4.0.3" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.3.tgz#ca03833310f6889a3264781aa82e63eb9cfe7848" - integrity sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg== - dependencies: - esrecurse "^4.1.0" - estraverse "^4.1.1" - -esprima@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633" - integrity sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM= - -esprima@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" - integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== - -esrecurse@^4.1.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf" - integrity sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ== - dependencies: - estraverse "^4.1.0" - -estraverse@^4.1.0, estraverse@^4.1.1, estraverse@^4.2.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" - integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== - -estree-walker@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-0.6.1.tgz#53049143f40c6eb918b23671d1fe3219f3a1b362" - integrity sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w== - -esutils@^2.0.2: - version "2.0.3" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" - integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== - -etag@~1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" - integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc= - -eventemitter3@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.0.tgz#d65176163887ee59f386d64c82610b696a4a74eb" - integrity sha512-qerSRB0p+UDEssxTtm6EDKcE7W4OaoisfIMl4CngyEhjpYglocpNg6UEqCvemdGhosAsg4sO2dXJOdyBifPGCg== - -events@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/events/-/events-3.0.0.tgz#9a0a0dfaf62893d92b875b8f2698ca4114973e88" - integrity sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA== - -eventsource@^1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/eventsource/-/eventsource-1.0.7.tgz#8fbc72c93fcd34088090bc0a4e64f4b5cee6d8d0" - integrity sha512-4Ln17+vVT0k8aWq+t/bF5arcS3EpT9gYtW66EPacdj/mAFevznsnyoHLPy2BA8gbIQeIHoPsvwmfBftfcG//BQ== - dependencies: - original "^1.0.0" - -evp_bytestokey@^1.0.0, evp_bytestokey@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz#7fcbdb198dc71959432efe13842684e0525acb02" - integrity sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA== - dependencies: - md5.js "^1.3.4" - safe-buffer "^5.1.1" - -execa@^0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-0.7.0.tgz#944becd34cc41ee32a63a9faf27ad5a65fc59777" - integrity sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c= - dependencies: - cross-spawn "^5.0.1" - get-stream "^3.0.0" - is-stream "^1.1.0" - npm-run-path "^2.0.0" - p-finally "^1.0.0" - signal-exit "^3.0.0" - strip-eof "^1.0.0" - -execa@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8" - integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA== - dependencies: - cross-spawn "^6.0.0" - get-stream "^4.0.0" - is-stream "^1.1.0" - npm-run-path "^2.0.0" - p-finally "^1.0.0" - signal-exit "^3.0.0" - strip-eof "^1.0.0" - -exit@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" - integrity sha1-BjJjj42HfMghB9MKD/8aF8uhzQw= - -expand-brackets@^2.1.4: - version "2.1.4" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" - integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= - dependencies: - debug "^2.3.3" - define-property "^0.2.5" - extend-shallow "^2.0.1" - posix-character-classes "^0.1.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -express@4.17.1, express@^4.17.1: - version "4.17.1" - resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134" - integrity sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g== - dependencies: - accepts "~1.3.7" - array-flatten "1.1.1" - body-parser "1.19.0" - content-disposition "0.5.3" - content-type "~1.0.4" - cookie "0.4.0" - cookie-signature "1.0.6" - debug "2.6.9" - depd "~1.1.2" - encodeurl "~1.0.2" - escape-html "~1.0.3" - etag "~1.8.1" - finalhandler "~1.1.2" - fresh "0.5.2" - merge-descriptors "1.0.1" - methods "~1.1.2" - on-finished "~2.3.0" - parseurl "~1.3.3" - path-to-regexp "0.1.7" - proxy-addr "~2.0.5" - qs "6.7.0" - range-parser "~1.2.1" - safe-buffer "5.1.2" - send "0.17.1" - serve-static "1.14.1" - setprototypeof "1.1.1" - statuses "~1.5.0" - type-is "~1.6.18" - utils-merge "1.0.1" - vary "~1.1.2" - -extend-shallow@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" - integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= - dependencies: - is-extendable "^0.1.0" - -extend-shallow@^3.0.0, extend-shallow@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" - integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= - dependencies: - assign-symbols "^1.0.0" - is-extendable "^1.0.1" - -extend@^3.0.0, extend@~3.0.1, extend@~3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" - integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== - -external-editor@^3.0.3: - version "3.1.0" - resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" - integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== - dependencies: - chardet "^0.7.0" - iconv-lite "^0.4.24" - tmp "^0.0.33" - -extglob@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" - integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== - dependencies: - array-unique "^0.3.2" - define-property "^1.0.0" - expand-brackets "^2.1.4" - extend-shallow "^2.0.1" - fragment-cache "^0.2.1" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -extract-zip@^1.6.6: - version "1.6.7" - resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-1.6.7.tgz#a840b4b8af6403264c8db57f4f1a74333ef81fe9" - integrity sha1-qEC0uK9kAyZMjbV/Txp0Mz74H+k= - dependencies: - concat-stream "1.6.2" - debug "2.6.9" - mkdirp "0.5.1" - yauzl "2.4.1" - -extsprintf@1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - integrity sha1-lpGEQOMEGnpBT4xS48V06zw+HgU= - -extsprintf@^1.2.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" - integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8= - -falafel@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/falafel/-/falafel-2.1.0.tgz#96bb17761daba94f46d001738b3cedf3a67fe06c" - integrity sha1-lrsXdh2rqU9G0AFzizzt86Z/4Gw= - dependencies: - acorn "^5.0.0" - foreach "^2.0.5" - isarray "0.0.1" - object-keys "^1.0.6" - -fast-deep-equal@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614" - integrity sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ= - -fast-deep-equal@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz#7b05218ddf9667bf7f370bf7fdb2cb15fdd0aa49" - integrity sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk= - -fast-json-stable-stringify@2.0.0, fast-json-stable-stringify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" - integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I= - -fast-levenshtein@~2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= - -fastparse@^1.1.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/fastparse/-/fastparse-1.1.2.tgz#91728c5a5942eced8531283c79441ee4122c35a9" - integrity sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ== - -faye-websocket@^0.10.0: - version "0.10.0" - resolved "https://registry.yarnpkg.com/faye-websocket/-/faye-websocket-0.10.0.tgz#4e492f8d04dfb6f89003507f6edbf2d501e7c6f4" - integrity sha1-TkkvjQTftviQA1B/btvy1QHnxvQ= - dependencies: - websocket-driver ">=0.5.1" - -faye-websocket@~0.11.1: - version "0.11.3" - resolved "https://registry.yarnpkg.com/faye-websocket/-/faye-websocket-0.11.3.tgz#5c0e9a8968e8912c286639fde977a8b209f2508e" - integrity sha512-D2y4bovYpzziGgbHYtGCMjlJM36vAl/y+xUyn1C+FVx8szd1E+86KwVw6XvYSzOP8iMpm1X0I4xJD+QtUb36OA== - dependencies: - websocket-driver ">=0.5.1" - -fd-slicer@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65" - integrity sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU= - dependencies: - pend "~1.2.0" - -figgy-pudding@^3.4.1, figgy-pudding@^3.5.1: - version "3.5.1" - resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.1.tgz#862470112901c727a0e495a80744bd5baa1d6790" - integrity sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w== - -figures@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/figures/-/figures-3.1.0.tgz#4b198dd07d8d71530642864af2d45dd9e459c4ec" - integrity sha512-ravh8VRXqHuMvZt/d8GblBeqDMkdJMBdv/2KntFH+ra5MXkO7nxNKpzQ3n6QD/2da1kH0aWmNISdvhM7gl2gVg== - dependencies: - escape-string-regexp "^1.0.5" - -file-loader@4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/file-loader/-/file-loader-4.2.0.tgz#5fb124d2369d7075d70a9a5abecd12e60a95215e" - integrity sha512-+xZnaK5R8kBJrHK0/6HRlrKNamvVS5rjyuju+rnyxRGuwUJwpAMsVzUl5dz6rK8brkzjV6JpcFNjp6NqV0g1OQ== - dependencies: - loader-utils "^1.2.3" - schema-utils "^2.0.0" - -fileset@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/fileset/-/fileset-2.0.3.tgz#8e7548a96d3cc2327ee5e674168723a333bba2a0" - integrity sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA= - dependencies: - glob "^7.0.3" - minimatch "^3.0.3" - -fill-range@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" - integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= - dependencies: - extend-shallow "^2.0.1" - is-number "^3.0.0" - repeat-string "^1.6.1" - to-regex-range "^2.1.0" - -fill-range@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" - integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== - dependencies: - to-regex-range "^5.0.1" - -finalhandler@1.1.2, finalhandler@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.2.tgz#b7e7d000ffd11938d0fdb053506f6ebabe9f587d" - integrity sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA== - dependencies: - debug "2.6.9" - encodeurl "~1.0.2" - escape-html "~1.0.3" - on-finished "~2.3.0" - parseurl "~1.3.3" - statuses "~1.5.0" - unpipe "~1.0.0" - -find-cache-dir@3.1.0, find-cache-dir@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-3.1.0.tgz#9935894999debef4cf9f677fdf646d002c4cdecb" - integrity sha512-zw+EFiNBNPgI2NTrKkDd1xd7q0cs6wr/iWnr/oUkI0yF9K9GqQ+riIt4aiyFaaqpaWbxPrJXHI+QvmNUQbX+0Q== - dependencies: - commondir "^1.0.1" - make-dir "^3.0.0" - pkg-dir "^4.1.0" - -find-cache-dir@^2.0.0, find-cache-dir@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-2.1.0.tgz#8d0f94cd13fe43c6c7c261a0d86115ca918c05f7" - integrity sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ== - dependencies: - commondir "^1.0.1" - make-dir "^2.0.0" - pkg-dir "^3.0.0" - -find-parent-dir@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/find-parent-dir/-/find-parent-dir-0.3.0.tgz#33c44b429ab2b2f0646299c5f9f718f376ff8d54" - integrity sha1-M8RLQpqysvBkYpnF+fcY83b/jVQ= - -find-up@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" - integrity sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8= - dependencies: - path-exists "^2.0.0" - pinkie-promise "^2.0.0" - -find-up@^2.0.0, find-up@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" - integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= - dependencies: - locate-path "^2.0.0" - -find-up@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" - integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== - dependencies: - locate-path "^3.0.0" - -find-up@^4.0.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" - integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== - dependencies: - locate-path "^5.0.0" - path-exists "^4.0.0" - -flatted@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" - integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== - -flush-write-stream@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz#8dd7d873a1babc207d94ead0c2e0e44276ebf2e8" - integrity sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w== - dependencies: - inherits "^2.0.3" - readable-stream "^2.3.6" - -follow-redirects@^1.0.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.9.0.tgz#8d5bcdc65b7108fe1508649c79c12d732dcedb4f" - integrity sha512-CRcPzsSIbXyVDl0QI01muNDu69S8trU4jArW9LpOt2WtC6LyUJetcIrmfHsRBx7/Jb6GHJUiuqyYxPooFfNt6A== - dependencies: - debug "^3.0.0" - -font-awesome@^4.7.0: - version "4.7.0" - resolved "https://registry.yarnpkg.com/font-awesome/-/font-awesome-4.7.0.tgz#8fa8cf0411a1a31afd07b06d2902bb9fc815a133" - integrity sha1-j6jPBBGhoxr9B7BtKQK7n8gVoTM= - -for-in@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" - integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= - -foreach@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99" - integrity sha1-C+4AUBiusmDQo6865ljdATbsG5k= - -foreground-child@^1.5.6: - version "1.5.6" - resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-1.5.6.tgz#4fd71ad2dfde96789b980a5c0a295937cb2f5ce9" - integrity sha1-T9ca0t/elnibmApcCilZN8svXOk= - dependencies: - cross-spawn "^4" - signal-exit "^3.0.0" - -forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - integrity sha1-+8cfDEGt6zf5bFd60e1C2P2sypE= - -form-data@^2.5.0: - version "2.5.1" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.5.1.tgz#f2cbec57b5e59e23716e128fe44d4e5dd23895f4" - integrity sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA== - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.6" - mime-types "^2.1.12" - -form-data@~2.3.1, form-data@~2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6" - integrity sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ== - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.6" - mime-types "^2.1.12" - -forwarded@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.1.2.tgz#98c23dab1175657b8c0573e8ceccd91b0ff18c84" - integrity sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ= - -fragment-cache@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" - integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= - dependencies: - map-cache "^0.2.2" - -fresh@0.5.2: - version "0.5.2" - resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" - integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac= - -from2@^2.1.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/from2/-/from2-2.3.0.tgz#8bfb5502bde4a4d36cfdeea007fcca21d7e382af" - integrity sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8= - dependencies: - inherits "^2.0.1" - readable-stream "^2.0.0" - -fs-access@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/fs-access/-/fs-access-1.0.1.tgz#d6a87f262271cefebec30c553407fb995da8777a" - integrity sha1-1qh/JiJxzv6+wwxVNAf7mV2od3o= - dependencies: - null-check "^1.0.0" - -fs-extra@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9" - integrity sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw== - dependencies: - graceful-fs "^4.1.2" - jsonfile "^4.0.0" - universalify "^0.1.0" - -fs-extra@^8.1.0: - version "8.1.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" - integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== - dependencies: - graceful-fs "^4.2.0" - jsonfile "^4.0.0" - universalify "^0.1.0" - -fs-minipass@^1.2.5: - version "1.2.7" - resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-1.2.7.tgz#ccff8570841e7fe4265693da88936c55aed7f7c7" - integrity sha512-GWSSJGFy4e9GUeCcbIkED+bgAoFyj7XF1mV8rma3QW4NIqX9Kyx79N/PF61H5udOV3aY1IaMLs6pGbH71nlCTA== - dependencies: - minipass "^2.6.0" - -fs-minipass@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.0.0.tgz#a6415edab02fae4b9e9230bc87ee2e4472003cd1" - integrity sha512-40Qz+LFXmd9tzYVnnBmZvFfvAADfUA14TXPK1s7IfElJTIZ97rA8w4Kin7Wt5JBrC3ShnnFJO/5vPjPEeJIq9A== - dependencies: - minipass "^3.0.0" - -fs-write-stream-atomic@^1.0.8: - version "1.0.10" - resolved "https://registry.yarnpkg.com/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz#b47df53493ef911df75731e70a9ded0189db40c9" - integrity sha1-tH31NJPvkR33VzHnCp3tAYnbQMk= - dependencies: - graceful-fs "^4.1.2" - iferr "^0.1.5" - imurmurhash "^0.1.4" - readable-stream "1 || 2" - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= - -fsevents@^1.2.7: - version "1.2.9" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.9.tgz#3f5ed66583ccd6f400b5a00db6f7e861363e388f" - integrity sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw== - dependencies: - nan "^2.12.1" - node-pre-gyp "^0.12.0" - -fsevents@~2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.2.tgz#4c0a1fb34bc68e543b4b82a9ec392bfbda840805" - integrity sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA== - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -gauge@~2.7.3: - version "2.7.4" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7" - integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c= - dependencies: - aproba "^1.0.3" - console-control-strings "^1.0.0" - has-unicode "^2.0.0" - object-assign "^4.1.0" - signal-exit "^3.0.0" - string-width "^1.0.1" - strip-ansi "^3.0.1" - wide-align "^1.1.0" - -get-caller-file@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a" - integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w== - -get-caller-file@^2.0.1: - version "2.0.5" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" - integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== - -get-pkg-repo@^1.0.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/get-pkg-repo/-/get-pkg-repo-1.4.0.tgz#c73b489c06d80cc5536c2c853f9e05232056972d" - integrity sha1-xztInAbYDMVTbCyFP54FIyBWly0= - dependencies: - hosted-git-info "^2.1.4" - meow "^3.3.0" - normalize-package-data "^2.3.0" - parse-github-repo-url "^1.3.0" - through2 "^2.0.0" - -get-stdin@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe" - integrity sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4= - -get-stdin@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-6.0.0.tgz#9e09bf712b360ab9225e812048f71fde9c89657b" - integrity sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g== - -get-stream@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14" - integrity sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ= - -get-stream@^4.0.0, get-stream@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-4.1.0.tgz#c1b255575f3dc21d59bfc79cd3d2b46b1c3a54b5" - integrity sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w== - dependencies: - pump "^3.0.0" - -get-stream@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.1.0.tgz#01203cdc92597f9b909067c3e656cc1f4d3c4dc9" - integrity sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw== - dependencies: - pump "^3.0.0" - -get-value@^2.0.3, get-value@^2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" - integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= - -getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - integrity sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo= - dependencies: - assert-plus "^1.0.0" - -gh-got@^8.0.1: - version "8.1.0" - resolved "https://registry.yarnpkg.com/gh-got/-/gh-got-8.1.0.tgz#2378d07ac293f524549c75f8dc6f3604a885ab01" - integrity sha512-Jy7+73XqsAVeAtM5zA0dd+A7mmzkQVIzFuw3xRjFbPsQVqS+aeci8v8H1heOCAPlBYWED5ZYPhlYqZVXdD3Fmg== - dependencies: - got "^9.5.0" - -git-raw-commits@^1.3.6: - version "1.3.6" - resolved "https://registry.yarnpkg.com/git-raw-commits/-/git-raw-commits-1.3.6.tgz#27c35a32a67777c1ecd412a239a6c19d71b95aff" - integrity sha512-svsK26tQ8vEKnMshTDatSIQSMDdz8CxIIqKsvPqbtV23Etmw6VNaFAitu8zwZ0VrOne7FztwPyRLxK7/DIUTQg== - dependencies: - dargs "^4.0.1" - lodash.template "^4.0.2" - meow "^4.0.0" - split2 "^2.0.0" - through2 "^2.0.0" - -git-raw-commits@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/git-raw-commits/-/git-raw-commits-2.0.2.tgz#0ffdb5881e1f9d1ed73edbda47389614543afb99" - integrity sha512-HVvl6J3dx7CS9fWTtyZXA2ejhdq9p/GSU9EEVlJPb2pSgMuD7IWK3dERcUPsJj9SZrJJ6IIB+3Rsjx9FUDdE1Q== - dependencies: - dargs "^4.0.1" - lodash.template "^4.0.2" - meow "^4.0.0" - split2 "^2.0.0" - through2 "^3.0.0" - -git-remote-origin-url@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/git-remote-origin-url/-/git-remote-origin-url-2.0.0.tgz#5282659dae2107145a11126112ad3216ec5fa65f" - integrity sha1-UoJlna4hBxRaERJhEq0yFuxfpl8= - dependencies: - gitconfiglocal "^1.0.0" - pify "^2.3.0" - -git-semver-tags@^1.3.6: - version "1.3.6" - resolved "https://registry.yarnpkg.com/git-semver-tags/-/git-semver-tags-1.3.6.tgz#357ea01f7280794fe0927f2806bee6414d2caba5" - integrity sha512-2jHlJnln4D/ECk9FxGEBh3k44wgYdWjWDtMmJPaecjoRmxKo3Y1Lh8GMYuOPu04CHw86NTAODchYjC5pnpMQig== - dependencies: - meow "^4.0.0" - semver "^5.5.0" - -gitconfiglocal@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/gitconfiglocal/-/gitconfiglocal-1.0.0.tgz#41d045f3851a5ea88f03f24ca1c6178114464b9b" - integrity sha1-QdBF84UaXqiPA/JMocYXgRRGS5s= - dependencies: - ini "^1.3.2" - -glob-parent@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz#9e6af6299d8d3bd2bd40430832bd113df906c5ae" - integrity sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4= - dependencies: - is-glob "^3.1.0" - path-dirname "^1.0.0" - -glob-parent@~5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.0.tgz#5f4c1d1e748d30cd73ad2944b3577a81b081e8c2" - integrity sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw== - dependencies: - is-glob "^4.0.1" - -glob@7.1.2: - version "7.1.2" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - integrity sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@7.1.6, glob@^7.0.3, glob@^7.0.6, glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4: - version "7.1.6" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" - integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^6.0.1: - version "6.0.4" - resolved "https://registry.yarnpkg.com/glob/-/glob-6.0.4.tgz#0f08860f6a155127b2fadd4f9ce24b1aab6e4d22" - integrity sha1-DwiGD2oVUSey+t1PnOJLGqtuTSI= - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - -global-dirs@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/global-dirs/-/global-dirs-0.1.1.tgz#b319c0dd4607f353f3be9cca4c72fc148c49f445" - integrity sha1-sxnA3UYH81PzvpzKTHL8FIxJ9EU= - dependencies: - ini "^1.3.4" - -globals@^11.1.0: - version "11.12.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e" - integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== - -globals@^9.18.0: - version "9.18.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" - integrity sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ== - -globby@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" - integrity sha1-69hGZ8oNuzMLmbz8aOrCvFQ3Dg0= - dependencies: - array-union "^1.0.1" - arrify "^1.0.0" - glob "^7.0.3" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -globby@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-6.1.0.tgz#f5a6d70e8395e21c858fb0489d64df02424d506c" - integrity sha1-9abXDoOV4hyFj7BInWTfAkJNUGw= - dependencies: - array-union "^1.0.1" - glob "^7.0.3" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -globby@^7.1.1: - version "7.1.1" - resolved "https://registry.yarnpkg.com/globby/-/globby-7.1.1.tgz#fb2ccff9401f8600945dfada97440cca972b8680" - integrity sha1-+yzP+UAfhgCUXfral0QMypcrhoA= - dependencies: - array-union "^1.0.1" - dir-glob "^2.0.0" - glob "^7.1.2" - ignore "^3.3.5" - pify "^3.0.0" - slash "^1.0.0" - -got@^9.5.0, got@^9.6.0: - version "9.6.0" - resolved "https://registry.yarnpkg.com/got/-/got-9.6.0.tgz#edf45e7d67f99545705de1f7bbeeeb121765ed85" - integrity sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q== - dependencies: - "@sindresorhus/is" "^0.14.0" - "@szmarczak/http-timer" "^1.1.2" - cacheable-request "^6.0.0" - decompress-response "^3.3.0" - duplexer3 "^0.1.4" - get-stream "^4.1.0" - lowercase-keys "^1.0.1" - mimic-response "^1.0.1" - p-cancelable "^1.0.0" - to-readable-stream "^1.0.0" - url-parse-lax "^3.0.0" - -graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.2: - version "4.2.3" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" - integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ== - -handle-thing@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/handle-thing/-/handle-thing-2.0.0.tgz#0e039695ff50c93fc288557d696f3c1dc6776754" - integrity sha512-d4sze1JNC454Wdo2fkuyzCr6aHcbL6PGGuFAz0Li/NcOm1tCHGnWDRmJP85dh9IhQErTc2svWFEX5xHIOo//kQ== - -handlebars@4.3.1: - version "4.3.1" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.3.1.tgz#6febc1890851f62a8932d495cc88d29390fa850d" - integrity sha512-c0HoNHzDiHpBt4Kqe99N8tdLPKAnGCQ73gYMPWtAYM4PwGnf7xl8PBUHJqh9ijlzt2uQKaSRxbXRt+rZ7M2/kA== - dependencies: - neo-async "^2.6.0" - optimist "^0.6.1" - source-map "^0.6.1" - optionalDependencies: - uglify-js "^3.1.4" - -handlebars@^4.0.2, handlebars@^4.0.3, handlebars@^4.1.2: - version "4.5.1" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.5.1.tgz#8a01c382c180272260d07f2d1aa3ae745715c7ba" - integrity sha512-C29UoFzHe9yM61lOsIlCE5/mQVGrnIOrOq7maQl76L7tYPCgC1og0Ajt6uWnX4ZTxBPnjw+CUvawphwCfJgUnA== - dependencies: - neo-async "^2.6.0" - optimist "^0.6.1" - source-map "^0.6.1" - optionalDependencies: - uglify-js "^3.1.4" - -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI= - -har-validator@~5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" - integrity sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0= - dependencies: - ajv "^5.1.0" - har-schema "^2.0.0" - -har-validator@~5.1.0: - version "5.1.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.3.tgz#1ef89ebd3e4996557675eed9893110dc350fa080" - integrity sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g== - dependencies: - ajv "^6.5.5" - har-schema "^2.0.0" - -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE= - dependencies: - ansi-regex "^2.0.0" - -has-binary2@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has-binary2/-/has-binary2-1.0.3.tgz#7776ac627f3ea77250cfc332dab7ddf5e4f5d11d" - integrity sha512-G1LWKhDSvhGeAQ8mPVQlqNcOB2sJdwATtZKl2pDKKHfpf/rYj24lkinxf69blJbnsvtqqNU+L3SL50vzZhXOnw== - dependencies: - isarray "2.0.1" - -has-cors@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/has-cors/-/has-cors-1.1.0.tgz#5e474793f7ea9843d1bb99c23eef49ff126fff39" - integrity sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk= - -has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - integrity sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo= - -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= - -has-flag@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" - integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== - -has-symbols@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" - integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= - -has-unicode@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" - integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk= - -has-value@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" - integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= - dependencies: - get-value "^2.0.3" - has-values "^0.1.4" - isobject "^2.0.0" - -has-value@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" - integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= - dependencies: - get-value "^2.0.6" - has-values "^1.0.0" - isobject "^3.0.0" - -has-values@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" - integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= - -has-values@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" - integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= - dependencies: - is-number "^3.0.0" - kind-of "^4.0.0" - -has-yarn@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/has-yarn/-/has-yarn-2.1.0.tgz#137e11354a7b5bf11aa5cb649cf0c6f3ff2b2e77" - integrity sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw== - -has@^1.0.1, has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - -hash-base@^3.0.0: - version "3.0.4" - resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-3.0.4.tgz#5fc8686847ecd73499403319a6b0a3f3f6ae4918" - integrity sha1-X8hoaEfs1zSZQDMZprCj8/auSRg= - dependencies: - inherits "^2.0.1" - safe-buffer "^5.0.1" - -hash.js@^1.0.0, hash.js@^1.0.3: - version "1.1.7" - resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42" - integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA== - dependencies: - inherits "^2.0.3" - minimalistic-assert "^1.0.1" - -hmac-drbg@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" - integrity sha1-0nRXAQJabHdabFRXk+1QL8DGSaE= - dependencies: - hash.js "^1.0.3" - minimalistic-assert "^1.0.0" - minimalistic-crypto-utils "^1.0.1" - -hosted-git-info@^2.1.4, hosted-git-info@^2.7.1: - version "2.8.5" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.5.tgz#759cfcf2c4d156ade59b0b2dfabddc42a6b9c70c" - integrity sha512-kssjab8CvdXfcXMXVcvsXum4Hwdq9XGtRD3TteMEvEbq0LXyiNQr6AprqKqfeaDXze7SxWvRxdpwE6ku7ikLkg== - -hosted-git-info@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-3.0.2.tgz#8b7e3bd114b59b51786f8bade0f39ddc80275a97" - integrity sha512-ezZMWtHXm7Eb7Rq4Mwnx2vs79WUx2QmRg3+ZqeGroKzfDO+EprOcgRPYghsOP9JuYBfK18VojmRTGCg8Ma+ktw== - dependencies: - lru-cache "^5.1.1" - -hpack.js@^2.1.6: - version "2.1.6" - resolved "https://registry.yarnpkg.com/hpack.js/-/hpack.js-2.1.6.tgz#87774c0949e513f42e84575b3c45681fade2a0b2" - integrity sha1-h3dMCUnlE/QuhFdbPEVoH63ioLI= - dependencies: - inherits "^2.0.1" - obuf "^1.0.0" - readable-stream "^2.0.1" - wbuf "^1.1.0" - -html-encoding-sniffer@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz#e70d84b94da53aa375e11fe3a351be6642ca46f8" - integrity sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw== - dependencies: - whatwg-encoding "^1.0.1" - -html-entities@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/html-entities/-/html-entities-1.2.1.tgz#0df29351f0721163515dfb9e5543e5f6eed5162f" - integrity sha1-DfKTUfByEWNRXfueVUPl9u7VFi8= - -http-cache-semantics@^3.8.1: - version "3.8.1" - resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-3.8.1.tgz#39b0e16add9b605bf0a9ef3d9daaf4843b4cacd2" - integrity sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w== - -http-cache-semantics@^4.0.0: - version "4.0.3" - resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.0.3.tgz#495704773277eeef6e43f9ab2c2c7d259dda25c5" - integrity sha512-TcIMG3qeVLgDr1TEd2XvHaTnMPwYQUQMIBLy+5pLSDKYFc7UIqj39w8EGzZkaxoLv/l2K8HaI0t5AVA+YYgUew== - -http-deceiver@^1.2.7: - version "1.2.7" - resolved "https://registry.yarnpkg.com/http-deceiver/-/http-deceiver-1.2.7.tgz#fa7168944ab9a519d337cb0bec7284dc3e723d87" - integrity sha1-+nFolEq5pRnTN8sL7HKE3D5yPYc= - -http-errors@1.7.2: - version "1.7.2" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.2.tgz#4f5029cf13239f31036e5b2e55292bcfbcc85c8f" - integrity sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg== - dependencies: - depd "~1.1.2" - inherits "2.0.3" - setprototypeof "1.1.1" - statuses ">= 1.5.0 < 2" - toidentifier "1.0.0" - -http-errors@1.7.3, http-errors@~1.7.2: - version "1.7.3" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.3.tgz#6c619e4f9c60308c38519498c14fbb10aacebb06" - integrity sha512-ZTTX0MWrsQ2ZAhA1cejAwDLycFsd7I7nVtnkT3Ol0aqodaKW+0CTZDQ1uBv5whptCnc8e8HeRRJxRs0kmm/Qfw== - dependencies: - depd "~1.1.2" - inherits "2.0.4" - setprototypeof "1.1.1" - statuses ">= 1.5.0 < 2" - toidentifier "1.0.0" - -http-errors@~1.6.2: - version "1.6.3" - resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d" - integrity sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0= - dependencies: - depd "~1.1.2" - inherits "2.0.3" - setprototypeof "1.1.0" - statuses ">= 1.4.0 < 2" - -"http-parser-js@>=0.4.0 <0.4.11": - version "0.4.10" - resolved "https://registry.yarnpkg.com/http-parser-js/-/http-parser-js-0.4.10.tgz#92c9c1374c35085f75db359ec56cc257cbb93fa4" - integrity sha1-ksnBN0w1CF912zWexWzCV8u5P6Q= - -http-proxy-agent@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz#e4821beef5b2142a2026bd73926fe537631c5405" - integrity sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg== - dependencies: - agent-base "4" - debug "3.1.0" - -http-proxy-middleware@0.19.1: - version "0.19.1" - resolved "https://registry.yarnpkg.com/http-proxy-middleware/-/http-proxy-middleware-0.19.1.tgz#183c7dc4aa1479150306498c210cdaf96080a43a" - integrity sha512-yHYTgWMQO8VvwNS22eLLloAkvungsKdKTLO8AJlftYIKNfJr3GK3zK0ZCfzDDGUBttdGc8xFy1mCitvNKQtC3Q== - dependencies: - http-proxy "^1.17.0" - is-glob "^4.0.0" - lodash "^4.17.11" - micromatch "^3.1.10" - -http-proxy@^1.13.0, http-proxy@^1.17.0: - version "1.18.0" - resolved "https://registry.yarnpkg.com/http-proxy/-/http-proxy-1.18.0.tgz#dbe55f63e75a347db7f3d99974f2692a314a6a3a" - integrity sha512-84I2iJM/n1d4Hdgc6y2+qY5mDaz2PUVjlg9znE9byl+q0uC3DeByqBGReQu5tpLK0TAqTIXScRUV+dg7+bUPpQ== - dependencies: - eventemitter3 "^4.0.0" - follow-redirects "^1.0.0" - requires-port "^1.0.0" - -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - integrity sha1-muzZJRFHcvPZW2WmCruPfBj7rOE= - dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - -http-status-codes@1.3.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/http-status-codes/-/http-status-codes-1.3.2.tgz#181dfa4455ef454e5e4d827718fca3936680d10d" - integrity sha512-nDUtj0ltIt08tGi2VWSpSzNNFye0v3YSe9lX3lIqLTuVvvRiYCvs4QQBSHo0eomFYw1wlUuofurUAlTm+vHnXg== - -https-browserify@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-1.0.0.tgz#ec06c10e0a34c0f2faf199f7fd7fc78fffd03c73" - integrity sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM= - -https-proxy-agent@^2.2.1, https-proxy-agent@^2.2.3: - version "2.2.4" - resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-2.2.4.tgz#4ee7a737abd92678a293d9b34a1af4d0d08c787b" - integrity sha512-OmvfoQ53WLjtA9HeYP9RNrWMJzzAz1JGaSFr1nijg0PVR1JaD/xbJq1mdEIIlxGpXp9eSe/O2LgU9DJmTPd0Eg== - dependencies: - agent-base "^4.3.0" - debug "^3.1.0" - -https-proxy-agent@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz#b8c286433e87602311b01c8ea34413d856a4af81" - integrity sha512-+ML2Rbh6DAuee7d07tYGEKOEi2voWPUGan+ExdPbPW6Z3svq+JCqr0v8WmKPOkz1vOVykPCBSuobe7G8GJUtVg== - dependencies: - agent-base "^4.3.0" - debug "^3.1.0" - -humanize-ms@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/humanize-ms/-/humanize-ms-1.2.1.tgz#c46e3159a293f6b896da29316d8b6fe8bb79bbed" - integrity sha1-xG4xWaKT9riW2ikxbYtv6Lt5u+0= - dependencies: - ms "^2.0.0" - -husky@^1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/husky/-/husky-1.3.1.tgz#26823e399300388ca2afff11cfa8a86b0033fae0" - integrity sha512-86U6sVVVf4b5NYSZ0yvv88dRgBSSXXmHaiq5pP4KDj5JVzdwKgBjEtUPOm8hcoytezFwbU+7gotXNhpHdystlg== - dependencies: - cosmiconfig "^5.0.7" - execa "^1.0.0" - find-up "^3.0.0" - get-stdin "^6.0.0" - is-ci "^2.0.0" - pkg-dir "^3.0.0" - please-upgrade-node "^3.1.1" - read-pkg "^4.0.1" - run-node "^1.0.0" - slash "^2.0.0" - -iconv-lite@0.4.24, iconv-lite@^0.4.24, iconv-lite@^0.4.4, iconv-lite@~0.4.13: - version "0.4.24" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" - integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== - dependencies: - safer-buffer ">= 2.1.2 < 3" - -ieee754@^1.1.4: - version "1.1.13" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.13.tgz#ec168558e95aa181fd87d37f55c32bbcb6708b84" - integrity sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg== - -iferr@^0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/iferr/-/iferr-0.1.5.tgz#c60eed69e6d8fdb6b3104a1fcbca1c192dc5b501" - integrity sha1-xg7taebY/bazEEofy8ocGS3FtQE= - -ignore-walk@^3.0.1: - version "3.0.3" - resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-3.0.3.tgz#017e2447184bfeade7c238e4aefdd1e8f95b1e37" - integrity sha512-m7o6xuOaT1aqheYHKf8W6J5pYH85ZI9w077erOzLje3JsB1gkafkAhHHY19dqjulgIZHFm32Cp5uNZgcQqdJKw== - dependencies: - minimatch "^3.0.4" - -ignore@^3.3.5: - version "3.3.10" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.10.tgz#0a97fb876986e8081c631160f8f9f389157f0043" - integrity sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug== - -image-size@~0.5.0: - version "0.5.5" - resolved "https://registry.yarnpkg.com/image-size/-/image-size-0.5.5.tgz#09dfd4ab9d20e29eb1c3e80b8990378df9e3cb9c" - integrity sha1-Cd/Uq50g4p6xw+gLiZA3jfnjy5w= - -immediate@~3.0.5: - version "3.0.6" - resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b" - integrity sha1-nbHb0Pr43m++D13V5Wu2BigN5ps= - -immediate@~3.2.3: - version "3.2.3" - resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.2.3.tgz#d140fa8f614659bd6541233097ddaac25cdd991c" - integrity sha1-0UD6j2FGWb1lQSMwl92qwlzdmRw= - -immutable@^3.8.2: - version "3.8.2" - resolved "https://registry.yarnpkg.com/immutable/-/immutable-3.8.2.tgz#c2439951455bb39913daf281376f1530e104adf3" - integrity sha1-wkOZUUVbs5kT2vKBN28VMOEErfM= - -import-cwd@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/import-cwd/-/import-cwd-2.1.0.tgz#aa6cf36e722761285cb371ec6519f53e2435b0a9" - integrity sha1-qmzzbnInYShcs3HsZRn1PiQ1sKk= - dependencies: - import-from "^2.1.0" - -import-fresh@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-2.0.0.tgz#d81355c15612d386c61f9ddd3922d4304822a546" - integrity sha1-2BNVwVYS04bGH53dOSLUMEgipUY= - dependencies: - caller-path "^2.0.0" - resolve-from "^3.0.0" - -import-from@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/import-from/-/import-from-2.1.0.tgz#335db7f2a7affd53aaa471d4b8021dee36b7f3b1" - integrity sha1-M1238qev/VOqpHHUuAId7ja387E= - dependencies: - resolve-from "^3.0.0" - -import-lazy@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/import-lazy/-/import-lazy-2.1.0.tgz#05698e3d45c88e8d7e9d92cb0584e77f096f3e43" - integrity sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM= - -import-local@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/import-local/-/import-local-2.0.0.tgz#55070be38a5993cf18ef6db7e961f5bee5c5a09d" - integrity sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ== - dependencies: - pkg-dir "^3.0.0" - resolve-cwd "^2.0.0" - -imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= - -indent-string@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80" - integrity sha1-ji1INIdCEhtKghi3oTfppSBJ3IA= - dependencies: - repeating "^2.0.0" - -indent-string@^3.0.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-3.2.0.tgz#4a5fd6d27cc332f37e5419a504dbb837105c9289" - integrity sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok= - -indent-string@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" - integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== - -indexof@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/indexof/-/indexof-0.0.1.tgz#82dc336d232b9062179d05ab3293a66059fd435d" - integrity sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10= - -infer-owner@^1.0.3, infer-owner@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/infer-owner/-/infer-owner-1.0.4.tgz#c4cefcaa8e51051c2a40ba2ce8a3d27295af9467" - integrity sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A== - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2, inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.1, inherits@~2.0.3: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -inherits@2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.1.tgz#b17d08d326b4423e568eff719f91b0b1cbdf69f1" - integrity sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE= - -inherits@2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" - integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4= - -ini@1.3.5, ini@^1.3.2, ini@^1.3.4, ini@~1.3.0: - version "1.3.5" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" - integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== - -injection-js@^2.2.1: - version "2.2.2" - resolved "https://registry.yarnpkg.com/injection-js/-/injection-js-2.2.2.tgz#5bfbeb951ab7bc8e1f359dea5d20e10ed4b84cef" - integrity sha512-9K4fW2NNPG3JCvORx5G/T6q/PZYIr43RFgxBvtk3OV4omh5iqvpK4cChuBfhgPnRbXSgZRfuROh0XG5KNA8Xlg== - -inquirer@7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.0.0.tgz#9e2b032dde77da1db5db804758b8fea3a970519a" - integrity sha512-rSdC7zelHdRQFkWnhsMu2+2SO41mpv2oF2zy4tMhmiLWkcKbOAs87fWAJhVXttKVwhdZvymvnuM95EyEXg2/tQ== - dependencies: - ansi-escapes "^4.2.1" - chalk "^2.4.2" - cli-cursor "^3.1.0" - cli-width "^2.0.0" - external-editor "^3.0.3" - figures "^3.0.0" - lodash "^4.17.15" - mute-stream "0.0.8" - run-async "^2.2.0" - rxjs "^6.4.0" - string-width "^4.1.0" - strip-ansi "^5.1.0" - through "^2.3.6" - -internal-ip@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/internal-ip/-/internal-ip-4.3.0.tgz#845452baad9d2ca3b69c635a137acb9a0dad0907" - integrity sha512-S1zBo1D6zcsyuC6PMmY5+55YMILQ9av8lotMx447Bq6SAgo/sDK6y6uUKmuYhW7eacnIhFfsPmCNYdDzsnnDCg== - dependencies: - default-gateway "^4.2.0" - ipaddr.js "^1.9.0" - -invariant@^2.2.2: - version "2.2.4" - resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" - integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== - dependencies: - loose-envify "^1.0.0" - -invert-kv@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-2.0.0.tgz#7393f5afa59ec9ff5f67a27620d11c226e3eec02" - integrity sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA== - -ip-regex@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-2.1.0.tgz#fa78bf5d2e6913c911ce9f819ee5146bb6d844e9" - integrity sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk= - -ip@1.1.5, ip@^1.1.0, ip@^1.1.5: - version "1.1.5" - resolved "https://registry.yarnpkg.com/ip/-/ip-1.1.5.tgz#bdded70114290828c0a039e72ef25f5aaec4354a" - integrity sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo= - -ipaddr.js@1.9.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.0.tgz#37df74e430a0e47550fe54a2defe30d8acd95f65" - integrity sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA== - -ipaddr.js@^1.9.0: - version "1.9.1" - resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" - integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== - -is-absolute-url@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/is-absolute-url/-/is-absolute-url-3.0.3.tgz#96c6a22b6a23929b11ea0afb1836c36ad4a5d698" - integrity sha512-opmNIX7uFnS96NtPmhWQgQx6/NYFgsUXYMllcfzwWKUMwfo8kku1TvE6hkNcH+Q1ts5cMVrsY7j0bxXQDciu9Q== - -is-accessor-descriptor@^0.1.6: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" - integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= - dependencies: - kind-of "^3.0.2" - -is-accessor-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" - integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== - dependencies: - kind-of "^6.0.0" - -is-arguments@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/is-arguments/-/is-arguments-1.0.4.tgz#3faf966c7cba0ff437fb31f6250082fcf0448cf3" - integrity sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA== - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= - -is-binary-path@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" - integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= - dependencies: - binary-extensions "^1.0.0" - -is-binary-path@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" - integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== - dependencies: - binary-extensions "^2.0.0" - -is-buffer@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" - integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== - -is-callable@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" - integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== - -is-ci@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c" - integrity sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w== - dependencies: - ci-info "^2.0.0" - -is-data-descriptor@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" - integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= - dependencies: - kind-of "^3.0.2" - -is-data-descriptor@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" - integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== - dependencies: - kind-of "^6.0.0" - -is-date-object@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" - integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= - -is-descriptor@^0.1.0: - version "0.1.6" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" - integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== - dependencies: - is-accessor-descriptor "^0.1.6" - is-data-descriptor "^0.1.4" - kind-of "^5.0.0" - -is-descriptor@^1.0.0, is-descriptor@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" - integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== - dependencies: - is-accessor-descriptor "^1.0.0" - is-data-descriptor "^1.0.0" - kind-of "^6.0.2" - -is-directory@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/is-directory/-/is-directory-0.3.1.tgz#61339b6f2475fc772fd9c9d83f5c8575dc154ae1" - integrity sha1-YTObbyR1/Hcv2cnYP1yFddwVSuE= - -is-extendable@^0.1.0, is-extendable@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" - integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= - -is-extendable@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" - integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== - dependencies: - is-plain-object "^2.0.4" - -is-extglob@^2.1.0, is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= - -is-finite@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" - integrity sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko= - dependencies: - number-is-nan "^1.0.0" - -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" - integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= - dependencies: - number-is-nan "^1.0.0" - -is-fullwidth-code-point@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" - integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= - -is-fullwidth-code-point@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" - integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== - -is-glob@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" - integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= - dependencies: - is-extglob "^2.1.0" - -is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" - integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== - dependencies: - is-extglob "^2.1.1" - -is-installed-globally@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.1.0.tgz#0dfd98f5a9111716dd535dda6492f67bf3d25a80" - integrity sha1-Df2Y9akRFxbdU13aZJL2e/PSWoA= - dependencies: - global-dirs "^0.1.0" - is-path-inside "^1.0.0" - -is-interactive@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" - integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== - -is-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-module/-/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591" - integrity sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE= - -is-npm@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-npm/-/is-npm-3.0.0.tgz#ec9147bfb629c43f494cf67936a961edec7e8053" - integrity sha512-wsigDr1Kkschp2opC4G3yA6r9EgVA6NjRpWzIi9axXqeIaAATPRJc4uLujXe3Nd9uO8KoDyA4MD6aZSeXTADhA== - -is-number@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" - integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= - dependencies: - kind-of "^3.0.2" - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - -is-obj@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" - integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= - -is-path-cwd@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" - integrity sha1-0iXsIxMuie3Tj9p2dHLmLmXxEG0= - -is-path-cwd@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-2.2.0.tgz#67d43b82664a7b5191fd9119127eb300048a9fdb" - integrity sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ== - -is-path-in-cwd@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz#5ac48b345ef675339bd6c7a48a912110b241cf52" - integrity sha512-FjV1RTW48E7CWM7eE/J2NJvAEEVektecDBVBE5Hh3nM1Jd0kvhHtX68Pr3xsDf857xt3Y4AkwVULK1Vku62aaQ== - dependencies: - is-path-inside "^1.0.0" - -is-path-in-cwd@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-2.1.0.tgz#bfe2dca26c69f397265a4009963602935a053acb" - integrity sha512-rNocXHgipO+rvnP6dk3zI20RpOtrAM/kzbB258Uw5BWr3TpXi861yzjo16Dn4hUox07iw5AyeMLHWsujkjzvRQ== - dependencies: - is-path-inside "^2.1.0" - -is-path-inside@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.1.tgz#8ef5b7de50437a3fdca6b4e865ef7aa55cb48036" - integrity sha1-jvW33lBDej/cprToZe96pVy0gDY= - dependencies: - path-is-inside "^1.0.1" - -is-path-inside@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-2.1.0.tgz#7c9810587d659a40d27bcdb4d5616eab059494b2" - integrity sha512-wiyhTzfDWsvwAW53OBWF5zuvaOGlZ6PwYxAbPVDhpm+gM09xKQGjBq/8uYN12aDvMxnAnq3dxTyoSoRNmg5YFg== - dependencies: - path-is-inside "^1.0.2" - -is-plain-obj@^1.0.0, is-plain-obj@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e" - integrity sha1-caUMhCnfync8kqOQpKA7OfzVHT4= - -is-plain-object@^2.0.3, is-plain-object@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" - integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== - dependencies: - isobject "^3.0.1" - -is-promise@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-2.1.0.tgz#79a2a9ece7f096e80f36d2b2f3bc16c1ff4bf3fa" - integrity sha1-eaKp7OfwlugPNtKy87wWwf9L8/o= - -is-reference@^1.1.2: - version "1.1.4" - resolved "https://registry.yarnpkg.com/is-reference/-/is-reference-1.1.4.tgz#3f95849886ddb70256a3e6d062b1a68c13c51427" - integrity sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw== - dependencies: - "@types/estree" "0.0.39" - -is-regex@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" - integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= - dependencies: - has "^1.0.1" - -is-stream@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" - integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ= - -is-subset@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/is-subset/-/is-subset-0.1.1.tgz#8a59117d932de1de00f245fcdd39ce43f1e939a6" - integrity sha1-ilkRfZMt4d4A8kX83TnOQ/HpOaY= - -is-symbol@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" - integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== - dependencies: - has-symbols "^1.0.0" - -is-text-path@^1.0.0, is-text-path@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-text-path/-/is-text-path-1.0.1.tgz#4e1aa0fb51bfbcb3e92688001397202c1775b66e" - integrity sha1-Thqg+1G/vLPpJogAE5cgLBd1tm4= - dependencies: - text-extensions "^1.0.0" - -is-typedarray@^1.0.0, is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo= - -is-utf8@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" - integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI= - -is-windows@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" - integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== - -is-wsl@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-1.1.0.tgz#1f16e4aa22b04d1336b66188a66af3c600c3a66d" - integrity sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0= - -is-wsl@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.1.1.tgz#4a1c152d429df3d441669498e2486d3596ebaf1d" - integrity sha512-umZHcSrwlDHo2TGMXv0DZ8dIUGunZ2Iv68YZnrmCiBPkZ4aaOhtv7pXJKeki9k3qJ3RJr0cDyitcl5wEH3AYog== - -is-yarn-global@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/is-yarn-global/-/is-yarn-global-0.3.0.tgz#d502d3382590ea3004893746754c89139973e232" - integrity sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw== - -isarray@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" - integrity sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8= - -isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= - -isarray@2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.1.tgz#a37d94ed9cda2d59865c9f76fe596ee1f338741e" - integrity sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4= - -isbinaryfile@^3.0.0: - version "3.0.3" - resolved "https://registry.yarnpkg.com/isbinaryfile/-/isbinaryfile-3.0.3.tgz#5d6def3edebf6e8ca8cae9c30183a804b5f8be80" - integrity sha512-8cJBL5tTd2OS0dM4jz07wQd5g0dCCqIhUxPIGtZfa5L6hWlvV5MHTITy/DBAsF+Oe2LS1X3krBUhNwaGUWpWxw== - dependencies: - buffer-alloc "^1.2.0" - -isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= - -isobject@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" - integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= - dependencies: - isarray "1.0.0" - -isobject@^3.0.0, isobject@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" - integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= - -isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - integrity sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo= - -istanbul-api@^2.1.6: - version "2.1.6" - resolved "https://registry.yarnpkg.com/istanbul-api/-/istanbul-api-2.1.6.tgz#d61702a9d1c66ad89d92e66d401e16b0bda4a35f" - integrity sha512-x0Eicp6KsShG1k1rMgBAi/1GgY7kFGEBwQpw3PXGEmu+rBcBNhqU8g2DgY9mlepAsLPzrzrbqSgCGANnki4POA== - dependencies: - async "^2.6.2" - compare-versions "^3.4.0" - fileset "^2.0.3" - istanbul-lib-coverage "^2.0.5" - istanbul-lib-hook "^2.0.7" - istanbul-lib-instrument "^3.3.0" - istanbul-lib-report "^2.0.8" - istanbul-lib-source-maps "^3.0.6" - istanbul-reports "^2.2.4" - js-yaml "^3.13.1" - make-dir "^2.1.0" - minimatch "^3.0.4" - once "^1.4.0" - -istanbul-instrumenter-loader@3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/istanbul-instrumenter-loader/-/istanbul-instrumenter-loader-3.0.1.tgz#9957bd59252b373fae5c52b7b5188e6fde2a0949" - integrity sha512-a5SPObZgS0jB/ixaKSMdn6n/gXSrK2S6q/UfRJBT3e6gQmVjwZROTODQsYW5ZNwOu78hG62Y3fWlebaVOL0C+w== - dependencies: - convert-source-map "^1.5.0" - istanbul-lib-instrument "^1.7.3" - loader-utils "^1.1.0" - schema-utils "^0.3.0" - -istanbul-lib-coverage@^1.2.0, istanbul-lib-coverage@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-1.2.1.tgz#ccf7edcd0a0bb9b8f729feeb0930470f9af664f0" - integrity sha512-PzITeunAgyGbtY1ibVIUiV679EFChHjoMNRibEIobvmrCRaIgwLxNucOSimtNWUhEib/oO7QY2imD75JVgCJWQ== - -istanbul-lib-coverage@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz#675f0ab69503fad4b1d849f736baaca803344f49" - integrity sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA== - -istanbul-lib-hook@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/istanbul-lib-hook/-/istanbul-lib-hook-2.0.7.tgz#c95695f383d4f8f60df1f04252a9550e15b5b133" - integrity sha512-vrRztU9VRRFDyC+aklfLoeXyNdTfga2EI3udDGn4cZ6fpSXpHLV9X6CHvfoMCPtggg8zvDDmC4b9xfu0z6/llA== - dependencies: - append-transform "^1.0.0" - -istanbul-lib-instrument@^1.7.3: - version "1.10.2" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-1.10.2.tgz#1f55ed10ac3c47f2bdddd5307935126754d0a9ca" - integrity sha512-aWHxfxDqvh/ZlxR8BBaEPVSWDPUkGD63VjGQn3jcw8jCp7sHEMKcrj4xfJn/ABzdMEHiQNyvDQhqm5o8+SQg7A== - dependencies: - babel-generator "^6.18.0" - babel-template "^6.16.0" - babel-traverse "^6.18.0" - babel-types "^6.18.0" - babylon "^6.18.0" - istanbul-lib-coverage "^1.2.1" - semver "^5.3.0" - -istanbul-lib-instrument@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz#a5f63d91f0bbc0c3e479ef4c5de027335ec6d630" - integrity sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA== - dependencies: - "@babel/generator" "^7.4.0" - "@babel/parser" "^7.4.3" - "@babel/template" "^7.4.0" - "@babel/traverse" "^7.4.3" - "@babel/types" "^7.4.0" - istanbul-lib-coverage "^2.0.5" - semver "^6.0.0" - -istanbul-lib-report@^1.1.3: - version "1.1.5" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-1.1.5.tgz#f2a657fc6282f96170aaf281eb30a458f7f4170c" - integrity sha512-UsYfRMoi6QO/doUshYNqcKJqVmFe9w51GZz8BS3WB0lYxAllQYklka2wP9+dGZeHYaWIdcXUx8JGdbqaoXRXzw== - dependencies: - istanbul-lib-coverage "^1.2.1" - mkdirp "^0.5.1" - path-parse "^1.0.5" - supports-color "^3.1.2" - -istanbul-lib-report@^2.0.8: - version "2.0.8" - resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz#5a8113cd746d43c4889eba36ab10e7d50c9b4f33" - integrity sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ== - dependencies: - istanbul-lib-coverage "^2.0.5" - make-dir "^2.1.0" - supports-color "^6.1.0" - -istanbul-lib-source-maps@^3.0.6: - version "3.0.6" - resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz#284997c48211752ec486253da97e3879defba8c8" - integrity sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw== - dependencies: - debug "^4.1.1" - istanbul-lib-coverage "^2.0.5" - make-dir "^2.1.0" - rimraf "^2.6.3" - source-map "^0.6.1" - -istanbul-reports@^1.3.0: - version "1.5.1" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-1.5.1.tgz#97e4dbf3b515e8c484caea15d6524eebd3ff4e1a" - integrity sha512-+cfoZ0UXzWjhAdzosCPP3AN8vvef8XDkWtTfgaN+7L3YTpNYITnCaEkceo5SEYy644VkHka/P1FvkWvrG/rrJw== - dependencies: - handlebars "^4.0.3" - -istanbul-reports@^2.2.4: - version "2.2.6" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-2.2.6.tgz#7b4f2660d82b29303a8fe6091f8ca4bf058da1af" - integrity sha512-SKi4rnMyLBKe0Jy2uUdx28h8oG7ph2PPuQPvIAh31d+Ci+lSiEu4C+h3oBPuJ9+mPKhOyW0M8gY4U5NM1WLeXA== - dependencies: - handlebars "^4.1.2" - -jasmine-core@2.8.0, jasmine-core@~2.8.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/jasmine-core/-/jasmine-core-2.8.0.tgz#bcc979ae1f9fd05701e45e52e65d3a5d63f1a24e" - integrity sha1-vMl5rh+f0FcB5F5S5l06XWPxok4= - -jasmine-core@^3.3, jasmine-core@~3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/jasmine-core/-/jasmine-core-3.5.0.tgz#132c23e645af96d85c8bca13c8758b18429fc1e4" - integrity sha512-nCeAiw37MIMA9w9IXso7bRaLl+c/ef3wnxsoSAlYrzS+Ot0zTG6nU8G/cIfGkqpkjX2wNaIW9RFG0TwIFnG6bA== - -jasmine-core@~3.4.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/jasmine-core/-/jasmine-core-3.4.0.tgz#2a74618e966026530c3518f03e9f845d26473ce3" - integrity sha512-HU/YxV4i6GcmiH4duATwAbJQMlE0MsDIR5XmSVxURxKHn3aGAdbY1/ZJFmVRbKtnLwIxxMJD7gYaPsypcbYimg== - -jasmine-spec-reporter@^4.2.1, jasmine-spec-reporter@~4.2.1: - version "4.2.1" - resolved "https://registry.yarnpkg.com/jasmine-spec-reporter/-/jasmine-spec-reporter-4.2.1.tgz#1d632aec0341670ad324f92ba84b4b32b35e9e22" - integrity sha512-FZBoZu7VE5nR7Nilzy+Np8KuVIOxF4oXDPDknehCYBDE080EnlPu0afdZNmpGDBRCUBv3mj5qgqCRmk6W/K8vg== - dependencies: - colors "1.1.2" - -jasmine@2.8.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/jasmine/-/jasmine-2.8.0.tgz#6b089c0a11576b1f16df11b80146d91d4e8b8a3e" - integrity sha1-awicChFXax8W3xG4AUbZHU6Lij4= - dependencies: - exit "^0.1.2" - glob "^7.0.6" - jasmine-core "~2.8.0" - -jasmine@^3.3.1: - version "3.5.0" - resolved "https://registry.yarnpkg.com/jasmine/-/jasmine-3.5.0.tgz#7101eabfd043a1fc82ac24e0ab6ec56081357f9e" - integrity sha512-DYypSryORqzsGoMazemIHUfMkXM7I7easFaxAvNM3Mr6Xz3Fy36TupTrAOxZWN8MVKEU5xECv22J4tUQf3uBzQ== - dependencies: - glob "^7.1.4" - jasmine-core "~3.5.0" - -jasmine@~3.4.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/jasmine/-/jasmine-3.4.0.tgz#0fa68903ff0c9697459cd044b44f4dcef5ec8bdc" - integrity sha512-sR9b4n+fnBFDEd7VS2el2DeHgKcPiMVn44rtKFumq9q7P/t8WrxsVIZPob4UDdgcDNCwyDqwxCt4k9TDRmjPoQ== - dependencies: - glob "^7.1.3" - jasmine-core "~3.4.0" - -jasminewd2@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/jasminewd2/-/jasminewd2-2.2.0.tgz#e37cf0b17f199cce23bea71b2039395246b4ec4e" - integrity sha1-43zwsX8ZnM4jvqcbIDk5Uka07E4= - -jest-worker@24.9.0, jest-worker@^24.9.0: - version "24.9.0" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-24.9.0.tgz#5dbfdb5b2d322e98567898238a9697bcce67b3e5" - integrity sha512-51PE4haMSXcHohnSMdM42anbvZANYTqMrr52tVKPqqsPJMzoP6FYYDVqahX/HrAoKEKz3uUPzSvKs9A3qR4iVw== - dependencies: - merge-stream "^2.0.0" - supports-color "^6.1.0" - -jquery@^3.3.1: - version "3.4.1" - resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.4.1.tgz#714f1f8d9dde4bdfa55764ba37ef214630d80ef2" - integrity sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw== - -js-base64@^2.4.3: - version "2.5.1" - resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-2.5.1.tgz#1efa39ef2c5f7980bb1784ade4a8af2de3291121" - integrity sha512-M7kLczedRMYX4L8Mdh4MzyAMM9O5osx+4FcOQuTvr3A9F2D9S5JXheN0ewNbrvK2UatkTRhL5ejGmGSjNMiZuw== - -js-levenshtein@^1.1.3: - version "1.1.6" - resolved "https://registry.yarnpkg.com/js-levenshtein/-/js-levenshtein-1.1.6.tgz#c6cee58eb3550372df8deb85fad5ce66ce01d59d" - integrity sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g== - -"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" - integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== - -js-tokens@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" - integrity sha1-mGbfOVECEw449/mWvOtlRDIJwls= - -js-yaml@3.13.1, js-yaml@^3.13.1: - version "3.13.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" - integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= - -jsdom@15.2.0: - version "15.2.0" - resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-15.2.0.tgz#4baead4f464e733533ed6ac607ce440918cf5cbb" - integrity sha512-+hRyEfjRPFwTYMmSQ3/f7U9nP8ZNZmbkmUek760ZpxnCPWJIhaaLRuUSvpJ36fZKCGENxLwxClzwpOpnXNfChQ== - dependencies: - abab "^2.0.0" - acorn "^7.1.0" - acorn-globals "^4.3.2" - array-equal "^1.0.0" - cssom "^0.4.1" - cssstyle "^2.0.0" - data-urls "^1.1.0" - domexception "^1.0.1" - escodegen "^1.11.1" - html-encoding-sniffer "^1.0.2" - nwsapi "^2.1.4" - parse5 "5.1.0" - pn "^1.1.0" - request "^2.88.0" - request-promise-native "^1.0.7" - saxes "^3.1.9" - symbol-tree "^3.2.2" - tough-cookie "^3.0.1" - w3c-hr-time "^1.0.1" - w3c-xmlserializer "^1.1.2" - webidl-conversions "^4.0.2" - whatwg-encoding "^1.0.5" - whatwg-mimetype "^2.3.0" - whatwg-url "^7.0.0" - ws "^7.0.0" - xml-name-validator "^3.0.0" - -jsesc@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" - integrity sha1-RsP+yMGJKxKwgz25vHYiF226s0s= - -jsesc@^2.5.1: - version "2.5.2" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" - integrity sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA== - -jsesc@~0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d" - integrity sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0= - -json-buffer@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.0.tgz#5b1f397afc75d677bde8bcfc0e47e1f9a3d9a898" - integrity sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg= - -json-parse-better-errors@^1.0.1, json-parse-better-errors@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" - integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== - -json-schema-traverse@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" - integrity sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A= - -json-schema-traverse@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" - integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== - -json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM= - -json-stringify-safe@^5.0.1, json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus= - -json3@^3.3.2: - version "3.3.3" - resolved "https://registry.yarnpkg.com/json3/-/json3-3.3.3.tgz#7fc10e375fc5ae42c4705a5cc0aa6f62be305b81" - integrity sha512-c7/8mbUsKigAbLkD5B010BK4D9LZm7A1pNItkEwiUZRpIN66exu/e7YQWysGun+TRKaJp8MhemM+VkfWv42aCA== - -json5@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.1.tgz#779fb0018604fa854eacbf6252180d83543e3dbe" - integrity sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow== - dependencies: - minimist "^1.2.0" - -json5@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.1.tgz#81b6cb04e9ba496f1c7005d07b4368a2638f90b6" - integrity sha512-l+3HXD0GEI3huGq1njuqtzYK8OYJyXMkOLtQ53pjWh89tvWS2h6l+1zMkYWqlb57+SiQodKZyvMEFb2X+KrFhQ== - dependencies: - minimist "^1.2.0" - -jsonfile@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" - integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= - optionalDependencies: - graceful-fs "^4.1.6" - -jsonparse@^1.2.0, jsonparse@^1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280" - integrity sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA= - -jsonwebtoken@8.5.1: - version "8.5.1" - resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d" - integrity sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w== - dependencies: - jws "^3.2.2" - lodash.includes "^4.3.0" - lodash.isboolean "^3.0.3" - lodash.isinteger "^4.0.4" - lodash.isnumber "^3.0.3" - lodash.isplainobject "^4.0.6" - lodash.isstring "^4.0.1" - lodash.once "^4.0.0" - ms "^2.1.1" - semver "^5.6.0" - -jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - integrity sha1-MT5mvB5cwG5Di8G3SZwuXFastqI= - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.2.3" - verror "1.10.0" - -jszip@^3.1.3, jszip@^3.1.5: - version "3.2.2" - resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.2.2.tgz#b143816df7e106a9597a94c77493385adca5bd1d" - integrity sha512-NmKajvAFQpbg3taXQXr/ccS2wcucR1AZ+NtyWp2Nq7HHVsXhcJFR8p0Baf32C2yVvBylFWVeKf+WI2AnvlPhpA== - dependencies: - lie "~3.3.0" - pako "~1.0.2" - readable-stream "~2.3.6" - set-immediate-shim "~1.0.1" - -jwa@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a" - integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA== - dependencies: - buffer-equal-constant-time "1.0.1" - ecdsa-sig-formatter "1.0.11" - safe-buffer "^5.0.1" - -jws@^3.2.2: - version "3.2.2" - resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304" - integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA== - dependencies: - jwa "^1.4.1" - safe-buffer "^5.0.1" - -karma-chrome-launcher@2.2.0, karma-chrome-launcher@~2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/karma-chrome-launcher/-/karma-chrome-launcher-2.2.0.tgz#cf1b9d07136cc18fe239327d24654c3dbc368acf" - integrity sha512-uf/ZVpAabDBPvdPdveyk1EPgbnloPvFFGgmRhYLTDH7gEB4nZdSBk8yTU47w1g/drLSx5uMOkjKk7IWKfWg/+w== - dependencies: - fs-access "^1.0.0" - which "^1.2.1" - -karma-coverage-istanbul-reporter@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-2.1.0.tgz#5f1bcc13c5e14ee1d91821ee8946861674f54c75" - integrity sha512-UH0mXPJFJyK5uiK7EkwGtQ8f30lCBAfqRResnZ4pzLJ04SOp4SPlYkmwbbZ6iVJ6sQFVzlDUXlntBEsLRdgZpg== - dependencies: - istanbul-api "^2.1.6" - minimatch "^3.0.4" - -karma-firefox-launcher@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/karma-firefox-launcher/-/karma-firefox-launcher-1.1.0.tgz#2c47030452f04531eb7d13d4fc7669630bb93339" - integrity sha512-LbZ5/XlIXLeQ3cqnCbYLn+rOVhuMIK9aZwlP6eOLGzWdo1UVp7t6CN3DP4SafiRLjexKwHeKHDm0c38Mtd3VxA== - -karma-jasmine-html-reporter@^1.4.0: - version "1.4.2" - resolved "https://registry.yarnpkg.com/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-1.4.2.tgz#16d100fd701271192d27fd28ddc90b710ad36fff" - integrity sha512-7g0gPj8+9JepCNJR9WjDyQ2RkZ375jpdurYQyAYv8PorUCadepl8vrD6LmMqOGcM17cnrynBawQYZHaumgDjBw== - -karma-jasmine@2.0.1, karma-jasmine@^2.0.1, karma-jasmine@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/karma-jasmine/-/karma-jasmine-2.0.1.tgz#26e3e31f2faf272dd80ebb0e1898914cc3a19763" - integrity sha512-iuC0hmr9b+SNn1DaUD2QEYtUxkS1J+bSJSn7ejdEexs7P8EYvA1CWkEdrDQ+8jVH3AgWlCNwjYsT1chjcNW9lA== - dependencies: - jasmine-core "^3.3" - -karma-requirejs@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/karma-requirejs/-/karma-requirejs-1.1.0.tgz#fddae2cb87d7ebc16fb0222893564d7fee578798" - integrity sha1-/driy4fX68FvsCIok1ZNf+5Xh5g= - -karma-sauce-launcher@2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/karma-sauce-launcher/-/karma-sauce-launcher-2.0.2.tgz#dbf98e70d86bf287b03a537cf637eb7aefa975c3" - integrity sha512-jLUFaJhHMcKpxFWUesyWYihzM5FvQiJsDwGcCtKeOy2lsWhkVw0V0Byqb1d+wU6myU1mribBtsIcub23HS4kWA== - dependencies: - sauce-connect-launcher "^1.2.4" - saucelabs "^1.5.0" - selenium-webdriver "^4.0.0-alpha.1" - -karma-source-map-support@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/karma-source-map-support/-/karma-source-map-support-1.4.0.tgz#58526ceccf7e8730e56effd97a4de8d712ac0d6b" - integrity sha512-RsBECncGO17KAoJCYXjv+ckIz+Ii9NCi+9enk+rq6XC81ezYkb4/RHE6CTXdA7IOJqoF3wcaLfVG0CPmE5ca6A== - dependencies: - source-map-support "^0.5.5" - -karma-sourcemap-loader@0.3.7: - version "0.3.7" - resolved "https://registry.yarnpkg.com/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.7.tgz#91322c77f8f13d46fed062b042e1009d4c4505d8" - integrity sha1-kTIsd/jxPUb+0GKwQuEAnUxFBdg= - dependencies: - graceful-fs "^4.1.2" - -karma@~4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/karma/-/karma-4.1.0.tgz#d07387c9743a575b40faf73e8a3eb5421c2193e1" - integrity sha512-xckiDqyNi512U4dXGOOSyLKPwek6X/vUizSy2f3geYevbLj+UIdvNwbn7IwfUIL2g1GXEPWt/87qFD1fBbl/Uw== - dependencies: - bluebird "^3.3.0" - body-parser "^1.16.1" - braces "^2.3.2" - chokidar "^2.0.3" - colors "^1.1.0" - connect "^3.6.0" - core-js "^2.2.0" - di "^0.0.1" - dom-serialize "^2.2.0" - flatted "^2.0.0" - glob "^7.1.1" - graceful-fs "^4.1.2" - http-proxy "^1.13.0" - isbinaryfile "^3.0.0" - lodash "^4.17.11" - log4js "^4.0.0" - mime "^2.3.1" - minimatch "^3.0.2" - optimist "^0.6.1" - qjobs "^1.1.4" - range-parser "^1.2.0" - rimraf "^2.6.0" - safe-buffer "^5.0.1" - socket.io "2.1.1" - source-map "^0.6.1" - tmp "0.0.33" - useragent "2.3.0" - -karma@~4.4.0: - version "4.4.1" - resolved "https://registry.yarnpkg.com/karma/-/karma-4.4.1.tgz#6d9aaab037a31136dc074002620ee11e8c2e32ab" - integrity sha512-L5SIaXEYqzrh6b1wqYC42tNsFMx2PWuxky84pK9coK09MvmL7mxii3G3bZBh/0rvD27lqDd0le9jyhzvwif73A== - dependencies: - bluebird "^3.3.0" - body-parser "^1.16.1" - braces "^3.0.2" - chokidar "^3.0.0" - colors "^1.1.0" - connect "^3.6.0" - di "^0.0.1" - dom-serialize "^2.2.0" - flatted "^2.0.0" - glob "^7.1.1" - graceful-fs "^4.1.2" - http-proxy "^1.13.0" - isbinaryfile "^3.0.0" - lodash "^4.17.14" - log4js "^4.0.0" - mime "^2.3.1" - minimatch "^3.0.2" - optimist "^0.6.1" - qjobs "^1.1.4" - range-parser "^1.2.0" - rimraf "^2.6.0" - safe-buffer "^5.0.1" - socket.io "2.1.1" - source-map "^0.6.1" - tmp "0.0.33" - useragent "2.3.0" - -keygrip@~1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/keygrip/-/keygrip-1.0.3.tgz#399d709f0aed2bab0a059e0cdd3a5023a053e1dc" - integrity sha512-/PpesirAIfaklxUzp4Yb7xBper9MwP6hNRA6BGGUFCgbJ+BM5CKBtsoxinNXkLHAr+GXS1/lSlF2rP7cv5Fl+g== - -keyv@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/keyv/-/keyv-3.1.0.tgz#ecc228486f69991e49e9476485a5be1e8fc5c4d9" - integrity sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA== - dependencies: - json-buffer "3.0.0" - -killable@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/killable/-/killable-1.0.1.tgz#4c8ce441187a061c7474fb87ca08e2a638194892" - integrity sha512-LzqtLKlUwirEUyl/nicirVmNiPvYs7l5n8wOPP7fyJVpUPkvCnW/vuiXGpylGUlnPDnB7311rARzAt3Mhswpjg== - -kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" - integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= - dependencies: - is-buffer "^1.1.5" - -kind-of@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" - integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= - dependencies: - is-buffer "^1.1.5" - -kind-of@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" - integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== - -kind-of@^6.0.0, kind-of@^6.0.2: - version "6.0.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051" - integrity sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA== - -kleur@3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" - integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== - -latest-version@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/latest-version/-/latest-version-5.1.0.tgz#119dfe908fe38d15dfa43ecd13fa12ec8832face" - integrity sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA== - dependencies: - package-json "^6.3.0" - -lcid@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-2.0.0.tgz#6ef5d2df60e52f82eb228a4c373e8d1f397253cf" - integrity sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA== - dependencies: - invert-kv "^2.0.0" - -less-loader@5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/less-loader/-/less-loader-5.0.0.tgz#498dde3a6c6c4f887458ee9ed3f086a12ad1b466" - integrity sha512-bquCU89mO/yWLaUq0Clk7qCsKhsF/TZpJUzETRvJa9KSVEL9SO3ovCvdEHISBhrC81OwC8QSVX7E0bzElZj9cg== - dependencies: - clone "^2.1.1" - loader-utils "^1.1.0" - pify "^4.0.1" - -less@3.10.3, less@^3.10.3: - version "3.10.3" - resolved "https://registry.yarnpkg.com/less/-/less-3.10.3.tgz#417a0975d5eeecc52cff4bcfa3c09d35781e6792" - integrity sha512-vz32vqfgmoxF1h3K4J+yKCtajH0PWmjkIFgbs5d78E/c/e+UQTnI+lWK+1eQRE95PXM2mC3rJlLSSP9VQHnaow== - dependencies: - clone "^2.1.2" - optionalDependencies: - errno "^0.1.1" - graceful-fs "^4.1.2" - image-size "~0.5.0" - mime "^1.4.1" - mkdirp "^0.5.0" - promise "^7.1.1" - request "^2.83.0" - source-map "~0.6.0" - -level-codec@^9.0.0: - version "9.0.1" - resolved "https://registry.yarnpkg.com/level-codec/-/level-codec-9.0.1.tgz#042f4aa85e56d4328ace368c950811ba802b7247" - integrity sha512-ajFP0kJ+nyq4i6kptSM+mAvJKLOg1X5FiFPtLG9M5gCEZyBmgDi3FkDrvlMkEzrUn1cWxtvVmrvoS4ASyO/q+Q== - -level-concat-iterator@~2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/level-concat-iterator/-/level-concat-iterator-2.0.1.tgz#1d1009cf108340252cb38c51f9727311193e6263" - integrity sha512-OTKKOqeav2QWcERMJR7IS9CUo1sHnke2C0gkSmcR7QuEtFNLLzHQAvnMw8ykvEcv0Qtkg0p7FOwP1v9e5Smdcw== - -level-errors@^2.0.0, level-errors@~2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/level-errors/-/level-errors-2.0.1.tgz#2132a677bf4e679ce029f517c2f17432800c05c8" - integrity sha512-UVprBJXite4gPS+3VznfgDSU8PTRuVX0NXwoWW50KLxd2yw4Y1t2JUR5In1itQnudZqRMT9DlAM3Q//9NCjCFw== - dependencies: - errno "~0.1.1" - -level-iterator-stream@~4.0.0: - version "4.0.2" - resolved "https://registry.yarnpkg.com/level-iterator-stream/-/level-iterator-stream-4.0.2.tgz#7ceba69b713b0d7e22fcc0d1f128ccdc8a24f79c" - integrity sha512-ZSthfEqzGSOMWoUGhTXdX9jv26d32XJuHz/5YnuHZzH6wldfWMOVwI9TBtKcya4BKTyTt3XVA0A3cF3q5CY30Q== - dependencies: - inherits "^2.0.4" - readable-stream "^3.4.0" - xtend "^4.0.2" - -level-js@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/level-js/-/level-js-4.0.1.tgz#3bad57d8bb46ebba7b13bc7442b56f4b45c8a2e0" - integrity sha512-m5JRIyHZn5VnCCFeRegJkn5bQd3MJK5qZX12zg3Oivc8+BUIS2yFS6ANMMeHX2ieGxucNvEn6/ZnyjmZQLLUWw== - dependencies: - abstract-leveldown "~6.0.1" - immediate "~3.2.3" - inherits "^2.0.3" - ltgt "^2.1.2" - typedarray-to-buffer "~3.1.5" - -level-packager@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/level-packager/-/level-packager-5.1.0.tgz#9c01c6c8e2380d3196d61e56bd79c2eff4a9d5c3" - integrity sha512-3pbJmDgGvp/lUQNULPoYQZtUbhMI8KoViYDw7Sa0kWl1mPeHWWJF7T/9upWI/NTMuEikkEE/cd6wBvmrW1+ZnQ== - dependencies: - encoding-down "^6.3.0" - levelup "^4.3.2" - -level-supports@~1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/level-supports/-/level-supports-1.0.1.tgz#2f530a596834c7301622521988e2c36bb77d122d" - integrity sha512-rXM7GYnW8gsl1vedTJIbzOrRv85c/2uCMpiiCzO2fndd06U/kUXEEU9evYn4zFggBOg36IsBW8LzqIpETwwQzg== - dependencies: - xtend "^4.0.2" - -level@5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/level/-/level-5.0.1.tgz#8528cc1ee37ac413270129a1eab938c610be3ccb" - integrity sha512-wcak5OQeA4rURGacqS62R/xNHjCYnJSQDBOlm4KNUGJVE9bWv2B04TclqReYejN+oD65PzD4FsqeWoI5wNC5Lg== - dependencies: - level-js "^4.0.0" - level-packager "^5.0.0" - leveldown "^5.0.0" - opencollective-postinstall "^2.0.0" - -leveldown@^5.0.0: - version "5.4.1" - resolved "https://registry.yarnpkg.com/leveldown/-/leveldown-5.4.1.tgz#83a8fdd9bb52b1ed69be2ef59822b6cdfcdb51ec" - integrity sha512-3lMPc7eU3yj5g+qF1qlALInzIYnkySIosR1AsUKFjL9D8fYbTLuENBAeDRZXIG4qeWOAyqRItOoLu2v2avWiMA== - dependencies: - abstract-leveldown "~6.2.1" - napi-macros "~2.0.0" - node-gyp-build "~4.1.0" - -levelup@^4.3.2: - version "4.3.2" - resolved "https://registry.yarnpkg.com/levelup/-/levelup-4.3.2.tgz#31c5b1b29f146d1d35d692e01a6da4d28fa55ebd" - integrity sha512-cRTjU4ktWo59wf13PHEiOayHC3n0dOh4i5+FHr4tv4MX9+l7mqETicNq3Aj07HKlLdk0z5muVoDL2RD+ovgiyA== - dependencies: - deferred-leveldown "~5.3.0" - level-errors "~2.0.0" - level-iterator-stream "~4.0.0" - level-supports "~1.0.0" - xtend "~4.0.0" - -levn@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" - integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= - dependencies: - prelude-ls "~1.1.2" - type-check "~0.3.2" - -license-checker@^20.1.0: - version "20.2.0" - resolved "https://registry.yarnpkg.com/license-checker/-/license-checker-20.2.0.tgz#edb2605fd714514ed16e7eeee5b88a41900241d2" - integrity sha512-bseotvz8lfzEY7siilsJhQd2K/z+IF9aeJ+ZscieyZ70S6Ql2iJdVp1IfnL6gkdU4ny5JctT5Y2lFCQerSCfGA== - dependencies: - chalk "^2.4.1" - debug "^3.1.0" - mkdirp "^0.5.1" - nopt "^4.0.1" - read-installed "~4.0.3" - semver "^5.5.0" - spdx "^0.5.1" - spdx-correct "^3.0.0" - spdx-satisfies "^4.0.0" - strip-ansi "^4.0.0" - treeify "^1.1.0" - -license-webpack-plugin@2.1.3: - version "2.1.3" - resolved "https://registry.yarnpkg.com/license-webpack-plugin/-/license-webpack-plugin-2.1.3.tgz#656fa6a8b2e711ee35c27ac8e1659a87240ef7f3" - integrity sha512-vTSY5r9HOq4sxR2BIxdIXWKI+9n3b+DoQkhKHedB3TdSxTfXUDRxKXdAj5iejR+qNXprXsxvEu9W+zOhgGIkAw== - dependencies: - "@types/webpack-sources" "^0.1.5" - webpack-sources "^1.2.0" - -lie@~3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/lie/-/lie-3.3.0.tgz#dcf82dee545f46074daf200c7c1c5a08e0f40f6a" - integrity sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ== - dependencies: - immediate "~3.0.5" - -lines-and-columns@^1.1.6: - version "1.1.6" - resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" - integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= - -load-json-file@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" - integrity sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA= - dependencies: - graceful-fs "^4.1.2" - parse-json "^2.2.0" - pify "^2.0.0" - pinkie-promise "^2.0.0" - strip-bom "^2.0.0" - -load-json-file@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-4.0.0.tgz#2f5f45ab91e33216234fd53adab668eb4ec0993b" - integrity sha1-L19Fq5HjMhYjT9U62rZo607AmTs= - dependencies: - graceful-fs "^4.1.2" - parse-json "^4.0.0" - pify "^3.0.0" - strip-bom "^3.0.0" - -loader-runner@^2.4.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-2.4.0.tgz#ed47066bfe534d7e84c4c7b9998c2a75607d9357" - integrity sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw== - -loader-utils@1.2.3, loader-utils@^1.0.2, loader-utils@^1.1.0, loader-utils@^1.2.3: - version "1.2.3" - resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.2.3.tgz#1ff5dc6911c9f0a062531a4c04b609406108c2c7" - integrity sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA== - dependencies: - big.js "^5.2.2" - emojis-list "^2.0.0" - json5 "^1.0.1" - -locate-path@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" - integrity sha1-K1aLJl7slExtnA3pw9u7ygNUzY4= - dependencies: - p-locate "^2.0.0" - path-exists "^3.0.0" - -locate-path@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" - integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== - dependencies: - p-locate "^3.0.0" - path-exists "^3.0.0" - -locate-path@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" - integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== - dependencies: - p-locate "^4.1.0" - -lockfile-lint-api@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/lockfile-lint-api/-/lockfile-lint-api-2.3.0.tgz#c200de37f07bee35eca2a52a8e560f013c87910c" - integrity sha512-4jp8ULItLgsaPgPjxm/nuupIiBbxWf/nA05gRGMtvJQxGoSOOYA1LxSunY5p1b4kw7u6ZW5TZNgcIs4cFvp9lw== - dependencies: - "@yarnpkg/lockfile" "^1.1.0" - debug "^4.1.0" - -lockfile-lint@2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/lockfile-lint/-/lockfile-lint-2.0.1.tgz#b2ccd71530f2861a433cfec3b9deb18b01a2c5e0" - integrity sha512-hT6Nrx2ewTtmZ/N3KjaEpLaXujHmIjcKU32pcuX20JhGgkTVWBlU3bDkIh+Lob7NG6zD96ASOUL6t/dQUa89WQ== - dependencies: - debug "^4.1.0" - lockfile-lint-api "^2.0.0" - yargs "^13.2.4" - -lockfile@1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/lockfile/-/lockfile-1.0.4.tgz#07f819d25ae48f87e538e6578b6964a4981a5609" - integrity sha512-cvbTwETRfsFh4nHsL1eGWapU1XFi5Ot9E85sWAwia7Y7EgB7vfqcZhTKZ+l7hCGxSPoushMv5GKhT5PdLv03WA== - dependencies: - signal-exit "^3.0.2" - -lodash._reinterpolate@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d" - integrity sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0= - -lodash.clonedeep@^4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef" - integrity sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8= - -lodash.includes@^4.3.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/lodash.includes/-/lodash.includes-4.3.0.tgz#60bb98a87cb923c68ca1e51325483314849f553f" - integrity sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8= - -lodash.isboolean@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz#6c2e171db2a257cd96802fd43b01b20d5f5870f6" - integrity sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY= - -lodash.isinteger@^4.0.4: - version "4.0.4" - resolved "https://registry.yarnpkg.com/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz#619c0af3d03f8b04c31f5882840b77b11cd68343" - integrity sha1-YZwK89A/iwTDH1iChAt3sRzWg0M= - -lodash.isnumber@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz#3ce76810c5928d03352301ac287317f11c0b1ffc" - integrity sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w= - -lodash.isplainobject@^4.0.6: - version "4.0.6" - resolved "https://registry.yarnpkg.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz#7c526a52d89b45c45cc690b88163be0497f550cb" - integrity sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs= - -lodash.isstring@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451" - integrity sha1-1SfftUVuynzJu5XV2ur4i6VKVFE= - -lodash.once@^4.0.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac" - integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w= - -lodash.sortby@^4.7.0: - version "4.7.0" - resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438" - integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg= - -lodash.template@^4.0.2: - version "4.5.0" - resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-4.5.0.tgz#f976195cf3f347d0d5f52483569fe8031ccce8ab" - integrity sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A== - dependencies: - lodash._reinterpolate "^3.0.0" - lodash.templatesettings "^4.0.0" - -lodash.templatesettings@^4.0.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/lodash.templatesettings/-/lodash.templatesettings-4.2.0.tgz#e481310f049d3cf6d47e912ad09313b154f0fb33" - integrity sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ== - dependencies: - lodash._reinterpolate "^3.0.0" - -lodash@4.17.15, lodash@^4.16.6, lodash@^4.17.11, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.4, lodash@^4.2.1: - version "4.17.15" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" - integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== - -log-symbols@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" - integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== - dependencies: - chalk "^2.4.2" - -log4js@^3.0.0: - version "3.0.6" - resolved "https://registry.yarnpkg.com/log4js/-/log4js-3.0.6.tgz#e6caced94967eeeb9ce399f9f8682a4b2b28c8ff" - integrity sha512-ezXZk6oPJCWL483zj64pNkMuY/NcRX5MPiB0zE6tjZM137aeusrOnW1ecxgF9cmwMWkBMhjteQxBPoZBh9FDxQ== - dependencies: - circular-json "^0.5.5" - date-format "^1.2.0" - debug "^3.1.0" - rfdc "^1.1.2" - streamroller "0.7.0" - -log4js@^4.0.0: - version "4.5.1" - resolved "https://registry.yarnpkg.com/log4js/-/log4js-4.5.1.tgz#e543625e97d9e6f3e6e7c9fc196dd6ab2cae30b5" - integrity sha512-EEEgFcE9bLgaYUKuozyFfytQM2wDHtXn4tAN41pkaxpNjAykv11GVdeI4tHtmPWW4Xrgh9R/2d7XYghDVjbKKw== - dependencies: - date-format "^2.0.0" - debug "^4.1.1" - flatted "^2.0.0" - rfdc "^1.1.4" - streamroller "^1.0.6" - -loglevel@^1.6.4: - version "1.6.6" - resolved "https://registry.yarnpkg.com/loglevel/-/loglevel-1.6.6.tgz#0ee6300cc058db6b3551fa1c4bf73b83bb771312" - integrity sha512-Sgr5lbboAUBo3eXCSPL4/KoVz3ROKquOjcctxmHIt+vol2DrqTQe3SwkKKuYhEiWB5kYa13YyopJ69deJ1irzQ== - -long@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28" - integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA== - -loose-envify@^1.0.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" - integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== - dependencies: - js-tokens "^3.0.0 || ^4.0.0" - -loud-rejection@^1.0.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f" - integrity sha1-W0b4AUft7leIcPCG0Eghz5mOVR8= - dependencies: - currently-unhandled "^0.4.1" - signal-exit "^3.0.0" - -lowercase-keys@^1.0.0, lowercase-keys@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-1.0.1.tgz#6f9e30b47084d971a7c820ff15a6c5167b74c26f" - integrity sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA== - -lowercase-keys@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" - integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== - -lru-cache@4.1.x, lru-cache@^4.0.1: - version "4.1.5" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.5.tgz#8bbe50ea85bed59bc9e33dcab8235ee9bcf443cd" - integrity sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g== - dependencies: - pseudomap "^1.0.2" - yallist "^2.1.2" - -lru-cache@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" - integrity sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w== - dependencies: - yallist "^3.0.2" - -ltgt@^2.1.2: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ltgt/-/ltgt-2.2.1.tgz#f35ca91c493f7b73da0e07495304f17b31f87ee5" - integrity sha1-81ypHEk/e3PaDgdJUwTxezH4fuU= - -lunr-mutable-indexes@2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/lunr-mutable-indexes/-/lunr-mutable-indexes-2.3.2.tgz#864253489735d598c5140f3fb75c0a5c8be2e98c" - integrity sha512-Han6cdWAPPFM7C2AigS2Ofl3XjAT0yVMrUixodJEpyg71zCtZ2yzXc3s+suc/OaNt4ca6WJBEzVnEIjxCTwFMw== - dependencies: - lunr ">= 2.3.0 < 2.4.0" - -"lunr@>= 2.3.0 < 2.4.0": - version "2.3.8" - resolved "https://registry.yarnpkg.com/lunr/-/lunr-2.3.8.tgz#a8b89c31f30b5a044b97d2d28e2da191b6ba2072" - integrity sha512-oxMeX/Y35PNFuZoHp+jUj5OSEmLCaIH4KTFJh7a93cHBoFmpw2IoPs22VIz7vyO2YUnx2Tn9dzIwO2P/4quIRg== - -magic-string@0.25.4, magic-string@^0.25.0, magic-string@^0.25.2: - version "0.25.4" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.25.4.tgz#325b8a0a79fc423db109b77fd5a19183b7ba5143" - integrity sha512-oycWO9nEVAP2RVPbIoDoA4Y7LFIJ3xRYov93gAyJhZkET1tNuB0u7uWkZS2LpBWTJUWnmau/To8ECWRC+jKNfw== - dependencies: - sourcemap-codec "^1.4.4" - -magic-string@^0.22.4: - version "0.22.5" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.22.5.tgz#8e9cf5afddf44385c1da5bc2a6a0dbd10b03657e" - integrity sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w== - dependencies: - vlq "^0.2.2" - -make-dir@^1.0.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-1.3.0.tgz#79c1033b80515bd6d24ec9933e860ca75ee27f0c" - integrity sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ== - dependencies: - pify "^3.0.0" - -make-dir@^2.0.0, make-dir@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-2.1.0.tgz#5f0310e18b8be898cc07009295a30ae41e91e6f5" - integrity sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA== - dependencies: - pify "^4.0.1" - semver "^5.6.0" - -make-dir@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-3.0.0.tgz#1b5f39f6b9270ed33f9f054c5c0f84304989f801" - integrity sha512-grNJDhb8b1Jm1qeqW5R/O63wUo4UXo2v2HMic6YT9i/HBlF93S8jkMgH7yugvY9ABDShH4VZMn8I+U8+fCNegw== - dependencies: - semver "^6.0.0" - -make-error@^1.1.1: - version "1.3.5" - resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" - integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== - -make-fetch-happen@^6.0.0: - version "6.0.1" - resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-6.0.1.tgz#3992b9cc1a0564ac72eef3a9c27427487a985649" - integrity sha512-PAHjh/ohpW1lvc6eWHirvEoyQgRGa9g1Ugrddf0udiRdaVI/R4TMOqzGMEeM5tBzW6p4J+7kAQIKLgAxvLuT/A== - dependencies: - agentkeepalive "^3.4.1" - cacache "^13.0.1" - http-cache-semantics "^3.8.1" - http-proxy-agent "^2.1.0" - https-proxy-agent "^2.2.3" - lru-cache "^5.1.1" - minipass "^3.0.0" - minipass-collect "^1.0.2" - minipass-fetch "^1.1.2" - minipass-flush "^1.0.5" - minipass-pipeline "^1.2.2" - promise-retry "^1.1.1" - socks-proxy-agent "^4.0.0" - ssri "^7.0.1" - -mamacro@^0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/mamacro/-/mamacro-0.0.3.tgz#ad2c9576197c9f1abf308d0787865bd975a3f3e4" - integrity sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA== - -map-age-cleaner@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz#7d583a7306434c055fe474b0f45078e6e1b4b92a" - integrity sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w== - dependencies: - p-defer "^1.0.0" - -map-cache@^0.2.2: - version "0.2.2" - resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" - integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= - -map-obj@^1.0.0, map-obj@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" - integrity sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0= - -map-obj@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-2.0.0.tgz#a65cd29087a92598b8791257a523e021222ac1f9" - integrity sha1-plzSkIepJZi4eRJXpSPgISIqwfk= - -map-visit@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" - integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= - dependencies: - object-visit "^1.0.0" - -marked@0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.7.0.tgz#b64201f051d271b1edc10a04d1ae9b74bb8e5c0e" - integrity sha512-c+yYdCZJQrsRjTPhUx7VKkApw9bwDkNbHUKo1ovgcfDjb2kc8rLuRbIFyXL5WOEUwzSSKo3IXpph2K6DqB/KZg== - -md5.js@^1.3.4: - version "1.3.5" - resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f" - integrity sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg== - dependencies: - hash-base "^3.0.0" - inherits "^2.0.1" - safe-buffer "^5.1.2" - -media-typer@0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" - integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g= - -mem@^4.0.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/mem/-/mem-4.3.0.tgz#461af497bc4ae09608cdb2e60eefb69bff744178" - integrity sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w== - dependencies: - map-age-cleaner "^0.1.1" - mimic-fn "^2.0.0" - p-is-promise "^2.0.0" - -memory-fs@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" - integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= - dependencies: - errno "^0.1.3" - readable-stream "^2.0.1" - -memory-fs@^0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.5.0.tgz#324c01288b88652966d161db77838720845a8e3c" - integrity sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA== - dependencies: - errno "^0.1.3" - readable-stream "^2.0.1" - -meow@^3.3.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb" - integrity sha1-cstmi0JSKCkKu/qFaJJYcwioAfs= - dependencies: - camelcase-keys "^2.0.0" - decamelize "^1.1.2" - loud-rejection "^1.0.0" - map-obj "^1.0.1" - minimist "^1.1.3" - normalize-package-data "^2.3.4" - object-assign "^4.0.1" - read-pkg-up "^1.0.1" - redent "^1.0.0" - trim-newlines "^1.0.0" - -meow@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/meow/-/meow-4.0.1.tgz#d48598f6f4b1472f35bf6317a95945ace347f975" - integrity sha512-xcSBHD5Z86zaOc+781KrupuHAzeGXSLtiAOmBsiLDiPSaYSB6hdew2ng9EBAnZ62jagG9MHAOdxpDi/lWBFJ/A== - dependencies: - camelcase-keys "^4.0.0" - decamelize-keys "^1.0.0" - loud-rejection "^1.0.0" - minimist "^1.1.3" - minimist-options "^3.0.1" - normalize-package-data "^2.3.4" - read-pkg-up "^3.0.0" - redent "^2.0.0" - trim-newlines "^2.0.0" - -merge-descriptors@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" - integrity sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E= - -merge-source-map@1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/merge-source-map/-/merge-source-map-1.0.4.tgz#a5de46538dae84d4114cc5ea02b4772a6346701f" - integrity sha1-pd5GU42uhNQRTMXqArR3KmNGcB8= - dependencies: - source-map "^0.5.6" - -merge-stream@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" - integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== - -methods@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" - integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= - -micromatch@^3.1.10, micromatch@^3.1.4: - version "3.1.10" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" - integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== - dependencies: - arr-diff "^4.0.0" - array-unique "^0.3.2" - braces "^2.3.1" - define-property "^2.0.2" - extend-shallow "^3.0.2" - extglob "^2.0.4" - fragment-cache "^0.2.1" - kind-of "^6.0.2" - nanomatch "^1.2.9" - object.pick "^1.3.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.2" - -miller-rabin@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/miller-rabin/-/miller-rabin-4.0.1.tgz#f080351c865b0dc562a8462966daa53543c78a4d" - integrity sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA== - dependencies: - bn.js "^4.0.0" - brorand "^1.0.1" - -mime-db@1.40.0: - version "1.40.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32" - integrity sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA== - -"mime-db@>= 1.40.0 < 2": - version "1.42.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.42.0.tgz#3e252907b4c7adb906597b4b65636272cf9e7bac" - integrity sha512-UbfJCR4UAVRNgMpfImz05smAXK7+c+ZntjaA26ANtkXLlOe947Aag5zdIcKQULAiF9Cq4WxBi9jUs5zkA84bYQ== - -mime-types@^2.1.12, mime-types@~2.1.17, mime-types@~2.1.19, mime-types@~2.1.24: - version "2.1.24" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81" - integrity sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ== - dependencies: - mime-db "1.40.0" - -mime@1.6.0, mime@^1.4.1: - version "1.6.0" - resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" - integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== - -mime@2.4.4, mime@^2.0.3, mime@^2.3.1, mime@^2.4.4: - version "2.4.4" - resolved "https://registry.yarnpkg.com/mime/-/mime-2.4.4.tgz#bd7b91135fc6b01cde3e9bae33d659b63d8857e5" - integrity sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA== - -mimic-fn@^2.0.0, mimic-fn@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" - integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== - -mimic-response@^1.0.0, mimic-response@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" - integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== - -mini-css-extract-plugin@0.8.0: - version "0.8.0" - resolved "https://registry.yarnpkg.com/mini-css-extract-plugin/-/mini-css-extract-plugin-0.8.0.tgz#81d41ec4fe58c713a96ad7c723cdb2d0bd4d70e1" - integrity sha512-MNpRGbNA52q6U92i0qbVpQNsgk7LExy41MdAlG84FeytfDOtRIf/mCHdEgG8rpTKOaNKiqUnZdlptF469hxqOw== - dependencies: - loader-utils "^1.1.0" - normalize-url "1.9.1" - schema-utils "^1.0.0" - webpack-sources "^1.1.0" - -minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" - integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== - -minimalistic-crypto-utils@^1.0.0, minimalistic-crypto-utils@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" - integrity sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo= - -"minimatch@2 || 3", minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.3, minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== - dependencies: - brace-expansion "^1.1.7" - -minimist-options@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/minimist-options/-/minimist-options-3.0.2.tgz#fba4c8191339e13ecf4d61beb03f070103f3d954" - integrity sha512-FyBrT/d0d4+uiZRbqznPXqw3IpZZG3gl3wKWiX784FycUKVwBt0uLBFkQrtE4tZOrgo78nZp2jnKz3L65T5LdQ== - dependencies: - arrify "^1.0.1" - is-plain-obj "^1.1.0" - -minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0= - -minimist@1.2.0, minimist@^1.1.3, minimist@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ= - -minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - integrity sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8= - -minipass-collect@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-1.0.2.tgz#22b813bf745dc6edba2576b940022ad6edc8c617" - integrity sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA== - dependencies: - minipass "^3.0.0" - -minipass-fetch@^1.1.2, minipass-fetch@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/minipass-fetch/-/minipass-fetch-1.2.1.tgz#1b97ecb559be56b09812d45b2e9509f1f59ece2f" - integrity sha512-ssHt0dkljEDaKmTgQ04DQgx2ag6G2gMPxA5hpcsoeTbfDgRf2fC2gNSRc6kISjD7ckCpHwwQvXxuTBK8402fXg== - dependencies: - minipass "^3.1.0" - minipass-pipeline "^1.2.2" - minipass-sized "^1.0.3" - minizlib "^2.0.0" - optionalDependencies: - encoding "^0.1.12" - -minipass-flush@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/minipass-flush/-/minipass-flush-1.0.5.tgz#82e7135d7e89a50ffe64610a787953c4c4cbb373" - integrity sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw== - dependencies: - minipass "^3.0.0" - -minipass-json-stream@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minipass-json-stream/-/minipass-json-stream-1.0.1.tgz#7edbb92588fbfc2ff1db2fc10397acb7b6b44aa7" - integrity sha512-ODqY18UZt/I8k+b7rl2AENgbWE8IDYam+undIJONvigAz8KR5GWblsFTEfQs0WODsjbSXWlm+JHEv8Gr6Tfdbg== - dependencies: - jsonparse "^1.3.1" - minipass "^3.0.0" - -minipass-pipeline@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/minipass-pipeline/-/minipass-pipeline-1.2.2.tgz#3dcb6bb4a546e32969c7ad710f2c79a86abba93a" - integrity sha512-3JS5A2DKhD2g0Gg8x3yamO0pj7YeKGwVlDS90pF++kxptwx/F+B//roxf9SqYil5tQo65bijy+dAuAFZmYOouA== - dependencies: - minipass "^3.0.0" - -minipass-sized@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/minipass-sized/-/minipass-sized-1.0.3.tgz#70ee5a7c5052070afacfbc22977ea79def353b70" - integrity sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g== - dependencies: - minipass "^3.0.0" - -minipass@^2.6.0, minipass@^2.8.6, minipass@^2.9.0: - version "2.9.0" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.9.0.tgz#e713762e7d3e32fed803115cf93e04bca9fcc9a6" - integrity sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg== - dependencies: - safe-buffer "^5.1.2" - yallist "^3.0.0" - -minipass@^3.0.0, minipass@^3.0.1, minipass@^3.1.0, minipass@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.1.tgz#7607ce778472a185ad6d89082aa2070f79cedcd5" - integrity sha512-UFqVihv6PQgwj8/yTGvl9kPz7xIAY+R5z6XYjRInD3Gk3qx6QGSD6zEcpeG4Dy/lQnv1J6zv8ejV90hyYIKf3w== - dependencies: - yallist "^4.0.0" - -minizlib@^1.2.1: - version "1.3.3" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-1.3.3.tgz#2290de96818a34c29551c8a8d301216bd65a861d" - integrity sha512-6ZYMOEnmVsdCeTJVE0W9ZD+pVnE8h9Hma/iOwwRDsdQoePpoX56/8B6z3P9VNwppJuBKNRuFDRNRqRWexT9G9Q== - dependencies: - minipass "^2.9.0" - -minizlib@^2.0.0, minizlib@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.0.tgz#fd52c645301ef09a63a2c209697c294c6ce02cf3" - integrity sha512-EzTZN/fjSvifSX0SlqUERCN39o6T40AMarPbv0MrarSFtIITCBh7bi+dU8nxGFHuqs9jdIAeoYoKuQAAASsPPA== - dependencies: - minipass "^3.0.0" - yallist "^4.0.0" - -mississippi@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/mississippi/-/mississippi-3.0.0.tgz#ea0a3291f97e0b5e8776b363d5f0a12d94c67022" - integrity sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA== - dependencies: - concat-stream "^1.5.0" - duplexify "^3.4.2" - end-of-stream "^1.1.0" - flush-write-stream "^1.0.0" - from2 "^2.1.0" - parallel-transform "^1.1.0" - pump "^3.0.0" - pumpify "^1.3.3" - stream-each "^1.1.0" - through2 "^2.0.0" - -mixin-deep@^1.2.0: - version "1.3.2" - resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" - integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== - dependencies: - for-in "^1.0.2" - is-extendable "^1.0.1" - -mkdirp@0.5.1, mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.1, mkdirp@~0.5.x: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM= - dependencies: - minimist "0.0.8" - -modify-values@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/modify-values/-/modify-values-1.0.1.tgz#b3939fa605546474e3e3e3c63d64bd43b4ee6022" - integrity sha512-xV2bxeN6F7oYjZWTe/YPAy6MN2M+sL4u/Rlm2AHCIVGfo2p1yGmBHQ6vHehl4bRTZBdHu3TSkWdYgkwpYzAGSw== - -moment@^2.10.6: - version "2.24.0" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.24.0.tgz#0d055d53f5052aa653c9f6eb68bb5d12bf5c2b5b" - integrity sha512-bV7f+6l2QigeBBZSM/6yTNq4P2fNpSWj/0e7jQcy87A8e7o2nAfP/34/2ky5Vw4B9S446EtIhodAzkFCcR4dQg== - -move-concurrently@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/move-concurrently/-/move-concurrently-1.0.1.tgz#be2c005fda32e0b29af1f05d7c4b33214c701f92" - integrity sha1-viwAX9oy4LKa8fBdfEszIUxwH5I= - dependencies: - aproba "^1.1.1" - copy-concurrently "^1.0.0" - fs-write-stream-atomic "^1.0.8" - mkdirp "^0.5.1" - rimraf "^2.5.4" - run-queue "^1.0.3" - -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= - -ms@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a" - integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg== - -ms@^2.0.0, ms@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" - integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== - -multicast-dns-service-types@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz#899f11d9686e5e05cb91b35d5f0e63b773cfc901" - integrity sha1-iZ8R2WhuXgXLkbNdXw5jt3PPyQE= - -multicast-dns@^6.0.1: - version "6.2.3" - resolved "https://registry.yarnpkg.com/multicast-dns/-/multicast-dns-6.2.3.tgz#a0ec7bd9055c4282f790c3c82f4e28db3b31b229" - integrity sha512-ji6J5enbMyGRHIAkAOu3WdV8nggqviKCEKtXcOqfphZZtQrmHKycfynJ2V7eVPUA4NhJ6V7Wf4TmGbTwKE9B6g== - dependencies: - dns-packet "^1.3.1" - thunky "^1.0.2" - -mute-stream@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" - integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== - -mv@2.1.1, mv@~2: - version "2.1.1" - resolved "https://registry.yarnpkg.com/mv/-/mv-2.1.1.tgz#ae6ce0d6f6d5e0a4f7d893798d03c1ea9559b6a2" - integrity sha1-rmzg1vbV4KT32JN5jQPB6pVZtqI= - dependencies: - mkdirp "~0.5.1" - ncp "~2.0.0" - rimraf "~2.4.0" - -nan@^2.12.1, nan@^2.14.0: - version "2.14.0" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c" - integrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg== - -nanomatch@^1.2.9: - version "1.2.13" - resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" - integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== - dependencies: - arr-diff "^4.0.0" - array-unique "^0.3.2" - define-property "^2.0.2" - extend-shallow "^3.0.2" - fragment-cache "^0.2.1" - is-windows "^1.0.2" - kind-of "^6.0.2" - object.pick "^1.3.0" - regex-not "^1.0.0" - snapdragon "^0.8.1" - to-regex "^3.0.1" - -napi-macros@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/napi-macros/-/napi-macros-2.0.0.tgz#2b6bae421e7b96eb687aa6c77a7858640670001b" - integrity sha512-A0xLykHtARfueITVDernsAWdtIMbOJgKgcluwENp3AlsKN/PloyO10HtmoqnFAQAcxPkgZN7wdfPfEd0zNGxbg== - -ncp@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ncp/-/ncp-2.0.0.tgz#195a21d6c46e361d2fb1281ba38b91e9df7bdbb3" - integrity sha1-GVoh1sRuNh0vsSgbo4uR6d9727M= - -needle@^2.2.1: - version "2.4.0" - resolved "https://registry.yarnpkg.com/needle/-/needle-2.4.0.tgz#6833e74975c444642590e15a750288c5f939b57c" - integrity sha512-4Hnwzr3mi5L97hMYeNl8wRW/Onhy4nUKR/lVemJ8gJedxxUyBLm9kkrDColJvoSfwi0jCNhD+xCdOtiGDQiRZg== - dependencies: - debug "^3.2.6" - iconv-lite "^0.4.4" - sax "^1.2.4" - -negotiator@0.6.2: - version "0.6.2" - resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.2.tgz#feacf7ccf525a77ae9634436a64883ffeca346fb" - integrity sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw== - -neo-async@^2.5.0, neo-async@^2.6.0, neo-async@^2.6.1: - version "2.6.1" - resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c" - integrity sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw== - -ng-packagr@~9.0.0-rc.0: - version "9.0.0-rc.1" - resolved "https://registry.yarnpkg.com/ng-packagr/-/ng-packagr-9.0.0-rc.1.tgz#fc9bd8b4d6c7be11083b34325c29cddc6d324224" - integrity sha512-tP7WyuU99aDEWIXFCwqeqJzedMdtu79PR9RD9zzZJ2Wyu7/Yv81V740T0vAa+Tt1w1K5Ax1CwIQhIqSV+xZ5Yg== - dependencies: - ajv "^6.10.2" - autoprefixer "^9.6.5" - browserslist "^4.7.0" - chalk "^2.4.2" - chokidar "^3.2.1" - clean-css "^4.1.11" - commander "^3.0.2" - fs-extra "^8.1.0" - glob "^7.1.2" - injection-js "^2.2.1" - less "^3.10.3" - node-sass-tilde-importer "^1.0.0" - postcss "^7.0.18" - postcss-url "^8.0.0" - read-pkg-up "^5.0.0" - rimraf "^3.0.0" - rollup "1.25.2" - rollup-plugin-commonjs "^10.1.0" - rollup-plugin-json "^4.0.0" - rollup-plugin-node-resolve "^5.2.0" - rollup-plugin-sourcemaps "^0.4.2" - rxjs "^6.5.0" - sass "^1.23.0" - stylus "^0.54.7" - terser "^4.3.8" - update-notifier "^3.0.0" - -nice-try@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" - integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== - -node-fetch@^2.2.0: - version "2.6.0" - resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.0.tgz#e633456386d4aa55863f676a7ab0daa8fdecb0fd" - integrity sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA== - -node-forge@0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-0.9.0.tgz#d624050edbb44874adca12bb9a52ec63cb782579" - integrity sha512-7ASaDa3pD+lJ3WvXFsxekJQelBKRpne+GOVbLbtHYdd7pFspyeuJHnWfLplGf3SwKGbfs/aYl5V/JCIaHVUKKQ== - -node-gyp-build@~4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.1.1.tgz#d7270b5d86717068d114cc57fff352f96d745feb" - integrity sha512-dSq1xmcPDKPZ2EED2S6zw/b9NKsqzXRE6dVr8TVQnI3FJOTteUMuqF3Qqs6LZg+mLGYJWqQzMbIjMtJqTv87nQ== - -node-libs-browser@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/node-libs-browser/-/node-libs-browser-2.2.1.tgz#b64f513d18338625f90346d27b0d235e631f6425" - integrity sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q== - dependencies: - assert "^1.1.1" - browserify-zlib "^0.2.0" - buffer "^4.3.0" - console-browserify "^1.1.0" - constants-browserify "^1.0.0" - crypto-browserify "^3.11.0" - domain-browser "^1.1.1" - events "^3.0.0" - https-browserify "^1.0.0" - os-browserify "^0.3.0" - path-browserify "0.0.1" - process "^0.11.10" - punycode "^1.2.4" - querystring-es3 "^0.2.0" - readable-stream "^2.3.3" - stream-browserify "^2.0.1" - stream-http "^2.7.2" - string_decoder "^1.0.0" - timers-browserify "^2.0.4" - tty-browserify "0.0.0" - url "^0.11.0" - util "^0.11.0" - vm-browserify "^1.0.1" - -node-pre-gyp@^0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149" - integrity sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A== - dependencies: - detect-libc "^1.0.2" - mkdirp "^0.5.1" - needle "^2.2.1" - nopt "^4.0.1" - npm-packlist "^1.1.6" - npmlog "^4.0.2" - rc "^1.2.7" - rimraf "^2.6.1" - semver "^5.3.0" - tar "^4" - -node-releases@^1.1.38: - version "1.1.39" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-1.1.39.tgz#c1011f30343aff5b633153b10ff691d278d08e8d" - integrity sha512-8MRC/ErwNCHOlAFycy9OPca46fQYUjbJRDcZTHVWIGXIjYLM73k70vv3WkYutVnM4cCo4hE0MqBVVZjP6vjISA== - dependencies: - semver "^6.3.0" - -node-sass-tilde-importer@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/node-sass-tilde-importer/-/node-sass-tilde-importer-1.0.2.tgz#1a15105c153f648323b4347693fdb0f331bad1ce" - integrity sha512-Swcmr38Y7uB78itQeBm3mThjxBy9/Ah/ykPIaURY/L6Nec9AyRoL/jJ7ECfMR+oZeCTVQNxVMu/aHU+TLRVbdg== - dependencies: - find-parent-dir "^0.3.0" - -nopt@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.1.tgz#d0d4685afd5415193c8c7505602d0d17cd64474d" - integrity sha1-0NRoWv1UFRk8jHUFYC0NF81kR00= - dependencies: - abbrev "1" - osenv "^0.1.4" - -normalize-package-data@^2.0.0, normalize-package-data@^2.3.0, normalize-package-data@^2.3.2, normalize-package-data@^2.3.4, normalize-package-data@^2.3.5, normalize-package-data@^2.5.0, "normalize-package-data@~1.0.1 || ^2.0.0": - version "2.5.0" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" - integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== - dependencies: - hosted-git-info "^2.1.4" - resolve "^1.10.0" - semver "2 || 3 || 4 || 5" - validate-npm-package-license "^3.0.1" - -normalize-path@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" - integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= - dependencies: - remove-trailing-separator "^1.0.1" - -normalize-path@^3.0.0, normalize-path@~3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" - integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== - -normalize-range@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz#2d10c06bdfd312ea9777695a4d28439456b75942" - integrity sha1-LRDAa9/TEuqXd2laTShDlFa3WUI= - -normalize-url@1.9.1: - version "1.9.1" - resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-1.9.1.tgz#2cc0d66b31ea23036458436e3620d85954c66c3c" - integrity sha1-LMDWazHqIwNkWENuNiDYWVTGbDw= - dependencies: - object-assign "^4.0.1" - prepend-http "^1.0.0" - query-string "^4.1.0" - sort-keys "^1.0.0" - -normalize-url@^4.1.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-4.5.0.tgz#453354087e6ca96957bd8f5baf753f5982142129" - integrity sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ== - -npm-bundled@^1.0.1: - version "1.0.6" - resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-1.0.6.tgz#e7ba9aadcef962bb61248f91721cd932b3fe6bdd" - integrity sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g== - -npm-package-arg@7.0.0, npm-package-arg@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-7.0.0.tgz#52cdf08b491c0c59df687c4c925a89102ef794a5" - integrity sha512-xXxr8y5U0kl8dVkz2oK7yZjPBvqM2fwaO5l3Yg13p03v8+E3qQcD0JNhHzjL1vyGgxcKkD0cco+NLR72iuPk3g== - dependencies: - hosted-git-info "^3.0.2" - osenv "^0.1.5" - semver "^5.6.0" - validate-npm-package-name "^3.0.0" - -"npm-package-arg@^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0": - version "6.1.1" - resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-6.1.1.tgz#02168cb0a49a2b75bf988a28698de7b529df5cb7" - integrity sha512-qBpssaL3IOZWi5vEKUKW0cO7kzLeT+EQO9W8RsLOZf76KF9E/K9+wH0C7t06HXPpaH8WH5xF1MExLuCwbTqRUg== - dependencies: - hosted-git-info "^2.7.1" - osenv "^0.1.5" - semver "^5.6.0" - validate-npm-package-name "^3.0.0" - -npm-packlist@^1.1.6, npm-packlist@^1.4.6: - version "1.4.6" - resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-1.4.6.tgz#53ba3ed11f8523079f1457376dd379ee4ea42ff4" - integrity sha512-u65uQdb+qwtGvEJh/DgQgW1Xg7sqeNbmxYyrvlNznaVTjV3E5P6F/EFjM+BVHXl7JJlsdG8A64M0XI8FI/IOlg== - dependencies: - ignore-walk "^3.0.1" - npm-bundled "^1.0.1" - -npm-pick-manifest@4.0.0, npm-pick-manifest@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/npm-pick-manifest/-/npm-pick-manifest-4.0.0.tgz#5e1b392a2a6310378b9bab32332597030ca073ce" - integrity sha512-SsYReLe/16UgSL6GKX6GO4o3RVBthVy1uuHq6kZ9mkPeQXpOHbrLZoV13i8fr3LQtET+pLPSfD13e4RIYfkX5Q== - dependencies: - figgy-pudding "^3.5.1" - npm-package-arg "^7.0.0" - semver "^5.4.1" - -npm-registry-client@8.6.0: - version "8.6.0" - resolved "https://registry.yarnpkg.com/npm-registry-client/-/npm-registry-client-8.6.0.tgz#7f1529f91450732e89f8518e0f21459deea3e4c4" - integrity sha512-Qs6P6nnopig+Y8gbzpeN/dkt+n7IyVd8f45NTMotGk6Qo7GfBmzwYx6jRLoOOgKiMnaQfYxsuyQlD8Mc3guBhg== - dependencies: - concat-stream "^1.5.2" - graceful-fs "^4.1.6" - normalize-package-data "~1.0.1 || ^2.0.0" - npm-package-arg "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" - once "^1.3.3" - request "^2.74.0" - retry "^0.10.0" - safe-buffer "^5.1.1" - semver "2 >=2.2.1 || 3.x || 4 || 5" - slide "^1.1.3" - ssri "^5.2.4" - optionalDependencies: - npmlog "2 || ^3.1.0 || ^4.0.0" - -npm-registry-fetch@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/npm-registry-fetch/-/npm-registry-fetch-5.0.1.tgz#98f59f2ac83440baf7a4fbe800972cfe37c9334d" - integrity sha512-GK7SUx188KSkPvbceOGO59L3FGHLBYoP0YEhUAKYjAypL15v5xmoempZ9rIJS2R/1eOS0KS1Y9AQe79YfgNxaw== - dependencies: - bluebird "^3.5.1" - figgy-pudding "^3.4.1" - lru-cache "^5.1.1" - make-fetch-happen "^6.0.0" - minipass "^3.0.0" - minipass-fetch "^1.1.2" - minipass-json-stream "^1.0.1" - minizlib "^2.0.0" - npm-package-arg "^7.0.0" - safe-buffer "^5.2.0" - -npm-run-path@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f" - integrity sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8= - dependencies: - path-key "^2.0.0" - -"npmlog@2 || ^3.1.0 || ^4.0.0", npmlog@^4.0.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b" - integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg== - dependencies: - are-we-there-yet "~1.1.2" - console-control-strings "~1.1.0" - gauge "~2.7.3" - set-blocking "~2.0.0" - -null-check@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/null-check/-/null-check-1.0.0.tgz#977dffd7176012b9ec30d2a39db5cf72a0439edd" - integrity sha1-l33/1xdgErnsMNKjnbXPcqBDnt0= - -num2fraction@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/num2fraction/-/num2fraction-1.2.2.tgz#6f682b6a027a4e9ddfa4564cd2589d1d4e669ede" - integrity sha1-b2gragJ6Tp3fpFZM0lidHU5mnt4= - -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" - integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= - -nwsapi@^2.1.4: - version "2.2.0" - resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.0.tgz#204879a9e3d068ff2a55139c2c772780681a38b7" - integrity sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ== - -oauth-sign@~0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" - integrity sha1-Rqarfwrq2N6unsBWV4C31O/rnUM= - -oauth-sign@~0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455" - integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ== - -object-assign@^4, object-assign@^4.0.1, object-assign@^4.1.0, object-assign@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= - -object-component@0.0.3: - version "0.0.3" - resolved "https://registry.yarnpkg.com/object-component/-/object-component-0.0.3.tgz#f0c69aa50efc95b866c186f400a33769cb2f1291" - integrity sha1-8MaapQ78lbhmwYb0AKM3acsvEpE= - -object-copy@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" - integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= - dependencies: - copy-descriptor "^0.1.0" - define-property "^0.2.5" - kind-of "^3.0.3" - -object-inspect@^1.6.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.7.0.tgz#f4f6bd181ad77f006b5ece60bd0b6f398ff74a67" - integrity sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw== - -object-inspect@~1.4.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.4.1.tgz#37ffb10e71adaf3748d05f713b4c9452f402cbc4" - integrity sha512-wqdhLpfCUbEsoEwl3FXwGyv8ief1k/1aUdIPCqVnupM6e8l63BEJdiF/0swtn04/8p05tG/T0FrpTlfwvljOdw== - -object-is@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/object-is/-/object-is-1.0.1.tgz#0aa60ec9989a0b3ed795cf4d06f62cf1ad6539b6" - integrity sha1-CqYOyZiaCz7Xlc9NBvYs8a1lObY= - -object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.0.6, object-keys@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" - integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== - -object-visit@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" - integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= - dependencies: - isobject "^3.0.0" - -object.assign@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" - integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== - dependencies: - define-properties "^1.1.2" - function-bind "^1.1.1" - has-symbols "^1.0.0" - object-keys "^1.0.11" - -object.getownpropertydescriptors@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz#8758c846f5b407adab0f236e0986f14b051caa16" - integrity sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY= - dependencies: - define-properties "^1.1.2" - es-abstract "^1.5.1" - -object.pick@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" - integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= - dependencies: - isobject "^3.0.1" - -obuf@^1.0.0, obuf@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/obuf/-/obuf-1.1.2.tgz#09bea3343d41859ebd446292d11c9d4db619084e" - integrity sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg== - -on-finished@~2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947" - integrity sha1-IPEzZIGwg811M3mSoWlxqi2QaUc= - dependencies: - ee-first "1.1.1" - -on-headers@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.2.tgz#772b0ae6aaa525c399e489adfad90c403eb3c28f" - integrity sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA== - -once@^1.3.0, once@^1.3.1, once@^1.3.3, once@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= - dependencies: - wrappy "1" - -onetime@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.0.tgz#fff0f3c91617fe62bb50189636e99ac8a6df7be5" - integrity sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q== - dependencies: - mimic-fn "^2.1.0" - -open@7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/open/-/open-7.0.0.tgz#7e52999b14eb73f90f0f0807fe93897c4ae73ec9" - integrity sha512-K6EKzYqnwQzk+/dzJAQSBORub3xlBTxMz+ntpZpH/LyCa1o6KjXhuN+2npAaI9jaSmU3R1Q8NWf4KUWcyytGsQ== - dependencies: - is-wsl "^2.1.0" - -opencollective-postinstall@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/opencollective-postinstall/-/opencollective-postinstall-2.0.2.tgz#5657f1bede69b6e33a45939b061eb53d3c6c3a89" - integrity sha512-pVOEP16TrAO2/fjej1IdOyupJY8KDUM1CvsaScRbw6oddvpQoOfGk4ywha0HKKVAD6RkW4x6Q+tNBwhf3Bgpuw== - -opn@^5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/opn/-/opn-5.5.0.tgz#fc7164fab56d235904c51c3b27da6758ca3b9bfc" - integrity sha512-PqHpggC9bLV0VeWcdKhkpxY+3JTzetLSqTCWL/z/tFIbI6G8JCjondXklT1JinczLz2Xib62sSp0T/gKT4KksA== - dependencies: - is-wsl "^1.1.0" - -optimist@^0.6.1, optimist@~0.6.0: - version "0.6.1" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" - integrity sha1-2j6nRob6IaGaERwybpDrFaAZZoY= - dependencies: - minimist "~0.0.1" - wordwrap "~0.0.2" - -optionator@^0.8.1: - version "0.8.3" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" - integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== - dependencies: - deep-is "~0.1.3" - fast-levenshtein "~2.0.6" - levn "~0.3.0" - prelude-ls "~1.1.2" - type-check "~0.3.2" - word-wrap "~1.2.3" - -ora@4.0.3: - version "4.0.3" - resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.3.tgz#752a1b7b4be4825546a7a3d59256fa523b6b6d05" - integrity sha512-fnDebVFyz309A73cqCipVL1fBZewq4vwgSHfxh43vVy31mbyoQ8sCH3Oeaog/owYOs/lLlGVPCISQonTneg6Pg== - dependencies: - chalk "^3.0.0" - cli-cursor "^3.1.0" - cli-spinners "^2.2.0" - is-interactive "^1.0.0" - log-symbols "^3.0.0" - mute-stream "0.0.8" - strip-ansi "^6.0.0" - wcwidth "^1.0.1" - -ora@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.2.tgz#0e1e68fd45b135d28648b27cf08081fa6e8a297d" - integrity sha512-YUOZbamht5mfLxPmk4M35CD/5DuOkAacxlEUbStVXpBAt4fyhBf+vZHI/HRkI++QUp3sNoeA2Gw4C+hi4eGSig== - dependencies: - chalk "^2.4.2" - cli-cursor "^3.1.0" - cli-spinners "^2.2.0" - is-interactive "^1.0.0" - log-symbols "^3.0.0" - strip-ansi "^5.2.0" - wcwidth "^1.0.1" - -original@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/original/-/original-1.0.2.tgz#e442a61cffe1c5fd20a65f3261c26663b303f25f" - integrity sha512-hyBVl6iqqUOJ8FqRe+l/gS8H+kKYjrEndd5Pm1MfBtsEKA038HkkdbAl/72EAXGyonD/PFsvmVG+EvcIpliMBg== - dependencies: - url-parse "^1.4.3" - -os-browserify@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/os-browserify/-/os-browserify-0.3.0.tgz#854373c7f5c2315914fc9bfc6bd8238fdda1ec27" - integrity sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc= - -os-homedir@^1.0.0, os-homedir@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" - integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= - -os-locale@^3.0.0, os-locale@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-3.1.0.tgz#a802a6ee17f24c10483ab9935719cef4ed16bf1a" - integrity sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q== - dependencies: - execa "^1.0.0" - lcid "^2.0.0" - mem "^4.0.0" - -os-tmpdir@^1.0.0, os-tmpdir@~1.0.1, os-tmpdir@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= - -osenv@^0.1.4, osenv@^0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410" - integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g== - dependencies: - os-homedir "^1.0.0" - os-tmpdir "^1.0.0" - -p-cancelable@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-1.1.0.tgz#d078d15a3af409220c886f1d9a0ca2e441ab26cc" - integrity sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw== - -p-defer@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-defer/-/p-defer-1.0.0.tgz#9f6eb182f6c9aa8cd743004a7d4f96b196b0fb0c" - integrity sha1-n26xgvbJqozXQwBKfU+WsZaw+ww= - -p-finally@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae" - integrity sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4= - -p-is-promise@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/p-is-promise/-/p-is-promise-2.1.0.tgz#918cebaea248a62cf7ffab8e3bca8c5f882fc42e" - integrity sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg== - -p-limit@^1.1.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8" - integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q== - dependencies: - p-try "^1.0.0" - -p-limit@^2.0.0, p-limit@^2.2.0, p-limit@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.1.tgz#aa07a788cc3151c939b5131f63570f0dd2009537" - integrity sha512-85Tk+90UCVWvbDavCLKPOLC9vvY8OwEX/RtKF+/1OADJMVlFfEHOiMTPVyxg7mk/dKa+ipdHm0OUkTvCpMTuwg== - dependencies: - p-try "^2.0.0" - -p-locate@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" - integrity sha1-IKAQOyIqcMj9OcwuWAaA893l7EM= - dependencies: - p-limit "^1.1.0" - -p-locate@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" - integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== - dependencies: - p-limit "^2.0.0" - -p-locate@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" - integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== - dependencies: - p-limit "^2.2.0" - -p-map@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/p-map/-/p-map-2.1.0.tgz#310928feef9c9ecc65b68b17693018a665cea175" - integrity sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw== - -p-map@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/p-map/-/p-map-3.0.0.tgz#d704d9af8a2ba684e2600d9a215983d4141a979d" - integrity sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ== - dependencies: - aggregate-error "^3.0.0" - -p-retry@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/p-retry/-/p-retry-3.0.1.tgz#316b4c8893e2c8dc1cfa891f406c4b422bebf328" - integrity sha512-XE6G4+YTTkT2a0UWb2kjZe8xNwf8bIbnqpc/IS/idOBVhyves0mK5OJgeocjx7q5pvX/6m23xuzVPYT1uGM73w== - dependencies: - retry "^0.12.0" - -p-try@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3" - integrity sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M= - -p-try@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" - integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== - -package-json@^6.3.0: - version "6.5.0" - resolved "https://registry.yarnpkg.com/package-json/-/package-json-6.5.0.tgz#6feedaca35e75725876d0b0e64974697fed145b0" - integrity sha512-k3bdm2n25tkyxcjSKzB5x8kfVxlMdgsbPr0GkZcwHsLpba6cBjqCt1KlcChKEvxHIcTB1FVMuwoijZ26xex5MQ== - dependencies: - got "^9.6.0" - registry-auth-token "^4.0.0" - registry-url "^5.0.0" - semver "^6.2.0" - -pacote@10.1.3: - version "10.1.3" - resolved "https://registry.yarnpkg.com/pacote/-/pacote-10.1.3.tgz#fdcd37eadd5540ba1d0ec138367627d62a12db0a" - integrity sha512-U71/gHmr7ICs3jAa8573fu+KmMF9voxHA/L2hh6IiYgH0uWh2npuGNRfr+WhZ+ztzp4Qq8niHRsMeRNZqI+2mg== - dependencies: - cacache "^13.0.1" - chownr "^1.1.3" - fs-minipass "^2.0.0" - infer-owner "^1.0.4" - lru-cache "^5.1.1" - minipass "^3.0.1" - minipass-fetch "^1.2.1" - npm-package-arg "^7.0.0" - npm-packlist "^1.4.6" - npm-pick-manifest "^4.0.0" - npm-registry-fetch "^5.0.1" - osenv "^0.1.5" - promise-inflight "^1.0.1" - promise-retry "^1.1.1" - read-package-json "^2.1.0" - semver "^6.3.0" - ssri "^7.1.0" - tar "^5.0.5" - which "^2.0.1" - -pako@^0.2.5: - version "0.2.9" - resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75" - integrity sha1-8/dSL073gjSNqBYbrZ7P1Rv4OnU= - -pako@^1.0.6, pako@~1.0.2, pako@~1.0.5: - version "1.0.10" - resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.10.tgz#4328badb5086a426aa90f541977d4955da5c9732" - integrity sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw== - -parallel-transform@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/parallel-transform/-/parallel-transform-1.2.0.tgz#9049ca37d6cb2182c3b1d2c720be94d14a5814fc" - integrity sha512-P2vSmIu38uIlvdcU7fDkyrxj33gTUy/ABO5ZUbGowxNCopBq/OoD42bP4UmMrJoPyk4Uqf0mu3mtWBhHCZD8yg== - dependencies: - cyclist "^1.0.1" - inherits "^2.0.3" - readable-stream "^2.1.5" - -parse-asn1@^5.0.0: - version "5.1.5" - resolved "https://registry.yarnpkg.com/parse-asn1/-/parse-asn1-5.1.5.tgz#003271343da58dc94cace494faef3d2147ecea0e" - integrity sha512-jkMYn1dcJqF6d5CpU689bq7w/b5ALS9ROVSpQDPrZsqqesUJii9qutvoT5ltGedNXMO2e16YUWIghG9KxaViTQ== - dependencies: - asn1.js "^4.0.0" - browserify-aes "^1.0.0" - create-hash "^1.1.0" - evp_bytestokey "^1.0.0" - pbkdf2 "^3.0.3" - safe-buffer "^5.1.1" - -parse-github-repo-url@^1.3.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/parse-github-repo-url/-/parse-github-repo-url-1.4.1.tgz#9e7d8bb252a6cb6ba42595060b7bf6df3dbc1f50" - integrity sha1-nn2LslKmy2ukJZUGC3v23z28H1A= - -parse-json@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" - integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= - dependencies: - error-ex "^1.2.0" - -parse-json@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" - integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= - dependencies: - error-ex "^1.3.1" - json-parse-better-errors "^1.0.1" - -parse-json@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.0.0.tgz#73e5114c986d143efa3712d4ea24db9a4266f60f" - integrity sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw== - dependencies: - "@babel/code-frame" "^7.0.0" - error-ex "^1.3.1" - json-parse-better-errors "^1.0.1" - lines-and-columns "^1.1.6" - -parse5-html-rewriting-stream@5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/parse5-html-rewriting-stream/-/parse5-html-rewriting-stream-5.1.1.tgz#fc18570ba0d09b5091250956d1c3f716ef0a07b7" - integrity sha512-rbXBeMlJ3pk3tKxLKAUaqvQTZM5KTohXmZvYEv2gU9sQC70w65BxPsh3PVVnwiVNCnNYDtNZRqCKmiMlfdG07Q== - dependencies: - parse5 "^5.1.1" - parse5-sax-parser "^5.1.1" - -parse5-sax-parser@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/parse5-sax-parser/-/parse5-sax-parser-5.1.1.tgz#02834a9d08b23ea2d99584841c38be09d5247a15" - integrity sha512-9HIh6zd7bF1NJe95LPCUC311CekdOi55R+HWXNCsGY6053DWaMijVKOv1oPvdvPTvFicifZyimBVJ6/qvG039Q== - dependencies: - parse5 "^5.1.1" - -parse5@4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-4.0.0.tgz#6d78656e3da8d78b4ec0b906f7c08ef1dfe3f608" - integrity sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA== - -parse5@5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-5.1.0.tgz#c59341c9723f414c452975564c7c00a68d58acd2" - integrity sha512-fxNG2sQjHvlVAYmzBZS9YlDp6PTSSDwa98vkD4QgVDDCAo84z5X1t5XyJQ62ImdLXx5NdIIfihey6xpum9/gRQ== - -parse5@^5.0.0, parse5@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/parse5/-/parse5-5.1.1.tgz#f68e4e5ba1852ac2cadc00f4555fff6c2abb6178" - integrity sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug== - -parseqs@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/parseqs/-/parseqs-0.0.5.tgz#d5208a3738e46766e291ba2ea173684921a8b89d" - integrity sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0= - dependencies: - better-assert "~1.0.0" - -parseuri@0.0.5: - version "0.0.5" - resolved "https://registry.yarnpkg.com/parseuri/-/parseuri-0.0.5.tgz#80204a50d4dbb779bfdc6ebe2778d90e4bce320a" - integrity sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo= - dependencies: - better-assert "~1.0.0" - -parseurl@~1.3.2, parseurl@~1.3.3: - version "1.3.3" - resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" - integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== - -pascalcase@^0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" - integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= - -path-browserify@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/path-browserify/-/path-browserify-0.0.1.tgz#e6c4ddd7ed3aa27c68a20cc4e50e1a4ee83bbc4a" - integrity sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ== - -path-dirname@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0" - integrity sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA= - -path-exists@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" - integrity sha1-D+tsZPD8UY2adU3V77YscCJ2H0s= - dependencies: - pinkie-promise "^2.0.0" - -path-exists@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" - integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= - -path-exists@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" - integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-is-inside@^1.0.1, path-is-inside@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" - integrity sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM= - -path-key@^2.0.0, path-key@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" - integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= - -path-parse@^1.0.5, path-parse@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" - integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== - -path-to-regexp@0.1.7: - version "0.1.7" - resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" - integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w= - -path-type@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" - integrity sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE= - dependencies: - graceful-fs "^4.1.2" - pify "^2.0.0" - pinkie-promise "^2.0.0" - -path-type@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-3.0.0.tgz#cef31dc8e0a1a3bb0d105c0cd97cf3bf47f4e36f" - integrity sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg== - dependencies: - pify "^3.0.0" - -pbkdf2@^3.0.3: - version "3.0.17" - resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.0.17.tgz#976c206530617b14ebb32114239f7b09336e93a6" - integrity sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA== - dependencies: - create-hash "^1.1.2" - create-hmac "^1.1.4" - ripemd160 "^2.0.1" - safe-buffer "^5.0.1" - sha.js "^2.4.8" - -pend@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" - integrity sha1-elfrVQpng/kRUzH89GY9XI4AelA= - -performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= - -picomatch@^2.0.4: - version "2.1.1" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.1.1.tgz#ecdfbea7704adb5fe6fb47f9866c4c0e15e905c5" - integrity sha512-OYMyqkKzK7blWO/+XZYP6w8hH0LDvkBvdvKukti+7kqYFCiEAk+gI3DWnryapc0Dau05ugGTy0foQ6mqn4AHYA== - -pidtree@0.3.0, pidtree@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/pidtree/-/pidtree-0.3.0.tgz#f6fada10fccc9f99bf50e90d0b23d72c9ebc2e6b" - integrity sha512-9CT4NFlDcosssyg8KVFltgokyKZIFjoBxw8CTGy+5F38Y1eQWrt8tRayiUOXE+zVKQnYu5BR8JjCtvK3BcnBhg== - -pidusage@2.0.17, pidusage@^2.0.17: - version "2.0.17" - resolved "https://registry.yarnpkg.com/pidusage/-/pidusage-2.0.17.tgz#6b4a2b4a09026f0e9828f7e5627837e4c0672581" - integrity sha512-N8X5v18rBmlBoArfS83vrnD0gIFyZkXEo7a5pAS2aT0i2OLVymFb2AzVg+v8l/QcXnE1JwZcaXR8daJcoJqtjw== - dependencies: - safe-buffer "^5.1.2" - -pify@^2.0.0, pify@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" - integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= - -pify@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176" - integrity sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY= - -pify@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" - integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - integrity sha1-ITXW36ejWMBprJsXh3YogihFD/o= - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - integrity sha1-clVrgM+g1IqXToDnckjoDtT3+HA= - -pkg-dir@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-3.0.0.tgz#2749020f239ed990881b1f71210d51eb6523bea3" - integrity sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw== - dependencies: - find-up "^3.0.0" - -pkg-dir@^4.1.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" - integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== - dependencies: - find-up "^4.0.0" - -pkginfo@0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/pkginfo/-/pkginfo-0.4.1.tgz#b5418ef0439de5425fc4995042dced14fb2a84ff" - integrity sha1-tUGO8EOd5UJfxJlQQtztFPsqhP8= - -please-upgrade-node@^3.1.1: - version "3.2.0" - resolved "https://registry.yarnpkg.com/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz#aeddd3f994c933e4ad98b99d9a556efa0e2fe942" - integrity sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg== - dependencies: - semver-compare "^1.0.0" - -pluralize@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-7.0.0.tgz#298b89df8b93b0221dbf421ad2b1b1ea23fc6777" - integrity sha512-ARhBOdzS3e41FbkW/XWrTEtukqqLoK5+Z/4UeDaLuSW+39JPeFgs4gCGqsrJHVZX0fUrx//4OF0K1CUGwlIFow== - -pn@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/pn/-/pn-1.1.0.tgz#e2f4cef0e219f463c179ab37463e4e1ecdccbafb" - integrity sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA== - -popper.js@^1.14.1: - version "1.16.0" - resolved "https://registry.yarnpkg.com/popper.js/-/popper.js-1.16.0.tgz#2e1816bcbbaa518ea6c2e15a466f4cb9c6e2fbb3" - integrity sha512-+G+EkOPoE5S/zChTpmBSSDYmhXJ5PsW8eMhH8cP/CQHMFPBG/kC9Y5IIw6qNYgdJ+/COf0ddY2li28iHaZRSjw== - -portfinder@^1.0.25: - version "1.0.25" - resolved "https://registry.yarnpkg.com/portfinder/-/portfinder-1.0.25.tgz#254fd337ffba869f4b9d37edc298059cb4d35eca" - integrity sha512-6ElJnHBbxVA1XSLgBp7G1FiCkQdlqGzuF7DswL5tcea+E8UpuvPU7beVAjjRwCioTS9ZluNbu+ZyRvgTsmqEBg== - dependencies: - async "^2.6.2" - debug "^3.1.1" - mkdirp "^0.5.1" - -posix-character-classes@^0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" - integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= - -postcss-import@12.0.1: - version "12.0.1" - resolved "https://registry.yarnpkg.com/postcss-import/-/postcss-import-12.0.1.tgz#cf8c7ab0b5ccab5649024536e565f841928b7153" - integrity sha512-3Gti33dmCjyKBgimqGxL3vcV8w9+bsHwO5UrBawp796+jdardbcFl4RP5w/76BwNL7aGzpKstIfF9I+kdE8pTw== - dependencies: - postcss "^7.0.1" - postcss-value-parser "^3.2.3" - read-cache "^1.0.0" - resolve "^1.1.7" - -postcss-load-config@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/postcss-load-config/-/postcss-load-config-2.1.0.tgz#c84d692b7bb7b41ddced94ee62e8ab31b417b003" - integrity sha512-4pV3JJVPLd5+RueiVVB+gFOAa7GWc25XQcMp86Zexzke69mKf6Nx9LRcQywdz7yZI9n1udOxmLuAwTBypypF8Q== - dependencies: - cosmiconfig "^5.0.0" - import-cwd "^2.0.0" - -postcss-loader@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/postcss-loader/-/postcss-loader-3.0.0.tgz#6b97943e47c72d845fa9e03f273773d4e8dd6c2d" - integrity sha512-cLWoDEY5OwHcAjDnkyRQzAXfs2jrKjXpO/HQFcc5b5u/r7aa471wdmChmwfnv7x2u840iat/wi0lQ5nbRgSkUA== - dependencies: - loader-utils "^1.1.0" - postcss "^7.0.0" - postcss-load-config "^2.0.0" - schema-utils "^1.0.0" - -postcss-url@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/postcss-url/-/postcss-url-8.0.0.tgz#7b10059bd12929cdbb1971c60f61a0e5af86b4ca" - integrity sha512-E2cbOQ5aii2zNHh8F6fk1cxls7QVFZjLPSrqvmiza8OuXLzIpErij8BDS5Y3STPfJgpIMNCPEr8JlKQWEoozUw== - dependencies: - mime "^2.3.1" - minimatch "^3.0.4" - mkdirp "^0.5.0" - postcss "^7.0.2" - xxhashjs "^0.2.1" - -postcss-value-parser@^3.2.3: - version "3.3.1" - resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz#9ff822547e2893213cf1c30efa51ac5fd1ba8281" - integrity sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ== - -postcss-value-parser@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-4.0.2.tgz#482282c09a42706d1fc9a069b73f44ec08391dc9" - integrity sha512-LmeoohTpp/K4UiyQCwuGWlONxXamGzCMtFxLq4W1nZVGIQLYvMCJx3yAF9qyyuFpflABI9yVdtJAqbihOsCsJQ== - -postcss@7.0.21, postcss@^7.0.0, postcss@^7.0.1, postcss@^7.0.18, postcss@^7.0.2, postcss@^7.0.21: - version "7.0.21" - resolved "https://registry.yarnpkg.com/postcss/-/postcss-7.0.21.tgz#06bb07824c19c2021c5d056d5b10c35b989f7e17" - integrity sha512-uIFtJElxJo29QC753JzhidoAhvp/e/Exezkdhfmt8AymWT6/5B7W1WmponYWkHk2eg6sONyTch0A3nkMPun3SQ== - dependencies: - chalk "^2.4.2" - source-map "^0.6.1" - supports-color "^6.1.0" - -prelude-ls@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" - integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= - -prepend-http@^1.0.0: - version "1.0.4" - resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-1.0.4.tgz#d4f4562b0ce3696e41ac52d0e002e57a635dc6dc" - integrity sha1-1PRWKwzjaW5BrFLQ4ALlemNdxtw= - -prepend-http@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" - integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= - -prettier@^1.16.4: - version "1.19.1" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb" - integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew== - -private@^0.1.6: - version "0.1.8" - resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff" - integrity sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg== - -process-nextick-args@~2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" - integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== - -process@^0.11.10: - version "0.11.10" - resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" - integrity sha1-czIwDoQBYb2j5podHZGn1LwW8YI= - -progress@2.0.3, progress@^2.0.1: - version "2.0.3" - resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" - integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== - -promise-inflight@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3" - integrity sha1-mEcocL8igTL8vdhoEputEsPAKeM= - -promise-retry@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/promise-retry/-/promise-retry-1.1.1.tgz#6739e968e3051da20ce6497fb2b50f6911df3d6d" - integrity sha1-ZznpaOMFHaIM5kl/srUPaRHfPW0= - dependencies: - err-code "^1.0.0" - retry "^0.10.0" - -promise@^7.1.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/promise/-/promise-7.3.1.tgz#064b72602b18f90f29192b8b1bc418ffd1ebd3bf" - integrity sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg== - dependencies: - asap "~2.0.3" - -protobufjs@6.8.8: - version "6.8.8" - resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.8.8.tgz#c8b4f1282fd7a90e6f5b109ed11c84af82908e7c" - integrity sha512-AAmHtD5pXgZfi7GMpllpO3q1Xw1OYldr+dMUlAnffGTAhqkg72WdmSY71uKBF/JuyiKs8psYbtKrhi0ASCD8qw== - dependencies: - "@protobufjs/aspromise" "^1.1.2" - "@protobufjs/base64" "^1.1.2" - "@protobufjs/codegen" "^2.0.4" - "@protobufjs/eventemitter" "^1.1.0" - "@protobufjs/fetch" "^1.1.0" - "@protobufjs/float" "^1.0.2" - "@protobufjs/inquire" "^1.1.0" - "@protobufjs/path" "^1.1.2" - "@protobufjs/pool" "^1.1.0" - "@protobufjs/utf8" "^1.1.0" - "@types/long" "^4.0.0" - "@types/node" "^10.1.0" - long "^4.0.0" - -protractor@~5.4.0: - version "5.4.2" - resolved "https://registry.yarnpkg.com/protractor/-/protractor-5.4.2.tgz#329efe37f48b2141ab9467799be2d4d12eb48c13" - integrity sha512-zlIj64Cr6IOWP7RwxVeD8O4UskLYPoyIcg0HboWJL9T79F1F0VWtKkGTr/9GN6BKL+/Q/GmM7C9kFVCfDbP5sA== - dependencies: - "@types/q" "^0.0.32" - "@types/selenium-webdriver" "^3.0.0" - blocking-proxy "^1.0.0" - browserstack "^1.5.1" - chalk "^1.1.3" - glob "^7.0.3" - jasmine "2.8.0" - jasminewd2 "^2.1.0" - optimist "~0.6.0" - q "1.4.1" - saucelabs "^1.5.0" - selenium-webdriver "3.6.0" - source-map-support "~0.4.0" - webdriver-js-extender "2.1.0" - webdriver-manager "^12.0.6" - -proxy-addr@~2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.5.tgz#34cbd64a2d81f4b1fd21e76f9f06c8a45299ee34" - integrity sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ== - dependencies: - forwarded "~0.1.2" - ipaddr.js "1.9.0" - -proxy-from-env@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.0.0.tgz#33c50398f70ea7eb96d21f7b817630a55791c7ee" - integrity sha1-M8UDmPcOp+uW0h97gXYwpVeRx+4= - -prr@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" - integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= - -pseudomap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" - integrity sha1-8FKijacOYYkX7wqKw0wa5aaChrM= - -psl@^1.1.24, psl@^1.1.28: - version "1.4.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.4.0.tgz#5dd26156cdb69fa1fdb8ab1991667d3f80ced7c2" - integrity sha512-HZzqCGPecFLyoRj5HLfuDSKYTJkAfB5thKBIkRHtGjWwY7p1dAyveIbXIq4tO0KYfDF2tHqPUgY9SDnGm00uFw== - -public-encrypt@^4.0.0: - version "4.0.3" - resolved "https://registry.yarnpkg.com/public-encrypt/-/public-encrypt-4.0.3.tgz#4fcc9d77a07e48ba7527e7cbe0de33d0701331e0" - integrity sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q== - dependencies: - bn.js "^4.1.0" - browserify-rsa "^4.0.0" - create-hash "^1.1.0" - parse-asn1 "^5.0.0" - randombytes "^2.0.1" - safe-buffer "^5.1.2" - -pump@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz#12399add6e4cf7526d973cbc8b5ce2e2908b3909" - integrity sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA== - dependencies: - end-of-stream "^1.1.0" - once "^1.3.1" - -pump@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" - integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== - dependencies: - end-of-stream "^1.1.0" - once "^1.3.1" - -pumpify@^1.3.3: - version "1.5.1" - resolved "https://registry.yarnpkg.com/pumpify/-/pumpify-1.5.1.tgz#36513be246ab27570b1a374a5ce278bfd74370ce" - integrity sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ== - dependencies: - duplexify "^3.6.0" - inherits "^2.0.3" - pump "^2.0.0" - -punycode@1.3.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" - integrity sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0= - -punycode@^1.2.4, punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - integrity sha1-wNWmOycYgArY4esPpSachN1BhF4= - -punycode@^2.1.0, punycode@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" - integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== - -puppeteer@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/puppeteer/-/puppeteer-2.0.0.tgz#0612992e29ec418e0a62c8bebe61af1a64d7ec01" - integrity sha512-t3MmTWzQxPRP71teU6l0jX47PHXlc4Z52sQv4LJQSZLq1ttkKS2yGM3gaI57uQwZkNaoGd0+HPPMELZkcyhlqA== - dependencies: - debug "^4.1.0" - extract-zip "^1.6.6" - https-proxy-agent "^3.0.0" - mime "^2.0.3" - progress "^2.0.1" - proxy-from-env "^1.0.0" - rimraf "^2.6.1" - ws "^6.1.0" - -q@1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/q/-/q-1.4.1.tgz#55705bcd93c5f3673530c2c2cbc0c2b3addc286e" - integrity sha1-VXBbzZPF82c1MMLCy8DCs63cKG4= - -q@^1.4.1, q@^1.5.1: - version "1.5.1" - resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7" - integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc= - -qjobs@^1.1.4: - version "1.2.0" - resolved "https://registry.yarnpkg.com/qjobs/-/qjobs-1.2.0.tgz#c45e9c61800bd087ef88d7e256423bdd49e5d071" - integrity sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg== - -qs@6.7.0: - version "6.7.0" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.7.0.tgz#41dc1a015e3d581f1621776be31afb2876a9b1bc" - integrity sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ== - -qs@~6.5.1, qs@~6.5.2: - version "6.5.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" - integrity sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA== - -query-string@^4.1.0: - version "4.3.4" - resolved "https://registry.yarnpkg.com/query-string/-/query-string-4.3.4.tgz#bbb693b9ca915c232515b228b1a02b609043dbeb" - integrity sha1-u7aTucqRXCMlFbIosaArYJBD2+s= - dependencies: - object-assign "^4.1.0" - strict-uri-encode "^1.0.0" - -querystring-es3@^0.2.0: - version "0.2.1" - resolved "https://registry.yarnpkg.com/querystring-es3/-/querystring-es3-0.2.1.tgz#9ec61f79049875707d69414596fd907a4d711e73" - integrity sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM= - -querystring@0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" - integrity sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA= - -querystringify@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.1.1.tgz#60e5a5fd64a7f8bfa4d2ab2ed6fdf4c85bad154e" - integrity sha512-w7fLxIRCRT7U8Qu53jQnJyPkYZIaR4n5151KMfcJlO/A9397Wxb1amJvROTK6TOnp7PfoAmg/qXiNHI+08jRfA== - -quick-lru@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-1.1.0.tgz#4360b17c61136ad38078397ff11416e186dcfbb8" - integrity sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g= - -quicktype-core@^6.0.15: - version "6.0.52" - resolved "https://registry.yarnpkg.com/quicktype-core/-/quicktype-core-6.0.52.tgz#d646473fd4116ca627c08ace71ed2501437230f4" - integrity sha512-SGYbekWPukIumxpIRAaSq0t12VH3uCl0OHnzFSXFu+cfW5ibo2Z9FktX5lhX291eYs/LXRe2vneZ49i2Z2Qm5Q== - dependencies: - "@mark.probst/unicode-properties" "~1.1.0" - "@types/urijs" "^1.19.1" - collection-utils "^1.0.1" - js-base64 "^2.4.3" - pako "^1.0.6" - pluralize "^7.0.0" - urijs "^1.19.1" - wordwrap "^1.0.0" - yaml "^1.5.0" - -quote-stream@^1.0.1, quote-stream@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/quote-stream/-/quote-stream-1.0.2.tgz#84963f8c9c26b942e153feeb53aae74652b7e0b2" - integrity sha1-hJY/jJwmuULhU/7rU6rnRlK34LI= - dependencies: - buffer-equal "0.0.1" - minimist "^1.1.3" - through2 "^2.0.0" - -randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.5: - version "2.1.0" - resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" - integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== - dependencies: - safe-buffer "^5.1.0" - -randomfill@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/randomfill/-/randomfill-1.0.4.tgz#c92196fc86ab42be983f1bf31778224931d61458" - integrity sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw== - dependencies: - randombytes "^2.0.5" - safe-buffer "^5.1.0" - -range-parser@^1.2.0, range-parser@^1.2.1, range-parser@~1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" - integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== - -raw-body@2.4.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.4.0.tgz#a1ce6fb9c9bc356ca52e89256ab59059e13d0332" - integrity sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q== - dependencies: - bytes "3.1.0" - http-errors "1.7.2" - iconv-lite "0.4.24" - unpipe "1.0.0" - -raw-loader@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/raw-loader/-/raw-loader-3.1.0.tgz#5e9d399a5a222cc0de18f42c3bc5e49677532b3f" - integrity sha512-lzUVMuJ06HF4rYveaz9Tv0WRlUMxJ0Y1hgSkkgg+50iEdaI0TthyEDe08KIHb0XsF6rn8WYTqPCaGTZg3sX+qA== - dependencies: - loader-utils "^1.1.0" - schema-utils "^2.0.1" - -rc@^1.2.7, rc@^1.2.8: - version "1.2.8" - resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" - integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw== - dependencies: - deep-extend "^0.6.0" - ini "~1.3.0" - minimist "^1.2.0" - strip-json-comments "~2.0.1" - -read-cache@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/read-cache/-/read-cache-1.0.0.tgz#e664ef31161166c9751cdbe8dbcf86b5fb58f774" - integrity sha1-5mTvMRYRZsl1HNvo28+GtftY93Q= - dependencies: - pify "^2.3.0" - -read-installed@~4.0.3: - version "4.0.3" - resolved "https://registry.yarnpkg.com/read-installed/-/read-installed-4.0.3.tgz#ff9b8b67f187d1e4c29b9feb31f6b223acd19067" - integrity sha1-/5uLZ/GH0eTCm5/rMfayI6zRkGc= - dependencies: - debuglog "^1.0.1" - read-package-json "^2.0.0" - readdir-scoped-modules "^1.0.0" - semver "2 || 3 || 4 || 5" - slide "~1.1.3" - util-extend "^1.0.1" - optionalDependencies: - graceful-fs "^4.1.2" - -read-package-json@^2.0.0, read-package-json@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-2.1.0.tgz#e3d42e6c35ea5ae820d9a03ab0c7291217fc51d5" - integrity sha512-KLhu8M1ZZNkMcrq1+0UJbR8Dii8KZUqB0Sha4mOx/bknfKI/fyrQVrG/YIt2UOtG667sD8+ee4EXMM91W9dC+A== - dependencies: - glob "^7.1.1" - json-parse-better-errors "^1.0.1" - normalize-package-data "^2.0.0" - slash "^1.0.0" - optionalDependencies: - graceful-fs "^4.1.2" - -read-package-tree@5.3.1: - version "5.3.1" - resolved "https://registry.yarnpkg.com/read-package-tree/-/read-package-tree-5.3.1.tgz#a32cb64c7f31eb8a6f31ef06f9cedf74068fe636" - integrity sha512-mLUDsD5JVtlZxjSlPPx1RETkNjjvQYuweKwNVt1Sn8kP5Jh44pvYuUHCp6xSVDZWbNxVxG5lyZJ921aJH61sTw== - dependencies: - read-package-json "^2.0.0" - readdir-scoped-modules "^1.0.0" - util-promisify "^2.1.0" - -read-pkg-up@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" - integrity sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI= - dependencies: - find-up "^1.0.0" - read-pkg "^1.0.0" - -read-pkg-up@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-3.0.0.tgz#3ed496685dba0f8fe118d0691dc51f4a1ff96f07" - integrity sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc= - dependencies: - find-up "^2.0.0" - read-pkg "^3.0.0" - -read-pkg-up@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-4.0.0.tgz#1b221c6088ba7799601c808f91161c66e58f8978" - integrity sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA== - dependencies: - find-up "^3.0.0" - read-pkg "^3.0.0" - -read-pkg-up@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-5.0.0.tgz#b6a6741cb144ed3610554f40162aa07a6db621b8" - integrity sha512-XBQjqOBtTzyol2CpsQOw8LHV0XbDZVG7xMMjmXAJomlVY03WOBRmYgDJETlvcg0H63AJvPRwT7GFi5rvOzUOKg== - dependencies: - find-up "^3.0.0" - read-pkg "^5.0.0" - -read-pkg@^1.0.0, read-pkg@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" - integrity sha1-9f+qXs0pyzHAR0vKfXVra7KePyg= - dependencies: - load-json-file "^1.0.0" - normalize-package-data "^2.3.2" - path-type "^1.0.0" - -read-pkg@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-3.0.0.tgz#9cbc686978fee65d16c00e2b19c237fcf6e38389" - integrity sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k= - dependencies: - load-json-file "^4.0.0" - normalize-package-data "^2.3.2" - path-type "^3.0.0" - -read-pkg@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-4.0.1.tgz#963625378f3e1c4d48c85872b5a6ec7d5d093237" - integrity sha1-ljYlN48+HE1IyFhytabsfV0JMjc= - dependencies: - normalize-package-data "^2.3.2" - parse-json "^4.0.0" - pify "^3.0.0" - -read-pkg@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-5.2.0.tgz#7bf295438ca5a33e56cd30e053b34ee7250c93cc" - integrity sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg== - dependencies: - "@types/normalize-package-data" "^2.4.0" - normalize-package-data "^2.5.0" - parse-json "^5.0.0" - type-fest "^0.6.0" - -"readable-stream@1 || 2", readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.6, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.0, readable-stream@^2.3.3, readable-stream@^2.3.6, readable-stream@~2.3.3, readable-stream@~2.3.6: - version "2.3.6" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" - integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~2.0.0" - safe-buffer "~5.1.1" - string_decoder "~1.1.1" - util-deprecate "~1.0.1" - -"readable-stream@2 || 3", readable-stream@^3.0.6, readable-stream@^3.4.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.4.0.tgz#a51c26754658e0a3c21dbf59163bd45ba6f447fc" - integrity sha512-jItXPLmrSR8jmTRmRWJXCnGJsfy85mB3Wd/uINMXA65yrnFo0cPClFIUWzo2najVNSl+mx7/4W8ttlLWJe99pQ== - dependencies: - inherits "^2.0.3" - string_decoder "^1.1.1" - util-deprecate "^1.0.1" - -readdir-scoped-modules@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/readdir-scoped-modules/-/readdir-scoped-modules-1.1.0.tgz#8d45407b4f870a0dcaebc0e28670d18e74514309" - integrity sha512-asaikDeqAQg7JifRsZn1NJZXo9E+VwlyCfbkZhwyISinqk5zNS6266HS5kah6P0SaQKGF6SkNnZVHUzHFYxYDw== - dependencies: - debuglog "^1.0.1" - dezalgo "^1.0.0" - graceful-fs "^4.1.2" - once "^1.3.0" - -readdirp@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" - integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== - dependencies: - graceful-fs "^4.1.11" - micromatch "^3.1.10" - readable-stream "^2.0.2" - -readdirp@~3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.2.0.tgz#c30c33352b12c96dfb4b895421a49fd5a9593839" - integrity sha512-crk4Qu3pmXwgxdSgGhgA/eXiJAPQiX4GMOZZMXnqKxHX7TaoL+3gQVo/WeuAiogr07DpnfjIMpXXa+PAIvwPGQ== - dependencies: - picomatch "^2.0.4" - -redent@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde" - integrity sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94= - dependencies: - indent-string "^2.1.0" - strip-indent "^1.0.1" - -redent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/redent/-/redent-2.0.0.tgz#c1b2007b42d57eb1389079b3c8333639d5e1ccaa" - integrity sha1-wbIAe0LVfrE4kHmzyDM2OdXhzKo= - dependencies: - indent-string "^3.0.0" - strip-indent "^2.0.0" - -reflect-metadata@^0.1.2: - version "0.1.13" - resolved "https://registry.yarnpkg.com/reflect-metadata/-/reflect-metadata-0.1.13.tgz#67ae3ca57c972a2aa1642b10fe363fe32d49dc08" - integrity sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg== - -regenerate-unicode-properties@^8.1.0: - version "8.1.0" - resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz#ef51e0f0ea4ad424b77bf7cb41f3e015c70a3f0e" - integrity sha512-LGZzkgtLY79GeXLm8Dp0BVLdQlWICzBnJz/ipWUgo59qBaZ+BHtq51P2q1uVZlppMuUAT37SDk39qUbjTWB7bA== - dependencies: - regenerate "^1.4.0" - -regenerate@^1.2.1, regenerate@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.4.0.tgz#4a856ec4b56e4077c557589cae85e7a4c8869a11" - integrity sha512-1G6jJVDWrt0rK99kBjvEtziZNCICAuvIPkSiUFIQxVP06RCVpq3dmDo2oi6ABpYaDYaTRr67BEhL8r1wgEZZKg== - -regenerator-runtime@0.13.3, regenerator-runtime@^0.13.2: - version "0.13.3" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz#7cf6a77d8f5c6f60eb73c5fc1955b2ceb01e6bf5" - integrity sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw== - -regenerator-runtime@^0.11.0: - version "0.11.1" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9" - integrity sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg== - -regenerator-transform@^0.14.0: - version "0.14.1" - resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.14.1.tgz#3b2fce4e1ab7732c08f665dfdb314749c7ddd2fb" - integrity sha512-flVuee02C3FKRISbxhXl9mGzdbWUVHubl1SMaknjxkFB1/iqpJhArQUvRxOOPEc/9tAiX0BaQ28FJH10E4isSQ== - dependencies: - private "^0.1.6" - -regex-not@^1.0.0, regex-not@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" - integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== - dependencies: - extend-shallow "^3.0.2" - safe-regex "^1.1.0" - -regexp.prototype.flags@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/regexp.prototype.flags/-/regexp.prototype.flags-1.2.0.tgz#6b30724e306a27833eeb171b66ac8890ba37e41c" - integrity sha512-ztaw4M1VqgMwl9HlPpOuiYgItcHlunW0He2fE6eNfT6E/CF2FtYi9ofOYe4mKntstYk0Fyh/rDRBdS3AnxjlrA== - dependencies: - define-properties "^1.1.2" - -regexpu-core@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-1.0.0.tgz#86a763f58ee4d7c2f6b102e4764050de7ed90c6b" - integrity sha1-hqdj9Y7k18L2sQLkdkBQ3n7ZDGs= - dependencies: - regenerate "^1.2.1" - regjsgen "^0.2.0" - regjsparser "^0.1.4" - -regexpu-core@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-4.6.0.tgz#2037c18b327cfce8a6fea2a4ec441f2432afb8b6" - integrity sha512-YlVaefl8P5BnFYOITTNzDvan1ulLOiXJzCNZxduTIosN17b87h3bvG9yHMoHaRuo88H4mQ06Aodj5VtYGGGiTg== - dependencies: - regenerate "^1.4.0" - regenerate-unicode-properties "^8.1.0" - regjsgen "^0.5.0" - regjsparser "^0.6.0" - unicode-match-property-ecmascript "^1.0.4" - unicode-match-property-value-ecmascript "^1.1.0" - -registry-auth-token@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/registry-auth-token/-/registry-auth-token-4.0.0.tgz#30e55961eec77379da551ea5c4cf43cbf03522be" - integrity sha512-lpQkHxd9UL6tb3k/aHAVfnVtn+Bcs9ob5InuFLLEDqSqeq+AljB8GZW9xY0x7F+xYwEcjKe07nyoxzEYz6yvkw== - dependencies: - rc "^1.2.8" - safe-buffer "^5.0.1" - -registry-url@^5.0.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/registry-url/-/registry-url-5.1.0.tgz#e98334b50d5434b81136b44ec638d9c2009c5009" - integrity sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw== - dependencies: - rc "^1.2.8" - -regjsgen@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.2.0.tgz#6c016adeac554f75823fe37ac05b92d5a4edb1f7" - integrity sha1-bAFq3qxVT3WCP+N6wFuS1aTtsfc= - -regjsgen@^0.5.0: - version "0.5.1" - resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.5.1.tgz#48f0bf1a5ea205196929c0d9798b42d1ed98443c" - integrity sha512-5qxzGZjDs9w4tzT3TPhCJqWdCc3RLYwy9J2NB0nm5Lz+S273lvWcpjaTGHsT1dc6Hhfq41uSEOw8wBmxrKOuyg== - -regjsparser@^0.1.4: - version "0.1.5" - resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.1.5.tgz#7ee8f84dc6fa792d3fd0ae228d24bd949ead205c" - integrity sha1-fuj4Tcb6eS0/0K4ijSS9lJ6tIFw= - dependencies: - jsesc "~0.5.0" - -regjsparser@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.6.0.tgz#f1e6ae8b7da2bae96c99399b868cd6c933a2ba9c" - integrity sha512-RQ7YyokLiQBomUJuUG8iGVvkgOLxwyZM8k6d3q5SAXpg4r5TZJZigKFvC6PpD+qQ98bCDC5YelPeA3EucDoNeQ== - dependencies: - jsesc "~0.5.0" - -remove-trailing-separator@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" - integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= - -repeat-element@^1.1.2: - version "1.1.3" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" - integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== - -repeat-string@^1.6.1: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" - integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= - -repeating@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" - integrity sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo= - dependencies: - is-finite "^1.0.0" - -request-promise-core@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/request-promise-core/-/request-promise-core-1.1.3.tgz#e9a3c081b51380dfea677336061fea879a829ee9" - integrity sha512-QIs2+ArIGQVp5ZYbWD5ZLCY29D5CfWizP8eWnm8FoGD1TX61veauETVQbrV60662V0oFBkrDOuaBI8XgtuyYAQ== - dependencies: - lodash "^4.17.15" - -request-promise-native@^1.0.7: - version "1.0.8" - resolved "https://registry.yarnpkg.com/request-promise-native/-/request-promise-native-1.0.8.tgz#a455b960b826e44e2bf8999af64dff2bfe58cb36" - integrity sha512-dapwLGqkHtwL5AEbfenuzjTYg35Jd6KPytsC2/TLkVMz8rm+tNt72MGUWT1RP/aYawMpN6HqbNGBQaRcBtjQMQ== - dependencies: - request-promise-core "1.1.3" - stealthy-require "^1.1.1" - tough-cookie "^2.3.3" - -request@2.87.0: - version "2.87.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.87.0.tgz#32f00235cd08d482b4d0d68db93a829c0ed5756e" - integrity sha512-fcogkm7Az5bsS6Sl0sibkbhcKsnyon/jV1kF3ajGmF0c8HrttdKTPRT9hieOaQHA5HEq6r8OyWOo/o781C1tNw== - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.6.0" - caseless "~0.12.0" - combined-stream "~1.0.5" - extend "~3.0.1" - forever-agent "~0.6.1" - form-data "~2.3.1" - har-validator "~5.0.3" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.17" - oauth-sign "~0.8.2" - performance-now "^2.1.0" - qs "~6.5.1" - safe-buffer "^5.1.1" - tough-cookie "~2.3.3" - tunnel-agent "^0.6.0" - uuid "^3.1.0" - -request@2.88.0, request@^2.74.0, request@^2.83.0, request@^2.87.0, request@^2.88.0: - version "2.88.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.88.0.tgz#9c2fca4f7d35b592efe57c7f0a55e81052124fef" - integrity sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg== - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.8.0" - caseless "~0.12.0" - combined-stream "~1.0.6" - extend "~3.0.2" - forever-agent "~0.6.1" - form-data "~2.3.2" - har-validator "~5.1.0" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.19" - oauth-sign "~0.9.0" - performance-now "^2.1.0" - qs "~6.5.2" - safe-buffer "^5.1.2" - tough-cookie "~2.4.3" - tunnel-agent "^0.6.0" - uuid "^3.3.2" - -require-directory@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" - integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= - -require-main-filename@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" - integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE= - -require-main-filename@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" - integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== - -requirejs@2.3.5: - version "2.3.5" - resolved "https://registry.yarnpkg.com/requirejs/-/requirejs-2.3.5.tgz#617b9acbbcb336540ef4914d790323a8d4b861b0" - integrity sha512-svnO+aNcR/an9Dpi44C7KSAy5fFGLtmPbaaCeQaklUz8BQhS64tWWIIlvEA5jrWICzlO/X9KSzSeXFnZdBu8nw== - -requires-port@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" - integrity sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8= - -resolve-cwd@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-2.0.0.tgz#00a9f7387556e27038eae232caa372a6a59b665a" - integrity sha1-AKn3OHVW4nA46uIyyqNypqWbZlo= - dependencies: - resolve-from "^3.0.0" - -resolve-from@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-3.0.0.tgz#b22c7af7d9d6881bc8b6e653335eebcb0a188748" - integrity sha1-six699nWiBvItuZTM17rywoYh0g= - -resolve-url@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" - integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= - -resolve@^1.1.5, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.11.0, resolve@^1.11.1, resolve@^1.3.2: - version "1.12.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.12.0.tgz#3fc644a35c84a48554609ff26ec52b66fa577df6" - integrity sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w== - dependencies: - path-parse "^1.0.6" - -responselike@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/responselike/-/responselike-1.0.2.tgz#918720ef3b631c5642be068f15ade5a46f4ba1e7" - integrity sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec= - dependencies: - lowercase-keys "^1.0.0" - -restore-cursor@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" - integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== - dependencies: - onetime "^5.1.0" - signal-exit "^3.0.2" - -ret@~0.1.10: - version "0.1.15" - resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" - integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== - -retry@^0.10.0: - version "0.10.1" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.10.1.tgz#e76388d217992c252750241d3d3956fed98d8ff4" - integrity sha1-52OI0heZLCUnUCQdPTlW/tmNj/Q= - -retry@^0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b" - integrity sha1-G0KmJmoh8HQh0bC1S33BZ7AcATs= - -rfdc@^1.1.2, rfdc@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.1.4.tgz#ba72cc1367a0ccd9cf81a870b3b58bd3ad07f8c2" - integrity sha512-5C9HXdzK8EAqN7JDif30jqsBzavB7wLpaubisuQIGHWf2gUXSpzy6ArX/+Da8RjFpagWsCn+pIgxTMAmKw9Zug== - -rimraf@3.0.0, rimraf@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.0.tgz#614176d4b3010b75e5c390eb0ee96f6dc0cebb9b" - integrity sha512-NDGVxTsjqfunkds7CqsOiEnxln4Bo7Nddl3XhS4pXg5OzwkLqJ971ZVAAnB+DDLnF76N+VnDEiBHaVV8I06SUg== - dependencies: - glob "^7.1.3" - -rimraf@^2.2.8, rimraf@^2.5.2, rimraf@^2.5.4, rimraf@^2.6.0, rimraf@^2.6.1, rimraf@^2.6.2, rimraf@^2.6.3, rimraf@^2.7.1: - version "2.7.1" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" - integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== - dependencies: - glob "^7.1.3" - -rimraf@~2.4.0: - version "2.4.5" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.4.5.tgz#ee710ce5d93a8fdb856fb5ea8ff0e2d75934b2da" - integrity sha1-7nEM5dk6j9uFb7Xqj/Di11k0sto= - dependencies: - glob "^6.0.1" - -rimraf@~2.6.2: - version "2.6.3" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" - integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== - dependencies: - glob "^7.1.3" - -ripemd160@^2.0.0, ripemd160@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.2.tgz#a1c1a6f624751577ba5d07914cbc92850585890c" - integrity sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA== - dependencies: - hash-base "^3.0.0" - inherits "^2.0.1" - -rollup-plugin-commonjs@^10.1.0: - version "10.1.0" - resolved "https://registry.yarnpkg.com/rollup-plugin-commonjs/-/rollup-plugin-commonjs-10.1.0.tgz#417af3b54503878e084d127adf4d1caf8beb86fb" - integrity sha512-jlXbjZSQg8EIeAAvepNwhJj++qJWNJw1Cl0YnOqKtP5Djx+fFGkp3WRh+W0ASCaFG5w1jhmzDxgu3SJuVxPF4Q== - dependencies: - estree-walker "^0.6.1" - is-reference "^1.1.2" - magic-string "^0.25.2" - resolve "^1.11.0" - rollup-pluginutils "^2.8.1" - -rollup-plugin-json@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/rollup-plugin-json/-/rollup-plugin-json-4.0.0.tgz#a18da0a4b30bf5ca1ee76ddb1422afbb84ae2b9e" - integrity sha512-hgb8N7Cgfw5SZAkb3jf0QXii6QX/FOkiIq2M7BAQIEydjHvTyxXHQiIzZaTFgx1GK0cRCHOCBHIyEkkLdWKxow== - dependencies: - rollup-pluginutils "^2.5.0" - -rollup-plugin-node-resolve@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-5.2.0.tgz#730f93d10ed202473b1fb54a5997a7db8c6d8523" - integrity sha512-jUlyaDXts7TW2CqQ4GaO5VJ4PwwaV8VUGA7+km3n6k6xtOEacf61u0VXwN80phY/evMcaS+9eIeJ9MOyDxt5Zw== - dependencies: - "@types/resolve" "0.0.8" - builtin-modules "^3.1.0" - is-module "^1.0.0" - resolve "^1.11.1" - rollup-pluginutils "^2.8.1" - -rollup-plugin-sourcemaps@^0.4.2: - version "0.4.2" - resolved "https://registry.yarnpkg.com/rollup-plugin-sourcemaps/-/rollup-plugin-sourcemaps-0.4.2.tgz#62125aa94087aadf7b83ef4dfaf629b473135e87" - integrity sha1-YhJaqUCHqt97g+9N+vYptHMTXoc= - dependencies: - rollup-pluginutils "^2.0.1" - source-map-resolve "^0.5.0" - -rollup-pluginutils@^2.0.1, rollup-pluginutils@^2.5.0, rollup-pluginutils@^2.8.1: - version "2.8.2" - resolved "https://registry.yarnpkg.com/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz#72f2af0748b592364dbd3389e600e5a9444a351e" - integrity sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ== - dependencies: - estree-walker "^0.6.1" - -rollup@1.25.2: - version "1.25.2" - resolved "https://registry.yarnpkg.com/rollup/-/rollup-1.25.2.tgz#739f508bd8f7ece52bb6c1fcda83466af82b7f6d" - integrity sha512-+7z6Wab/L45QCPcfpuTZKwKiB0tynj05s/+s2U3F2Bi7rOLPr9UcjUwO7/xpjlPNXA/hwnth6jBExFRGyf3tMg== - dependencies: - "@types/estree" "*" - "@types/node" "*" - acorn "^7.1.0" - -rollup@1.27.2: - version "1.27.2" - resolved "https://registry.yarnpkg.com/rollup/-/rollup-1.27.2.tgz#caf54a93df228bf7864f13dddcdb363d3e958509" - integrity sha512-sD3iyd0zlvgK1S3MmICi6F/Y+R/QWY5XxzsTGN4pAd+nCasDUizmAhgq2hdh1t2eLux974NHU2TW41fhuGPv+Q== - dependencies: - "@types/estree" "*" - "@types/node" "*" - acorn "^7.1.0" - -run-async@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.3.0.tgz#0371ab4ae0bdd720d4166d7dfda64ff7a445a6c0" - integrity sha1-A3GrSuC91yDUFm19/aZP96RFpsA= - dependencies: - is-promise "^2.1.0" - -run-node@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/run-node/-/run-node-1.0.0.tgz#46b50b946a2aa2d4947ae1d886e9856fd9cabe5e" - integrity sha512-kc120TBlQ3mih1LSzdAJXo4xn/GWS2ec0l3S+syHDXP9uRr0JAT8Qd3mdMuyjqCzeZktgP3try92cEgf9Nks8A== - -run-queue@^1.0.0, run-queue@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/run-queue/-/run-queue-1.0.3.tgz#e848396f057d223f24386924618e25694161ec47" - integrity sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec= - dependencies: - aproba "^1.1.1" - -rxjs@6.5.3, rxjs@^6.4.0, rxjs@^6.5.0: - version "6.5.3" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.5.3.tgz#510e26317f4db91a7eb1de77d9dd9ba0a4899a3a" - integrity sha512-wuYsAYYFdWTAnAaPoKGNhfpWwKZbJW+HgAJ+mImp+Epl7BG8oNWBCTyRM8gba9k4lk8BgWdoYm21Mo/RYhhbgA== - dependencies: - tslib "^1.9.0" - -safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.2" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" - integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== - -safe-buffer@>=5.1.0, safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@^5.2.0, safe-buffer@~5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.0.tgz#b74daec49b1148f88c64b68d49b1e815c1f2f519" - integrity sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg== - -safe-json-stringify@~1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/safe-json-stringify/-/safe-json-stringify-1.2.0.tgz#356e44bc98f1f93ce45df14bcd7c01cda86e0afd" - integrity sha512-gH8eh2nZudPQO6TytOvbxnuhYBOvDBBLW52tz5q6X58lJcd/tkmqFR+5Z9adS8aJtURSXWThWy/xJtJwixErvg== - -safe-regex@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" - integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= - dependencies: - ret "~0.1.10" - -"safer-buffer@>= 2.1.2 < 3", safer-buffer@^2.0.2, safer-buffer@^2.1.0, safer-buffer@^2.1.2, safer-buffer@~2.1.0: - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== - -sass-loader@8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/sass-loader/-/sass-loader-8.0.0.tgz#e7b07a3e357f965e6b03dd45b016b0a9746af797" - integrity sha512-+qeMu563PN7rPdit2+n5uuYVR0SSVwm0JsOUsaJXzgYcClWSlmX0iHDnmeOobPkf5kUglVot3QS6SyLyaQoJ4w== - dependencies: - clone-deep "^4.0.1" - loader-utils "^1.2.3" - neo-async "^2.6.1" - schema-utils "^2.1.0" - semver "^6.3.0" - -sass@1.23.6: - version "1.23.6" - resolved "https://registry.yarnpkg.com/sass/-/sass-1.23.6.tgz#7cce6dbeac1b8caeb33301a817642ee2708f7d7e" - integrity sha512-awBvj9xrAuiS2TOCcYSUGCmaBV3UW6fVSK4oJ2LHS8IRfnRLc5EJihw90C7ZJ/skcEwFGSf9/XO5NlMiKupBCg== - dependencies: - chokidar ">=2.0.0 <4.0.0" - -sass@^1.23.0: - version "1.23.3" - resolved "https://registry.yarnpkg.com/sass/-/sass-1.23.3.tgz#f07503b9e8d2bcf06ef69e8beea5d085589b1620" - integrity sha512-1DKRZxJMOh4Bme16AbWTyYeJAjTlrvw2+fWshHHaepeJfGq2soFZTnt0YhWit+bohtDu4LdyPoEj6VFD4APHog== - dependencies: - chokidar ">=2.0.0 <4.0.0" - -sauce-connect-launcher@^1.2.4: - version "1.3.1" - resolved "https://registry.yarnpkg.com/sauce-connect-launcher/-/sauce-connect-launcher-1.3.1.tgz#31137f57b0f7176e1c0525b7fb09c6da746647cf" - integrity sha512-vIf9qDol3q2FlYzrKt0dr3kvec6LSjX2WS+/mVnAJIhqh1evSkPKCR2AzcJrnSmx9Xt9PtV0tLY7jYh0wsQi8A== - dependencies: - adm-zip "~0.4.3" - async "^2.1.2" - https-proxy-agent "^3.0.0" - lodash "^4.16.6" - rimraf "^2.5.4" - -"sauce-connect-proxy@https://saucelabs.com/downloads/sc-4.5.4-linux.tar.gz": - version "0.0.0" - uid dc5efcd2be24ddb099a85b923d6e754754651fa8 - resolved "https://saucelabs.com/downloads/sc-4.5.4-linux.tar.gz#dc5efcd2be24ddb099a85b923d6e754754651fa8" - -saucelabs@^1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/saucelabs/-/saucelabs-1.5.0.tgz#9405a73c360d449b232839919a86c396d379fd9d" - integrity sha512-jlX3FGdWvYf4Q3LFfFWS1QvPg3IGCGWxIc8QBFdPTbpTJnt/v17FHXYVAn7C8sHf1yUXo2c7yIM0isDryfYtHQ== - dependencies: - https-proxy-agent "^2.2.1" - -sax@>=0.6.0, sax@^1.2.4, sax@~1.2.4: - version "1.2.4" - resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" - integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== - -saxes@^3.1.9: - version "3.1.11" - resolved "https://registry.yarnpkg.com/saxes/-/saxes-3.1.11.tgz#d59d1fd332ec92ad98a2e0b2ee644702384b1c5b" - integrity sha512-Ydydq3zC+WYDJK1+gRxRapLIED9PWeSuuS41wqyoRmzvhhh9nc+QQrVMKJYzJFULazeGhzSV0QleN2wD3boh2g== - dependencies: - xmlchars "^2.1.1" - -schema-utils@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.3.0.tgz#f5877222ce3e931edae039f17eb3716e7137f8cf" - integrity sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8= - dependencies: - ajv "^5.0.0" - -schema-utils@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-1.0.0.tgz#0b79a93204d7b600d4b2850d1f66c2a34951c770" - integrity sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g== - dependencies: - ajv "^6.1.0" - ajv-errors "^1.0.0" - ajv-keywords "^3.1.0" - -schema-utils@^2.0.0, schema-utils@^2.0.1, schema-utils@^2.1.0, schema-utils@^2.5.0: - version "2.5.0" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.5.0.tgz#8f254f618d402cc80257486213c8970edfd7c22f" - integrity sha512-32ISrwW2scPXHUSusP8qMg5dLUawKkyV+/qIEV9JdXKx+rsM6mi8vZY8khg2M69Qom16rtroWXD3Ybtiws38gQ== - dependencies: - ajv "^6.10.2" - ajv-keywords "^3.4.1" - -seedrandom@^2.4.4: - version "2.4.4" - resolved "https://registry.yarnpkg.com/seedrandom/-/seedrandom-2.4.4.tgz#b25ea98632c73e45f58b77cfaa931678df01f9ba" - integrity sha512-9A+PDmgm+2du77B5i0Ip2cxOqqHjgNxnBgglxLcX78A2D6c2rTo61z4jnVABpF4cKeDMDG+cmXXvdnqse2VqMA== - -select-hose@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/select-hose/-/select-hose-2.0.0.tgz#625d8658f865af43ec962bfc376a37359a4994ca" - integrity sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo= - -selenium-webdriver@3.6.0, selenium-webdriver@^3.0.1: - version "3.6.0" - resolved "https://registry.yarnpkg.com/selenium-webdriver/-/selenium-webdriver-3.6.0.tgz#2ba87a1662c020b8988c981ae62cb2a01298eafc" - integrity sha512-WH7Aldse+2P5bbFBO4Gle/nuQOdVwpHMTL6raL3uuBj/vPG07k6uzt3aiahu352ONBr5xXh0hDlM3LhtXPOC4Q== - dependencies: - jszip "^3.1.3" - rimraf "^2.5.4" - tmp "0.0.30" - xml2js "^0.4.17" - -selenium-webdriver@^4.0.0-alpha.1: - version "4.0.0-alpha.5" - resolved "https://registry.yarnpkg.com/selenium-webdriver/-/selenium-webdriver-4.0.0-alpha.5.tgz#e4683b3dbf827d70df09a7e43bf02ebad20fa7c1" - integrity sha512-hktl3DSrhzM59yLhWzDGHIX9o56DvA+cVK7Dw6FcJR6qQ4CGzkaHeXQPcdrslkWMTeq0Ci9AmCxq0EMOvm2Rkg== - dependencies: - jszip "^3.1.5" - rimraf "^2.6.3" - tmp "0.0.30" - xml2js "^0.4.19" - -selfsigned@^1.10.7: - version "1.10.7" - resolved "https://registry.yarnpkg.com/selfsigned/-/selfsigned-1.10.7.tgz#da5819fd049d5574f28e88a9bcc6dbc6e6f3906b" - integrity sha512-8M3wBCzeWIJnQfl43IKwOmC4H/RAp50S8DF60znzjW5GVqTcSe2vWclt7hmYVPkKPlHWOu5EaWOMZ2Y6W8ZXTA== - dependencies: - node-forge "0.9.0" - -semver-compare@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" - integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= - -semver-diff@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/semver-diff/-/semver-diff-2.1.0.tgz#4bbb8437c8d37e4b0cf1a68fd726ec6d645d6d36" - integrity sha1-S7uEN8jTfksM8aaP1ybsbWRdbTY= - dependencies: - semver "^5.0.3" - -semver-dsl@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/semver-dsl/-/semver-dsl-1.0.1.tgz#d3678de5555e8a61f629eed025366ae5f27340a0" - integrity sha1-02eN5VVeimH2Ke7QJTZq5fJzQKA= - dependencies: - semver "^5.3.0" - -semver-intersect@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/semver-intersect/-/semver-intersect-1.4.0.tgz#bdd9c06bedcdd2fedb8cd352c3c43ee8c61321f3" - integrity sha512-d8fvGg5ycKAq0+I6nfWeCx6ffaWJCsBYU0H2Rq56+/zFePYfT8mXkB3tWBSjR5BerkHNZ5eTPIk1/LBYas35xQ== - dependencies: - semver "^5.0.0" - -"semver@2 >=2.2.1 || 3.x || 4 || 5", "semver@2 || 3 || 4 || 5", semver@^5.0.0, semver@^5.0.3, semver@^5.3.0, semver@^5.4.1, semver@^5.5.0, semver@^5.6.0: - version "5.7.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" - integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== - -semver@5.6.0: - version "5.6.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.6.0.tgz#7e74256fbaa49c75aa7c7a205cc22799cac80004" - integrity sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg== - -semver@6.3.0, semver@^6.0.0, semver@^6.2.0, semver@^6.3.0: - version "6.3.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" - integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== - -send@0.17.1: - version "0.17.1" - resolved "https://registry.yarnpkg.com/send/-/send-0.17.1.tgz#c1d8b059f7900f7466dd4938bdc44e11ddb376c8" - integrity sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg== - dependencies: - debug "2.6.9" - depd "~1.1.2" - destroy "~1.0.4" - encodeurl "~1.0.2" - escape-html "~1.0.3" - etag "~1.8.1" - fresh "0.5.2" - http-errors "~1.7.2" - mime "1.6.0" - ms "2.1.1" - on-finished "~2.3.0" - range-parser "~1.2.1" - statuses "~1.5.0" - -serialize-javascript@^1.7.0: - version "1.9.1" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-1.9.1.tgz#cfc200aef77b600c47da9bb8149c943e798c2fdb" - integrity sha512-0Vb/54WJ6k5v8sSWN09S0ora+Hnr+cX40r9F170nT+mSkaxltoE/7R3OrIdBSUv1OoiobH1QoWQbCnAO+e8J1A== - -serialize-javascript@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-2.1.0.tgz#9310276819efd0eb128258bb341957f6eb2fc570" - integrity sha512-a/mxFfU00QT88umAJQsNWOnUKckhNCqOl028N48e7wFmo2/EHpTo9Wso+iJJCMrQnmFvcjto5RJdAHEvVhcyUQ== - -serve-index@^1.9.1: - version "1.9.1" - resolved "https://registry.yarnpkg.com/serve-index/-/serve-index-1.9.1.tgz#d3768d69b1e7d82e5ce050fff5b453bea12a9239" - integrity sha1-03aNabHn2C5c4FD/9bRTvqEqkjk= - dependencies: - accepts "~1.3.4" - batch "0.6.1" - debug "2.6.9" - escape-html "~1.0.3" - http-errors "~1.6.2" - mime-types "~2.1.17" - parseurl "~1.3.2" - -serve-static@1.14.1: - version "1.14.1" - resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.14.1.tgz#666e636dc4f010f7ef29970a88a674320898b2f9" - integrity sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg== - dependencies: - encodeurl "~1.0.2" - escape-html "~1.0.3" - parseurl "~1.3.3" - send "0.17.1" - -set-blocking@^2.0.0, set-blocking@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" - integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= - -set-immediate-shim@~1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz#4b2b1b27eb808a9f8dcc481a58e5e56f599f3f61" - integrity sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E= - -set-value@^2.0.0, set-value@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" - integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== - dependencies: - extend-shallow "^2.0.1" - is-extendable "^0.1.1" - is-plain-object "^2.0.3" - split-string "^3.0.1" - -setimmediate@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" - integrity sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU= - -setprototypeof@1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656" - integrity sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ== - -setprototypeof@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.1.tgz#7e95acb24aa92f5885e0abef5ba131330d4ae683" - integrity sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw== - -sha.js@^2.4.0, sha.js@^2.4.8: - version "2.4.11" - resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.11.tgz#37a5cf0b81ecbc6943de109ba2960d1b26584ae7" - integrity sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ== - dependencies: - inherits "^2.0.1" - safe-buffer "^5.0.1" - -shallow-clone@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" - integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== - dependencies: - kind-of "^6.0.2" - -shallow-copy@~0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/shallow-copy/-/shallow-copy-0.0.1.tgz#415f42702d73d810330292cc5ee86eae1a11a170" - integrity sha1-QV9CcC1z2BAzApLMXuhurhoRoXA= - -shebang-command@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" - integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= - dependencies: - shebang-regex "^1.0.0" - -shebang-regex@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" - integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= - -signal-exit@^3.0.0, signal-exit@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" - integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0= - -slash@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" - integrity sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU= - -slash@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-2.0.0.tgz#de552851a1759df3a8f206535442f5ec4ddeab44" - integrity sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A== - -slide@^1.1.3, slide@~1.1.3: - version "1.1.6" - resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" - integrity sha1-VusCfWW00tzmyy4tMsTUr8nh1wc= - -smart-buffer@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.1.0.tgz#91605c25d91652f4661ea69ccf45f1b331ca21ba" - integrity sha512-iVICrxOzCynf/SNaBQCw34eM9jROU/s5rzIhpOvzhzuYHfJR/DhZfDkXiZSgKXfgv26HT3Yni3AV/DGw0cGnnw== - -snapdragon-node@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" - integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== - dependencies: - define-property "^1.0.0" - isobject "^3.0.0" - snapdragon-util "^3.0.1" - -snapdragon-util@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" - integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== - dependencies: - kind-of "^3.2.0" - -snapdragon@^0.8.1: - version "0.8.2" - resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" - integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== - dependencies: - base "^0.11.1" - debug "^2.2.0" - define-property "^0.2.5" - extend-shallow "^2.0.1" - map-cache "^0.2.2" - source-map "^0.5.6" - source-map-resolve "^0.5.0" - use "^3.1.0" - -socket.io-adapter@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/socket.io-adapter/-/socket.io-adapter-1.1.1.tgz#2a805e8a14d6372124dd9159ad4502f8cb07f06b" - integrity sha1-KoBeihTWNyEk3ZFZrUUC+MsH8Gs= - -socket.io-client@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/socket.io-client/-/socket.io-client-2.1.1.tgz#dcb38103436ab4578ddb026638ae2f21b623671f" - integrity sha512-jxnFyhAuFxYfjqIgduQlhzqTcOEQSn+OHKVfAxWaNWa7ecP7xSNk2Dx/3UEsDcY7NcFafxvNvKPmmO7HTwTxGQ== - dependencies: - backo2 "1.0.2" - base64-arraybuffer "0.1.5" - component-bind "1.0.0" - component-emitter "1.2.1" - debug "~3.1.0" - engine.io-client "~3.2.0" - has-binary2 "~1.0.2" - has-cors "1.1.0" - indexof "0.0.1" - object-component "0.0.3" - parseqs "0.0.5" - parseuri "0.0.5" - socket.io-parser "~3.2.0" - to-array "0.1.4" - -socket.io-parser@~3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/socket.io-parser/-/socket.io-parser-3.2.0.tgz#e7c6228b6aa1f814e6148aea325b51aa9499e077" - integrity sha512-FYiBx7rc/KORMJlgsXysflWx/RIvtqZbyGLlHZvjfmPTPeuD/I8MaW7cfFrj5tRltICJdgwflhfZ3NVVbVLFQA== - dependencies: - component-emitter "1.2.1" - debug "~3.1.0" - isarray "2.0.1" - -socket.io@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/socket.io/-/socket.io-2.1.1.tgz#a069c5feabee3e6b214a75b40ce0652e1cfb9980" - integrity sha512-rORqq9c+7W0DAK3cleWNSyfv/qKXV99hV4tZe+gGLfBECw3XEhBy7x85F3wypA9688LKjtwO9pX9L33/xQI8yA== - dependencies: - debug "~3.1.0" - engine.io "~3.2.0" - has-binary2 "~1.0.2" - socket.io-adapter "~1.1.0" - socket.io-client "2.1.1" - socket.io-parser "~3.2.0" - -sockjs-client@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/sockjs-client/-/sockjs-client-1.4.0.tgz#c9f2568e19c8fd8173b4997ea3420e0bb306c7d5" - integrity sha512-5zaLyO8/nri5cua0VtOrFXBPK1jbL4+1cebT/mmKA1E1ZXOvJrII75bPu0l0k843G/+iAbhEqzyKr0w/eCCj7g== - dependencies: - debug "^3.2.5" - eventsource "^1.0.7" - faye-websocket "~0.11.1" - inherits "^2.0.3" - json3 "^3.3.2" - url-parse "^1.4.3" - -sockjs@0.3.19: - version "0.3.19" - resolved "https://registry.yarnpkg.com/sockjs/-/sockjs-0.3.19.tgz#d976bbe800af7bd20ae08598d582393508993c0d" - integrity sha512-V48klKZl8T6MzatbLlzzRNhMepEys9Y4oGFpypBFFn1gLI/QQ9HtLLyWJNbPlwGLelOVOEijUbTTJeLLI59jLw== - dependencies: - faye-websocket "^0.10.0" - uuid "^3.0.1" - -socks-proxy-agent@^4.0.0: - version "4.0.2" - resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-4.0.2.tgz#3c8991f3145b2799e70e11bd5fbc8b1963116386" - integrity sha512-NT6syHhI9LmuEMSK6Kd2V7gNv5KFZoLE7V5udWmn0de+3Mkj3UMA/AJPLyeNUVmElCurSHtUdM3ETpR3z770Wg== - dependencies: - agent-base "~4.2.1" - socks "~2.3.2" - -socks@~2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/socks/-/socks-2.3.3.tgz#01129f0a5d534d2b897712ed8aceab7ee65d78e3" - integrity sha512-o5t52PCNtVdiOvzMry7wU4aOqYWL0PeCXRWBEiJow4/i/wr+wpsJQ9awEu1EonLIqsfGd5qSgDdxEOvCdmBEpA== - dependencies: - ip "1.1.5" - smart-buffer "^4.1.0" - -sort-keys@^1.0.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/sort-keys/-/sort-keys-1.1.2.tgz#441b6d4d346798f1b4e49e8920adfba0e543f9ad" - integrity sha1-RBttTTRnmPG05J6JIK37oOVD+a0= - dependencies: - is-plain-obj "^1.0.0" - -source-list-map@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/source-list-map/-/source-list-map-2.0.1.tgz#3993bd873bfc48479cca9ea3a547835c7c154b34" - integrity sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw== - -source-map-loader@0.2.4: - version "0.2.4" - resolved "https://registry.yarnpkg.com/source-map-loader/-/source-map-loader-0.2.4.tgz#c18b0dc6e23bf66f6792437557c569a11e072271" - integrity sha512-OU6UJUty+i2JDpTItnizPrlpOIBLmQbWMuBg9q5bVtnHACqw1tn9nNwqJLbv0/00JjnJb/Ee5g5WS5vrRv7zIQ== - dependencies: - async "^2.5.0" - loader-utils "^1.1.0" - -source-map-resolve@^0.5.0, source-map-resolve@^0.5.2: - version "0.5.2" - resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259" - integrity sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA== - dependencies: - atob "^2.1.1" - decode-uri-component "^0.2.0" - resolve-url "^0.2.1" - source-map-url "^0.4.0" - urix "^0.1.0" - -source-map-support@0.5.16, source-map-support@^0.5.0, source-map-support@^0.5.3, source-map-support@^0.5.5, source-map-support@~0.5.12: - version "0.5.16" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.16.tgz#0ae069e7fe3ba7538c64c98515e35339eac5a042" - integrity sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map-support@0.5.9: - version "0.5.9" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.9.tgz#41bc953b2534267ea2d605bccfa7bfa3111ced5f" - integrity sha512-gR6Rw4MvUlYy83vP0vxoVNzM6t8MUXqNuRsuBmBHQDu1Fh6X015FrLdgoDKcNdkwGubozq0P4N0Q37UyFVr1EA== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map-support@~0.4.0: - version "0.4.18" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f" - integrity sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA== - dependencies: - source-map "^0.5.6" - -source-map-url@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" - integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= - -source-map@0.7.3, source-map@^0.7.3: - version "0.7.3" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383" - integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ== - -source-map@^0.5.0, source-map@^0.5.6, source-map@^0.5.7: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" - integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= - -source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.0, source-map@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -sourcemap-codec@^1.4.4: - version "1.4.6" - resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.6.tgz#e30a74f0402bad09807640d39e971090a08ce1e9" - integrity sha512-1ZooVLYFxC448piVLBbtOxFcXwnymH9oUF8nRd3CuYDVvkRBxRl6pB4Mtas5a4drtL+E8LDgFkQNcgIw6tc8Hg== - -spawn-wrap@^1.4.2: - version "1.4.3" - resolved "https://registry.yarnpkg.com/spawn-wrap/-/spawn-wrap-1.4.3.tgz#81b7670e170cca247d80bf5faf0cfb713bdcf848" - integrity sha512-IgB8md0QW/+tWqcavuFgKYR/qIRvJkRLPJDFaoXtLLUaVcCDK0+HeFTkmQHj3eprcYhc+gOl0aEA1w7qZlYezw== - dependencies: - foreground-child "^1.5.6" - mkdirp "^0.5.0" - os-homedir "^1.0.1" - rimraf "^2.6.2" - signal-exit "^3.0.2" - which "^1.3.0" - -spdx-compare@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/spdx-compare/-/spdx-compare-1.0.0.tgz#2c55f117362078d7409e6d7b08ce70a857cd3ed7" - integrity sha512-C1mDZOX0hnu0ep9dfmuoi03+eOdDoz2yvK79RxbcrVEG1NO1Ph35yW102DHWKN4pk80nwCgeMmSY5L25VE4D9A== - dependencies: - array-find-index "^1.0.2" - spdx-expression-parse "^3.0.0" - spdx-ranges "^2.0.0" - -spdx-correct@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" - integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== - dependencies: - spdx-expression-parse "^3.0.0" - spdx-license-ids "^3.0.0" - -spdx-exceptions@^1.0.0: - version "1.0.5" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-1.0.5.tgz#9d21ac4da4bdb71d060fb74e5a67531d032cbba6" - integrity sha1-nSGsTaS9tx0GD7dOWmdTHQMsu6Y= - -spdx-exceptions@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" - integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== - -spdx-expression-parse@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" - integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== - dependencies: - spdx-exceptions "^2.1.0" - spdx-license-ids "^3.0.0" - -spdx-license-ids@^1.0.0: - version "1.2.2" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" - integrity sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc= - -spdx-license-ids@^3.0.0: - version "3.0.5" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654" - integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q== - -spdx-ranges@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/spdx-ranges/-/spdx-ranges-2.1.1.tgz#87573927ba51e92b3f4550ab60bfc83dd07bac20" - integrity sha512-mcdpQFV7UDAgLpXEE/jOMqvK4LBoO0uTQg0uvXUewmEFhpiZx5yJSZITHB8w1ZahKdhfZqP5GPEOKLyEq5p8XA== - -spdx-satisfies@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/spdx-satisfies/-/spdx-satisfies-4.0.1.tgz#9a09a68d80f5f1a31cfaebb384b0c6009e4969fe" - integrity sha512-WVzZ/cXAzoNmjCWiEluEA3BjHp5tiUmmhn9MK+X0tBbR9sOqtC6UQwmgCNrAIZvNlMuBUYAaHYfb2oqlF9SwKA== - dependencies: - spdx-compare "^1.0.0" - spdx-expression-parse "^3.0.0" - spdx-ranges "^2.0.0" - -spdx@^0.5.1: - version "0.5.2" - resolved "https://registry.yarnpkg.com/spdx/-/spdx-0.5.2.tgz#76a428b9b97e7904ef83e62a4af0d06fdb50c265" - integrity sha512-WQbfCQT2uKLsDllnO9ItpcGUiiF1O/ZvBGCyqFZRg122HgiZubpwpZiM7BkmH19HC3XR3Z+DFMGJNzXSPebG8A== - dependencies: - spdx-exceptions "^1.0.0" - spdx-license-ids "^1.0.0" - -spdy-transport@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/spdy-transport/-/spdy-transport-3.0.0.tgz#00d4863a6400ad75df93361a1608605e5dcdcf31" - integrity sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw== - dependencies: - debug "^4.1.0" - detect-node "^2.0.4" - hpack.js "^2.1.6" - obuf "^1.1.2" - readable-stream "^3.0.6" - wbuf "^1.7.3" - -spdy@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/spdy/-/spdy-4.0.1.tgz#6f12ed1c5db7ea4f24ebb8b89ba58c87c08257f2" - integrity sha512-HeZS3PBdMA+sZSu0qwpCxl3DeALD5ASx8pAX0jZdKXSpPWbQ6SYGnlg3BBmYLx5LtiZrmkAZfErCm2oECBcioA== - dependencies: - debug "^4.1.0" - handle-thing "^2.0.0" - http-deceiver "^1.2.7" - select-hose "^2.0.0" - spdy-transport "^3.0.0" - -speed-measure-webpack-plugin@1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/speed-measure-webpack-plugin/-/speed-measure-webpack-plugin-1.3.1.tgz#69840a5cdc08b4638697dac7db037f595d7f36a0" - integrity sha512-qVIkJvbtS9j/UeZumbdfz0vg+QfG/zxonAjzefZrqzkr7xOncLVXkeGbTpzd1gjCBM4PmVNkWlkeTVhgskAGSQ== - dependencies: - chalk "^2.0.1" - -split-string@^3.0.1, split-string@^3.0.2: - version "3.1.0" - resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" - integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== - dependencies: - extend-shallow "^3.0.0" - -split2@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/split2/-/split2-2.2.0.tgz#186b2575bcf83e85b7d18465756238ee4ee42493" - integrity sha512-RAb22TG39LhI31MbreBgIuKiIKhVsawfTgEGqKHTK87aG+ul/PB8Sqoi3I7kVdRWiCfrKxK3uo4/YUkpNvhPbw== - dependencies: - through2 "^2.0.2" - -split@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/split/-/split-1.0.1.tgz#605bd9be303aa59fb35f9229fbea0ddec9ea07d9" - integrity sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg== - dependencies: - through "2" - -sprintf-js@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.2.tgz#da1765262bf8c0f571749f2ad6c26300207ae673" - integrity sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug== - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= - -sshpk@^1.7.0: - version "1.16.1" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877" - integrity sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg== - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - bcrypt-pbkdf "^1.0.0" - dashdash "^1.12.0" - ecc-jsbn "~0.1.1" - getpass "^0.1.1" - jsbn "~0.1.0" - safer-buffer "^2.0.2" - tweetnacl "~0.14.0" - -ssri@^5.2.4: - version "5.3.0" - resolved "https://registry.yarnpkg.com/ssri/-/ssri-5.3.0.tgz#ba3872c9c6d33a0704a7d71ff045e5ec48999d06" - integrity sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ== - dependencies: - safe-buffer "^5.1.1" - -ssri@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/ssri/-/ssri-6.0.1.tgz#2a3c41b28dd45b62b63676ecb74001265ae9edd8" - integrity sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA== - dependencies: - figgy-pudding "^3.5.1" - -ssri@^7.0.0, ssri@^7.0.1, ssri@^7.1.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/ssri/-/ssri-7.1.0.tgz#92c241bf6de82365b5c7fb4bd76e975522e1294d" - integrity sha512-77/WrDZUWocK0mvA5NTRQyveUf+wsrIc6vyrxpS8tVvYBcX215QbafrJR3KtkpskIzoFLqqNuuYQvxaMjXJ/0g== - dependencies: - figgy-pudding "^3.5.1" - minipass "^3.1.1" - -static-eval@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/static-eval/-/static-eval-2.0.2.tgz#2d1759306b1befa688938454c546b7871f806a42" - integrity sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg== - dependencies: - escodegen "^1.8.1" - -static-extend@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" - integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= - dependencies: - define-property "^0.2.5" - object-copy "^0.1.0" - -static-module@^2.2.0: - version "2.2.5" - resolved "https://registry.yarnpkg.com/static-module/-/static-module-2.2.5.tgz#bd40abceae33da6b7afb84a0e4329ff8852bfbbf" - integrity sha512-D8vv82E/Kpmz3TXHKG8PPsCPg+RAX6cbCOyvjM6x04qZtQ47EtJFVwRsdov3n5d6/6ynrOY9XB4JkaZwB2xoRQ== - dependencies: - concat-stream "~1.6.0" - convert-source-map "^1.5.1" - duplexer2 "~0.1.4" - escodegen "~1.9.0" - falafel "^2.1.0" - has "^1.0.1" - magic-string "^0.22.4" - merge-source-map "1.0.4" - object-inspect "~1.4.0" - quote-stream "~1.0.2" - readable-stream "~2.3.3" - shallow-copy "~0.0.1" - static-eval "^2.0.0" - through2 "~2.0.3" - -"statuses@>= 1.4.0 < 2", "statuses@>= 1.5.0 < 2", statuses@~1.5.0: - version "1.5.0" - resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" - integrity sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow= - -stealthy-require@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b" - integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks= - -stream-browserify@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/stream-browserify/-/stream-browserify-2.0.2.tgz#87521d38a44aa7ee91ce1cd2a47df0cb49dd660b" - integrity sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg== - dependencies: - inherits "~2.0.1" - readable-stream "^2.0.2" - -stream-each@^1.1.0: - version "1.2.3" - resolved "https://registry.yarnpkg.com/stream-each/-/stream-each-1.2.3.tgz#ebe27a0c389b04fbcc233642952e10731afa9bae" - integrity sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw== - dependencies: - end-of-stream "^1.1.0" - stream-shift "^1.0.0" - -stream-http@^2.7.2: - version "2.8.3" - resolved "https://registry.yarnpkg.com/stream-http/-/stream-http-2.8.3.tgz#b2d242469288a5a27ec4fe8933acf623de6514fc" - integrity sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw== - dependencies: - builtin-status-codes "^3.0.0" - inherits "^2.0.1" - readable-stream "^2.3.6" - to-arraybuffer "^1.0.0" - xtend "^4.0.0" - -stream-shift@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.0.tgz#d5c752825e5367e786f78e18e445ea223a155952" - integrity sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI= - -streamroller@0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/streamroller/-/streamroller-0.7.0.tgz#a1d1b7cf83d39afb0d63049a5acbf93493bdf64b" - integrity sha512-WREzfy0r0zUqp3lGO096wRuUp7ho1X6uo/7DJfTlEi0Iv/4gT7YHqXDjKC2ioVGBZtE8QzsQD9nx1nIuoZ57jQ== - dependencies: - date-format "^1.2.0" - debug "^3.1.0" - mkdirp "^0.5.1" - readable-stream "^2.3.0" - -streamroller@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/streamroller/-/streamroller-1.0.6.tgz#8167d8496ed9f19f05ee4b158d9611321b8cacd9" - integrity sha512-3QC47Mhv3/aZNFpDDVO44qQb9gwB9QggMEE0sQmkTAwBVYdBRWISdsywlkfm5II1Q5y/pmrHflti/IgmIzdDBg== - dependencies: - async "^2.6.2" - date-format "^2.0.0" - debug "^3.2.6" - fs-extra "^7.0.1" - lodash "^4.17.14" - -strict-uri-encode@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz#279b225df1d582b1f54e65addd4352e18faa0713" - integrity sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM= - -string-width@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" - integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - -"string-width@^1.0.2 || 2", string-width@^2.0.0, string-width@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" - integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== - dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" - -string-width@^3.0.0, string-width@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" - integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== - dependencies: - emoji-regex "^7.0.1" - is-fullwidth-code-point "^2.0.0" - strip-ansi "^5.1.0" - -string-width@^4.1.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" - integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.0" - -string.prototype.trimleft@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz#6cc47f0d7eb8d62b0f3701611715a3954591d634" - integrity sha512-FJ6b7EgdKxxbDxc79cOlok6Afd++TTs5szo+zJTUyow3ycrRfJVE2pq3vcN53XexvKZu/DJMDfeI/qMiZTrjTw== - dependencies: - define-properties "^1.1.3" - function-bind "^1.1.1" - -string.prototype.trimright@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/string.prototype.trimright/-/string.prototype.trimright-2.1.0.tgz#669d164be9df9b6f7559fa8e89945b168a5a6c58" - integrity sha512-fXZTSV55dNBwv16uw+hh5jkghxSnc5oHq+5K/gXgizHwAvMetdAJlHqqoFC1FSDVPYWLkAKl2cxpUT41sV7nSg== - dependencies: - define-properties "^1.1.3" - function-bind "^1.1.1" - -string_decoder@^1.0.0, string_decoder@^1.1.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" - integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== - dependencies: - safe-buffer "~5.2.0" - -string_decoder@~1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" - integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== - dependencies: - safe-buffer "~5.1.0" - -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= - dependencies: - ansi-regex "^2.0.0" - -strip-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" - integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= - dependencies: - ansi-regex "^3.0.0" - -strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" - integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== - dependencies: - ansi-regex "^4.1.0" - -strip-ansi@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" - integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== - dependencies: - ansi-regex "^5.0.0" - -strip-bom@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" - integrity sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4= - dependencies: - is-utf8 "^0.2.0" - -strip-bom@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" - integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= - -strip-eof@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf" - integrity sha1-u0P/VZim6wXYm1n80SnJgzE2Br8= - -strip-indent@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2" - integrity sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI= - dependencies: - get-stdin "^4.0.1" - -strip-indent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-2.0.0.tgz#5ef8db295d01e6ed6cbf7aab96998d7822527b68" - integrity sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g= - -strip-json-comments@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" - integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= - -style-loader@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/style-loader/-/style-loader-1.0.0.tgz#1d5296f9165e8e2c85d24eee0b7caf9ec8ca1f82" - integrity sha512-B0dOCFwv7/eY31a5PCieNwMgMhVGFe9w+rh7s/Bx8kfFkrth9zfTZquoYvdw8URgiqxObQKcpW51Ugz1HjfdZw== - dependencies: - loader-utils "^1.2.3" - schema-utils "^2.0.1" - -stylus-loader@3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/stylus-loader/-/stylus-loader-3.0.2.tgz#27a706420b05a38e038e7cacb153578d450513c6" - integrity sha512-+VomPdZ6a0razP+zinir61yZgpw2NfljeSsdUF5kJuEzlo3khXhY19Fn6l8QQz1GRJGtMCo8nG5C04ePyV7SUA== - dependencies: - loader-utils "^1.0.2" - lodash.clonedeep "^4.5.0" - when "~3.6.x" - -stylus@0.54.7, stylus@^0.54.7: - version "0.54.7" - resolved "https://registry.yarnpkg.com/stylus/-/stylus-0.54.7.tgz#c6ce4793965ee538bcebe50f31537bfc04d88cd2" - integrity sha512-Yw3WMTzVwevT6ZTrLCYNHAFmanMxdylelL3hkWNgPMeTCpMwpV3nXjpOHuBXtFv7aiO2xRuQS6OoAdgkNcSNug== - dependencies: - css-parse "~2.0.0" - debug "~3.1.0" - glob "^7.1.3" - mkdirp "~0.5.x" - safer-buffer "^2.1.2" - sax "~1.2.4" - semver "^6.0.0" - source-map "^0.7.3" - -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= - -supports-color@^3.1.2: - version "3.2.3" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" - integrity sha1-ZawFBLOVQXHYpklGsq48u4pfVPY= - dependencies: - has-flag "^1.0.0" - -supports-color@^5.3.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - -supports-color@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-6.1.0.tgz#0764abc69c63d5ac842dd4867e8d025e880df8f3" - integrity sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ== - dependencies: - has-flag "^3.0.0" - -supports-color@^7.1.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.1.0.tgz#68e32591df73e25ad1c4b49108a2ec507962bfd1" - integrity sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g== - dependencies: - has-flag "^4.0.0" - -symbol-observable@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" - integrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ== - -symbol-tree@^3.2.2: - version "3.2.4" - resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" - integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== - -tapable@^1.0.0, tapable@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" - integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== - -tar@^4, tar@^4.4.4: - version "4.4.13" - resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.13.tgz#43b364bc52888d555298637b10d60790254ab525" - integrity sha512-w2VwSrBoHa5BsSyH+KxEqeQBAllHhccyMFVHtGtdMpF4W7IRWfZjFiQceJPChOeTsSDVUpER2T8FA93pr0L+QA== - dependencies: - chownr "^1.1.1" - fs-minipass "^1.2.5" - minipass "^2.8.6" - minizlib "^1.2.1" - mkdirp "^0.5.0" - safe-buffer "^5.1.2" - yallist "^3.0.3" - -tar@^5.0.5: - version "5.0.5" - resolved "https://registry.yarnpkg.com/tar/-/tar-5.0.5.tgz#03fcdb7105bc8ea3ce6c86642b9c942495b04f93" - integrity sha512-MNIgJddrV2TkuwChwcSNds/5E9VijOiw7kAc1y5hTNJoLDSuIyid2QtLYiCYNnICebpuvjhPQZsXwUL0O3l7OQ== - dependencies: - chownr "^1.1.3" - fs-minipass "^2.0.0" - minipass "^3.0.0" - minizlib "^2.1.0" - mkdirp "^0.5.0" - yallist "^4.0.0" - -temp@^0.9.0: - version "0.9.1" - resolved "https://registry.yarnpkg.com/temp/-/temp-0.9.1.tgz#2d666114fafa26966cd4065996d7ceedd4dd4697" - integrity sha512-WMuOgiua1xb5R56lE0eH6ivpVmg/lq2OHm4+LtT/xtEtPQ+sz6N3bBM6WZ5FvO1lO4IKIOb43qnhoc4qxP5OeA== - dependencies: - rimraf "~2.6.2" - -term-size@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/term-size/-/term-size-1.2.0.tgz#458b83887f288fc56d6fffbfad262e26638efa69" - integrity sha1-RYuDiH8oj8Vtb/+/rSYuJmOO+mk= - dependencies: - execa "^0.7.0" - -terser-webpack-plugin@2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-2.2.1.tgz#5569e6c7d8be79e5e43d6da23acc3b6ba77d22bd" - integrity sha512-jwdauV5Al7zopR6OAYvIIRcxXCSvLjZjr7uZE8l2tIWb/ryrGN48sJftqGf5k9z09tWhajx53ldp0XPI080YnA== - dependencies: - cacache "^13.0.1" - find-cache-dir "^3.0.0" - jest-worker "^24.9.0" - schema-utils "^2.5.0" - serialize-javascript "^2.1.0" - source-map "^0.6.1" - terser "^4.3.9" - webpack-sources "^1.4.3" - -terser-webpack-plugin@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-1.4.1.tgz#61b18e40eaee5be97e771cdbb10ed1280888c2b4" - integrity sha512-ZXmmfiwtCLfz8WKZyYUuuHf3dMYEjg8NrjHMb0JqHVHVOSkzp3cW2/XG1fP3tRhqEqSzMwzzRQGtAPbs4Cncxg== - dependencies: - cacache "^12.0.2" - find-cache-dir "^2.1.0" - is-wsl "^1.1.0" - schema-utils "^1.0.0" - serialize-javascript "^1.7.0" - source-map "^0.6.1" - terser "^4.1.2" - webpack-sources "^1.4.0" - worker-farm "^1.7.0" - -terser@4.4.0, terser@^4.1.2, terser@^4.3.8, terser@^4.3.9: - version "4.4.0" - resolved "https://registry.yarnpkg.com/terser/-/terser-4.4.0.tgz#22c46b4817cf4c9565434bfe6ad47336af259ac3" - integrity sha512-oDG16n2WKm27JO8h4y/w3iqBGAOSCtq7k8dRmrn4Wf9NouL0b2WpMHGChFGZq4nFAQy1FsNJrVQHfurXOSTmOA== - dependencies: - commander "^2.20.0" - source-map "~0.6.1" - source-map-support "~0.5.12" - -test-exclude@^5.2.2: - version "5.2.3" - resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-5.2.3.tgz#c3d3e1e311eb7ee405e092dac10aefd09091eac0" - integrity sha512-M+oxtseCFO3EDtAaGH7iiej3CBkzXqFMbzqYAACdzKui4eZA+pq3tZEwChvOdNfa7xxy8BfbmgJSIr43cC/+2g== - dependencies: - glob "^7.1.3" - minimatch "^3.0.4" - read-pkg-up "^4.0.0" - require-main-filename "^2.0.0" - -text-extensions@^1.0.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/text-extensions/-/text-extensions-1.9.0.tgz#1853e45fee39c945ce6f6c36b2d659b5aabc2a26" - integrity sha512-wiBrwC1EhBelW12Zy26JeOUkQ5mRu+5o8rpsJk5+2t+Y5vE7e842qtZDQ2g1NpX/29HdyFeJ4nSIhI47ENSxlQ== - -through2@^2.0.0, through2@^2.0.2, through2@^2.0.3, through2@~2.0.3: - version "2.0.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" - integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== - dependencies: - readable-stream "~2.3.6" - xtend "~4.0.1" - -through2@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/through2/-/through2-3.0.1.tgz#39276e713c3302edf9e388dd9c812dd3b825bd5a" - integrity sha512-M96dvTalPT3YbYLaKaCuwu+j06D/8Jfib0o/PxbVt6Amhv3dUAtW6rTV1jPgJSBG83I/e04Y6xkVdVhSRhi0ww== - dependencies: - readable-stream "2 || 3" - -through@2, "through@>=2.2.7 <3", through@X.X.X, through@^2.3.6: - version "2.3.8" - resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" - integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= - -thunky@^1.0.2: - version "1.1.0" - resolved "https://registry.yarnpkg.com/thunky/-/thunky-1.1.0.tgz#5abaf714a9405db0504732bbccd2cedd9ef9537d" - integrity sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA== - -timers-browserify@^2.0.4: - version "2.0.11" - resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-2.0.11.tgz#800b1f3eee272e5bc53ee465a04d0e804c31211f" - integrity sha512-60aV6sgJ5YEbzUdn9c8kYGIqOubPoUdqQCul3SBAsRCZ40s6Y5cMcrW4dt3/k/EsbLVJNl9n6Vz3fTc+k2GeKQ== - dependencies: - setimmediate "^1.0.4" - -tiny-inflate@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/tiny-inflate/-/tiny-inflate-1.0.2.tgz#93d9decffc8805bd57eae4310f0b745e9b6fb3a7" - integrity sha1-k9nez/yIBb1X6uQxDwt0Xptvs6c= - -tmp@0.0.30: - version "0.0.30" - resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.30.tgz#72419d4a8be7d6ce75148fd8b324e593a711c2ed" - integrity sha1-ckGdSovn1s51FI/YsyTlk6cRwu0= - dependencies: - os-tmpdir "~1.0.1" - -tmp@0.0.33, tmp@0.0.x, tmp@^0.0.33: - version "0.0.33" - resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" - integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== - dependencies: - os-tmpdir "~1.0.2" - -to-array@0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/to-array/-/to-array-0.1.4.tgz#17e6c11f73dd4f3d74cda7a4ff3238e9ad9bf890" - integrity sha1-F+bBH3PdTz10zaek/zI46a2b+JA= - -to-arraybuffer@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz#7d229b1fcc637e466ca081180836a7aabff83f43" - integrity sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M= - -to-fast-properties@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" - integrity sha1-uDVx+k2MJbguIxsG46MFXeTKGkc= - -to-fast-properties@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz#dc5e698cbd079265bc73e0377681a4e4e83f616e" - integrity sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4= - -to-object-path@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" - integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= - dependencies: - kind-of "^3.0.2" - -to-readable-stream@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/to-readable-stream/-/to-readable-stream-1.0.0.tgz#ce0aa0c2f3df6adf852efb404a783e77c0475771" - integrity sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q== - -to-regex-range@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" - integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= - dependencies: - is-number "^3.0.0" - repeat-string "^1.6.1" - -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - -to-regex@^3.0.1, to-regex@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" - integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== - dependencies: - define-property "^2.0.2" - extend-shallow "^3.0.2" - regex-not "^1.0.2" - safe-regex "^1.1.0" - -toidentifier@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.0.tgz#7e1be3470f1e77948bc43d94a3c8f4d7752ba553" - integrity sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw== - -tough-cookie@^2.3.3: - version "2.5.0" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.5.0.tgz#cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2" - integrity sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g== - dependencies: - psl "^1.1.28" - punycode "^2.1.1" - -tough-cookie@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-3.0.1.tgz#9df4f57e739c26930a018184887f4adb7dca73b2" - integrity sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg== - dependencies: - ip-regex "^2.1.0" - psl "^1.1.28" - punycode "^2.1.1" - -tough-cookie@~2.3.3: - version "2.3.4" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655" - integrity sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA== - dependencies: - punycode "^1.4.1" - -tough-cookie@~2.4.3: - version "2.4.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781" - integrity sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ== - dependencies: - psl "^1.1.24" - punycode "^1.4.1" - -tr46@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-1.0.1.tgz#a8b13fd6bfd2489519674ccde55ba3693b706d09" - integrity sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk= - dependencies: - punycode "^2.1.0" - -tree-kill@1.2.1, tree-kill@^1.2.0: - version "1.2.1" - resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.1.tgz#5398f374e2f292b9dcc7b2e71e30a5c3bb6c743a" - integrity sha512-4hjqbObwlh2dLyW4tcz0Ymw0ggoaVDMveUB9w8kFSQScdRLo0gxO9J7WFcUBo+W3C1TLdFIEwNOWebgZZ0RH9Q== - -treeify@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/treeify/-/treeify-1.1.0.tgz#4e31c6a463accd0943879f30667c4fdaff411bb8" - integrity sha512-1m4RA7xVAJrSGrrXGs0L3YTwyvBs2S8PbRHaLZAkFw7JR8oIFwYtysxlBZhYIa7xSyiYJKZ3iGrrk55cGA3i9A== - -trim-newlines@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" - integrity sha1-WIeWa7WCpFA6QetST301ARgVphM= - -trim-newlines@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-2.0.0.tgz#b403d0b91be50c331dfc4b82eeceb22c3de16d20" - integrity sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA= - -trim-off-newlines@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/trim-off-newlines/-/trim-off-newlines-1.0.1.tgz#9f9ba9d9efa8764c387698bcbfeb2c848f11adb3" - integrity sha1-n5up2e+odkw4dpi8v+sshI8RrbM= - -trim-right@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" - integrity sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM= - -ts-api-guardian@0.4.6: - version "0.4.6" - resolved "https://registry.yarnpkg.com/ts-api-guardian/-/ts-api-guardian-0.4.6.tgz#ebd9a700b40de6ca4dbc5c468e322fe86476b6db" - integrity sha512-V+AVEe4HCi3j0mKrvSBNZN6zoY0eIw2r9vcWrqu4vhGlpASgPTSwuPHtxctx4qMBH5ieyqO6rf1LrQfsr8s5tw== - dependencies: - chalk "^2.3.1" - diff "^3.5.0" - minimist "^1.2.0" - -ts-node@^5.0.0: - version "5.0.1" - resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-5.0.1.tgz#78e5d1cb3f704de1b641e43b76be2d4094f06f81" - integrity sha512-XK7QmDcNHVmZkVtkiwNDWiERRHPyU8nBqZB1+iv2UhOG0q3RQ9HsZ2CMqISlFbxjrYFGfG2mX7bW4dAyxBVzUw== - dependencies: - arrify "^1.0.0" - chalk "^2.3.0" - diff "^3.1.0" - make-error "^1.1.1" - minimist "^1.2.0" - mkdirp "^0.5.1" - source-map-support "^0.5.3" - yn "^2.0.0" - -tslib@1.10.0, tslib@^1.10.0, tslib@^1.7.1, tslib@^1.8.0, tslib@^1.8.1, tslib@^1.9.0, tslib@~1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" - integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== - -tslint-no-circular-imports@^0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/tslint-no-circular-imports/-/tslint-no-circular-imports-0.7.0.tgz#9df0a15654d66b172e0b7843eed073fa5ae99b5f" - integrity sha512-k3wxpeMC4ef40UbpfBVHEHIzKfNZq5/SCtAO1YjGsaNTklo+K53/TWLrym+poA65RJFDiYgYNWvkeIIkJNA0Vw== - -tslint-sonarts@1.9.0: - version "1.9.0" - resolved "https://registry.yarnpkg.com/tslint-sonarts/-/tslint-sonarts-1.9.0.tgz#feb593e92db328c0328b430b838adbe65d504de9" - integrity sha512-CJWt+IiYI8qggb2O/JPkS6CkC5DY1IcqRsm9EHJ+AxoWK70lvtP7jguochyNDMP2vIz/giGdWCfEM39x/I/Vnw== - dependencies: - immutable "^3.8.2" - -tslint@^5.15.0: - version "5.20.1" - resolved "https://registry.yarnpkg.com/tslint/-/tslint-5.20.1.tgz#e401e8aeda0152bc44dd07e614034f3f80c67b7d" - integrity sha512-EcMxhzCFt8k+/UP5r8waCf/lzmeSyVlqxqMEDQE7rWYiQky8KpIBz1JAoYXfROHrPZ1XXd43q8yQnULOLiBRQg== - dependencies: - "@babel/code-frame" "^7.0.0" - builtin-modules "^1.1.1" - chalk "^2.3.0" - commander "^2.12.1" - diff "^4.0.1" - glob "^7.1.1" - js-yaml "^3.13.1" - minimatch "^3.0.4" - mkdirp "^0.5.1" - resolve "^1.3.2" - semver "^5.3.0" - tslib "^1.8.0" - tsutils "^2.29.0" - -tsutils@2.27.2: - version "2.27.2" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.27.2.tgz#60ba88a23d6f785ec4b89c6e8179cac9b431f1c7" - integrity sha512-qf6rmT84TFMuxAKez2pIfR8UCai49iQsfB7YWVjV1bKpy/d0PWT5rEOSM6La9PiHZ0k1RRZQiwVdVJfQ3BPHgg== - dependencies: - tslib "^1.8.1" - -tsutils@^2.29.0: - version "2.29.0" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.29.0.tgz#32b488501467acbedd4b85498673a0812aca0b99" - integrity sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA== - dependencies: - tslib "^1.8.1" - -tty-browserify@0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6" - integrity sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY= - -tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - integrity sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0= - dependencies: - safe-buffer "^5.0.1" - -tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - integrity sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q= - -type-check@~0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" - integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= - dependencies: - prelude-ls "~1.1.2" - -type-fest@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" - integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ== - -type-fest@^0.5.2: - version "0.5.2" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.5.2.tgz#d6ef42a0356c6cd45f49485c3b6281fc148e48a2" - integrity sha512-DWkS49EQKVX//Tbupb9TFa19c7+MK1XmzkrZUR8TAktmE/DizXoaoJV6TZ/tSIPXipqNiRI6CyAe7x69Jb6RSw== - -type-fest@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.6.0.tgz#8d2a2370d3df886eb5c90ada1c5bf6188acf838b" - integrity sha512-q+MB8nYR1KDLrgr4G5yemftpMC7/QLqVndBmEEdqzmNj5dcFOO4Oo8qlwZE3ULT3+Zim1F8Kq4cBnikNhlCMlg== - -type-is@~1.6.17, type-is@~1.6.18: - version "1.6.18" - resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" - integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== - dependencies: - media-typer "0.3.0" - mime-types "~2.1.24" - -typedarray-to-buffer@~3.1.5: - version "3.1.5" - resolved "https://registry.yarnpkg.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz#a97ee7a9ff42691b9f783ff1bc5112fe3fca9080" - integrity sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q== - dependencies: - is-typedarray "^1.0.0" - -typedarray@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" - integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= - -typescript@3.6.4: - version "3.6.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.6.4.tgz#b18752bb3792bc1a0281335f7f6ebf1bbfc5b91d" - integrity sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg== - -uglify-js@^3.1.4: - version "3.6.8" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.6.8.tgz#5edcbcf9d49cbb0403dc49f856fe81530d65145e" - integrity sha512-XhHJ3S3ZyMwP8kY1Gkugqx3CJh2C3O0y8NPiSxtm1tyD/pktLAkFZsFGpuNfTZddKDQ/bbDBLAd2YyA1pbi8HQ== - dependencies: - commander "~2.20.3" - source-map "~0.6.1" - -ultron@~1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/ultron/-/ultron-1.1.1.tgz#9fe1536a10a664a65266a1e3ccf85fd36302bc9c" - integrity sha512-UIEXBNeYmKptWH6z8ZnqTeS8fV74zG0/eRU9VGkpzz+LIJNs8W/zM/L+7ctCkRrgbNnnR0xxw4bKOr0cW0N0Og== - -unicode-canonical-property-names-ecmascript@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz#2619800c4c825800efdd8343af7dd9933cbe2818" - integrity sha512-jDrNnXWHd4oHiTZnx/ZG7gtUTVp+gCcTTKr8L0HjlwphROEW3+Him+IpvC+xcJEFegapiMZyZe02CyuOnRmbnQ== - -unicode-match-property-ecmascript@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-1.0.4.tgz#8ed2a32569961bce9227d09cd3ffbb8fed5f020c" - integrity sha512-L4Qoh15vTfntsn4P1zqnHulG0LdXgjSO035fEpdtp6YxXhMT51Q6vgM5lYdG/5X3MjS+k/Y9Xw4SFCY9IkR0rg== - dependencies: - unicode-canonical-property-names-ecmascript "^1.0.4" - unicode-property-aliases-ecmascript "^1.0.4" - -unicode-match-property-value-ecmascript@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-1.1.0.tgz#5b4b426e08d13a80365e0d657ac7a6c1ec46a277" - integrity sha512-hDTHvaBk3RmFzvSl0UVrUmC3PuW9wKVnpoUDYH0JDkSIovzw+J5viQmeYHxVSBptubnr7PbH2e0fnpDRQnQl5g== - -unicode-property-aliases-ecmascript@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-1.0.5.tgz#a9cc6cc7ce63a0a3023fc99e341b94431d405a57" - integrity sha512-L5RAqCfXqAwR3RriF8pM0lU0w4Ryf/GgzONwi6KnL1taJQa7x1TCxdJnILX59WIGOwR57IVxn7Nej0fz1Ny6fw== - -unicode-trie@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/unicode-trie/-/unicode-trie-0.3.1.tgz#d671dddd89101a08bac37b6a5161010602052085" - integrity sha1-1nHd3YkQGgi6w3tqUWEBBgIFIIU= - dependencies: - pako "^0.2.5" - tiny-inflate "^1.0.0" - -union-value@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" - integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== - dependencies: - arr-union "^3.1.0" - get-value "^2.0.6" - is-extendable "^0.1.1" - set-value "^2.0.1" - -unique-filename@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-1.1.1.tgz#1d69769369ada0583103a1e6ae87681b56573230" - integrity sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ== - dependencies: - unique-slug "^2.0.0" - -unique-slug@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-2.0.2.tgz#baabce91083fc64e945b0f3ad613e264f7cd4e6c" - integrity sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w== - dependencies: - imurmurhash "^0.1.4" - -unique-string@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/unique-string/-/unique-string-1.0.0.tgz#9e1057cca851abb93398f8b33ae187b99caec11a" - integrity sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo= - dependencies: - crypto-random-string "^1.0.0" - -universal-analytics@^0.4.20: - version "0.4.20" - resolved "https://registry.yarnpkg.com/universal-analytics/-/universal-analytics-0.4.20.tgz#d6b64e5312bf74f7c368e3024a922135dbf24b03" - integrity sha512-gE91dtMvNkjO+kWsPstHRtSwHXz0l2axqptGYp5ceg4MsuurloM0PU3pdOfpb5zBXUvyjT4PwhWK2m39uczZuw== - dependencies: - debug "^3.0.0" - request "^2.88.0" - uuid "^3.0.0" - -universalify@^0.1.0: - version "0.1.2" - resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" - integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== - -unix-crypt-td-js@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/unix-crypt-td-js/-/unix-crypt-td-js-1.0.0.tgz#1c0824150481bc7a01d49e98f1ec668d82412f3b" - integrity sha1-HAgkFQSBvHoB1J6Y8exmjYJBLzs= - -unpipe@1.0.0, unpipe@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" - integrity sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw= - -unset-value@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" - integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= - dependencies: - has-value "^0.3.1" - isobject "^3.0.0" - -upath@^1.1.1: - version "1.2.0" - resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz#8f66dbcd55a883acdae4408af8b035a5044c1894" - integrity sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg== - -update-notifier@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/update-notifier/-/update-notifier-3.0.1.tgz#78ecb68b915e2fd1be9f767f6e298ce87b736250" - integrity sha512-grrmrB6Zb8DUiyDIaeRTBCkgISYUgETNe7NglEbVsrLWXeESnlCSP50WfRSj/GmzMPl6Uchj24S/p80nP/ZQrQ== - dependencies: - boxen "^3.0.0" - chalk "^2.0.1" - configstore "^4.0.0" - has-yarn "^2.1.0" - import-lazy "^2.1.0" - is-ci "^2.0.0" - is-installed-globally "^0.1.0" - is-npm "^3.0.0" - is-yarn-global "^0.3.0" - latest-version "^5.0.0" - semver-diff "^2.0.0" - xdg-basedir "^3.0.0" - -uri-js@^4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.2.2.tgz#94c540e1ff772956e2299507c010aea6c8838eb0" - integrity sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ== - dependencies: - punycode "^2.1.0" - -urijs@^1.19.1: - version "1.19.2" - resolved "https://registry.yarnpkg.com/urijs/-/urijs-1.19.2.tgz#f9be09f00c4c5134b7cb3cf475c1dd394526265a" - integrity sha512-s/UIq9ap4JPZ7H1EB5ULo/aOUbWqfDi7FKzMC2Nz+0Si8GiT1rIEaprt8hy3Vy2Ex2aJPpOQv4P4DuOZ+K1c6w== - -urix@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" - integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= - -url-parse-lax@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/url-parse-lax/-/url-parse-lax-3.0.0.tgz#16b5cafc07dbe3676c1b1999177823d6503acb0c" - integrity sha1-FrXK/Afb42dsGxmZF3gj1lA6yww= - dependencies: - prepend-http "^2.0.0" - -url-parse@^1.4.3: - version "1.4.7" - resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.4.7.tgz#a8a83535e8c00a316e403a5db4ac1b9b853ae278" - integrity sha512-d3uaVyzDB9tQoSXFvuSUNFibTd9zxd2bkVrDRvF5TmvWWQwqE4lgYJ5m+x1DbecWkw+LK4RNl2CU1hHuOKPVlg== - dependencies: - querystringify "^2.1.1" - requires-port "^1.0.0" - -url@^0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1" - integrity sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE= - dependencies: - punycode "1.3.2" - querystring "0.2.0" - -use@^3.1.0: - version "3.1.1" - resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" - integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== - -useragent@2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/useragent/-/useragent-2.3.0.tgz#217f943ad540cb2128658ab23fc960f6a88c9972" - integrity sha512-4AoH4pxuSvHCjqLO04sU6U/uE65BYza8l/KKBS0b0hnUPWi+cQ2BpeTEwejCSx9SPV5/U03nniDTrWx5NrmKdw== - dependencies: - lru-cache "4.1.x" - tmp "0.0.x" - -util-deprecate@^1.0.1, util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= - -util-extend@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/util-extend/-/util-extend-1.0.3.tgz#a7c216d267545169637b3b6edc6ca9119e2ff93f" - integrity sha1-p8IW0mdUUWljeztu3GypEZ4v+T8= - -util-promisify@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/util-promisify/-/util-promisify-2.1.0.tgz#3c2236476c4d32c5ff3c47002add7c13b9a82a53" - integrity sha1-PCI2R2xNMsX/PEcAKt18E7moKlM= - dependencies: - object.getownpropertydescriptors "^2.0.3" - -util.promisify@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/util.promisify/-/util.promisify-1.0.0.tgz#440f7165a459c9a16dc145eb8e72f35687097030" - integrity sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA== - dependencies: - define-properties "^1.1.2" - object.getownpropertydescriptors "^2.0.3" - -util@0.10.3: - version "0.10.3" - resolved "https://registry.yarnpkg.com/util/-/util-0.10.3.tgz#7afb1afe50805246489e3db7fe0ed379336ac0f9" - integrity sha1-evsa/lCAUkZInj23/g7TeTNqwPk= - dependencies: - inherits "2.0.1" - -util@^0.11.0: - version "0.11.1" - resolved "https://registry.yarnpkg.com/util/-/util-0.11.1.tgz#3236733720ec64bb27f6e26f421aaa2e1b588d61" - integrity sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ== - dependencies: - inherits "2.0.3" - -utils-merge@1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" - integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM= - -uuid@^3.0.0, uuid@^3.0.1, uuid@^3.1.0, uuid@^3.3.2: - version "3.3.3" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.3.tgz#4568f0216e78760ee1dbf3a4d2cf53e224112866" - integrity sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ== - -v8-coverage@1.0.9: - version "1.0.9" - resolved "https://registry.yarnpkg.com/v8-coverage/-/v8-coverage-1.0.9.tgz#780889680c0fea0f587adf22e2b5f443b9434745" - integrity sha512-JolsCH1JDI2QULrxkAGZaovJPvg/Q0p20Uj0F5N8fPtYDtz38gNBRPQ/WVXlLLd3d8WHvKN96AfE4XFk4u0g2g== - dependencies: - debug "^3.1.0" - foreground-child "^1.5.6" - istanbul-lib-coverage "^1.2.0" - istanbul-lib-report "^1.1.3" - istanbul-reports "^1.3.0" - mkdirp "^0.5.1" - rimraf "^2.6.2" - signal-exit "^3.0.2" - spawn-wrap "^1.4.2" - test-exclude "^5.2.2" - uuid "^3.3.2" - v8-to-istanbul "1.2.0" - yargs "^11.0.0" - -v8-to-istanbul@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-1.2.0.tgz#f6a22ffb08b2202aaba8c2be497d1d41fe8fb4b6" - integrity sha512-rVSmjdEfJmOHN8GYCbg+XUhbzXZr7DzdaXIslB9DdcopGZEMsW5x5qIdxr/8DcW7msULHNnvs/xUY1TszvhKRw== - -validate-npm-package-license@^3.0.1: - version "3.0.4" - resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" - integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== - dependencies: - spdx-correct "^3.0.0" - spdx-expression-parse "^3.0.0" - -validate-npm-package-name@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz#5fa912d81eb7d0c74afc140de7317f0ca7df437e" - integrity sha1-X6kS2B630MdK/BQN5zF/DKffQ34= - dependencies: - builtins "^1.0.3" - -vary@^1, vary@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" - integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw= - -verdaccio-audit@8.1.4: - version "8.1.4" - resolved "https://registry.yarnpkg.com/verdaccio-audit/-/verdaccio-audit-8.1.4.tgz#b2005927cbfe29229b01034e9d2d8bc635f12970" - integrity sha512-Ehg9XS1soO5xfbtut64MU+FutF42kay0tw1wwB84UaQJ7YgZ58ftgvLZcL3AuPlTzI9KHMCf6ZOdyt6/fNmsVw== - dependencies: - express "4.17.1" - request "2.88.0" - -verdaccio-htpasswd@8.2.0: - version "8.2.0" - resolved "https://registry.yarnpkg.com/verdaccio-htpasswd/-/verdaccio-htpasswd-8.2.0.tgz#fc942bf1e5aab698782b704a6494fc62ef311954" - integrity sha512-ukbKWzH4DtsNH9NF9wKo0axU/uupudANcuG7Hc1FL/PopOq7Z1rLRF7MgA+P8BJGnwaZRB4pq32hblM931AEWg== - dependencies: - "@verdaccio/file-locking" "1.0.0" - apache-md5 "1.1.2" - bcryptjs "2.4.3" - http-errors "1.7.3" - unix-crypt-td-js "1.0.0" - -verdaccio@4.3.4: - version "4.3.4" - resolved "https://registry.yarnpkg.com/verdaccio/-/verdaccio-4.3.4.tgz#236527d579379eadc18f8aaa444cbd63d995de13" - integrity sha512-qoz52LvEqAiR7KVUttMn0/S02TeTSB5LSEhcM+JaQXDZzOSEjMOj+45gTeWR+GbmLL0Ug+njgEPHF/LH4EjZmA== - dependencies: - "@verdaccio/commons-api" "8.2.0" - "@verdaccio/local-storage" "8.2.0" - "@verdaccio/readme" "8.2.0" - "@verdaccio/streams" "8.2.0" - "@verdaccio/ui-theme" "0.3.2" - JSONStream "1.3.5" - async "3.1.0" - body-parser "1.19.0" - bunyan "1.8.12" - commander "3.0.2" - compression "1.7.4" - cookies "0.7.3" - cors "2.8.5" - dayjs "1.8.16" - envinfo "7.4.0" - express "4.17.1" - handlebars "4.3.1" - http-errors "1.7.3" - js-yaml "3.13.1" - jsonwebtoken "8.5.1" - kleur "3.0.3" - lockfile-lint "2.0.1" - lodash "4.17.15" - lunr-mutable-indexes "2.3.2" - marked "0.7.0" - mime "2.4.4" - minimatch "3.0.4" - mkdirp "0.5.1" - mv "2.1.1" - pkginfo "0.4.1" - request "2.87.0" - semver "6.3.0" - verdaccio-audit "8.1.4" - verdaccio-htpasswd "8.2.0" - -verror@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - integrity sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA= - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - -vlq@^0.2.2: - version "0.2.3" - resolved "https://registry.yarnpkg.com/vlq/-/vlq-0.2.3.tgz#8f3e4328cf63b1540c0d67e1b2778386f8975b26" - integrity sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow== - -vm-browserify@^1.0.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/vm-browserify/-/vm-browserify-1.1.2.tgz#78641c488b8e6ca91a75f511e7a3b32a86e5dda0" - integrity sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ== - -void-elements@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/void-elements/-/void-elements-2.0.1.tgz#c066afb582bb1cb4128d60ea92392e94d5e9dbec" - integrity sha1-wGavtYK7HLQSjWDqkjkulNXp2+w= - -w3c-hr-time@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz#82ac2bff63d950ea9e3189a58a65625fedf19045" - integrity sha1-gqwr/2PZUOqeMYmlimViX+3xkEU= - dependencies: - browser-process-hrtime "^0.1.2" - -w3c-xmlserializer@^1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-1.1.2.tgz#30485ca7d70a6fd052420a3d12fd90e6339ce794" - integrity sha512-p10l/ayESzrBMYWRID6xbuCKh2Fp77+sA0doRuGn4tTIMrrZVeqfpKjXHY+oDh3K4nLdPgNwMTVP6Vp4pvqbNg== - dependencies: - domexception "^1.0.1" - webidl-conversions "^4.0.2" - xml-name-validator "^3.0.0" - -watchpack@^1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-1.6.0.tgz#4bc12c2ebe8aa277a71f1d3f14d685c7b446cd00" - integrity sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA== - dependencies: - chokidar "^2.0.2" - graceful-fs "^4.1.2" - neo-async "^2.5.0" - -wbuf@^1.1.0, wbuf@^1.7.3: - version "1.7.3" - resolved "https://registry.yarnpkg.com/wbuf/-/wbuf-1.7.3.tgz#c1d8d149316d3ea852848895cb6a0bfe887b87df" - integrity sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA== - dependencies: - minimalistic-assert "^1.0.0" - -wcwidth@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" - integrity sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g= - dependencies: - defaults "^1.0.3" - -webdriver-js-extender@2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/webdriver-js-extender/-/webdriver-js-extender-2.1.0.tgz#57d7a93c00db4cc8d556e4d3db4b5db0a80c3bb7" - integrity sha512-lcUKrjbBfCK6MNsh7xaY2UAUmZwe+/ib03AjVOpFobX4O7+83BUveSrLfU0Qsyb1DaKJdQRbuU+kM9aZ6QUhiQ== - dependencies: - "@types/selenium-webdriver" "^3.0.0" - selenium-webdriver "^3.0.1" - -webdriver-manager@^12.0.6: - version "12.1.7" - resolved "https://registry.yarnpkg.com/webdriver-manager/-/webdriver-manager-12.1.7.tgz#ed4eaee8f906b33c146e869b55e850553a1b1162" - integrity sha512-XINj6b8CYuUYC93SG3xPkxlyUc3IJbD6Vvo75CVGuG9uzsefDzWQrhz0Lq8vbPxtb4d63CZdYophF8k8Or/YiA== - dependencies: - adm-zip "^0.4.9" - chalk "^1.1.1" - del "^2.2.0" - glob "^7.0.3" - ini "^1.3.4" - minimist "^1.2.0" - q "^1.4.1" - request "^2.87.0" - rimraf "^2.5.2" - semver "^5.3.0" - xml2js "^0.4.17" - -webidl-conversions@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad" - integrity sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg== - -webpack-dev-middleware@3.7.2, webpack-dev-middleware@^3.7.2: - version "3.7.2" - resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-3.7.2.tgz#0019c3db716e3fa5cecbf64f2ab88a74bab331f3" - integrity sha512-1xC42LxbYoqLNAhV6YzTYacicgMZQTqRd27Sim9wn5hJrX3I5nxYy1SxSd4+gjUFsz1dQFj+yEe6zEVmSkeJjw== - dependencies: - memory-fs "^0.4.1" - mime "^2.4.4" - mkdirp "^0.5.1" - range-parser "^1.2.1" - webpack-log "^2.0.0" - -webpack-dev-server@3.9.0, webpack-dev-server@^3.1.4: - version "3.9.0" - resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-3.9.0.tgz#27c3b5d0f6b6677c4304465ac817623c8b27b89c" - integrity sha512-E6uQ4kRrTX9URN9s/lIbqTAztwEPdvzVrcmHE8EQ9YnuT9J8Es5Wrd8n9BKg1a0oZ5EgEke/EQFgUsp18dSTBw== - dependencies: - ansi-html "0.0.7" - bonjour "^3.5.0" - chokidar "^2.1.8" - compression "^1.7.4" - connect-history-api-fallback "^1.6.0" - debug "^4.1.1" - del "^4.1.1" - express "^4.17.1" - html-entities "^1.2.1" - http-proxy-middleware "0.19.1" - import-local "^2.0.0" - internal-ip "^4.3.0" - ip "^1.1.5" - is-absolute-url "^3.0.3" - killable "^1.0.1" - loglevel "^1.6.4" - opn "^5.5.0" - p-retry "^3.0.1" - portfinder "^1.0.25" - schema-utils "^1.0.0" - selfsigned "^1.10.7" - semver "^6.3.0" - serve-index "^1.9.1" - sockjs "0.3.19" - sockjs-client "1.4.0" - spdy "^4.0.1" - strip-ansi "^3.0.1" - supports-color "^6.1.0" - url "^0.11.0" - webpack-dev-middleware "^3.7.2" - webpack-log "^2.0.0" - ws "^6.2.1" - yargs "12.0.5" - -webpack-log@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/webpack-log/-/webpack-log-2.0.0.tgz#5b7928e0637593f119d32f6227c1e0ac31e1b47f" - integrity sha512-cX8G2vR/85UYG59FgkoMamwHUIkSSlV3bBMRsbxVXVUk2j6NleCKjQ/WE9eYg9WY4w25O9w8wKP4rzNZFmUcUg== - dependencies: - ansi-colors "^3.0.0" - uuid "^3.3.2" - -webpack-merge@4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-4.2.2.tgz#a27c52ea783d1398afd2087f547d7b9d2f43634d" - integrity sha512-TUE1UGoTX2Cd42j3krGYqObZbOD+xF7u28WB7tfUordytSjbWTIjK/8V0amkBfTYN4/pB/GIDlJZZ657BGG19g== - dependencies: - lodash "^4.17.15" - -webpack-sources@1.4.3, webpack-sources@^1.1.0, webpack-sources@^1.2.0, webpack-sources@^1.3.0, webpack-sources@^1.4.0, webpack-sources@^1.4.1, webpack-sources@^1.4.3: - version "1.4.3" - resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-1.4.3.tgz#eedd8ec0b928fbf1cbfe994e22d2d890f330a933" - integrity sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ== - dependencies: - source-list-map "^2.0.0" - source-map "~0.6.1" - -webpack-subresource-integrity@1.3.4: - version "1.3.4" - resolved "https://registry.yarnpkg.com/webpack-subresource-integrity/-/webpack-subresource-integrity-1.3.4.tgz#4554e0c622d6787f880eba009cdb73139c107bad" - integrity sha512-6XbGYzjh30cGQT/NsC+9IAkJP8IL7/t47sbwR5DLSsamiD56Rwv4/+hsgEHsviPvrEFZ0JRAQtCRN3UsR2Pw9g== - dependencies: - webpack-sources "^1.3.0" - -webpack@4.41.2: - version "4.41.2" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.41.2.tgz#c34ec76daa3a8468c9b61a50336d8e3303dce74e" - integrity sha512-Zhw69edTGfbz9/8JJoyRQ/pq8FYUoY0diOXqW0T6yhgdhCv6wr0hra5DwwWexNRns2Z2+gsnrNcbe9hbGBgk/A== - dependencies: - "@webassemblyjs/ast" "1.8.5" - "@webassemblyjs/helper-module-context" "1.8.5" - "@webassemblyjs/wasm-edit" "1.8.5" - "@webassemblyjs/wasm-parser" "1.8.5" - acorn "^6.2.1" - ajv "^6.10.2" - ajv-keywords "^3.4.1" - chrome-trace-event "^1.0.2" - enhanced-resolve "^4.1.0" - eslint-scope "^4.0.3" - json-parse-better-errors "^1.0.2" - loader-runner "^2.4.0" - loader-utils "^1.2.3" - memory-fs "^0.4.1" - micromatch "^3.1.10" - mkdirp "^0.5.1" - neo-async "^2.6.1" - node-libs-browser "^2.2.1" - schema-utils "^1.0.0" - tapable "^1.1.3" - terser-webpack-plugin "^1.4.1" - watchpack "^1.6.0" - webpack-sources "^1.4.1" - -websocket-driver@>=0.5.1: - version "0.7.3" - resolved "https://registry.yarnpkg.com/websocket-driver/-/websocket-driver-0.7.3.tgz#a2d4e0d4f4f116f1e6297eba58b05d430100e9f9" - integrity sha512-bpxWlvbbB459Mlipc5GBzzZwhoZgGEZLuqPaR0INBGnPAY1vdBX6hPnoFXiw+3yWxDuHyQjO2oXTMyS8A5haFg== - dependencies: - http-parser-js ">=0.4.0 <0.4.11" - safe-buffer ">=5.1.0" - websocket-extensions ">=0.1.1" - -websocket-extensions@>=0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/websocket-extensions/-/websocket-extensions-0.1.3.tgz#5d2ff22977003ec687a4b87073dfbbac146ccf29" - integrity sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg== - -whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz#5abacf777c32166a51d085d6b4f3e7d27113ddb0" - integrity sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw== - dependencies: - iconv-lite "0.4.24" - -whatwg-mimetype@^2.2.0, whatwg-mimetype@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf" - integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g== - -whatwg-url@^7.0.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-7.1.0.tgz#c2c492f1eca612988efd3d2266be1b9fc6170d06" - integrity sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg== - dependencies: - lodash.sortby "^4.7.0" - tr46 "^1.0.1" - webidl-conversions "^4.0.2" - -when@~3.6.x: - version "3.6.4" - resolved "https://registry.yarnpkg.com/when/-/when-3.6.4.tgz#473b517ec159e2b85005497a13983f095412e34e" - integrity sha1-RztRfsFZ4rhQBUl6E5g/CVQS404= - -which-module@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" - integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= - -which@^1.2.1, which@^1.2.9, which@^1.3.0: - version "1.3.1" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" - integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== - dependencies: - isexe "^2.0.0" - -which@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/which/-/which-2.0.1.tgz#f1cf94d07a8e571b6ff006aeb91d0300c47ef0a4" - integrity sha512-N7GBZOTswtB9lkQBZA4+zAXrjEIWAUOB93AvzUiudRzRxhUdLURQ7D/gAIMY1gatT/LTbmbcv8SiYazy3eYB7w== - dependencies: - isexe "^2.0.0" - -wide-align@^1.1.0: - version "1.1.3" - resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" - integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== - dependencies: - string-width "^1.0.2 || 2" - -widest-line@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/widest-line/-/widest-line-2.0.1.tgz#7438764730ec7ef4381ce4df82fb98a53142a3fc" - integrity sha512-Ba5m9/Fa4Xt9eb2ELXt77JxVDV8w7qQrH0zS/TWSJdLyAwQjWoOzpzj5lwVftDz6n/EOu3tNACS84v509qwnJA== - dependencies: - string-width "^2.1.1" - -word-wrap@~1.2.3: - version "1.2.3" - resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" - integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== - -wordwrap@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - integrity sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus= - -wordwrap@~0.0.2: - version "0.0.3" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" - integrity sha1-o9XabNXAvAAI03I0u68b7WMFkQc= - -worker-farm@^1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.7.0.tgz#26a94c5391bbca926152002f69b84a4bf772e5a8" - integrity sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw== - dependencies: - errno "~0.1.7" - -worker-plugin@3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/worker-plugin/-/worker-plugin-3.2.0.tgz#ddae9f161b76fcbaacf8f54ecd037844584e43e7" - integrity sha512-W5nRkw7+HlbsEt3qRP6MczwDDISjiRj2GYt9+bpe8A2La00TmJdwzG5bpdMXhRt1qcWmwAvl1TiKaHRa+XDS9Q== - dependencies: - loader-utils "^1.1.0" - -wrap-ansi@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" - integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU= - dependencies: - string-width "^1.0.1" - strip-ansi "^3.0.1" - -wrap-ansi@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz#1fd1f67235d5b6d0fee781056001bfb694c03b09" - integrity sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q== - dependencies: - ansi-styles "^3.2.0" - string-width "^3.0.0" - strip-ansi "^5.0.0" - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= - -write-file-atomic@^2.0.0: - version "2.4.3" - resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-2.4.3.tgz#1fd2e9ae1df3e75b8d8c367443c692d4ca81f481" - integrity sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ== - dependencies: - graceful-fs "^4.1.11" - imurmurhash "^0.1.4" - signal-exit "^3.0.2" - -ws@^6.1.0, ws@^6.2.1: - version "6.2.1" - resolved "https://registry.yarnpkg.com/ws/-/ws-6.2.1.tgz#442fdf0a47ed64f59b6a5d8ff130f4748ed524fb" - integrity sha512-GIyAXC2cB7LjvpgMt9EKS2ldqr0MTrORaleiOno6TweZ6r3TKtoFQWay/2PceJ3RuBasOHzXNn5Lrw1X0bEjqA== - dependencies: - async-limiter "~1.0.0" - -ws@^7.0.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-7.2.0.tgz#422eda8c02a4b5dba7744ba66eebbd84bcef0ec7" - integrity sha512-+SqNqFbwTm/0DC18KYzIsMTnEWpLwJsiasW/O17la4iDRRIO9uaHbvKiAS3AHgTiuuWerK/brj4O6MYZkei9xg== - dependencies: - async-limiter "^1.0.0" - -ws@~3.3.1: - version "3.3.3" - resolved "https://registry.yarnpkg.com/ws/-/ws-3.3.3.tgz#f1cf84fe2d5e901ebce94efaece785f187a228f2" - integrity sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA== - dependencies: - async-limiter "~1.0.0" - safe-buffer "~5.1.0" - ultron "~1.1.0" - -xdg-basedir@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/xdg-basedir/-/xdg-basedir-3.0.0.tgz#496b2cc109eca8dbacfe2dc72b603c17c5870ad4" - integrity sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ= - -xhr2@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/xhr2/-/xhr2-0.1.4.tgz#7f87658847716db5026323812f818cadab387a5f" - integrity sha1-f4dliEdxbbUCYyOBL4GMras4el8= - -xml-name-validator@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" - integrity sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw== - -xml2js@^0.4.17, xml2js@^0.4.19: - version "0.4.22" - resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.22.tgz#4fa2d846ec803237de86f30aa9b5f70b6600de02" - integrity sha512-MWTbxAQqclRSTnehWWe5nMKzI3VmJ8ltiJEco8akcC6j3miOhjjfzKum5sId+CWhfxdOs/1xauYr8/ZDBtQiRw== - dependencies: - sax ">=0.6.0" - util.promisify "~1.0.0" - xmlbuilder "~11.0.0" - -xmlbuilder@~11.0.0: - version "11.0.1" - resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" - integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== - -xmlchars@^2.1.1: - version "2.2.0" - resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" - integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== - -xmlhttprequest-ssl@~1.5.4: - version "1.5.5" - resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.5.tgz#c2876b06168aadc40e57d97e81191ac8f4398b3e" - integrity sha1-wodrBhaKrcQOV9l+gRkayPQ5iz4= - -xtend@^4.0.0, xtend@^4.0.2, xtend@~4.0.0, xtend@~4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" - integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== - -xxhashjs@^0.2.1: - version "0.2.2" - resolved "https://registry.yarnpkg.com/xxhashjs/-/xxhashjs-0.2.2.tgz#8a6251567621a1c46a5ae204da0249c7f8caa9d8" - integrity sha512-AkTuIuVTET12tpsVIQo+ZU6f/qDmKuRUcjaqR+OIvm+aCBsZ95i7UVY5WJ9TMsSaZ0DA2WxoZ4acu0sPH+OKAw== - dependencies: - cuint "^0.2.2" - -y18n@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" - integrity sha1-bRX7qITAhnnA136I53WegR4H+kE= - -"y18n@^3.2.1 || ^4.0.0", y18n@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b" - integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w== - -yallist@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" - integrity sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI= - -yallist@^3.0.0, yallist@^3.0.2, yallist@^3.0.3: - version "3.1.1" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.1.1.tgz#dbb7daf9bfd8bac9ab45ebf602b8cbad0d5d08fd" - integrity sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g== - -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== - -yaml@^1.5.0: - version "1.7.2" - resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.7.2.tgz#f26aabf738590ab61efaca502358e48dc9f348b2" - integrity sha512-qXROVp90sb83XtAoqE8bP9RwAkTTZbugRUTm5YeFCBfNRPEp2YzTeqWiz7m5OORHzEvrA/qcGS8hp/E+MMROYw== - dependencies: - "@babel/runtime" "^7.6.3" - -yargs-parser@^11.1.1: - version "11.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-11.1.1.tgz#879a0865973bca9f6bab5cbdf3b1c67ec7d3bcf4" - integrity sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ== - dependencies: - camelcase "^5.0.0" - decamelize "^1.2.0" - -yargs-parser@^13.0.0, yargs-parser@^13.1.1: - version "13.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.1.tgz#d26058532aa06d365fe091f6a1fc06b2f7e5eca0" - integrity sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ== - dependencies: - camelcase "^5.0.0" - decamelize "^1.2.0" - -yargs-parser@^9.0.2: - version "9.0.2" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-9.0.2.tgz#9ccf6a43460fe4ed40a9bb68f48d43b8a68cc077" - integrity sha1-nM9qQ0YP5O1Aqbto9I1DuKaMwHc= - dependencies: - camelcase "^4.1.0" - -yargs@12.0.5: - version "12.0.5" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-12.0.5.tgz#05f5997b609647b64f66b81e3b4b10a368e7ad13" - integrity sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw== - dependencies: - cliui "^4.0.0" - decamelize "^1.2.0" - find-up "^3.0.0" - get-caller-file "^1.0.1" - os-locale "^3.0.0" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^2.0.0" - which-module "^2.0.0" - y18n "^3.2.1 || ^4.0.0" - yargs-parser "^11.1.1" - -yargs@13.1.0: - version "13.1.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.1.0.tgz#b2729ce4bfc0c584939719514099d8a916ad2301" - integrity sha512-1UhJbXfzHiPqkfXNHYhiz79qM/kZqjTE8yGlEjZa85Q+3+OwcV6NRkV7XOV1W2Eom2bzILeUn55pQYffjVOLAg== - dependencies: - cliui "^4.0.0" - find-up "^3.0.0" - get-caller-file "^2.0.1" - os-locale "^3.1.0" - require-directory "^2.1.1" - require-main-filename "^2.0.0" - set-blocking "^2.0.0" - string-width "^3.0.0" - which-module "^2.0.0" - y18n "^4.0.0" - yargs-parser "^13.0.0" - -yargs@^11.0.0: - version "11.1.1" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-11.1.1.tgz#5052efe3446a4df5ed669c995886cc0f13702766" - integrity sha512-PRU7gJrJaXv3q3yQZ/+/X6KBswZiaQ+zOmdprZcouPYtQgvNU35i+68M4b1ZHLZtYFT5QObFLV+ZkmJYcwKdiw== - dependencies: - cliui "^4.0.0" - decamelize "^1.1.1" - find-up "^2.1.0" - get-caller-file "^1.0.1" - os-locale "^3.1.0" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^2.0.0" - which-module "^2.0.0" - y18n "^3.2.1" - yargs-parser "^9.0.2" - -yargs@^13.2.4: - version "13.3.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.0.tgz#4c657a55e07e5f2cf947f8a366567c04a0dedc83" - integrity sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA== - dependencies: - cliui "^5.0.0" - find-up "^3.0.0" - get-caller-file "^2.0.1" - require-directory "^2.1.1" - require-main-filename "^2.0.0" - set-blocking "^2.0.0" - string-width "^3.0.0" - which-module "^2.0.0" - y18n "^4.0.0" - yargs-parser "^13.1.1" - -yauzl@2.4.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.4.1.tgz#9528f442dab1b2284e58b4379bb194e22e0c4005" - integrity sha1-lSj0QtqxsihOWLQ3m7GU4i4MQAU= - dependencies: - fd-slicer "~1.0.1" - -yeast@0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/yeast/-/yeast-0.1.2.tgz#008e06d8094320c372dbc2f8ed76a0ca6c8ac419" - integrity sha1-AI4G2AlDIMNy28L47XagymyKxBk= - -yn@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/yn/-/yn-2.0.0.tgz#e5adabc8acf408f6385fc76495684c88e6af689a" - integrity sha1-5a2ryKz0CPY4X8dklWhMiOavaJo= - -zone.js@^0.10.0: - version "0.10.2" - resolved "https://registry.yarnpkg.com/zone.js/-/zone.js-0.10.2.tgz#67ca084b3116fc33fc40435e0d5ea40a207e392e" - integrity sha512-UAYfiuvxLN4oyuqhJwd21Uxb4CNawrq6fPS/05Su5L4G+1TN+HVDJMUHNMobVQDFJRir2cLAODXwluaOKB7HFg==