diff --git a/.github/actions/build-local-sdk/action.yml b/.github/actions/build-local-sdk/action.yml new file mode 100644 index 000000000000..03b17a4484bc --- /dev/null +++ b/.github/actions/build-local-sdk/action.yml @@ -0,0 +1,34 @@ +name: 'Build SDK packages locally' +description: 'Restore workspace dependencies and build the SDK outputs needed by this job.' +inputs: + setup: + description: 'Set up the build Node version and restore workspace dependencies.' + default: 'true' + package-path: + description: 'Comma-separated package paths whose SDK dependencies to build; use . only for repo-wide checks.' + default: '' + targets: + description: 'Nx targets to build for the selected packages and their dependencies.' + default: 'build:transpile build:types' +runs: + using: composite + steps: + - name: Set up repository-pinned Node.js for building + if: inputs.setup == 'true' + uses: ./.github/actions/setup-node + - name: Restore workspace dependencies + if: inputs.setup == 'true' + uses: ./.github/actions/install-dependencies + - name: Select SDK packages + id: projects + env: + INPUT_PACKAGE_PATH: ${{ inputs.package-path }} + run: node "$GITHUB_ACTION_PATH/select-projects.mjs" >> "$GITHUB_OUTPUT" + shell: bash + - name: Build SDK packages + env: + BUILD_PROJECTS: ${{ steps.projects.outputs.projects }} + run: | + node scripts/verify-packages-versions.js + pnpm exec nx run-many -t ${{ inputs.targets }} --projects="$BUILD_PROJECTS" --parallel=4 + shell: bash diff --git a/.github/actions/build-local-sdk/select-projects.mjs b/.github/actions/build-local-sdk/select-projects.mjs new file mode 100644 index 000000000000..bdf608b17894 --- /dev/null +++ b/.github/actions/build-local-sdk/select-projects.mjs @@ -0,0 +1,47 @@ +// Select the workspace packages needed by a CI job, including their transitive dependencies. +// Workspace paths select the package itself; E2E app paths select their workspace dependencies. +// The build action passes the resulting project names to Nx. + +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +const readPackage = directory => JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8')); +const workspaces = readPackage('.').workspaces; +const names = new Set(workspaces.map(directory => readPackage(directory).name)); +const packagePath = process.env.INPUT_PACKAGE_PATH; +if (!packagePath) { + throw new Error('Select a package path, or explicitly use . for repo-wide checks.'); +} +const roots = [ + ...new Set( + packagePath.split(',').flatMap(directory => { + if (directory === '.') { + return [...names]; + } + if (workspaces.includes(directory)) { + return [readPackage(directory).name]; + } + return fs.globSync('**/package.json', { cwd: directory, exclude: ['**/node_modules/**'] }).flatMap(file => { + const manifest = readPackage(path.join(directory, path.dirname(file))); + return Object.keys({ ...manifest.dependencies, ...manifest.devDependencies }).filter(name => names.has(name)); + }); + }), + ), +]; +if (!roots.length) { + throw new Error(`No workspace dependencies found for ${packagePath}`); +} + +// pnpm's ... selector includes workspace dependencies, including shared test runners and build tools. +const packages = JSON.parse( + execFileSync('pnpm', [...roots.flatMap(name => ['--filter', `${name}...`]), '-r', 'list', '--depth=-1', '--json'], { + encoding: 'utf8', + }), +); +const projects = packages.map(pkg => pkg.name); +if (!projects.length) { + throw new Error(`No SDK build projects selected for ${packagePath}`); +} +process.stderr.write(`Selected ${projects.length} workspace projects for ${packagePath}: ${projects.join(', ')}\n`); +process.stdout.write(`projects=${projects.join(',')}\n`); diff --git a/.github/actions/prepare-e2e-test/action.yml b/.github/actions/prepare-e2e-test/action.yml index 89217b9e355c..58d37a99f311 100644 --- a/.github/actions/prepare-e2e-test/action.yml +++ b/.github/actions/prepare-e2e-test/action.yml @@ -27,6 +27,9 @@ inputs: github-token: description: 'Token to download artifacts from `artifacts-run-id`. Only needed when that is set.' default: '' + download-artifacts: + description: 'Download SDK artifacts instead of using outputs already built in this workspace.' + default: 'true' runs: using: 'composite' @@ -57,7 +60,7 @@ runs: uses: ./.github/actions/install-pnpm - name: Restore SDK build and dependencies for Lambda layer - if: inputs.build-lambda-layer == 'true' + if: inputs.build-lambda-layer == 'true' && inputs.download-artifacts == 'true' uses: ./.github/actions/restore-cache with: dependency_cache_key: ${{ inputs.dependency-cache-key }} @@ -71,6 +74,7 @@ runs: # upload-artifact strips the path through the first `*`, so the tarballs are stored as /*.tgz and have to be # downloaded into packages/. - name: Restore tarball artifacts + if: inputs.download-artifacts == 'true' uses: actions/download-artifact@v8 with: name: build-tarball-output @@ -79,6 +83,7 @@ runs: github-token: ${{ inputs.github-token }} - name: Restore test-utils tarball artifact + if: inputs.download-artifacts == 'true' uses: actions/download-artifact@v8 with: name: build-test-utils-tarball-output @@ -87,7 +92,9 @@ runs: github-token: ${{ inputs.github-token }} - name: Restore build layer artifacts - if: inputs.test-application == 'aws-serverless-layer' && inputs.build-lambda-layer != 'true' + if: + inputs.download-artifacts == 'true' && inputs.test-application == 'aws-serverless-layer' && + inputs.build-lambda-layer != 'true' uses: actions/download-artifact@v8 with: name: build-layer-output @@ -97,7 +104,7 @@ runs: # The Lambda functions install the built workspace packages directly (see `src/stack.ts`). - name: Restore build artifacts - if: inputs.test-application == 'aws-serverless' + if: inputs.download-artifacts == 'true' && inputs.test-application == 'aws-serverless' uses: actions/download-artifact@v8 with: name: build-output diff --git a/.github/actions/setup-nx-planner/action.yml b/.github/actions/setup-nx-planner/action.yml new file mode 100644 index 000000000000..1dfb1a574ce0 --- /dev/null +++ b/.github/actions/setup-nx-planner/action.yml @@ -0,0 +1,34 @@ +name: 'Set up Nx planner' +description: 'Restores only the locked Nx runtime needed for affected-project selection.' + +runs: + using: 'composite' + steps: + - name: Compute planner cache key + id: dependencies + shell: bash + run: | + node scripts/dependency-hash-key.js >> "$GITHUB_OUTPUT" + if [ -x node_modules/.bin/nx ]; then echo 'installed=true' >> "$GITHUB_OUTPUT"; fi + + - name: Restore Nx runtime + id: cache + uses: actions/cache@v6.1.0 + with: + path: ${{ runner.temp }}/nx-planner + key: nx-planner-v1-${{ steps.dependencies.outputs.hash }}-${{ runner.os }}-${{ runner.arch }} + + # A miss uses the regular install; develop also seeds this cache from its existing install. + - name: Install dependencies on cache miss + if: steps.cache.outputs.cache-hit != 'true' && steps.dependencies.outputs.installed != 'true' + uses: ./.github/actions/install-dependencies + + - name: Package Nx runtime + if: steps.cache.outputs.cache-hit != 'true' + shell: bash + run: node "$GITHUB_ACTION_PATH/package-runtime.mjs" "$RUNNER_TEMP/nx-planner" + + - name: Use cached Nx runtime + if: steps.cache.outputs.cache-hit == 'true' && steps.dependencies.outputs.installed != 'true' + shell: bash + run: ln -s "$RUNNER_TEMP/nx-planner/node_modules" node_modules diff --git a/.github/actions/setup-nx-planner/package-runtime.mjs b/.github/actions/setup-nx-planner/package-runtime.mjs new file mode 100644 index 000000000000..d127531439aa --- /dev/null +++ b/.github/actions/setup-nx-planner/package-runtime.mjs @@ -0,0 +1,19 @@ +import fs from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import { createRequire } from 'node:module'; + +const require = createRequire(path.join(process.cwd(), 'package.json')); +const nxPackage = fs.realpathSync(require.resolve('nx/package.json')); +const destination = path.resolve(process.argv[2]); +const modules = path.join(destination, 'node_modules'); + +// Nx lists its runtime dependency closure directly; pnpm links it all in this directory. +const nxDependencies = path.resolve(nxPackage, '../..'); +fs.rmSync(destination, { recursive: true, force: true }); +fs.mkdirSync(destination, { recursive: true }); +execFileSync('cp', ['-RL', nxDependencies, modules]); +// Nx's pnpm lockfile reader requires the install metadata, even without workspace dependencies. +fs.copyFileSync('node_modules/.modules.yaml', path.join(modules, '.modules.yaml')); +fs.mkdirSync(path.join(modules, '.bin'), { recursive: true }); +fs.symlinkSync('../nx/dist/bin/nx.js', path.join(modules, '.bin/nx')); diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d384e87116e5..5e933ae046ec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,4 @@ name: 'CI: Build & Test' -# Full-CI baseline for the Nuxt production/development split benchmark. on: push: branches: @@ -52,19 +51,17 @@ env: BUNDLE_ARTIFACT_GLOB: packages/*/build/bundles BUNDLE_ARTIFACT_DOWNLOAD_PATH: ${{ github.workspace }}/packages - NX_CACHE_KEY: nx-Linux-${{ github.head_ref || github.ref }}-${{ github.run_id }} - # https://bsky.app/profile/joyeecheung.bsky.social/post/3lhy6o54fo22h # Apparently some of our CI failures are attributable to a corrupt v8 cache, causing v8 failures with: "Check failed: current == end_slot_index.". # This option both controls the `v8-compile-cache-lib` and `v8-compile-cache` packages. DISABLE_V8_COMPILE_CACHE: '1' -# Jobs that need the monorepo dependencies restore them from the GitHub Actions cache (see `restore-cache`), -# keyed by the lockfile hash. E2E jobs install their test application separately and do not use that cache. +# Test jobs restore workspace dependencies and build their SDK outputs locally. +# The central build still produces the shared release artifacts. jobs: - job_get_metadata: - uses: ./.github/workflows/ci-metadata.yml - name: Get CI Metadata + job_plan_ci: + uses: ./.github/workflows/ci-planning.yml + name: Plan CI jobs with: head_commit: ${{ github.event.inputs.commit || github.sha }} permissions: @@ -72,14 +69,14 @@ jobs: job_build: name: Build - needs: job_get_metadata + needs: job_plan_ci runs-on: ubuntu-24.04-arm timeout-minutes: 15 if: | - needs.job_get_metadata.outputs.changed_any_code == 'true' || - needs.job_get_metadata.outputs.is_base_branch == 'true' || - needs.job_get_metadata.outputs.is_release == 'true' || - (needs.job_get_metadata.outputs.is_gitflow_sync == 'false' && needs.job_get_metadata.outputs.has_gitflow_label == 'false' && needs.job_get_metadata.outputs.changed_any_code == 'true') + needs.job_plan_ci.outputs.changed_any_code == 'true' || + needs.job_plan_ci.outputs.is_base_branch == 'true' || + needs.job_plan_ci.outputs.is_release == 'true' || + (needs.job_plan_ci.outputs.is_gitflow_sync == 'false' && needs.job_plan_ci.outputs.has_gitflow_label == 'false' && needs.job_plan_ci.outputs.changed_any_code == 'true') steps: - name: Check out base commit (${{ github.event.pull_request.base.sha }}) uses: actions/checkout@v7 @@ -87,7 +84,7 @@ jobs: with: ref: ${{ github.event.pull_request.base.sha }} - - name: 'Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }})' + - name: 'Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }})' uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -99,16 +96,15 @@ jobs: uses: ./.github/actions/install-dependencies id: install_dependencies - - name: Check for Affected Nx Projects - uses: ./.github/actions/nx-affected-list - id: checkForAffected - if: github.event_name == 'pull_request' - with: - base: ${{ github.event.pull_request.base.sha }} - head: ${{ env.HEAD_COMMIT }} + - name: Seed planner cache + if: github.ref == 'refs/heads/develop' + uses: ./.github/actions/setup-nx-planner - name: Build packages - run: pnpm run build:ci + uses: ./.github/actions/build-local-sdk + with: + setup: 'false' + package-path: . - name: Compute build artifact paths from Nx id: nx_build_paths @@ -119,16 +115,6 @@ jobs: echo 'EOF' } >> "$GITHUB_OUTPUT" - - name: Store NX cache - uses: actions/cache/save@v6.1.0 - # Only cache this per-PR to speed up CI. - if: github.event_name == 'pull_request' - with: - path: | - .nx/cache - .nx/workspace-data - key: ${{ env.NX_CACHE_KEY }}-${{ runner.arch }} - - name: Upload build artifacts uses: actions/upload-artifact@v7 with: @@ -138,26 +124,15 @@ jobs: compression-level: 6 overwrite: true - - name: Determine which test applications should be run - id: matrix - run: - pnpm --silent run ci:build-matrix --shards=2 --separate-aws-layer --base=${{ (github.event_name == - 'pull_request' && needs.job_get_metadata.outputs.changed_ci != 'true' && github.event.pull_request.base.sha) - || '' }} >> $GITHUB_OUTPUT - working-directory: dev-packages/e2e-tests - - - name: Determine which optional E2E test applications should be run - id: matrix-optional - run: - pnpm --silent run ci:build-matrix-optional --base=${{ (github.event_name == 'pull_request' && - needs.job_get_metadata.outputs.changed_ci != 'true' && github.event.pull_request.base.sha) || '' }} >> - $GITHUB_OUTPUT - working-directory: dev-packages/e2e-tests + - name: Clean tarballs + run: pnpm run clean:tarballs - name: Build tarballs and bundles - run: | - pnpm run clean:tarballs - pnpm exec nx run-many -t build:tarball build:bundle --parallel=4 + uses: ./.github/actions/build-local-sdk + with: + setup: 'false' + package-path: . + targets: build:tarball build:bundle - name: Upload tarball artifacts uses: actions/upload-artifact@v7 @@ -190,51 +165,15 @@ jobs: outputs: dependency_cache_key: ${{ steps.install_dependencies.outputs.cache_key }} - changed_node_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/node-integration-tests') }} - changed_node: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry/node') }} - changed_deno: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry/deno') }} - changed_bun: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry/bun') }} - changed_bun_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/bun-integration-tests') }} - changed_deno_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/deno-integration-tests') }} - changed_browser_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/browser-integration-tests') }} - changed_cloudflare_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/cloudflare-integration-tests') }} - changed_bundler_plugin_integration: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry-internal/bundler-plugin-integration-tests') }} - changed_aws_serverless: - ${{ needs.job_get_metadata.outputs.changed_ci == 'true' || contains(steps.checkForAffected.outputs.affected, - '@sentry/aws-serverless') }} - e2e-matrix-1: ${{ steps.matrix.outputs.matrix-1 }} - e2e-matrix-2: ${{ steps.matrix.outputs.matrix-2 }} - e2e-matrix-aws-layer: ${{ steps.matrix.outputs.matrix-aws-layer }} - e2e-matrix-with-secrets: ${{ steps.matrix.outputs.matrix-with-secrets }} - e2e-matrix-optional: ${{ steps.matrix-optional.outputs.matrix }} - e2e-matrix-optional-without-secrets: ${{ steps.matrix-optional.outputs.matrix-without-secrets }} job_build_layer: name: Build Lambda layer - needs: [job_get_metadata, job_build] - if: needs.job_get_metadata.outputs.is_release == 'true' + needs: [job_plan_ci, job_build] + if: needs.job_plan_ci.outputs.is_release == 'true' timeout-minutes: 10 runs-on: ubuntu-24.04 steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -267,7 +206,7 @@ jobs: job_check_branches: name: Check PR branches - needs: job_get_metadata + needs: job_plan_ci runs-on: ubuntu-24.04 if: github.event_name == 'pull_request' permissions: @@ -282,28 +221,22 @@ jobs: job_size_check: name: Size Check - needs: [job_get_metadata, job_build] + needs: job_plan_ci timeout-minutes: 15 runs-on: ubuntu-24.04-arm - if: - github.event_name == 'pull_request' || needs.job_get_metadata.outputs.is_base_branch == 'true' || - needs.job_get_metadata.outputs.is_release == 'true' + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (github.event_name == 'pull_request' || + needs.job_plan_ci.outputs.is_base_branch == 'true' || needs.job_plan_ci.outputs.is_release == 'true') steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - name: Restore build bundle artifacts - uses: actions/download-artifact@v8 + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - name: build-bundle-output - path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + package-path: . + targets: build:transpile build:types build:bundle - name: Check bundle sizes uses: ./dev-packages/size-limit-gh-action with: @@ -315,20 +248,19 @@ jobs: name: Lint # Even though the linter only checks source code, not built code, it needs the built code in order check that all # inter-package dependencies resolve cleanly. - needs: [job_get_metadata, job_build] + needs: job_plan_ci + if: needs.job_plan_ci.outputs.should_run_tests == 'true' timeout-minutes: 10 runs-on: ubuntu-24.04-arm steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + package-path: . - parallel: - name: Lint source files run: pnpm run lint @@ -354,16 +286,16 @@ jobs: job_check_lockfile: name: Check lockfile - needs: [job_get_metadata] + needs: job_plan_ci # `pnpm dedupe` fetches metadata for every package from npm, so this job can take 8+ min on PRs. timeout-minutes: 20 runs-on: ubuntu-24.04 if: | - needs.job_get_metadata.outputs.changed_deps == 'true' || - needs.job_get_metadata.outputs.is_base_branch == 'true' || - needs.job_get_metadata.outputs.is_release == 'true' + needs.job_plan_ci.outputs.changed_deps == 'true' || + needs.job_plan_ci.outputs.is_base_branch == 'true' || + needs.job_plan_ci.outputs.is_release == 'true' steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -391,11 +323,11 @@ jobs: job_check_format: name: Check file formatting - needs: [job_get_metadata] + needs: job_plan_ci timeout-minutes: 10 runs-on: ubuntu-24.04 steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -411,12 +343,12 @@ jobs: job_artifacts: name: Upload Artifacts - needs: [job_get_metadata, job_build, job_build_layer] + needs: [job_plan_ci, job_build, job_build_layer] runs-on: ubuntu-24.04 # Build artifacts are only needed for releasing workflow. - if: needs.job_get_metadata.outputs.is_release == 'true' + if: needs.job_plan_ci.outputs.is_release == 'true' steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -462,7 +394,8 @@ jobs: job_browser_unit_tests: name: Browser Unit Tests - needs: [job_get_metadata, job_build] + needs: job_plan_ci + if: needs.job_plan_ci.outputs.should_run_tests == 'true' timeout-minutes: 10 runs-on: ubuntu-24.04 steps: @@ -472,17 +405,20 @@ jobs: with: ref: ${{ github.event.pull_request.base.sha }} - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node + - name: Set up repository-pinned Node.js for building uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - + - name: Restore workspace dependencies + uses: ./.github/actions/install-dependencies + - name: Build selected unit-test dependencies + env: + UNIT_TEST_ENV: browser + run: >- + pnpm exec tsx scripts/ci-unit-tests.ts --build-only ${{ github.event_name == 'pull_request' && + format('--affected --base={0}', github.event.pull_request.base.sha) || '' }} - name: Run affected tests run: pnpm run test:pr:browser --base=${{ github.event.pull_request.base.sha }} if: github.event_name == 'pull_request' @@ -493,8 +429,10 @@ jobs: job_bun_unit_tests: name: Bun (${{ matrix.bun }}) Unit Tests - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_bun == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_bun == 'true' || + github.event_name != 'pull_request') timeout-minutes: 10 runs-on: ubuntu-24.04-arm strategy: @@ -503,54 +441,51 @@ jobs: # 1.3.14 is the oldest supported Bun version bun: ['1.3.14', '1.4'] steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: bun-version: ${{ matrix.bun }} - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + package-path: packages/bun - name: Run tests run: | pnpm run test:ci:bun job_deno_unit_tests: name: Deno Unit Tests - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_deno == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_deno == 'true' || + github.event_name != 'pull_request') timeout-minutes: 10 runs-on: ubuntu-24.04-arm steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: deno-version: 'v2.8.3' - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + package-path: packages/deno - name: Run tests - run: | - cd packages/deno - pnpm run build - pnpm run test + working-directory: packages/deno + run: pnpm run test job_node_unit_tests: name: Node (${{ matrix.node }}) Unit Tests (${{ matrix.shard }}/2) - needs: [job_get_metadata, job_build] + needs: job_plan_ci + if: needs.job_plan_ci.outputs.should_run_tests == 'true' timeout-minutes: 10 runs-on: ubuntu-24.04-arm # Node 27 is an alpha: its ABI and APIs can change, so its failures must not fail the required checks. @@ -566,18 +501,25 @@ jobs: if: github.event_name == 'pull_request' with: ref: ${{ github.event.pull_request.base.sha }} - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} + - name: Set up repository-pinned Node.js for building + uses: ./.github/actions/setup-node + - name: Restore workspace dependencies + uses: ./.github/actions/install-dependencies + - name: Build selected unit-test dependencies + env: + UNIT_TEST_ENV: node + UNIT_TEST_SHARD: ${{ matrix.shard }} + run: >- + pnpm exec tsx scripts/ci-unit-tests.ts --build-only ${{ github.event_name == 'pull_request' && + format('--affected --base={0}', github.event.pull_request.base.sha) || '' }} - name: Set up Node uses: actions/setup-node@v7 with: node-version: ${{ matrix.node }} - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} # The native modules have no prebuilt binaries for the Node 27 alpha, so compile them like an install on a # user's machine does. - name: Compile native modules @@ -602,8 +544,10 @@ jobs: name: Playwright ${{ matrix.bundle }}${{ matrix.project && matrix.project != 'chromium' && format(' {0}', matrix.project) || ''}}${{ matrix.shard && format(' ({0}/{1})', matrix.shard, matrix.shards) || ''}} Tests - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_browser_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-large-js timeout-minutes: 25 strategy: @@ -689,22 +633,15 @@ jobs: shards: 3 steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - - name: Restore build bundle artifacts - uses: actions/download-artifact@v8 - with: - name: build-bundle-output - path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + package-path: dev-packages/browser-integration-tests + targets: build:transpile build:types build:bundle - name: Install Playwright uses: ./.github/actions/install-playwright @@ -733,8 +670,10 @@ jobs: job_browser_loader_tests: name: PW ${{ matrix.bundle }} Tests - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_browser_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04 timeout-minutes: 15 strategy: @@ -750,22 +689,15 @@ jobs: - loader_tracing_replay steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - - name: Restore build bundle artifacts - uses: actions/download-artifact@v8 - with: - name: build-bundle-output - path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + package-path: packages/browser + targets: build:transpile build:types build:bundle - name: Install Playwright uses: ./.github/actions/install-playwright @@ -792,27 +724,22 @@ jobs: # Runs the CDN bundles in the oldest Chromium we support. Chromium snapshots only exist for x64. job_browser_min_version_tests: name: Minimum Chromium Version Tests - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_browser_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04 timeout-minutes: 5 steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - - name: Restore build bundle artifacts - uses: actions/download-artifact@v8 - with: - name: build-bundle-output - path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + package-path: dev-packages/browser-min-version-tests,packages/browser + targets: build:transpile build:types build:bundle # Chromium itself isn't cached: `run.mjs` downloads the 127 MB zip on each run, which is about as quick as a # cache restore. @@ -824,8 +751,10 @@ jobs: job_node_integration_tests: name: Node (${{ matrix.node }}) Integration Tests (${{ matrix.shard }}/${{ matrix.shards }}) - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_node_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_node_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-arm timeout-minutes: 20 # Node 27 is an alpha: its ABI and APIs can change, so its failures must not fail the required checks. @@ -837,7 +766,7 @@ jobs: shard: [1, 2, 3, 4, 5, 6] shards: [6] steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -854,14 +783,14 @@ jobs: else echo "Sufficient disk space — skipping cleanup" fi + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk + with: + package-path: dev-packages/node-integration-tests - name: Set up Node uses: actions/setup-node@v7 with: node-version: ${{ matrix.node }} - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} # The native modules have no prebuilt binaries for the Node 27 alpha, so compile them like an install on a # user's machine does. - name: Compile native modules @@ -875,25 +804,26 @@ jobs: job_sql_server_integration_tests: name: SQL Server Integration Tests (Node 24) - needs: [job_get_metadata, job_build] + needs: job_plan_ci if: >- - needs.job_build.outputs.changed_node_integration == 'true' || needs.job_build.outputs.changed_bun_integration == - 'true' || needs.job_build.outputs.changed_deno_integration == 'true' || github.event_name != 'pull_request' + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_node_integration == + 'true' || needs.job_plan_ci.outputs.changed_bun_integration == 'true' || + needs.job_plan_ci.outputs.changed_deno_integration == 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk + with: + package-path: dev-packages/node-integration-tests - name: Set up Node uses: actions/setup-node@v7 with: node-version: '24' - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - name: Run SQL Server integration tests working-directory: dev-packages/node-integration-tests run: pnpm run test suites/tracing/tedious/test.ts @@ -901,8 +831,10 @@ jobs: # Runs on the wrangler pinned in the package, so the required run stays on a fixed, older runtime. job_cloudflare_integration_tests: name: Cloudflare Integration Tests (${{ matrix.shard }}/${{ matrix.shards }}) - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_cloudflare_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_cloudflare_integration + == 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-arm timeout-minutes: 15 strategy: @@ -911,16 +843,14 @@ jobs: shard: [1, 2, 3, 4, 5, 6] shards: [6] steps: &cloudflare_integration_tests_steps - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + package-path: dev-packages/cloudflare-integration-tests # The Vite plugin depends on wrangler and writes config for it, so both move together. In the hoisted layout, # pnpm keeps the nested `node_modules` folders of the old versions (for example an old workerd under @@ -940,10 +870,10 @@ jobs: # block a PR, and like the optional E2E tests it does not run on release branches. job_optional_cloudflare_integration_tests: name: Cloudflare Integration Tests (${{ matrix.shard }}/2, latest wrangler) (optional) - needs: [job_get_metadata, job_build] - if: - needs.job_get_metadata.outputs.is_release != 'true' && (needs.job_build.outputs.changed_cloudflare_integration == - 'true' || github.event_name != 'pull_request') + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.is_release != 'true' && + (needs.job_plan_ci.outputs.changed_cloudflare_integration == 'true' || github.event_name != 'pull_request')) runs-on: ubuntu-24.04-arm timeout-minutes: 15 strategy: @@ -956,8 +886,10 @@ jobs: job_bundler_plugin_integration_tests: name: Bundler Plugin Integration Tests (Node ${{ matrix.node }}) - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_bundler_plugin_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && + (needs.job_plan_ci.outputs.changed_bundler_plugin_integration == 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-arm timeout-minutes: 15 # Node 27 is an alpha: its ABI and APIs can change, so its failures must not fail the required checks. @@ -967,18 +899,18 @@ jobs: matrix: node: [20.19, 22, 24, 26, '^27.0.0-0'] steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk + with: + package-path: dev-packages/bundler-plugin-integration-tests - name: Set up Node uses: actions/setup-node@v7 with: node-version: ${{ matrix.node }} - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - name: Run integration tests working-directory: dev-packages/bundler-plugin-integration-tests @@ -986,8 +918,10 @@ jobs: job_bun_integration_tests: name: Bun (${{ matrix.bun }}) Integration Tests (${{ matrix.shard }}/6) - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_bun_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_bun_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-arm timeout-minutes: 15 strategy: @@ -997,20 +931,18 @@ jobs: bun: ['1.3.14', '1.4'] shard: [1, 2, 3, 4, 5, 6] steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: bun-version: ${{ matrix.bun }} - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + package-path: dev-packages/bun-integration-tests - name: Run integration tests working-directory: dev-packages/bun-integration-tests @@ -1018,8 +950,10 @@ jobs: job_deno_integration_tests: name: Deno Integration Tests (${{ matrix.shard }}/6) - needs: [job_get_metadata, job_build] - if: needs.job_build.outputs.changed_deno_integration == 'true' || github.event_name != 'pull_request' + needs: job_plan_ci + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (needs.job_plan_ci.outputs.changed_deno_integration == + 'true' || github.event_name != 'pull_request') runs-on: ubuntu-24.04-arm timeout-minutes: 15 strategy: @@ -1027,23 +961,18 @@ jobs: matrix: shard: [1, 2, 3, 4, 5, 6] steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: deno-version: 'v2.8.3' - - name: Restore caches - uses: ./.github/actions/restore-cache + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - name: Build @sentry/deno - working-directory: packages/deno - run: pnpm run build + package-path: dev-packages/deno-integration-tests - name: Run native Deno integration tests if: matrix.shard == 1 working-directory: dev-packages/deno-integration-tests @@ -1060,8 +989,10 @@ jobs: # and `steps`. job_e2e_tests_1: name: E2E ${{ matrix.label || matrix.test-application }} Test - if: always() && needs.job_build.result == 'success' && needs.job_build.outputs.e2e-matrix-1 != '{"include":[]}' - needs: [job_get_metadata, job_build] + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.result == 'success' && + needs.job_plan_ci.outputs.e2e-matrix-1 != '{"include":[]}') + needs: job_plan_ci runs-on: ubuntu-24.04 timeout-minutes: 15 # We just use a dummy DSN here, only send to the tunnel anyhow @@ -1080,21 +1011,26 @@ jobs: pnpm_config_verify_deps_before_run: 'false' strategy: fail-fast: false - matrix: ${{ fromJson(needs.job_build.outputs.e2e-matrix-1) }} + matrix: ${{ fromJson(needs.job_plan_ci.outputs.e2e-matrix-1) }} steps: &e2e-steps - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk + with: + package-path: dev-packages/e2e-tests/test-applications/${{ matrix.test-application }} + targets: build:tarball - name: Prepare E2E test application uses: ./.github/actions/prepare-e2e-test with: test-application: ${{ matrix.test-application }} build-lambda-layer: ${{ matrix.test-application == 'aws-serverless-layer' }} - dependency-cache-key: ${{ needs.job_build.outputs.dependency_cache_key }} runtime: ${{ matrix.runtime }} bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} + download-artifacts: 'false' - name: Start E2E databases background: true @@ -1142,39 +1078,42 @@ jobs: job_e2e_tests_2: name: E2E ${{ matrix.label || matrix.test-application }} Test - if: always() && needs.job_build.result == 'success' && needs.job_build.outputs.e2e-matrix-2 != '{"include":[]}' - needs: [job_get_metadata, job_build] + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.result == 'success' && + needs.job_plan_ci.outputs.e2e-matrix-2 != '{"include":[]}') + needs: job_plan_ci runs-on: ubuntu-24.04 timeout-minutes: 15 env: *e2e-env strategy: fail-fast: false - matrix: ${{ fromJson(needs.job_build.outputs.e2e-matrix-2) }} + matrix: ${{ fromJson(needs.job_plan_ci.outputs.e2e-matrix-2) }} steps: *e2e-steps job_e2e_aws_layer_tests: name: E2E ${{ matrix.label || matrix.test-application }} Test - needs: [job_get_metadata, job_build] + needs: job_plan_ci if: >- - always() && needs.job_build.result == 'success' && needs.job_build.outputs.e2e-matrix-aws-layer != - '{"include":[]}' + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.result == 'success' && + needs.job_plan_ci.outputs.e2e-matrix-aws-layer != '{"include":[]}') runs-on: ubuntu-24.04 timeout-minutes: 15 env: *e2e-env strategy: fail-fast: false - matrix: ${{ fromJson(needs.job_build.outputs.e2e-matrix-aws-layer) }} + matrix: ${{ fromJson(needs.job_plan_ci.outputs.e2e-matrix-aws-layer) }} steps: *e2e-steps # PRs from forks and Dependabot get no secrets, so they skip these jobs. Release branches skip them too, so that an # outage of an external API cannot block a release. job_e2e_tests_with_secrets: name: E2E ${{ matrix.label || matrix.test-application }} Test - if: - always() && needs.job_get_metadata.outputs.is_release != 'true' && needs.job_build.result == 'success' && - needs.job_build.outputs.e2e-matrix-with-secrets != '{"include":[]}' && (github.event_name != 'pull_request' || - github.event.pull_request.head.repo.full_name == github.repository) && github.actor != 'dependabot[bot]' - needs: [job_get_metadata, job_build] + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.outputs.is_release != + 'true' && needs.job_plan_ci.result == 'success' && needs.job_plan_ci.outputs.e2e-matrix-with-secrets != + '{"include":[]}' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == + github.repository) && github.actor != 'dependabot[bot]') + needs: job_plan_ci runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -1198,7 +1137,7 @@ jobs: pnpm_config_verify_deps_before_run: 'false' strategy: fail-fast: false - matrix: ${{ fromJson(needs.job_build.outputs.e2e-matrix-with-secrets) }} + matrix: ${{ fromJson(needs.job_plan_ci.outputs.e2e-matrix-with-secrets) }} steps: *e2e-steps # - We skip optional tests on release branches @@ -1207,11 +1146,12 @@ jobs: job_optional_e2e_tests: name: E2E Tests (optional) # A PR from a fork cannot dispatch optional-e2e.yml, see job_optional_e2e_tests_without_secrets. - if: - always() && needs.job_get_metadata.outputs.is_release != 'true' && needs.job_build.result == 'success' && - needs.job_build.outputs.e2e-matrix-optional != '{"include":[]}' && (github.event_name != 'pull_request' || - github.event.pull_request.head.repo.full_name == github.repository) && github.actor != 'dependabot[bot]' - needs: [job_get_metadata, job_build] + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.outputs.is_release != + 'true' && needs.job_plan_ci.result == 'success' && needs.job_plan_ci.outputs.e2e-matrix-optional != + '{"include":[]}' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == + github.repository) && github.actor != 'dependabot[bot]') + needs: job_plan_ci # This job only waits for optional-e2e.yml, which can take most of an hour. runs-on: ubuntu-24.04 timeout-minutes: 60 @@ -1219,7 +1159,7 @@ jobs: contents: read actions: write steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + - name: Check out current commit (${{ needs.job_plan_ci.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} @@ -1235,15 +1175,16 @@ jobs: with: github_token: ${{ secrets.GITHUB_TOKEN }} commit: ${{ env.HEAD_COMMIT }} - matrix: ${{ needs.job_build.outputs.e2e-matrix-optional }} + matrix: ${{ needs.job_plan_ci.outputs.e2e-matrix-optional }} job_optional_e2e_tests_without_secrets: name: E2E ${{ matrix.label || matrix.test-application }} Test (optional) - if: - always() && needs.job_get_metadata.outputs.is_release != 'true' && needs.job_build.result == 'success' && - needs.job_build.outputs.e2e-matrix-optional-without-secrets != '{"include":[]}' && github.event_name == - 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository - needs: [job_get_metadata, job_build] + if: >- + needs.job_plan_ci.outputs.should_run_tests == 'true' && (always() && needs.job_plan_ci.outputs.is_release != + 'true' && needs.job_plan_ci.result == 'success' && needs.job_plan_ci.outputs.e2e-matrix-optional-without-secrets + != '{"include":[]}' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != + github.repository) + needs: job_plan_ci runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -1251,7 +1192,7 @@ jobs: env: *e2e-env strategy: fail-fast: false - matrix: ${{ fromJson(needs.job_build.outputs.e2e-matrix-optional-without-secrets) }} + matrix: ${{ fromJson(needs.job_plan_ci.outputs.e2e-matrix-optional-without-secrets) }} steps: *e2e-steps job_required_jobs_passed: @@ -1259,6 +1200,7 @@ jobs: needs: [ job_build, + job_plan_ci, job_build_layer, job_browser_unit_tests, job_bun_unit_tests, diff --git a/.github/workflows/ci-metadata.yml b/.github/workflows/ci-metadata.yml deleted file mode 100644 index 3b5969cc1803..000000000000 --- a/.github/workflows/ci-metadata.yml +++ /dev/null @@ -1,98 +0,0 @@ -name: 'Get Metadata' -on: - workflow_call: - inputs: - head_commit: - description: 'The commit SHA to check out and test' - type: string - required: true - outputs: - commit_label: - description: 'Short SHA + commit message for display' - value: ${{ jobs.get_metadata.outputs.commit_label }} - is_base_branch: - description: 'Whether the ref is develop, v10, v9, or v8' - value: ${{ jobs.get_metadata.outputs.is_base_branch }} - is_release: - description: 'Whether the ref is a release branch' - value: ${{ jobs.get_metadata.outputs.is_release }} - changed_ci: - description: 'Whether .github/** files changed' - value: ${{ jobs.get_metadata.outputs.changed_ci }} - changed_any_code: - description: 'Whether any non-markdown files changed' - value: ${{ jobs.get_metadata.outputs.changed_any_code }} - changed_deps: - description: 'Whether any package.json, pnpm-lock.yaml or pnpm-workspace.yaml changed' - value: ${{ jobs.get_metadata.outputs.changed_deps }} - is_gitflow_sync: - description: 'Whether this is a gitflow sync (master merge)' - value: ${{ jobs.get_metadata.outputs.is_gitflow_sync }} - has_gitflow_label: - description: 'Whether the PR has the Gitflow label' - value: ${{ jobs.get_metadata.outputs.has_gitflow_label }} - force_skip_cache: - description: 'Whether to skip caching (schedule or ci-skip-cache label)' - value: ${{ jobs.get_metadata.outputs.force_skip_cache }} - -jobs: - get_metadata: - name: Get Metadata - runs-on: ubuntu-24.04 - permissions: - pull-requests: read - steps: - - name: Check out current commit - uses: actions/checkout@v7 - with: - ref: ${{ inputs.head_commit }} - # We need to check out not only the fake merge commit between the PR and the base branch which GH creates, but - # also its parents, so that we can pull the commit message from the head commit of the PR - fetch-depth: 2 - - - name: Get metadata - id: get_metadata - # We need to try a number of different options for finding the head commit, because each kind of trigger event - # stores it in a different location - env: - COMMIT_SHA_EXPR: - ${{ github.event.pull_request.head.sha || github.event.head_commit.id || inputs.head_commit }} - run: | - COMMIT_SHA=$(git rev-parse --short "$COMMIT_SHA_EXPR") - echo "COMMIT_SHA=$COMMIT_SHA" >> $GITHUB_ENV - echo "COMMIT_MESSAGE=$(git log -n 1 --pretty=format:%s $COMMIT_SHA)" >> $GITHUB_ENV - - # Most changed packages are determined in job_build via Nx - - name: Determine changed packages - uses: dorny/paths-filter@v4.0.3 - id: changed - with: - filters: | - workflow: - - '.github/**' - any_code: - - '!**/*.md' - deps: - - '**/package.json' - - 'pnpm-lock.yaml' - - 'pnpm-workspace.yaml' - - outputs: - commit_label: '${{ env.COMMIT_SHA }}: ${{ env.COMMIT_MESSAGE }}' - # Note: These next three have to be checked as strings ('true'/'false')! - is_base_branch: - ${{ github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/v10' || github.ref == 'refs/heads/v9' || - github.ref == 'refs/heads/v8'}} - is_release: ${{ startsWith(github.ref, 'refs/heads/release/') }} - changed_ci: ${{ steps.changed.outputs.workflow == 'true' }} - changed_any_code: ${{ steps.changed.outputs.any_code == 'true' }} - changed_deps: ${{ steps.changed.outputs.deps == 'true' }} - - # When merging into master, or from master - is_gitflow_sync: ${{ github.head_ref == 'master' || github.ref == 'refs/heads/master' }} - has_gitflow_label: - ${{ github.event_name == 'pull_request' && contains(toJSON(github.event.pull_request.labels.*.name), 'Gitflow') - }} - force_skip_cache: - ${{ github.event_name == 'schedule' || (github.event_name == 'pull_request' && - contains(toJSON(github.event.pull_request.labels.*.name), 'ci-skip-cache')) }} diff --git a/.github/workflows/ci-planning.yml b/.github/workflows/ci-planning.yml new file mode 100644 index 000000000000..c97d455f6035 --- /dev/null +++ b/.github/workflows/ci-planning.yml @@ -0,0 +1,244 @@ +name: 'Plan CI jobs' +on: + workflow_call: + inputs: + head_commit: + description: 'The commit SHA to check out and test' + type: string + required: true + outputs: + commit_label: + description: 'Short SHA + commit message for display' + value: ${{ jobs.plan_ci.outputs.commit_label }} + is_base_branch: + description: 'Whether the ref is develop, v10, v9, or v8' + value: ${{ jobs.plan_ci.outputs.is_base_branch }} + is_release: + description: 'Whether the ref is a release branch' + value: ${{ jobs.plan_ci.outputs.is_release }} + changed_ci: + description: 'Whether .github/** files changed' + value: ${{ jobs.plan_ci.outputs.changed_ci }} + changed_any_code: + description: 'Whether any non-markdown files changed' + value: ${{ jobs.plan_ci.outputs.changed_any_code }} + changed_deps: + description: 'Whether any package.json, pnpm-lock.yaml or pnpm-workspace.yaml changed' + value: ${{ jobs.plan_ci.outputs.changed_deps }} + is_gitflow_sync: + description: 'Whether this is a gitflow sync (master merge)' + value: ${{ jobs.plan_ci.outputs.is_gitflow_sync }} + has_gitflow_label: + description: 'Whether the PR has the Gitflow label' + value: ${{ jobs.plan_ci.outputs.has_gitflow_label }} + force_skip_cache: + description: 'Whether to skip caching (schedule or ci-skip-cache label)' + value: ${{ jobs.plan_ci.outputs.force_skip_cache }} + should_run_tests: + description: 'Skip tests for Markdown-only PRs; always run on base and release branches.' + value: ${{ jobs.plan_ci.outputs.should_run_tests }} + changed_node_integration: + description: 'Test planning output: changed_node_integration' + value: ${{ jobs.plan_ci.outputs.changed_node_integration }} + changed_node: + description: 'Test planning output: changed_node' + value: ${{ jobs.plan_ci.outputs.changed_node }} + changed_deno: + description: 'Test planning output: changed_deno' + value: ${{ jobs.plan_ci.outputs.changed_deno }} + changed_bun: + description: 'Test planning output: changed_bun' + value: ${{ jobs.plan_ci.outputs.changed_bun }} + changed_bun_integration: + description: 'Test planning output: changed_bun_integration' + value: ${{ jobs.plan_ci.outputs.changed_bun_integration }} + changed_deno_integration: + description: 'Test planning output: changed_deno_integration' + value: ${{ jobs.plan_ci.outputs.changed_deno_integration }} + changed_browser_integration: + description: 'Test planning output: changed_browser_integration' + value: ${{ jobs.plan_ci.outputs.changed_browser_integration }} + changed_cloudflare_integration: + description: 'Test planning output: changed_cloudflare_integration' + value: ${{ jobs.plan_ci.outputs.changed_cloudflare_integration }} + changed_bundler_plugin_integration: + description: 'Test planning output: changed_bundler_plugin_integration' + value: ${{ jobs.plan_ci.outputs.changed_bundler_plugin_integration }} + changed_aws_serverless: + description: 'Test planning output: changed_aws_serverless' + value: ${{ jobs.plan_ci.outputs.changed_aws_serverless }} + e2e-matrix-1: + description: 'Test planning output: e2e-matrix-1' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-1 }} + e2e-matrix-2: + description: 'Test planning output: e2e-matrix-2' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-2 }} + e2e-matrix-aws-layer: + description: 'Test planning output: e2e-matrix-aws-layer' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-aws-layer }} + e2e-matrix-with-secrets: + description: 'Test planning output: e2e-matrix-with-secrets' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-with-secrets }} + e2e-matrix-optional-without-secrets: + description: 'Test planning output: e2e-matrix-optional-without-secrets' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-optional-without-secrets }} + e2e-matrix-optional: + description: 'Test planning output: e2e-matrix-optional' + value: ${{ jobs.plan_ci.outputs.e2e-matrix-optional }} + +jobs: + plan_ci: + name: Plan CI jobs + runs-on: ubuntu-24.04-arm + env: + CACHED_DEPENDENCY_PATHS: | + ${{ github.workspace }}/node_modules + ${{ github.workspace }}/packages/*/node_modules + ${{ github.workspace }}/dev-packages/*/node_modules + ~/.cache/mongodb-binaries/ + permissions: + pull-requests: read + steps: + - name: Check out base commit (${{ github.event.pull_request.base.sha }}) + uses: actions/checkout@v7 + if: github.event_name == 'pull_request' + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + + - name: Check out current commit + uses: actions/checkout@v7 + with: + ref: ${{ inputs.head_commit }} + # We need to check out not only the fake merge commit between the PR and the base branch which GH creates, but + # also its parents, so that we can pull the commit message from the head commit of the PR + fetch-depth: 2 + + - name: Get metadata + id: get_metadata + # We need to try a number of different options for finding the head commit, because each kind of trigger event + # stores it in a different location + env: + COMMIT_SHA_EXPR: + ${{ github.event.pull_request.head.sha || github.event.head_commit.id || inputs.head_commit }} + run: | + COMMIT_SHA=$(git rev-parse --short "$COMMIT_SHA_EXPR") + echo "COMMIT_SHA=$COMMIT_SHA" >> $GITHUB_ENV + echo "COMMIT_MESSAGE=$(git log -n 1 --pretty=format:%s $COMMIT_SHA)" >> $GITHUB_ENV + + - name: Determine changed packages + uses: dorny/paths-filter@v4.0.3 + id: changed + with: + filters: | + workflow: + - '.github/**' + any_code: + - '!**/*.md' + deps: + - '**/package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + + - name: Determine whether tests should run + id: plan + env: + ENABLED: >- + ${{ steps.changed.outputs.any_code == 'true' || github.ref == 'refs/heads/develop' || github.ref == + 'refs/heads/v10' || github.ref == 'refs/heads/v9' || github.ref == 'refs/heads/v8' || startsWith(github.ref, + 'refs/heads/release/') }} + run: echo "enabled=$ENABLED" >> "$GITHUB_OUTPUT" + + - name: Set up Node + if: steps.plan.outputs.enabled == 'true' + uses: ./.github/actions/setup-node + + - name: Set up affected-project planner + if: + steps.plan.outputs.enabled == 'true' && github.event_name == 'pull_request' && steps.changed.outputs.workflow + != 'true' + uses: ./.github/actions/setup-nx-planner + + - name: Check for Affected Nx Projects + uses: ./.github/actions/nx-affected-list + id: checkForAffected + if: + steps.plan.outputs.enabled == 'true' && github.event_name == 'pull_request' && steps.changed.outputs.workflow + != 'true' + with: + base: ${{ github.event.pull_request.base.sha }} + head: ${{ inputs.head_commit }} + + - name: Determine which test applications should be run + id: matrix + if: steps.plan.outputs.enabled == 'true' + run: + node ./lib/getTestMatrix.mjs --shards=2 --separate-aws-layer --base=${{ (github.event_name == 'pull_request' + && steps.changed.outputs.workflow != 'true' && github.event.pull_request.base.sha) || '' }} >> $GITHUB_OUTPUT + working-directory: dev-packages/e2e-tests + + - name: Determine which optional E2E test applications should be run + id: matrix-optional + if: steps.plan.outputs.enabled == 'true' + run: + node ./lib/getTestMatrix.mjs --variant=optional --base=${{ (github.event_name == 'pull_request' && + steps.changed.outputs.workflow != 'true' && github.event.pull_request.base.sha) || '' }} >> $GITHUB_OUTPUT + working-directory: dev-packages/e2e-tests + + outputs: + commit_label: '${{ env.COMMIT_SHA }}: ${{ env.COMMIT_MESSAGE }}' + # Note: These next three have to be checked as strings ('true'/'false')! + is_base_branch: + ${{ github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/v10' || github.ref == 'refs/heads/v9' || + github.ref == 'refs/heads/v8'}} + is_release: ${{ startsWith(github.ref, 'refs/heads/release/') }} + changed_ci: ${{ steps.changed.outputs.workflow == 'true' }} + changed_any_code: ${{ steps.changed.outputs.any_code == 'true' }} + changed_deps: ${{ steps.changed.outputs.deps == 'true' }} + + # When merging into master, or from master + is_gitflow_sync: ${{ github.head_ref == 'master' || github.ref == 'refs/heads/master' }} + has_gitflow_label: + ${{ github.event_name == 'pull_request' && contains(toJSON(github.event.pull_request.labels.*.name), 'Gitflow') + }} + force_skip_cache: + ${{ github.event_name == 'schedule' || (github.event_name == 'pull_request' && + contains(toJSON(github.event.pull_request.labels.*.name), 'ci-skip-cache')) }} + should_run_tests: ${{ steps.plan.outputs.enabled == 'true' }} + changed_node_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/node-integration-tests') }} + changed_node: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry/node') }} + changed_deno: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry/deno') }} + changed_bun: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, '@sentry/bun') + }} + changed_bun_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/bun-integration-tests') }} + changed_deno_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/deno-integration-tests') }} + changed_browser_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/browser-integration-tests') }} + changed_cloudflare_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/cloudflare-integration-tests') }} + changed_bundler_plugin_integration: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry-internal/bundler-plugin-integration-tests') }} + changed_aws_serverless: + ${{ steps.changed.outputs.workflow == 'true' || contains(steps.checkForAffected.outputs.affected, + '@sentry/aws-serverless') }} + e2e-matrix-1: ${{ steps.matrix.outputs.matrix-1 || '{"include":[]}' }} + e2e-matrix-2: ${{ steps.matrix.outputs.matrix-2 || '{"include":[]}' }} + e2e-matrix-aws-layer: ${{ steps.matrix.outputs.matrix-aws-layer || '{"include":[]}' }} + e2e-matrix-optional: ${{ steps.matrix-optional.outputs.matrix || '{"include":[]}' }} + e2e-matrix-with-secrets: ${{ steps.matrix.outputs.matrix-with-secrets || '{"include":[]}' }} + e2e-matrix-optional-without-secrets: + ${{ steps.matrix-optional.outputs.matrix-without-secrets || '{"include":[]}' }} diff --git a/.github/workflows/optional-e2e.yml b/.github/workflows/optional-e2e.yml index fe5192f27db8..47871b2175dd 100644 --- a/.github/workflows/optional-e2e.yml +++ b/.github/workflows/optional-e2e.yml @@ -8,10 +8,7 @@ on: workflow_dispatch: inputs: commit: - description: The commit that the tarballs were built from - required: true - build_run_id: - description: The build.yml run that uploaded the tarball artifacts + description: The commit to build and test required: true matrix: description: The optional E2E test matrix as JSON @@ -31,6 +28,12 @@ concurrency: env: HEAD_COMMIT: ${{ inputs.commit }} + CACHED_DEPENDENCY_PATHS: | + ${{ github.workspace }}/node_modules + ${{ github.workspace }}/packages/*/node_modules + ${{ github.workspace }}/dev-packages/*/node_modules + ~/.cache/mongodb-binaries/ + # See build.yml DISABLE_V8_COMPILE_CACHE: '1' @@ -41,7 +44,6 @@ jobs: timeout-minutes: 15 permissions: contents: read - # To download the artifacts of the build.yml run actions: read # Keep the secrets the same as in job_e2e_tests_with_secrets (build.yml). env: @@ -76,6 +78,11 @@ jobs: uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} + - name: Build SDK packages locally + uses: ./.github/actions/build-local-sdk + with: + package-path: dev-packages/e2e-tests/test-applications/${{ matrix.test-application }} + targets: build:tarball - name: Prepare E2E test application uses: ./.github/actions/prepare-e2e-test with: @@ -83,8 +90,7 @@ jobs: runtime: ${{ matrix.runtime }} bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} - artifacts-run-id: ${{ inputs.build_run_id }} - github-token: ${{ github.token }} + download-artifacts: 'false' - name: Start E2E databases background: true diff --git a/CHANGELOG.md b/CHANGELOG.md index ef28e6ceb365..1f3bcce60f59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +## 11.19.0 + +- docs(aws-lambda): Fix the Lambda layer link in the v11 migration guide ([#26912](https://github.com/getsentry/sentry-javascript/pull/26912)) +- feat(solid): Turn Solid 2 observe build records into spans ([#26794](https://github.com/getsentry/sentry-javascript/pull/26794)) +- fix(cloudflare): Use the release that a Sentry bundler plugin injected ([#26914](https://github.com/getsentry/sentry-javascript/pull/26914)) +- fix(cloudflare): Wrap the TanStack Start server entry only once ([#26915](https://github.com/getsentry/sentry-javascript/pull/26915)) +- fix(nextjs): Keep the default Turbopack loader runtime in `next dev` on Bun ([#26923](https://github.com/getsentry/sentry-javascript/pull/26923)) +- fix(nuxt): Filter the query string in server error events ([#26919](https://github.com/getsentry/sentry-javascript/pull/26919)) +- fix(remix): Make `npx @sentry/remix` resolve an executable again ([#26890](https://github.com/getsentry/sentry-javascript/pull/26890)) +- fix(server-utils): Make the Flue instrumentation assignable to Flue's `instrument()` ([#26896](https://github.com/getsentry/sentry-javascript/pull/26896)) +- fix(tanstackstart-react): Instrument server function middlewares in builds without Nitro ([#26913](https://github.com/getsentry/sentry-javascript/pull/26913)) + +
+ Internal Changes + +- chore: Add external contributor to CHANGELOG.md ([#26918](https://github.com/getsentry/sentry-javascript/pull/26918)) +- chore(ci): Raise Warden review concurrency to 12 ([#26921](https://github.com/getsentry/sentry-javascript/pull/26921)) +- fix(ci): Check out the PR base commit before planning affected projects ([#26922](https://github.com/getsentry/sentry-javascript/pull/26922)) +- fix(ci): Read remaining E2E matrices from the planning job ([#26900](https://github.com/getsentry/sentry-javascript/pull/26900)) +- perf(ci): Build SDK dependencies within CI jobs ([#26732](https://github.com/getsentry/sentry-javascript/pull/26732)) +- perf(ci): Combine metadata collection and test planning ([#26889](https://github.com/getsentry/sentry-javascript/pull/26889)) +- ref(bundler-plugins): Pass the SDK's source map deletion through one internal option ([#26903](https://github.com/getsentry/sentry-javascript/pull/26903)) +- test(e2e): Make Bun, Deno and Cloudflare framework variants required ([#26887](https://github.com/getsentry/sentry-javascript/pull/26887)) +- test(e2e): Run hapi-21 on Bun and Deno ([#26872](https://github.com/getsentry/sentry-javascript/pull/26872)) +- test(nuxt): Add baseline span tree E2E tests ([#26885](https://github.com/getsentry/sentry-javascript/pull/26885)) + +
+ +Work in this release was contributed by @Caf3z1n. Thank you for your contribution! + ## 11.18.0 ### Important Changes diff --git a/MIGRATION.md b/MIGRATION.md index 9bde06ab53f1..85a5c6d6073c 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -61,7 +61,7 @@ We raised the minimum supported versions of several frameworks and libraries: ### AWS Lambda Layer Changes A new AWS Lambda Layer for version 11 will be published as `SentryNodeServerlessSDKv11`. -The ARN will be published in the [Sentry docs](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/install/cjs-layer/) once available. +The ARN will be published in the [Sentry docs](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/install/layer/) once available. The layer is compatible with the `nodejs20.x`, `nodejs22.x` and `nodejs24.x` runtimes. Functions still on `nodejs18.x` need to move to a newer runtime before upgrading. diff --git a/dev-packages/bundler-tests/package.json b/dev-packages/bundler-tests/package.json index f81497b5d9d7..de4cacc6c2c9 100644 --- a/dev-packages/bundler-tests/package.json +++ b/dev-packages/bundler-tests/package.json @@ -35,5 +35,15 @@ "vitest": "^4.1.12", "webpack": "^5.112.2" }, - "type": "module" + "type": "module", + "nx": { + "targets": { + "test": { + "dependsOn": [ + "^build:transpile", + "^build:types" + ] + } + } + } } diff --git a/dev-packages/e2e-tests/lib/getTestMatrix.mjs b/dev-packages/e2e-tests/lib/getTestMatrix.mjs index 47eef449591e..ea191bbedfbe 100644 --- a/dev-packages/e2e-tests/lib/getTestMatrix.mjs +++ b/dev-packages/e2e-tests/lib/getTestMatrix.mjs @@ -1,4 +1,4 @@ -import { execSync } from 'node:child_process'; +import { execFileSync, execSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -208,7 +208,13 @@ function getAffectedTestApplications(testApplications, { base = 'develop', head let affectedProjects = []; try { - affectedProjects = execSync(`pnpm --silent exec nx show projects --affected ${additionalArgs.join(' ')}`) + affectedProjects = execFileSync(process.execPath, [ + path.resolve(__dirname, '../../../node_modules/nx/dist/bin/nx.js'), + 'show', + 'projects', + '--affected', + ...additionalArgs, + ]) .toString() .split('\n') .map(line => line.trim()) diff --git a/dev-packages/e2e-tests/test-applications/astro-6/package.json b/dev-packages/e2e-tests/test-applications/astro-6/package.json index 75843fb7aa40..7d0895ecb303 100644 --- a/dev-packages/e2e-tests/test-applications/astro-6/package.json +++ b/dev-packages/e2e-tests/test-applications/astro-6/package.json @@ -29,7 +29,7 @@ "wrangler": "^4.72.0" }, "sentryTest": { - "optionalVariants": [ + "variants": [ { "runtime": "bun", "label": "astro-6 (bun)" diff --git a/dev-packages/e2e-tests/test-applications/express-5/package.json b/dev-packages/e2e-tests/test-applications/express-5/package.json index 8cef4a716563..f6ece8dfbe7b 100644 --- a/dev-packages/e2e-tests/test-applications/express-5/package.json +++ b/dev-packages/e2e-tests/test-applications/express-5/package.json @@ -39,7 +39,7 @@ "wrangler": "^4.120.0" }, "sentryTest": { - "optionalVariants": [ + "variants": [ { "runtime": "bun", "build-command": "pnpm test:build:bun", diff --git a/dev-packages/e2e-tests/test-applications/fastify-5/package.json b/dev-packages/e2e-tests/test-applications/fastify-5/package.json index 28b7fb98a031..aec851fbc6fa 100644 --- a/dev-packages/e2e-tests/test-applications/fastify-5/package.json +++ b/dev-packages/e2e-tests/test-applications/fastify-5/package.json @@ -26,7 +26,7 @@ "@sentry/core": "file:../../packed/sentry-core-packed.tgz" }, "sentryTest": { - "optionalVariants": [ + "variants": [ { "runtime": "bun", "bun-version": "1.4.5", diff --git a/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json b/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json index 75013991914f..733d9b966ddd 100644 --- a/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json +++ b/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json @@ -43,12 +43,14 @@ }, "sentryTest": { "needsSecrets": true, - "optionalVariants": [ + "variants": [ { "build-command": "pnpm test:build:cloudflare", "assert-command": "pnpm test:assert:cloudflare", "label": "gen-ai-libraries (cloudflare)" - }, + } + ], + "optionalVariants": [ { "build-command": "pnpm test:build-latest", "label": "gen-ai-libraries (latest)" diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/.gitignore b/dev-packages/e2e-tests/test-applications/hapi-21/.gitignore new file mode 100644 index 000000000000..364b830f8ebd --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/.gitignore @@ -0,0 +1,2 @@ +dist +dist-bun diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/bun-build.mjs b/dev-packages/e2e-tests/test-applications/hapi-21/bun-build.mjs new file mode 100644 index 000000000000..e1992eb786c6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/bun-build.mjs @@ -0,0 +1,11 @@ +// Bundles the app with `@sentry/bun/plugin`. Under `bun run` the SDK cannot inject diagnostics channels into +// packages, so only a bundled app gets the Hapi spans and error handler. +import { sentryBunPlugin } from '@sentry/bun/plugin'; +import { join } from 'node:path'; + +await Bun.build({ + entrypoints: [join(import.meta.dir, 'src/main.ts')], + target: 'bun', + outdir: join(import.meta.dir, 'dist-bun'), + plugins: [sentryBunPlugin({ telemetry: false })], +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/deno.json b/dev-packages/e2e-tests/test-applications/hapi-21/deno.json new file mode 100644 index 000000000000..afdc876f8771 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/deno.json @@ -0,0 +1,7 @@ +{ + "imports": { + "@sentry/deno/import": "./node_modules/@sentry/deno/build/import.mjs" + }, + "nodeModulesDir": "manual", + "unstable": ["sloppy-imports"] +} diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/package.json b/dev-packages/e2e-tests/test-applications/hapi-21/package.json new file mode 100644 index 000000000000..691ecd3fab6a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/package.json @@ -0,0 +1,44 @@ +{ + "name": "hapi-21", + "version": "1.0.0", + "private": true, + "scripts": { + "build": "tsc", + "start": "node dist/main.js", + "start:bun": "bun dist-bun/main.js", + "start:deno": "deno run -A --preload=@sentry/deno/import --preload=./src/instrument.ts src/main.ts", + "test": "playwright test", + "clean": "npx rimraf node_modules pnpm-lock.yaml", + "test:build": "pnpm install && pnpm build", + "test:build:bun": "pnpm install && pnpm build && bun ./bun-build.mjs", + "test:assert": "pnpm test" + }, + "dependencies": { + "@hapi/boom": "10.0.1", + "@hapi/hapi": "21.3.10", + "@sentry/bun": "file:../../packed/sentry-bun-packed.tgz", + "@sentry/deno": "file:../../packed/sentry-deno-packed.tgz", + "@sentry/node": "file:../../packed/sentry-node-packed.tgz", + "@types/node": "^18.19.1", + "typescript": "~5.7.2" + }, + "devDependencies": { + "@playwright/test": "1.64.1", + "@sentry/conventions": "0.36.0", + "@sentry/core": "file:../../packed/sentry-core-packed.tgz", + "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" + }, + "sentryTest": { + "optionalVariants": [ + { + "runtime": "bun", + "build-command": "pnpm test:build:bun", + "label": "hapi-21 (bun)" + }, + { + "runtime": "deno", + "label": "hapi-21 (deno)" + } + ] + } +} diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/hapi-21/playwright.config.mjs new file mode 100644 index 000000000000..0b3b962757f0 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/playwright.config.mjs @@ -0,0 +1,13 @@ +import { getPlaywrightConfig, getRuntime } from '@sentry-internal/test-utils'; + +const startCommands = { + node: 'pnpm start', + bun: 'pnpm start:bun', + deno: 'pnpm start:deno', +}; + +const config = getPlaywrightConfig({ + startCommand: startCommands[getRuntime()], +}); + +export default config; diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/hapi-21/pnpm-workspace.yaml similarity index 100% rename from dev-packages/e2e-tests/test-applications/node-hapi/pnpm-workspace.yaml rename to dev-packages/e2e-tests/test-applications/hapi-21/pnpm-workspace.yaml diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/app.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/app.ts new file mode 100644 index 000000000000..4b307d0a10be --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/app.ts @@ -0,0 +1,134 @@ +import Boom from '@hapi/boom'; +import Hapi from '@hapi/hapi'; +import * as Sentry from './sentry'; + +export const server = Hapi.server({ + port: 3030, + host: 'localhost', +}); + +server.route({ + method: 'GET', + path: '/test-success', + handler: function () { + return { version: 'v1' }; + }, +}); + +server.route({ + method: 'GET', + path: '/test-param/{param}', + handler: function (request) { + Sentry.setAttribute(`param-${request.params.param}`, 'yes'); + + return { paramWas: request.params.param }; + }, +}); + +server.route({ + method: 'GET', + path: '/test-log', + handler: function () { + Sentry.logger.debug('Accessed /test-log route'); + return { message: 'Log sent' }; + }, +}); + +server.route({ + method: 'GET', + path: '/test-error', + handler: async function () { + const exceptionId = Sentry.captureException(new Error('This is an error')); + + await Sentry.flush(2000); + + return { exceptionId }; + }, +}); + +server.route({ + method: 'GET', + path: '/test-error/{id}', + handler: function (request) { + throw new Error(`This is an error with id ${request.params.id}`); + }, +}); + +server.route({ + method: 'GET', + path: '/test-failure', + handler: async function () { + throw new Error('This is an error'); + }, +}); + +server.route({ + method: 'GET', + path: '/test-failure-boom-4xx', + handler: async function () { + throw new Error('This is a JS error (boom in onPreResponse)'); + }, +}); + +server.route({ + method: 'GET', + path: '/test-failure-boom-5xx', + handler: async function () { + throw new Error('This is an error (boom in onPreResponse)'); + }, +}); + +server.route({ + method: 'GET', + path: '/test-failure-JS-error-onPreResponse', + handler: async function () { + throw new Error('This is an error (another JS error in onPreResponse)'); + }, +}); + +server.route({ + method: 'GET', + path: '/test-failure-2xx-override-onPreResponse', + handler: async function () { + throw new Error('This is a JS error (2xx override in onPreResponse)'); + }, +}); + +server.route({ + method: 'GET', + path: '/test-isolation/{id}', + handler: async function (request) { + Sentry.setTag('isolation-id', request.params.id); + // Lets the concurrent requests of the isolation test overlap. + await new Promise(resolve => setTimeout(resolve, 200)); + Sentry.captureException(new Error(`Isolated error ${request.params.id}`)); + return {}; + }, +}); + +// The test runs a server on port 3040 that records the headers of the request. +server.route({ + method: 'GET', + path: '/test-outgoing-fetch', + handler: async function () { + const response = await fetch('http://localhost:3040/outgoing'); + return { status: response.status }; + }, +}); + +// This runs after the route handler +server.ext('onPreResponse', (request, h) => { + const path = request.route.path; + + if (path.includes('boom-4xx')) { + throw Boom.badRequest('4xx bad request (onPreResponse)'); + } else if (path.includes('boom-5xx')) { + throw Boom.gatewayTimeout('5xx not implemented (onPreResponse)'); + } else if (path.includes('JS-error-onPreResponse')) { + throw new Error('JS error (onPreResponse)'); + } else if (path.includes('2xx-override-onPreResponse')) { + return h.response('2xx override').code(200); + } else { + return h.continue; + } +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.bun.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.bun.ts new file mode 100644 index 000000000000..1e933d686aa1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.bun.ts @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/bun'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + debug: !!process.env.DEBUG, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.deno.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.deno.ts new file mode 100644 index 000000000000..dee01f30487d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.deno.ts @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/deno'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + debug: !!process.env.DEBUG, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.ts new file mode 100644 index 000000000000..82803544d370 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/instrument.ts @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/node'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + includeLocalVariables: true, + debug: !!process.env.DEBUG, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/main.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/main.ts new file mode 100644 index 000000000000..a453bfa45dca --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/main.ts @@ -0,0 +1,7 @@ +import './instrument'; + +import { server } from './app'; + +server.start().then(() => { + console.log('Server running on %s', server.info.uri); +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.bun.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.bun.ts new file mode 100644 index 000000000000..7bf1576974c3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.bun.ts @@ -0,0 +1 @@ +export * from '@sentry/bun'; diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.deno.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.deno.ts new file mode 100644 index 000000000000..412874a768aa --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.deno.ts @@ -0,0 +1 @@ +export * from '@sentry/deno'; diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.ts b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.ts new file mode 100644 index 000000000000..fb7328c77640 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/src/sentry.ts @@ -0,0 +1,2 @@ +// The app imports the Sentry API from this file. Each other runtime has a `sentry..ts` with its own SDK. +export * from '@sentry/node'; diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/hapi-21/start-event-proxy.mjs similarity index 77% rename from dev-packages/e2e-tests/test-applications/node-hapi/start-event-proxy.mjs rename to dev-packages/e2e-tests/test-applications/hapi-21/start-event-proxy.mjs index 0677757f657f..fe95886c1bee 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi/start-event-proxy.mjs +++ b/dev-packages/e2e-tests/test-applications/hapi-21/start-event-proxy.mjs @@ -2,5 +2,5 @@ import { startEventProxyServer } from '@sentry-internal/test-utils'; startEventProxyServer({ port: 3031, - proxyServerName: 'node-hapi', + proxyServerName: 'hapi-21', }); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/tests/constants.ts b/dev-packages/e2e-tests/test-applications/hapi-21/tests/constants.ts new file mode 100644 index 000000000000..a7199ff7d5ff --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tests/constants.ts @@ -0,0 +1,3 @@ +import { getRuntime } from '@sentry-internal/test-utils'; + +export const RUNTIME = getRuntime(); diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/tests/errors.test.ts b/dev-packages/e2e-tests/test-applications/hapi-21/tests/errors.test.ts similarity index 77% rename from dev-packages/e2e-tests/test-applications/node-hapi/tests/errors.test.ts rename to dev-packages/e2e-tests/test-applications/hapi-21/tests/errors.test.ts index f1f2aaf8aafb..f730ac169348 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi/tests/errors.test.ts +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tests/errors.test.ts @@ -7,11 +7,11 @@ import { } from '@sentry-internal/test-utils'; test('Sends thrown error to Sentry', async ({ baseURL }) => { - const errorEventPromise = waitForError('node-hapi', errorEvent => { + const errorEventPromise = waitForError('hapi-21', errorEvent => { return errorEvent?.exception?.values?.[0]?.value === 'This is an error'; }); - const spansPromise = collectStreamedSpansUntilSegment('node-hapi', 'GET /test-failure'); + const spansPromise = collectStreamedSpansUntilSegment('hapi-21', 'GET /test-failure'); await fetch(`${baseURL}/test-failure`); @@ -20,6 +20,10 @@ test('Sends thrown error to Sentry', async ({ baseURL }) => { const segmentSpan = spans.find(span => span.is_segment); expect(segmentSpan?.name).toBe('GET /test-failure'); + expect(segmentSpan?.attributes).toMatchObject({ + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'http.route': { type: 'string', value: '/test-failure' }, + }); expect(segmentSpan).toMatchObject({ trace_id: expect.stringMatching(/[a-f0-9]{32}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), @@ -40,8 +44,6 @@ test('Sends thrown error to Sentry', async ({ baseURL }) => { url: 'http://localhost:3030/test-failure', }); - expect(errorEvent.transaction).toEqual('GET /test-failure'); - expect(errorEvent.contexts?.trace).toEqual({ trace_id: expect.stringMatching(/[a-f0-9]{32}/), span_id: expect.stringMatching(/[a-f0-9]{16}/), @@ -56,16 +58,23 @@ test('Sends thrown error to Sentry', async ({ baseURL }) => { expect(errorEvent.contexts?.trace?.parent_span_id).toBe(segmentSpan?.span_id); }); -test('sends error with parameterized transaction name', async ({ baseURL }) => { - const errorEventPromise = waitForError('node-hapi', errorEvent => { +test('Sends an error thrown in a parameterized route with the trace of its request', async ({ baseURL }) => { + const errorEventPromise = waitForError('hapi-21', errorEvent => { return errorEvent?.exception?.values?.[0]?.value === 'This is an error with id 123'; }); + const spansPromise = collectStreamedSpansUntilSegment('hapi-21', 'GET /test-error/{id}'); + await fetch(`${baseURL}/test-error/123`); const errorEvent = await errorEventPromise; + const segmentSpan = (await spansPromise).find(span => span.is_segment); - expect(errorEvent?.transaction).toBe('GET /test-error/{id}'); + expect(segmentSpan?.attributes).toMatchObject({ + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'http.route': { type: 'string', value: '/test-error/{id}' }, + }); + expect(errorEvent.contexts?.trace?.trace_id).toBe(segmentSpan?.trace_id); }); test('Does not send errors to Sentry if boom throws in "onPreResponse" after JS error in route handler', async ({ @@ -73,7 +82,7 @@ test('Does not send errors to Sentry if boom throws in "onPreResponse" after JS }) => { let errorEventOccurred = false; - waitForError('node-hapi', event => { + waitForError('hapi-21', event => { if (event.exception?.values?.[0]?.value?.includes('This is a JS error (boom in onPreResponse)')) { errorEventOccurred = true; } @@ -81,12 +90,12 @@ test('Does not send errors to Sentry if boom throws in "onPreResponse" after JS }); const segmentEventPromise4xx = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && segment.name === 'GET /test-failure-boom-4xx', ); const segmentEventPromise5xx = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && segment.name === 'GET /test-failure-boom-5xx', ); @@ -109,7 +118,7 @@ test('Does not send error to Sentry if error response is overwritten with 2xx in }) => { let errorEventOccurred = false; - waitForError('node-hapi', event => { + waitForError('hapi-21', event => { if (event.exception?.values?.[0]?.value?.includes('This is a JS error (2xx override in onPreResponse)')) { errorEventOccurred = true; } @@ -117,7 +126,7 @@ test('Does not send error to Sentry if error response is overwritten with 2xx in }); const segmentEventPromise = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && segment.name === 'GET /test-failure-2xx-override-onPreResponse', ); @@ -133,13 +142,13 @@ test('Does not send error to Sentry if error response is overwritten with 2xx in test('Only sends onPreResponse error to Sentry if JS error is thrown in route handler AND onPreResponse', async ({ baseURL, }) => { - const errorEventPromise = waitForError('node-hapi', errorEvent => { + const errorEventPromise = waitForError('hapi-21', errorEvent => { return errorEvent?.exception?.values?.[0]?.value?.includes('JS error (onPreResponse)') || false; }); let routeHandlerErrorOccurred = false; - waitForError('node-hapi', event => { + waitForError('hapi-21', event => { if ( !event.type && event.exception?.values?.[0]?.value?.includes('This is an error (another JS error in onPreResponse)') @@ -150,7 +159,7 @@ test('Only sends onPreResponse error to Sentry if JS error is thrown in route ha }); const segmentEventPromise = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && segment.name === 'GET /test-failure-JS-error-onPreResponse', ); @@ -163,5 +172,9 @@ test('Only sends onPreResponse error to Sentry if JS error is thrown in route ha expect(routeHandlerErrorOccurred).toBe(false); expect(segmentEvent.name).toBe('GET /test-failure-JS-error-onPreResponse'); - expect(errorEvent.transaction).toEqual('GET /test-failure-JS-error-onPreResponse'); + expect(segmentEvent.attributes).toMatchObject({ + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'http.route': { type: 'string', value: '/test-failure-JS-error-onPreResponse' }, + }); + expect(errorEvent.contexts?.trace?.trace_id).toBe(segmentEvent.trace_id); }); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/tests/logs.test.ts b/dev-packages/e2e-tests/test-applications/hapi-21/tests/logs.test.ts new file mode 100644 index 000000000000..f2c6e9b3da66 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tests/logs.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from '@playwright/test'; +import { waitForEnvelopeItem } from '@sentry-internal/test-utils'; +import type { SerializedLogContainer } from '@sentry/core'; + +test('should send logs', async ({ baseURL }) => { + const logEnvelopePromise = waitForEnvelopeItem('hapi-21', envelope => { + return envelope[0].type === 'log' && (envelope[1] as SerializedLogContainer).items[0]?.level === 'debug'; + }); + + await fetch(`${baseURL}/test-log`); + + const logEnvelope = await logEnvelopePromise; + const log = (logEnvelope[1] as SerializedLogContainer).items[0]; + expect(log?.level).toBe('debug'); + expect(log?.body).toBe('Accessed /test-log route'); +}); diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/tests/request.test.ts b/dev-packages/e2e-tests/test-applications/hapi-21/tests/request.test.ts new file mode 100644 index 000000000000..2bbaf5be1de6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tests/request.test.ts @@ -0,0 +1,98 @@ +import { expect, test } from '@playwright/test'; +import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; +import type { IncomingHttpHeaders } from 'node:http'; +import { createServer } from 'node:http'; + +const TRACE_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; +const PARENT_SPAN_ID = 'bbbbbbbbbbbbbbbb'; + +test('Names the request span after the parameterized route', async ({ baseURL }) => { + const spansPromise = collectStreamedSpansUntilSegment('hapi-21', 'GET /test-param/{param}'); + + const response = await fetch(`${baseURL}/test-param/123`); + expect(await response.json()).toEqual({ paramWas: '123' }); + + const segmentSpan = (await spansPromise).find(span => span.is_segment)!; + expect(segmentSpan.attributes).toMatchObject({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'http.route': { type: 'string', value: '/test-param/{param}' }, + 'url.path': { type: 'string', value: '/test-param/123' }, + }); +}); + +test('Keeps the scope data of concurrent requests apart', async ({ baseURL }) => { + const ids = ['1', '2', '3']; + const errorPromises = ids.map(id => + waitForError('hapi-21', event => event.exception?.values?.[0]?.value === `Isolated error ${id}`), + ); + + const segmentSpansPromises = ids.map(id => + collectStreamedSpansUntilSegment( + 'hapi-21', + span => + span.name === 'GET /test-isolation/{id}' && span.attributes['url.path']?.value === `/test-isolation/${id}`, + ), + ); + + await Promise.all(ids.map(id => fetch(`${baseURL}/test-isolation/${id}`))); + + const errors = await Promise.all(errorPromises); + const segmentSpans = (await Promise.all(segmentSpansPromises)).map(spans => spans.find(span => span.is_segment)); + errors.forEach((error, index) => { + expect(error.tags?.['isolation-id']).toBe(ids[index]); + expect(error.contexts?.trace?.trace_id).toBe(segmentSpans[index]?.trace_id); + }); + + const traceIds = errors.map(error => error.contexts?.trace?.trace_id); + expect(new Set(traceIds).size).toBe(ids.length); +}); + +test('Continues the trace of an incoming request', async ({ baseURL }) => { + const spansPromise = collectStreamedSpansUntilSegment( + 'hapi-21', + span => span.name === 'GET /test-param/{param}' && span.trace_id === TRACE_ID, + ); + + await fetch(`${baseURL}/test-param/continued`, { + headers: { + 'sentry-trace': `${TRACE_ID}-${PARENT_SPAN_ID}-1`, + baggage: `sentry-trace_id=${TRACE_ID},sentry-environment=qa,sentry-public_key=public,sentry-sampled=true`, + }, + }); + + const segmentSpan = (await spansPromise).find(span => span.is_segment)!; + expect(segmentSpan.trace_id).toBe(TRACE_ID); + expect(segmentSpan.parent_span_id).toBe(PARENT_SPAN_ID); +}); + +test('Propagates the trace to an outgoing fetch request', async ({ baseURL }) => { + let receivedHeaders: IncomingHttpHeaders | undefined; + const server = createServer((req, res) => { + receivedHeaders = req.headers; + res.end('ok'); + }); + await new Promise(resolve => server.listen(3040, resolve)); + + try { + const spansPromise = collectStreamedSpansUntilSegment('hapi-21', 'GET /test-outgoing-fetch'); + + const response = await fetch(`${baseURL}/test-outgoing-fetch`); + expect(await response.json()).toEqual({ status: 200 }); + + const spans = await spansPromise; + const segmentSpan = spans.find(span => span.is_segment)!; + const fetchSpans = spans.filter(span => getSpanOp(span) === 'http.client'); + + expect(fetchSpans).toHaveLength(1); + const fetchSpan = fetchSpans[0]!; + expect(fetchSpan.trace_id).toBe(segmentSpan.trace_id); + expect(fetchSpan.attributes['http.request.method']).toEqual({ type: 'string', value: 'GET' }); + + expect(receivedHeaders?.['sentry-trace']).toBe(`${segmentSpan.trace_id}-${fetchSpan.span_id}-1`); + expect(receivedHeaders?.baggage).toContain(`sentry-trace_id=${segmentSpan.trace_id}`); + expect(receivedHeaders?.baggage).toContain('sentry-environment=qa'); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/tests/spans.test.ts b/dev-packages/e2e-tests/test-applications/hapi-21/tests/spans.test.ts similarity index 92% rename from dev-packages/e2e-tests/test-applications/node-hapi/tests/spans.test.ts rename to dev-packages/e2e-tests/test-applications/hapi-21/tests/spans.test.ts index 55c563a68ad9..1aba0456439d 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi/tests/spans.test.ts +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tests/spans.test.ts @@ -1,10 +1,11 @@ import { expect, test } from '@playwright/test'; import { HAPI_EXT_TYPE, HAPI_TYPE, SERVER_EXT_TYPE } from '@sentry/conventions/attributes'; import { waitForStreamedSpan, getSpanOp, collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { RUNTIME } from './constants'; test('Sends successful span', async ({ baseURL }) => { const pageloadSegmentEventPromise = collectStreamedSpansUntilSegment( - 'node-hapi', + 'hapi-21', segment => getSpanOp(segment) === 'http.server' && segment.name === 'GET /test-success', ); @@ -22,7 +23,6 @@ test('Sends successful span', async ({ baseURL }) => { trace_id: expect.stringMatching(/[a-f0-9]{32}/), attributes: expect.objectContaining({ 'sentry.segment.name.source': { value: 'route', type: 'string' }, - 'sentry.origin': { value: 'auto.http.http_server', type: 'string' }, 'sentry.op': { value: 'http.server', type: 'string' }, 'sentry.sample_rate': { value: 1, type: 'integer' }, 'sentry.kind': { value: 'server', type: 'string' }, @@ -33,25 +33,29 @@ test('Sends successful span', async ({ baseURL }) => { 'http.request.method': { value: 'GET', type: 'string' }, 'url.scheme': { value: 'http', type: 'string' }, 'user_agent.original': { value: 'node', type: 'string' }, - 'client.address': { value: '::1', type: 'string' }, + // Deno resolves the `localhost` host of the Hapi server to an IPv4 address. + 'client.address': { value: RUNTIME === 'deno' ? '127.0.0.1' : '::1', type: 'string' }, + 'network.protocol.name': { value: 'http', type: 'string' }, + 'network.protocol.version': { value: '1.1', type: 'string' }, + 'http.route': { value: '/test-success', type: 'string' }, + 'http.request.header.accept': { value: ['*/*'], type: 'array' }, + 'http.request.header.accept-language': { value: ['*'], type: 'array' }, + 'http.request.header.host': { value: [expect.any(String)], type: 'array' }, + 'http.request.header.sec-fetch-mode': { value: ['cors'], type: 'array' }, + 'http.request.header.user-agent': { value: ['node'], type: 'array' }, + 'sentry.origin': { value: 'auto.http.http_server', type: 'string' }, 'client.port': { value: expect.any(Number), type: 'integer' }, 'network.transport': { value: 'tcp', type: 'string' }, 'network.local.address': { value: expect.any(String), type: 'string' }, 'network.local.port': { value: expect.any(Number), type: 'integer' }, 'network.peer.address': { value: expect.any(String), type: 'string' }, 'network.peer.port': { value: expect.any(Number), type: 'integer' }, - 'network.protocol.name': { value: 'http', type: 'string' }, - 'network.protocol.version': { value: '1.1', type: 'string' }, 'server.port': { value: 3030, type: 'integer' }, - 'http.response.status_text': { value: 'OK', type: 'string' }, - 'http.route': { value: '/test-success', type: 'string' }, - 'http.request.header.accept': { value: ['*/*'], type: 'array' }, 'http.request.header.accept-encoding': { value: ['gzip, deflate'], type: 'array' }, - 'http.request.header.accept-language': { value: ['*'], type: 'array' }, 'http.request.header.connection': { value: ['keep-alive'], type: 'array' }, - 'http.request.header.host': { value: [expect.any(String)], type: 'array' }, - 'http.request.header.sec-fetch-mode': { value: ['cors'], type: 'array' }, - 'http.request.header.user-agent': { value: ['node'], type: 'array' }, + // Known defect: Bun's `node:http` leaves `statusMessage` unset when the app does not set it, and the + // SDK does not fall back to the standard reason phrase. + ...(RUNTIME === 'bun' ? {} : { 'http.response.status_text': { value: 'OK', type: 'string' } }), }), }), ); @@ -111,7 +115,7 @@ test('Sends successful span', async ({ baseURL }) => { test('Sends parameterized spans to Sentry', async ({ baseURL }) => { const pageloadSegmentEventPromise = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && getSpanOp(segment) === 'http.server' && segment.name === 'GET /test-param/{param}', ); @@ -126,14 +130,14 @@ test('Sends parameterized spans to Sentry', async ({ baseURL }) => { test('Isolates requests', async ({ baseURL }) => { const segment1Promise = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && getSpanOp(segment) === 'http.server' && segment.attributes?.['url.path']?.value === '/test-param/888', ); const segment2Promise = waitForStreamedSpan( - 'node-hapi', + 'hapi-21', segment => segment.is_segment && getSpanOp(segment) === 'http.server' && diff --git a/dev-packages/e2e-tests/test-applications/hapi-21/tsconfig.json b/dev-packages/e2e-tests/test-applications/hapi-21/tsconfig.json new file mode 100644 index 000000000000..5b6ed75dab3c --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/hapi-21/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "types": ["node"], + "esModuleInterop": true, + "lib": ["es2020"], + "strict": true, + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.bun.ts", "src/**/*.deno.ts"] +} diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/package.json b/dev-packages/e2e-tests/test-applications/nestjs-12/package.json index 1b5110a1e71f..1ace886ad1aa 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/package.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/package.json @@ -46,7 +46,7 @@ "wrangler": "^4.120.0" }, "sentryTest": { - "optionalVariants": [ + "variants": [ { "runtime": "bun", "bun-version": "1.4.4", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json index 7006db5a96f2..37c538447c0d 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json @@ -132,15 +132,21 @@ "build-command": "NEXT_PUBLIC_E2E_TEST_TRACE_LIFECYCLE=static pnpm test:build", "assert-command": "E2E_TEST_TRACE_LIFECYCLE=static pnpm test:prod", "label": "nextjs-16 (turbopack, production, static trace lifecycle)" - } - ], - "optionalVariants": [ + }, + { + "runtime": "bun", + "build-command": "pnpm install", + "assert-command": "pnpm test:dev", + "label": "nextjs-16 (bun, turbopack, development)" + }, { "runtime": "cloudflare", "build-command": "pnpm test:build-latest:cloudflare", "assert-command": "pnpm test:prod", "label": "nextjs-16 (cloudflare, latest)" - }, + } + ], + "optionalVariants": [ { "build-command": "pnpm test:build:vinext", "assert-command": "pnpm test:assert:vinext", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs index dd8046fb9611..778035690610 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs @@ -28,6 +28,11 @@ const getStartCommand = () => { } if (testEnv === 'development') { + if (getRuntime() === 'bun') { + // Use the bin name, not its path: then Bun puts its `node` shim in PATH, which the Turbopack loader processes use. + return 'bun --bun next dev -p 3030 2>&1 | tee .tmp_dev_server_logs'; + } + return 'pnpm next dev -p 3030 2>&1 | tee .tmp_dev_server_logs'; } diff --git a/dev-packages/e2e-tests/test-applications/node-flue/package.json b/dev-packages/e2e-tests/test-applications/node-flue/package.json index 4fad53c9a361..61da26a8642d 100644 --- a/dev-packages/e2e-tests/test-applications/node-flue/package.json +++ b/dev-packages/e2e-tests/test-applications/node-flue/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "NODE_OPTIONS='--import=@sentry/node/import' vite dev --port 3030", - "build": "vite build", + "build": "tsc && vite build", "start": "NODE_OPTIONS='--import=@sentry/node/import' PORT=3030 node dist/server.mjs", "clean": "npx rimraf node_modules dist pnpm-lock.yaml", "test:build": "pnpm install && pnpm build", diff --git a/dev-packages/e2e-tests/test-applications/node-flue/tsconfig.json b/dev-packages/e2e-tests/test-applications/node-flue/tsconfig.json index 2cb98b13c9f8..213e0d210343 100644 --- a/dev-packages/e2e-tests/test-applications/node-flue/tsconfig.json +++ b/dev-packages/e2e-tests/test-applications/node-flue/tsconfig.json @@ -5,6 +5,7 @@ "moduleResolution": "bundler", "types": ["node"], "strict": true, + "exactOptionalPropertyTypes": true, "allowImportingTsExtensions": true, "esModuleInterop": true, "skipLibCheck": true, diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/.gitignore b/dev-packages/e2e-tests/test-applications/node-hapi/.gitignore deleted file mode 100644 index 1521c8b7652b..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-hapi/.gitignore +++ /dev/null @@ -1 +0,0 @@ -dist diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/package.json b/dev-packages/e2e-tests/test-applications/node-hapi/package.json deleted file mode 100644 index 202b5a291ad1..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-hapi/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "node-hapi", - "version": "1.0.0", - "private": true, - "scripts": { - "build": "tsc", - "start": "node src/app.js", - "test": "playwright test", - "clean": "npx rimraf node_modules pnpm-lock.yaml", - "test:build": "pnpm install", - "test:assert": "pnpm test" - }, - "dependencies": { - "@hapi/boom": "10.0.1", - "@hapi/hapi": "21.3.10", - "@sentry/node": "file:../../packed/sentry-node-packed.tgz" - }, - "devDependencies": { - "@playwright/test": "1.64.1", - "@sentry/conventions": "0.36.0", - "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" - } -} diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/node-hapi/playwright.config.mjs deleted file mode 100644 index 31f2b913b58b..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-hapi/playwright.config.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { getPlaywrightConfig } from '@sentry-internal/test-utils'; - -const config = getPlaywrightConfig({ - startCommand: `pnpm start`, -}); - -export default config; diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/src/app.js b/dev-packages/e2e-tests/test-applications/node-hapi/src/app.js deleted file mode 100644 index 506b05812477..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-hapi/src/app.js +++ /dev/null @@ -1,122 +0,0 @@ -const Sentry = require('@sentry/node'); - -Sentry.init({ - environment: 'qa', // dynamic sampling bias to keep transactions - dsn: process.env.E2E_TEST_DSN, - includeLocalVariables: true, - debug: !!process.env.DEBUG, - tunnel: `http://localhost:3031/`, // proxy server - tracesSampleRate: 1, -}); - -const Hapi = require('@hapi/hapi'); -const Boom = require('@hapi/boom'); - -const server = Hapi.server({ - port: 3030, - host: 'localhost', -}); - -const init = async () => { - server.route({ - method: 'GET', - path: '/test-success', - handler: function (request, h) { - return { version: 'v1' }; - }, - }); - - server.route({ - method: 'GET', - path: '/test-param/{param}', - handler: function (request, h) { - Sentry.setAttribute(`param-${request.params.param}`, 'yes'); - - return { paramWas: request.params.param }; - }, - }); - - server.route({ - method: 'GET', - path: '/test-error', - handler: async function (request, h) { - const exceptionId = Sentry.captureException(new Error('This is an error')); - - await Sentry.flush(2000); - - return { exceptionId }; - }, - }); - - server.route({ - method: 'GET', - path: '/test-error/{id}', - handler: function (request) { - console.log('This is an error with id', request.params.id); - throw new Error(`This is an error with id ${request.params.id}`); - }, - }); - - server.route({ - method: 'GET', - path: '/test-failure', - handler: async function (request, h) { - throw new Error('This is an error'); - }, - }); - - server.route({ - method: 'GET', - path: '/test-failure-boom-4xx', - handler: async function (request, h) { - throw new Error('This is a JS error (boom in onPreResponse)'); - }, - }); - - server.route({ - method: 'GET', - path: '/test-failure-boom-5xx', - handler: async function (request, h) { - throw new Error('This is an error (boom in onPreResponse)'); - }, - }); - - server.route({ - method: 'GET', - path: '/test-failure-JS-error-onPreResponse', - handler: async function (request, h) { - throw new Error('This is an error (another JS error in onPreResponse)'); - }, - }); - - server.route({ - method: 'GET', - path: '/test-failure-2xx-override-onPreResponse', - handler: async function (request, h) { - throw new Error('This is a JS error (2xx override in onPreResponse)'); - }, - }); - - // This runs after the route handler - server.ext('onPreResponse', (request, h) => { - const path = request.route.path; - - if (path.includes('boom-4xx')) { - throw Boom.badRequest('4xx bad request (onPreResponse)'); - } else if (path.includes('boom-5xx')) { - throw Boom.gatewayTimeout('5xx not implemented (onPreResponse)'); - } else if (path.includes('JS-error-onPreResponse')) { - throw new Error('JS error (onPreResponse)'); - } else if (path.includes('2xx-override-onPreResponse')) { - return h.response('2xx override').code(200); - } else { - return h.continue; - } - }); -}; - -(async () => { - init(); - await server.start(); - console.log('Server running on %s', server.info.uri); -})(); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/ssr-error.vue b/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/ssr-error.vue new file mode 100644 index 000000000000..0016d2682d0b --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/app/pages/ssr-error.vue @@ -0,0 +1,10 @@ + + + diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts index a1e9672587d7..101861fe022f 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts @@ -1,5 +1,7 @@ +import { CACHE_HIT, URL_PATH } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; test.skip(isViteServer, NITRO_ONLY); @@ -18,6 +20,15 @@ test.describe('Cache Instrumentation', () => { return spans.filter(span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt'); } + /** Every span of the request's trace, whatever created it, so that a second span for one cache access shows up. */ + function collectRequestSpans() { + return collectStreamedSpansUntilSegment( + 'nuxt-4', + span => span.attributes[URL_PATH]?.value === '/api/cache-test', + span => getSpanOp(span) === CACHE_GET, + ); + } + test('instruments cachedFunction and cachedEventHandler calls and creates spans with correct attributes', async ({ request, }) => { @@ -151,4 +162,37 @@ test.describe('Cache Instrumentation', () => { // We should have at least one cache hit (second calls to getCachedUser and getCachedData) expect(cacheHitSpans.length).toBeGreaterThanOrEqual(1); }); + + test('creates exactly one span for each cache read and write', async ({ request }) => { + // Unique keys, so that the first call of each cached function is a cache miss. + const uniqueKey = `count-${Date.now()}`; + const spansPromise = collectRequestSpans(); + + await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`); + + const spans = await spansPromise; + const readSpans = spans.filter(span => getSpanOp(span) === CACHE_GET); + const writeSpans = spans.filter(span => getSpanOp(span) === CACHE_PUT); + const cacheMissSpans = readSpans.filter(span => span.attributes[CACHE_HIT]?.value === false); + + // 3x getCachedUser, 2x getCachedData, 1x cachedHandler. + expect(readSpans).toHaveLength(6); + // One write for each cache miss. An earlier test can have filled the cache of the handler, so the number of + // misses is not fixed. + expect(writeSpans).toHaveLength(cacheMissSpans.length); + }); + + test('makes each cache span a child of the request root span', async ({ request }) => { + const uniqueKey = `parent-${Date.now()}`; + const spansPromise = collectRequestSpans(); + + await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const cacheSpans = spans.filter(span => getSpanOp(span) === CACHE_GET || getSpanOp(span) === CACHE_PUT); + const parentSpanIds = new Set(cacheSpans.map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts index 7729f0e5251c..552ead3c7216 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts @@ -1,3 +1,5 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { DB_QUERY } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; @@ -12,15 +14,19 @@ const DB_ERROR_MECHANISM = ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 } : { handled: false, type: 'auto.db.nuxt' }; -async function collectDbSpans() { - const spans = await collectStreamedSpansUntilSegment( +function collectRequestSpans() { + return collectStreamedSpansUntilSegment( 'nuxt-4', - span => span.attributes['url.path']?.value === '/api/db-test', - span => getSpanOp(span) === 'db.query', + span => span.attributes[URL_PATH]?.value === '/api/db-test', + span => getSpanOp(span) === DB_QUERY, ); - const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test'); +} - return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === 'db.query'); +async function collectDbSpans() { + const spans = await collectRequestSpans(); + const rootSpan = spans.find(span => span.is_segment && span.attributes[URL_PATH]?.value === '/api/db-test'); + + return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === DB_QUERY); } test.describe('database integration', () => { @@ -210,4 +216,17 @@ test.describe('database integration', () => { expect(dbSpans.length).toBeGreaterThanOrEqual(1); expect(dbSpans.every(span => !span.is_segment)).toBe(true); }); + + test('makes each db.query span a child of the request root span', async ({ request }) => { + const spansPromise = collectRequestSpans(); + + await request.get('/api/db-test?method=prepare-get'); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const dbSpans = spans.filter(span => getSpanOp(span) === DB_QUERY); + const parentSpanIds = new Set(dbSpans.map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.server.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.server.test.ts index 69f290dffa6a..edf18f230aad 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.server.test.ts @@ -106,5 +106,23 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { }), ); }); + + test('filters a secret of the query string in the error event', async ({ request }) => { + const errorPromise = waitForError('nuxt-4', errorEvent => { + return ( + errorEvent?.exception?.values?.[0]?.value === 'Nuxt 4 Server error' && + errorEvent.request?.url?.includes(`${apiPrefix}/server-error`) === true && + errorEvent.request?.query_string?.startsWith('include=profile') === true + ); + }); + + await request.get(`${apiPrefix}/server-error?include=profile&auth=very-secret`); + + const error = await errorPromise; + + expect(error.transaction).toBe(`GET ${apiPrefix}/server-error`); + expect(error.contexts?.nuxt?.path).toBe(`${apiPrefix}/server-error?include=profile&auth=[Filtered]`); + expect(JSON.stringify(error)).not.toContain('very-secret'); + }); }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.ssr.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.ssr.streaming-lifecycle.test.ts new file mode 100644 index 000000000000..b30ebd221644 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/errors.ssr.streaming-lifecycle.test.ts @@ -0,0 +1,101 @@ +import { HTTP_RESPONSE_STATUS_CODE, URL_PATH } from '@sentry/conventions/attributes'; +import { expect, test } from '@playwright/test'; +import { waitForEnvelopeItem, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; +import { isViteServer, NITRO_ONLY } from './isViteServer'; + +type EnvelopeItem = Parameters[1]>[0]; +type SentryErrorEvent = Awaited>; + +const SSR_ERROR_PATH = '/ssr-error'; +const SSR_ERROR_MESSAGE = 'Nuxt 4 SSR error'; +// A page that every server API renders. The test requests it after the failing page, so its root span arrives +// after every event of the failing request. +const BARRIER_PATH = '/test-param/ssr-error-barrier'; + +function getErrorEvents([header, payload]: EnvelopeItem): SentryErrorEvent[] { + return header.type === 'event' ? [payload as SentryErrorEvent] : []; +} + +function getStreamedSpans([header, payload]: EnvelopeItem): SerializedStreamedSpan[] { + return header.type === 'span' ? (payload as { items: SerializedStreamedSpan[] }).items : []; +} + +function hasErrorMessage(errorEvent: SentryErrorEvent, message: string): boolean { + return !!errorEvent.exception?.values?.some(value => value.value?.startsWith(message)); +} + +function waitForRootSpan() { + return waitForStreamedSpan( + 'nuxt-4', + span => !!span.is_segment && span.attributes[URL_PATH]?.value === SSR_ERROR_PATH, + ); +} + +test.describe('page that fails during SSR', () => { + test('captures the error exactly once', async ({ request }) => { + test.fail(isViteServer, 'Known bug: the Vite server has no error hook, so the SDK captures no SSR error'); + + const requestId = `${Date.now()}`; + // One listener for events and spans, so it has every event that the proxy received before the barrier span. + const receivedErrors: SentryErrorEvent[] = []; + const barrierPromise = waitForEnvelopeItem('nuxt-4', envelopeItem => { + receivedErrors.push(...getErrorEvents(envelopeItem)); + return getStreamedSpans(envelopeItem).some( + span => span.is_segment && span.attributes[URL_PATH]?.value === BARRIER_PATH, + ); + }); + + await request.get(`${SSR_ERROR_PATH}?id=${requestId}`); + await request.get(BARRIER_PATH); + await barrierPromise; + + const errorsOfRequest = receivedErrors.filter(errorEvent => + hasErrorMessage(errorEvent, `${SSR_ERROR_MESSAGE} ${requestId}`), + ); + + expect(errorsOfRequest).toHaveLength(1); + }); + + test('reports the error through the Nitro error hook', async ({ request }) => { + test.skip(isViteServer, NITRO_ONLY); + + const errorPromise = waitForError('nuxt-4', errorEvent => hasErrorMessage(errorEvent, SSR_ERROR_MESSAGE)); + + await request.get(SSR_ERROR_PATH); + + const errorEvent = await errorPromise; + + expect(errorEvent.transaction).toBe(`GET ${SSR_ERROR_PATH}`); + expect(errorEvent.exception?.values?.map(value => value.mechanism)).toEqual([ + { handled: true, type: 'chained', exception_id: 1, parent_id: 0, source: 'cause' }, + { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 }, + ]); + }); + + test('marks the root span as errored', async ({ request }) => { + const rootSpanPromise = waitForRootSpan(); + + await request.get(SSR_ERROR_PATH); + + const rootSpan = await rootSpanPromise; + + expect(rootSpan.status).toBe('error'); + expect(rootSpan.attributes[HTTP_RESPONSE_STATUS_CODE]).toEqual({ type: 'integer', value: 500 }); + }); + + test('names the root span after the page route', async ({ request }) => { + test.fail( + true, + 'Known bug: the root span of a failed render gets no page route. On Nitro, it takes the name of the internal `/__nuxt_error` request. On the Vite server, the name is `GET`', + ); + + const rootSpanPromise = waitForRootSpan(); + + await request.get(SSR_ERROR_PATH); + + const rootSpan = await rootSpanPromise; + + expect(rootSpan.name).toBe(`GET ${SSR_ERROR_PATH}`); + }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts index d74f31e64e13..569ac8f06df7 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts @@ -1,3 +1,4 @@ +import { MIDDLEWARE as MIDDLEWARE_OP } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; @@ -346,3 +347,14 @@ test.describe('Server Middleware Instrumentation (#imports hooks)', () => { expect(onRequest0Span?.status).toBe('ok'); }); }); + +test('creates exactly one span for each server middleware handler of a request', async ({ request }) => { + const spansPromise = collectRequestSpans(); + + await request.get('/api/middleware-test'); + + // No filter on the middleware name, so a `middleware` span from any other source fails the count. + const middlewareSpans = (await spansPromise).filter(span => getSpanOp(span) === MIDDLEWARE_OP); + + expect(middlewareSpans).toHaveLength(MIDDLEWARE['#imports'].spanCount + MIDDLEWARE['nuxt/server'].spanCount); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts index 5f8ef9ccd540..71ce7d0c0fb9 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts @@ -1,5 +1,8 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; +import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; test.skip(isViteServer, NITRO_ONLY); @@ -17,6 +20,14 @@ async function collectStorageSpans(route: string) { ); } +const STORAGE_OPS: ReadonlyArray = [CACHE_GET, CACHE_PUT, CACHE_REMOVE]; +const isStorageSpan = (span: SerializedStreamedSpan) => STORAGE_OPS.includes(getSpanOp(span)); + +/** Every span of the request's trace, whatever created it, so that a second span for one storage call shows up. */ +function collectRequestSpans(route: string) { + return collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes[URL_PATH]?.value === route, isStorageSpan); +} + test.describe('Storage Instrumentation', () => { const prefixKey = (key: string) => `test-storage:${key}`; const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key'; @@ -158,4 +169,30 @@ test.describe('Storage Instrumentation', () => { expect(span.status).toBe('ok'); }); }); + + test('creates exactly one span for each storage driver call', async ({ request }) => { + const spansPromise = collectRequestSpans('/api/storage-test'); + + await request.get('/api/storage-test'); + + const spanOps = (await spansPromise).map(getSpanOp); + + // `/api/storage-test` writes 4 items, reads with hasItem, getItem, getItemRaw and 2x getKeys, and removes twice + // (removeItem, clear). Each `getKeys` call is 2 driver calls, because unstorage also asks the driver of the root mount. + expect(spanOps.filter(op => op === CACHE_PUT)).toHaveLength(4); + expect(spanOps.filter(op => op === CACHE_GET)).toHaveLength(7); + expect(spanOps.filter(op => op === CACHE_REMOVE)).toHaveLength(2); + }); + + test('makes each storage span a child of the request root span', async ({ request }) => { + const spansPromise = collectRequestSpans('/api/storage-test'); + + await request.get('/api/storage-test'); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const parentSpanIds = new Set(spans.filter(isStorageSpan).map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error.vue new file mode 100644 index 000000000000..0ef77c65255d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error.vue @@ -0,0 +1,10 @@ + + + diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts index e5163a76f359..a76a6e25d1a9 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts @@ -1,5 +1,7 @@ +import { CACHE_HIT, URL_PATH } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; // Nitro v3 only routes cached functions and handlers through KV storage with the `kv` cache driver, // so the default (`memory`) driver is traced through ocache's storage instead. @@ -27,6 +29,15 @@ test.describe('Cache Instrumentation', () => { ); } + /** Every span of the request's trace, whatever created it, so that a second span for one cache access shows up. */ + function collectRequestSpans() { + return collectStreamedSpansUntilSegment( + 'nuxt-5', + span => span.attributes[URL_PATH]?.value === '/api/cache-test', + span => getSpanOp(span) === CACHE_GET, + ); + } + test('instruments cachedFunction and cachedEventHandler calls and creates spans with correct attributes', async ({ request, }) => { @@ -160,4 +171,37 @@ test.describe('Cache Instrumentation', () => { // We should have at least one cache hit (second calls to getCachedUser and getCachedData) expect(cacheHitSpans.length).toBeGreaterThanOrEqual(1); }); + + test('creates exactly one span for each cache read and write', async ({ request }) => { + // Unique keys, so that the first call of each cached function is a cache miss. + const uniqueKey = `count-${Date.now()}`; + const spansPromise = collectRequestSpans(); + + await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`); + + const spans = await spansPromise; + const readSpans = spans.filter(span => getSpanOp(span) === CACHE_GET); + const writeSpans = spans.filter(span => getSpanOp(span) === CACHE_PUT); + const cacheMissSpans = readSpans.filter(span => span.attributes[CACHE_HIT]?.value === false); + + // 3x getCachedUser, 2x getCachedData, 1x cachedHandler. + expect(readSpans).toHaveLength(6); + // One write for each cache miss. An earlier test can have filled the cache of the handler, so the number of + // misses is not fixed. + expect(writeSpans).toHaveLength(cacheMissSpans.length); + }); + + test('makes each cache span a child of the request root span', async ({ request }) => { + const uniqueKey = `parent-${Date.now()}`; + const spansPromise = collectRequestSpans(); + + await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const cacheSpans = spans.filter(span => getSpanOp(span) === CACHE_GET || getSpanOp(span) === CACHE_PUT); + const parentSpanIds = new Set(cacheSpans.map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts index 184eac58bb50..7a15343131d8 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts @@ -1,3 +1,5 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { DB_QUERY } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime'; @@ -9,15 +11,19 @@ const DB_ERROR_MECHANISM = ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 } : { handled: false, type: 'auto.db.nuxt' }; -async function collectDbSpans() { - const spans = await collectStreamedSpansUntilSegment( +function collectRequestSpans() { + return collectStreamedSpansUntilSegment( 'nuxt-5', - span => span.attributes['url.path']?.value === '/api/db-test', - span => getSpanOp(span) === 'db.query', + span => span.attributes[URL_PATH]?.value === '/api/db-test', + span => getSpanOp(span) === DB_QUERY, ); - const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test'); +} - return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === 'db.query'); +async function collectDbSpans() { + const spans = await collectRequestSpans(); + const rootSpan = spans.find(span => span.is_segment && span.attributes[URL_PATH]?.value === '/api/db-test'); + + return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === DB_QUERY); } test.describe('database integration', () => { @@ -207,4 +213,17 @@ test.describe('database integration', () => { expect(dbSpans.length).toBeGreaterThanOrEqual(1); expect(dbSpans.every(span => !span.is_segment)).toBe(true); }); + + test('makes each db.query span a child of the request root span', async ({ request }) => { + const spansPromise = collectRequestSpans(); + + await request.get('/api/db-test?method=prepare-get'); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const dbSpans = spans.filter(span => getSpanOp(span) === DB_QUERY); + const parentSpanIds = new Set(dbSpans.map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.ssr.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.ssr.test.ts new file mode 100644 index 000000000000..8b3e573b116a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.ssr.test.ts @@ -0,0 +1,93 @@ +import { HTTP_RESPONSE_STATUS_CODE, URL_PATH } from '@sentry/conventions/attributes'; +import { expect, test } from '@playwright/test'; +import { waitForEnvelopeItem, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; + +type EnvelopeItem = Parameters[1]>[0]; +type SentryErrorEvent = Awaited>; + +const SSR_ERROR_PATH = '/ssr-error'; +const SSR_ERROR_MESSAGE = 'Nuxt 5 SSR error'; +// The test requests this page after the failing page, so its root span arrives after every event of the failing +// request. +const BARRIER_PATH = '/test-param/ssr-error-barrier'; + +function getErrorEvents([header, payload]: EnvelopeItem): SentryErrorEvent[] { + return header.type === 'event' ? [payload as SentryErrorEvent] : []; +} + +function getStreamedSpans([header, payload]: EnvelopeItem): SerializedStreamedSpan[] { + return header.type === 'span' ? (payload as { items: SerializedStreamedSpan[] }).items : []; +} + +function hasErrorMessage(errorEvent: SentryErrorEvent, message: string): boolean { + return !!errorEvent.exception?.values?.some(value => value.value?.startsWith(message)); +} + +function waitForRootSpan() { + return waitForStreamedSpan( + 'nuxt-5', + span => !!span.is_segment && span.attributes[URL_PATH]?.value === SSR_ERROR_PATH, + ); +} + +test.describe('page that fails during SSR', () => { + test('captures the error exactly once', async ({ request }) => { + const requestId = `${Date.now()}`; + // One listener for events and spans, so it has every event that the proxy received before the barrier span. + const receivedErrors: SentryErrorEvent[] = []; + const barrierPromise = waitForEnvelopeItem('nuxt-5', envelopeItem => { + receivedErrors.push(...getErrorEvents(envelopeItem)); + return getStreamedSpans(envelopeItem).some( + span => span.is_segment && span.attributes[URL_PATH]?.value === BARRIER_PATH, + ); + }); + + await request.get(`${SSR_ERROR_PATH}?id=${requestId}`); + await request.get(BARRIER_PATH); + await barrierPromise; + + const errorsOfRequest = receivedErrors.filter(errorEvent => + hasErrorMessage(errorEvent, `${SSR_ERROR_MESSAGE} ${requestId}`), + ); + + expect(errorsOfRequest).toHaveLength(1); + }); + + test('reports the error through the Nitro error hook', async ({ request }) => { + const errorPromise = waitForError('nuxt-5', errorEvent => hasErrorMessage(errorEvent, SSR_ERROR_MESSAGE)); + + await request.get(SSR_ERROR_PATH); + + const errorEvent = await errorPromise; + + expect(errorEvent.transaction).toBe(`GET ${SSR_ERROR_PATH}`); + expect(errorEvent.exception?.values?.map(value => value.mechanism)).toEqual([ + { handled: true, type: 'chained', exception_id: 1, parent_id: 0, source: 'cause' }, + { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 }, + ]); + }); + + test('marks the root span as errored', async ({ request }) => { + const rootSpanPromise = waitForRootSpan(); + + await request.get(SSR_ERROR_PATH); + + const rootSpan = await rootSpanPromise; + + expect(rootSpan.status).toBe('error'); + expect(rootSpan.attributes[HTTP_RESPONSE_STATUS_CODE]).toEqual({ type: 'integer', value: 500 }); + }); + + test('names the root span after the page route', async ({ request }) => { + test.fail(true, 'Known bug: the root span of a failed render gets no page route, so its name is `GET`'); + + const rootSpanPromise = waitForRootSpan(); + + await request.get(SSR_ERROR_PATH); + + const rootSpan = await rootSpanPromise; + + expect(rootSpan.name).toBe(`GET ${SSR_ERROR_PATH}`); + }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts index 3d1c14c1cb64..ebc2475faf89 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts @@ -1,3 +1,4 @@ +import { MIDDLEWARE as MIDDLEWARE_OP } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; @@ -201,3 +202,14 @@ test.describe('Server Middleware Instrumentation (nitro hooks)', () => { expect(errorEvent.exception?.values?.[0]?.value).toBe('OnRequest[1] hook error'); }); }); + +test('creates exactly one span for each server middleware handler of a request', async ({ request }) => { + const spansPromise = collectRequestSpans(); + + await request.get('/api/middleware-test'); + + // No filter on the middleware name, so a `middleware` span from any other source fails the count. + const middlewareSpans = (await spansPromise).filter(span => getSpanOp(span) === MIDDLEWARE_OP); + + expect(middlewareSpans).toHaveLength(MIDDLEWARE.nitro.spanCount + MIDDLEWARE['nuxt/server'].spanCount); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts index ab3b3f63456c..ad7eeb030eb5 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts @@ -1,5 +1,8 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; +import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; async function collectStorageSpans(route: string) { const spans = await collectStreamedSpansUntilSegment( @@ -14,6 +17,14 @@ async function collectStorageSpans(route: string) { ); } +const STORAGE_OPS: ReadonlyArray = [CACHE_GET, CACHE_PUT, CACHE_REMOVE]; +const isStorageSpan = (span: SerializedStreamedSpan) => STORAGE_OPS.includes(getSpanOp(span)); + +/** Every span of the request's trace, whatever created it, so that a second span for one storage call shows up. */ +function collectRequestSpans(route: string) { + return collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes[URL_PATH]?.value === route, isStorageSpan); +} + test.describe('Storage Instrumentation', () => { const prefixKey = (key: string) => `test-storage:${key}`; const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key'; @@ -155,4 +166,30 @@ test.describe('Storage Instrumentation', () => { expect(span.status).toBe('ok'); }); }); + + test('creates exactly one span for each storage driver call', async ({ request }) => { + const spansPromise = collectRequestSpans('/api/storage-test'); + + await request.get('/api/storage-test'); + + const spanOps = (await spansPromise).map(getSpanOp); + + // `/api/storage-test` writes 4 items, reads with hasItem, getItem, getItemRaw and 2x getKeys, and removes twice + // (removeItem, clear). Each `getKeys` call is 2 driver calls, because unstorage also asks the driver of the root mount. + expect(spanOps.filter(op => op === CACHE_PUT)).toHaveLength(4); + expect(spanOps.filter(op => op === CACHE_GET)).toHaveLength(7); + expect(spanOps.filter(op => op === CACHE_REMOVE)).toHaveLength(2); + }); + + test('makes each storage span a child of the request root span', async ({ request }) => { + const spansPromise = collectRequestSpans('/api/storage-test'); + + await request.get('/api/storage-test'); + + const spans = await spansPromise; + const rootSpan = spans.find(span => span.is_segment); + const parentSpanIds = new Set(spans.filter(isStorageSpan).map(span => span.parent_span_id)); + + expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id])); + }); }); diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json index 76a006213b41..836ca4036d89 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json @@ -9,6 +9,7 @@ "start": "PORT=3030 node dist/server/node.js", "start:cloudflare": "wrangler dev --config ./dist/server/wrangler.json --port 3030", "test:prod": "TEST_ENV=production playwright test", + "test:observe": "SOLID_OBSERVE=1 TEST_ENV=production playwright test", "test:build": "pnpm install && pnpm build", "test:build:observe": "pnpm install && pnpm build:observe", "test:assert": "pnpm test:prod" @@ -39,20 +40,18 @@ "variants": [ { "build-command": "pnpm test:build:observe", - "assert-command": "pnpm test:prod", + "assert-command": "pnpm test:observe", "label": "solid-2-ssr (observe build)" + }, + { + "runtime": "cloudflare", + "label": "solid-2-ssr (cloudflare)" } ], "baseVariant": { "build-command": "pnpm test:build", "assert-command": "pnpm test:prod", "label": "solid-2-ssr (production)" - }, - "optionalVariants": [ - { - "runtime": "cloudflare", - "label": "solid-2-ssr (cloudflare)" - } - ] + } } } diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/observe.server.test.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/observe.server.test.ts new file mode 100644 index 000000000000..77c7c56daa2c --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/observe.server.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from '@playwright/test'; +import { CODE_FUNCTION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; + +test('adds a span for a server function execution on observe builds', async ({ page }) => { + test.skip(process.env.SOLID_OBSERVE !== '1', 'Only observe builds record server function executions'); + + const functionSpanPromise = waitForStreamedSpan('solid-2-ssr', span => { + return ( + getSpanOp(span) === FUNCTION && span.attributes?.[SENTRY_ORIGIN]?.value === 'auto.function.solid.server_function' + ); + }); + // The server function's request span, found by its method within the trace of the function span. + const serverSpanPromise = functionSpanPromise.then(functionSpan => + waitForStreamedSpan( + 'solid-2-ssr', + span => + getSpanOp(span) === HTTP_SERVER && + span.is_segment && + span.trace_id === functionSpan.trace_id && + span.name.startsWith('POST'), + 0, + ), + ); + + await page.goto('/'); + await page.locator('#serverFunctionErrorBtn').click(); + + const [functionSpan, serverSpan] = await Promise.all([functionSpanPromise, serverSpanPromise]); + + expect(functionSpan.status).toBe('error'); + expect(functionSpan.attributes?.[CODE_FUNCTION_NAME]?.value).toEqual(expect.any(String)); + expect(functionSpan.name).toBe(functionSpan.attributes?.[CODE_FUNCTION_NAME]?.value); + expect(functionSpan.parent_span_id).toBe(serverSpan.span_id); +}); diff --git a/dev-packages/optional-e2e-gh-action/action.yml b/dev-packages/optional-e2e-gh-action/action.yml index 54edd85f97df..a793865e9ce2 100644 --- a/dev-packages/optional-e2e-gh-action/action.yml +++ b/dev-packages/optional-e2e-gh-action/action.yml @@ -11,7 +11,7 @@ inputs: description: '`dispatch` to run the tests and wait for them, `report` to report the current run in a PR comment' commit: required: false - description: 'The commit that the tarballs were built from (dispatch mode)' + description: 'The commit to build and test (dispatch mode)' matrix: required: false description: 'The optional E2E test matrix as JSON (dispatch mode)' diff --git a/dev-packages/optional-e2e-gh-action/index.mjs b/dev-packages/optional-e2e-gh-action/index.mjs index a67c689c16f4..e51612c193b2 100644 --- a/dev-packages/optional-e2e-gh-action/index.mjs +++ b/dev-packages/optional-e2e-gh-action/index.mjs @@ -35,7 +35,6 @@ async function run() { ref: process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME, inputs: { commit: core.getInput('commit'), - build_run_id: String(context.runId), matrix: core.getInput('matrix'), pr_number: pr ? String(pr.number) : '', correlation_id: correlationId, diff --git a/packages/astro/src/integration/index.ts b/packages/astro/src/integration/index.ts index 19c38019cb68..839bf661b36f 100644 --- a/packages/astro/src/integration/index.ts +++ b/packages/astro/src/integration/index.ts @@ -80,15 +80,11 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { sourceMapState.sdkEnabled && !hasEnvironmentSourceMapSetting(config, environment); // A user's own glob replaces the SDK's deletion. Maps in a Cloudflare `_worker.js` folder // stay, so that wrangler can read them for `upload_source_maps`. - // With `sourcemaps.delete` the bundler plugin ignores this option and warns if the user set it. - const deleteSourcemapsAfterUpload = - sourcemaps?.delete !== undefined - ? sourcemaps.deleteSourcemapsAfterUpload - : (sourcemaps?.deleteSourcemapsAfterUpload ?? - (sourcemaps?.filesToDeleteAfterUpload === undefined - ? (environment?: string) => - sdkEnabledSourceMaps(environment) && !buildState.writesCloudflareWorker ? true : undefined - : undefined)); + const sdkDeleteSourceMaps = + sourcemaps?.delete === undefined && sourcemaps?.filesToDeleteAfterUpload === undefined + ? (environment?: string) => + sdkEnabledSourceMaps(environment) && !buildState.writesCloudflareWorker ? true : undefined + : undefined; const sentryPlugins = sentryVitePlugin({ applicationKey, @@ -112,8 +108,7 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { sourcemaps: { ...sourcemaps, assets: sourcemaps?.assets ?? getSourcemapsAssetsGlobs(config), - deleteSourcemapsAfterUpload, - sdkEnabledSourceMaps, + sdkDeleteSourceMaps, }, bundleSizeOptimizations: { ...bundleSizeOptimizations, diff --git a/packages/astro/test/integration/index.test.ts b/packages/astro/test/integration/index.test.ts index c918b3905ade..0a8cf62111b9 100644 --- a/packages/astro/test/integration/index.test.ts +++ b/packages/astro/test/integration/index.test.ts @@ -5,8 +5,8 @@ import { _getUpdatedSourceMapSettings, sentryAstro } from '../../src/integration import type { SentryOptions } from '../../src/integration/types'; type CapturedSourcemapsOptions = { - deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); - sdkEnabledSourceMaps?: (environment?: string) => boolean; + deleteSourcemapsAfterUpload?: boolean; + sdkDeleteSourceMaps?: (environment?: string) => boolean | undefined; }; let capturedSourcemapsOptions: CapturedSourcemapsOptions | undefined; @@ -137,8 +137,7 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['out/**/*', 'out/**/.prerender/**/*'], - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + sdkDeleteSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -169,8 +168,7 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['dist/**/*', 'dist/**/.prerender/**/*'], - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + sdkDeleteSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -209,8 +207,7 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['{.vercel,dist}/**/*', '{.vercel,dist}/**/.prerender/**/*'], - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + sdkDeleteSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -249,8 +246,7 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['dist/server/**/*, dist/client/**/*'], - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + sdkDeleteSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -283,7 +279,7 @@ describe('sentryAstro integration', () => { expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: ['./custom/path/**/*'], - deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: undefined, }), }), ); @@ -301,15 +297,15 @@ describe('sentryAstro integration', () => { }); } - function expectSourcemapsOptions({ sdkEnabledSourceMaps, ...sourcemaps }: Record): void { + function expectSourcemapsOptions({ sdkDeleteSourceMaps, ...sourcemaps }: Record): void { expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); expect(sentryVitePluginSpy).toHaveBeenCalledWith( expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }), ); - expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.()).toBe(sdkEnabledSourceMaps); + expect(capturedSourcemapsOptions?.sdkDeleteSourceMaps?.()).toBe(sdkDeleteSourceMaps); } - // The bundler plugin calls the function form in its `config` hook, after the build state + // The bundler plugin calls `sdkDeleteSourceMaps` in its `config` hook, after the build state // plugin ran. function runBuildStatePlugin(viteConfig: { build?: { outDir?: string } }): void { const plugin = updateConfig.mock.calls @@ -318,10 +314,11 @@ describe('sentryAstro integration', () => { plugin.config(viteConfig); } + // Like the bundler plugin, the user's `deleteSourcemapsAfterUpload` wins over the SDK's value. function expectDeleteOption(value: boolean | undefined): void { expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); - const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; - expect(typeof option === 'function' ? option() : option).toBe(value); + const { deleteSourcemapsAfterUpload, sdkDeleteSourceMaps } = capturedSourcemapsOptions ?? {}; + expect(deleteSourcemapsAfterUpload ?? sdkDeleteSourceMaps?.()).toBe(value); } it('is `true` when the SDK enabled the source maps', async () => { @@ -343,10 +340,11 @@ describe('sentryAstro integration', () => { }, ); - it('lets a user-set `true` remove the maps of a Cloudflare `_worker.js` build', async () => { + it('passes a user-set `true` through, but asks for no SDK deletion of a Cloudflare `_worker.js` build', async () => { await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: true } }); runBuildStatePlugin({ build: { outDir: 'dist/_worker.js/' } }); - expectDeleteOption(true); + expect(capturedSourcemapsOptions?.deleteSourcemapsAfterUpload).toBe(true); + expect(capturedSourcemapsOptions?.sdkDeleteSourceMaps?.()).toBeUndefined(); }); it.each(['hidden', true] as const)('is not set when the user set `vite.build.sourcemap: %s`', async sourcemap => { @@ -369,23 +367,23 @@ describe('sentryAstro integration', () => { expectDeleteOption(undefined); }); - it('lets a user-set `true` win over the user glob', async () => { + it('passes a user-set `true` through, but asks for no SDK deletion with a user glob', async () => { await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: true, filesToDeleteAfterUpload: ['./dist/**/*.map'] }, }); - expectDeleteOption(true); + expectSourcemapsOptions({ deleteSourcemapsAfterUpload: true, sdkDeleteSourceMaps: undefined }); + expect(capturedSourcemapsOptions?.sdkDeleteSourceMaps).toBeUndefined(); }); // Then the plugin removes all of these maps, also those of chunks outside the user's // `assets` or `ignore`. - it('marks the source maps as SDK-enabled when the user narrowed the upload', async () => { + it('asks for SDK deletion when the user narrowed the upload', async () => { await runSetup({ sourcemaps: { assets: ['./dist/client/**/*'], ignore: ['**/vendor/**'] } }); expectSourcemapsOptions({ assets: ['./dist/client/**/*'], ignore: ['**/vendor/**'], - sdkEnabledSourceMaps: true, + sdkDeleteSourceMaps: true, }); - expectDeleteOption(true); }); // The output setting overrides `vite.build.sourcemap`, so these maps are the user's. @@ -396,44 +394,37 @@ describe('sentryAstro integration', () => { ] as const)('leaves the source maps to the user with the output options %j', async build => { await runSetup({}, { vite: { build } } as Partial); expectViteSourceMapSetting(undefined); - expectSourcemapsOptions({ sdkEnabledSourceMaps: false }); - expectDeleteOption(undefined); + expectSourcemapsOptions({ sdkDeleteSourceMaps: undefined }); }); // Astro copies the top-level setting into the `client` environment. - it('marks the source maps of the `client` environment as SDK-enabled', async () => { + it('asks for SDK deletion of the `client` environment', async () => { await runSetup({}); runBuildStatePlugin({ build: { outDir: 'dist/' } }); - expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(true); - const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; - expect(typeof option === 'function' ? option('client') : option).toBe(true); + expect(capturedSourcemapsOptions?.sdkDeleteSourceMaps?.('client')).toBe(true); }); - it('does not mark the source maps of an environment the user set as SDK-enabled', async () => { + it('asks for no SDK deletion of an environment the user set', async () => { await runSetup({}, { vite: { environments: { client: { build: { sourcemap: true } } } }, } as Partial); runBuildStatePlugin({ build: { outDir: 'dist/' } }); - expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(false); - const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; - expect(typeof option === 'function' ? option('client') : option).toBeUndefined(); - expectSourcemapsOptions({ sdkEnabledSourceMaps: true }); - expectDeleteOption(true); + expect(capturedSourcemapsOptions?.sdkDeleteSourceMaps?.('client')).toBeUndefined(); + expectSourcemapsOptions({ sdkDeleteSourceMaps: true }); }); it.each(['hidden', true, false] as const)( - 'does not mark source maps as SDK-enabled when the user set `vite.build.sourcemap: %s`', + 'asks for no SDK deletion when the user set `vite.build.sourcemap: %s`', async sourcemap => { await runSetup({}, { vite: { build: { sourcemap } } }); - expectSourcemapsOptions({ sdkEnabledSourceMaps: false }); + expectSourcemapsOptions({ sdkDeleteSourceMaps: undefined }); }, ); // The maps are removed in this mode too, after the plugin stamps the debug IDs. it("is `true` with `disable: 'disable-upload'`", async () => { await runSetup({ sourcemaps: { disable: 'disable-upload' } }); - expectSourcemapsOptions({ disable: 'disable-upload', sdkEnabledSourceMaps: true }); - expectDeleteOption(true); + expectSourcemapsOptions({ disable: 'disable-upload', sdkDeleteSourceMaps: true }); }); function expectViteSourceMapSetting(sourcemap: 'hidden' | undefined): void { @@ -449,8 +440,7 @@ describe('sentryAstro integration', () => { 'adds the plugin, turns no source maps on and asks for no deletion with %j', async sourcemaps => { await runSetup({ sourcemaps }); - expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: false }); - expectDeleteOption(undefined); + expectSourcemapsOptions({ ...sourcemaps, sdkDeleteSourceMaps: undefined }); expectViteSourceMapSetting(undefined); }, ); @@ -466,15 +456,14 @@ describe('sentryAstro integration', () => { [{ delete: false, deleteSourcemapsAfterUpload: true }, 'hidden', true], ] as const)('with %j it sets the source map setting to %s', async (sourcemaps, setting, deleteAfterUpload) => { await runSetup({ sourcemaps }); - expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: setting === 'hidden' }); + expectSourcemapsOptions({ ...sourcemaps, sdkDeleteSourceMaps: undefined }); expect(capturedSourcemapsOptions?.deleteSourcemapsAfterUpload).toBe(deleteAfterUpload); expectViteSourceMapSetting(setting); }); it('enables hidden source maps when `upload: true` replaces `disable: true`', async () => { await runSetup({ sourcemaps: { disable: true, upload: true } }); - expectSourcemapsOptions({ sdkEnabledSourceMaps: true }); - expectDeleteOption(true); + expectSourcemapsOptions({ sdkDeleteSourceMaps: true }); expectViteSourceMapSetting('hidden'); }); }); diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts index 5aec05052595..986079080c52 100644 --- a/packages/bundler-plugins/src/core/index.ts +++ b/packages/bundler-plugins/src/core/index.ts @@ -116,8 +116,7 @@ export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId export { decideSourceMapHandling, getDeleteOption, - getDeleteSourcemapsAfterUpload, - getSdkEnabledSourceMaps, + getSdkDeleteSourceMaps, getSourceMapFeatures, } from './sourcemap-settings'; export type { SourceMapDecision, SourceMapKind } from './sourcemap-settings'; diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index 29bf9bec22a6..1c1cad657957 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -34,8 +34,8 @@ export type NormalizedOptions = { rewriteSources?: RewriteSourcesHook; resolveSourceMap?: ResolveSourceMapHook; filesToDeleteAfterUpload?: string | string[] | Promise; - deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); - sdkEnabledSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + deleteSourcemapsAfterUpload?: boolean; + sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); } | undefined; release: { diff --git a/packages/bundler-plugins/src/core/sentry/telemetry.ts b/packages/bundler-plugins/src/core/sentry/telemetry.ts index ca8ed0037704..14e576f9ea1c 100644 --- a/packages/bundler-plugins/src/core/sentry/telemetry.ts +++ b/packages/bundler-plugins/src/core/sentry/telemetry.ts @@ -108,11 +108,7 @@ export function setTelemetryDataOnScope( scope.setTag('delete-after-upload', !!sourcemaps?.filesToDeleteAfterUpload); scope.setTag( 'delete-sourcemaps-after-upload', - typeof sourcemaps?.deleteSourcemapsAfterUpload === 'function' - ? 'function' - : sourcemaps?.deleteSourcemapsAfterUpload === undefined - ? 'auto' - : String(sourcemaps.deleteSourcemapsAfterUpload), + sourcemaps?.deleteSourcemapsAfterUpload === undefined ? 'auto' : String(sourcemaps.deleteSourcemapsAfterUpload), ); scope.setTag('sourcemaps-disabled', !!sourcemaps?.disable); scope.setTag('sourcemaps-upload', sourcemaps?.upload === undefined ? 'auto' : String(sourcemaps.upload)); diff --git a/packages/bundler-plugins/src/core/sourcemap-settings.ts b/packages/bundler-plugins/src/core/sourcemap-settings.ts index 1fb98809ce7b..0dc75c3f1008 100644 --- a/packages/bundler-plugins/src/core/sourcemap-settings.ts +++ b/packages/bundler-plugins/src/core/sourcemap-settings.ts @@ -58,27 +58,29 @@ export function getSourceMapFeatures(options: NormalizedOptions): SourceMapFeatu return { injectDebugIds, upload, stampEmittedFiles: injectDebugIds && !upload }; } -/** Reads `sourcemaps.deleteSourcemapsAfterUpload`, calling the internal function form if given. */ -export function getDeleteSourcemapsAfterUpload(options: NormalizedOptions, environment?: string): boolean | undefined { - const value = options.sourcemaps?.deleteSourcemapsAfterUpload; +/** Reads the internal `sourcemaps.sdkDeleteSourceMaps` option, calling its function form if given. */ +export function getSdkDeleteSourceMaps(options: NormalizedOptions, environment?: string): boolean | undefined { + const value = options.sourcemaps?.sdkDeleteSourceMaps; return typeof value === 'function' ? value(environment) : value; } -/** Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides. */ +/** + * Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides, and + * then the SDK. + */ export function getDeleteOption(options: NormalizedOptions, environment?: string): boolean | undefined { - return options.sourcemaps?.delete ?? getDeleteSourcemapsAfterUpload(options, environment); -} - -/** Reads the internal `sourcemaps.sdkEnabledSourceMaps` option, calling its function form if given. */ -export function getSdkEnabledSourceMaps(options: NormalizedOptions, environment?: string): boolean { - const value = options.sourcemaps?.sdkEnabledSourceMaps; - return (typeof value === 'function' ? value(environment) : value) === true; + return ( + options.sourcemaps?.delete ?? + options.sourcemaps?.deleteSourcemapsAfterUpload ?? + getSdkDeleteSourceMaps(options, environment) + ); } /** * Decides whether the plugin turns hidden source maps on and whether it removes the maps from the * build output after the upload. The plugin only turns maps on when an upload can run, and only - * removes maps it turned on itself unless `deleteSourcemapsAfterUpload` says otherwise. + * removes maps it turned on itself unless `deleteSourcemapsAfterUpload` or the SDK's + * `sdkDeleteSourceMaps` says otherwise. The user's `deleteSourcemapsAfterUpload` wins over the SDK. */ export function decideSourceMapHandling( kind: SourceMapKind, @@ -92,16 +94,19 @@ export function decideSourceMapHandling( return decideWithDeleteOption(kind, options.sourcemaps.delete, features, uploadPossible); } - const deleteOption = getDeleteSourcemapsAfterUpload(options, environment); - const sdkEnabledSourceMaps = getSdkEnabledSourceMaps(options, environment); + const userDeleteOption = options.sourcemaps?.deleteSourcemapsAfterUpload; + const sdkDeleteOption = getSdkDeleteSourceMaps(options, environment); + const deleteOption = userDeleteOption ?? sdkDeleteOption; + const sdkRemovesAll = sdkDeleteOption === true; + const fromUser = userDeleteOption !== undefined; if (!uploadPossible || !features.upload) { if (deleteOption !== true || (kind !== 'hidden' && kind !== 'visible')) { return NO_CHANGE; } - // Users switch the upload off to upload the maps themselves. Maps the - // SDK turned on are still removed, as the SDKs' own globs did. - if (!features.upload && !sdkEnabledSourceMaps) { + // Users switch the upload off to upload the maps themselves. The SDK's + // deletion still runs, as the SDKs' own globs did. + if (!features.upload && !sdkRemovesAll) { return { ...NO_CHANGE, log: { @@ -117,12 +122,17 @@ export function decideSourceMapHandling( return { enableHidden: kind === 'visible', deleteAfterUpload: true, - removeAllSourceMaps: sdkEnabledSourceMaps, - log: { - level: 'warn', - message: - 'Source maps are not uploaded, but they are removed from the build output because `sourcemaps.deleteSourcemapsAfterUpload` is set.', - }, + removeAllSourceMaps: sdkRemovesAll, + log: fromUser + ? { + level: 'warn', + message: + 'Source maps are not uploaded, but they are removed from the build output because `sourcemaps.deleteSourcemapsAfterUpload` is set.', + } + : { + level: 'info', + message: 'Source maps are not uploaded, but the Sentry SDK removes them from the build output.', + }, }; } @@ -164,7 +174,7 @@ export function decideSourceMapHandling( level: 'info', message: 'Enabling hidden source maps. They are uploaded to Sentry and removed from the build output. ' + - 'Set `sourcemaps.deleteSourcemapsAfterUpload: false` to keep them.', + 'Set `sourcemaps.delete: false` to keep them.', }, }; @@ -172,7 +182,7 @@ export function decideSourceMapHandling( if (deleteOption !== true) { return NO_CHANGE; } - return { enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: sdkEnabledSourceMaps }; + return { enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: sdkRemovesAll }; case 'visible': if (deleteOption !== true) { @@ -181,12 +191,14 @@ export function decideSourceMapHandling( return { enableHidden: true, deleteAfterUpload: true, - removeAllSourceMaps: sdkEnabledSourceMaps, + removeAllSourceMaps: sdkRemovesAll, log: { level: 'info', - message: - 'Switching to hidden source maps because `sourcemaps.deleteSourcemapsAfterUpload` is set. ' + - 'Without the `sourceMappingURL` comment browsers do not request the removed map files.', + message: fromUser + ? 'Switching to hidden source maps because `sourcemaps.deleteSourcemapsAfterUpload` is set. ' + + 'Without the `sourceMappingURL` comment browsers do not request the removed map files.' + : 'Switching to hidden source maps, because the Sentry SDK removes them from the build output. ' + + 'Without the `sourceMappingURL` comment browsers do not request the removed map files.', }, }; } diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index 1faf8a842488..c6854ea7e29e 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -736,20 +736,23 @@ export type HandleRecoverableErrorFn = (error: unknown, throwByDefault: boolean) /** * @internal For Sentry SDK packages only. It can change in any release. * - * Like `Options`, but `sourcemaps.deleteSourcemapsAfterUpload` can also be a function, and - * `sourcemaps.sdkEnabledSourceMaps` is added. The plugin calls the functions when it decides how - * to treat the bundler's source map setting, so an SDK can give a value that it only knows after it - * created the plugin. Vite passes the name of an environment with its own `build.sourcemap`, and - * `undefined` for the top-level `build.sourcemap`. + * Like `Options`, but with the SDK's own source map deletion decision in + * `sourcemaps.sdkDeleteSourceMaps`. The plugin calls its function form when it decides how to treat + * the bundler's source map setting, so an SDK can give a value that it only knows after it created + * the plugin. Vite passes the name of an environment with its own `build.sourcemap`, and `undefined` + * for the top-level `build.sourcemap`. */ export type InternalOptions = Omit & { - sourcemaps?: Omit, 'deleteSourcemapsAfterUpload'> & { - deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); + sourcemaps?: NonNullable & { /** - * The SDK turned on the bundler's source maps. With `deleteSourcemapsAfterUpload: true` the - * plugin then removes them like source maps it turned on itself: all of them, also those of CSS - * and of chunks that the upload leaves out. + * - `true`: the SDK turned the source maps on, so the plugin removes every source map, also those of + * CSS and of chunks that the upload leaves out. + * - `false`: the plugin keeps the source maps. + * - `undefined`: the plugin's own rules apply. + * + * The user's `sourcemaps.delete` replaces it. The user's `sourcemaps.deleteSourcemapsAfterUpload` + * decides whether source maps are removed, and `true` here still makes that all of them. */ - sdkEnabledSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined); }; }; diff --git a/packages/bundler-plugins/src/vite/source-map-hooks.ts b/packages/bundler-plugins/src/vite/source-map-hooks.ts index 7764439a465e..9e88ce2f27fd 100644 --- a/packages/bundler-plugins/src/vite/source-map-hooks.ts +++ b/packages/bundler-plugins/src/vite/source-map-hooks.ts @@ -1,6 +1,6 @@ import * as path from 'node:path'; import type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind } from '../core'; -import { getDeleteOption, getSdkEnabledSourceMaps } from '../core'; +import { getDeleteOption, getSdkDeleteSourceMaps } from '../core'; import type { OutputMatch, RollupSourceMapSetting, SourceMapHandling } from '../rollup/source-map-handling'; import { getOutputMatch, sourceMapKindFromRollupSetting } from '../rollup/source-map-handling'; @@ -122,7 +122,8 @@ export function createViteSourceMapHooks( const deleteOption = getDeleteOption(normalizedOptions, environmentName); // `sourcemaps.delete: true` removes every source map, like for maps the SDK turned on. const removeAll = - normalizedOptions.sourcemaps?.delete === true || getSdkEnabledSourceMaps(normalizedOptions, environmentName); + normalizedOptions.sourcemaps?.delete === true || + getSdkDeleteSourceMaps(normalizedOptions, environmentName) === true; for (const output of getOutputs(config.root, environment.build)) { // Hidden maps of an output's own setting are removed when the user diff --git a/packages/bundler-plugins/test/core/sourcemap-settings.test.ts b/packages/bundler-plugins/test/core/sourcemap-settings.test.ts index 1404fe7afd34..0fa3ee11f454 100644 --- a/packages/bundler-plugins/test/core/sourcemap-settings.test.ts +++ b/packages/bundler-plugins/test/core/sourcemap-settings.test.ts @@ -137,13 +137,11 @@ describe('decideSourceMapHandling', () => { it.each([true, 'disable-upload'] as const)( 'removes source maps the SDK turned on when `sourcemaps.disable` is `%s`', disable => { - expect( - decideSourceMapHandling( - 'hidden', - options({ disable, deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }), - true, - ), - ).toMatchObject({ enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: true }); + expect(decideSourceMapHandling('hidden', options({ disable, sdkDeleteSourceMaps: true }), true)).toMatchObject({ + enableHidden: false, + deleteAfterUpload: true, + removeAllSourceMaps: true, + }); }, ); @@ -157,8 +155,8 @@ describe('decideSourceMapHandling', () => { ); }); - describe('with source maps the SDK turned on', () => { - const sdkOptions = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }; + describe('with `sdkDeleteSourceMaps`', () => { + const sdkOptions = { sdkDeleteSourceMaps: true }; it.each(['hidden', 'visible'])('removes all `%s` source maps', kind => { expect(decideSourceMapHandling(kind, options(sdkOptions), true)).toMatchObject({ @@ -169,10 +167,25 @@ describe('decideSourceMapHandling', () => { }); it.each(['hidden', 'visible'])('removes all `%s` source maps when no upload can run', kind => { - expect(decideSourceMapHandling(kind, options(sdkOptions), false)).toMatchObject({ + const decision = decideSourceMapHandling(kind, options(sdkOptions), false); + + expect(decision).toEqual({ enableHidden: kind === 'visible', deleteAfterUpload: true, removeAllSourceMaps: true, + log: { + level: 'info', + message: 'Source maps are not uploaded, but the Sentry SDK removes them from the build output.', + }, + }); + }); + + it('names the SDK when it switches visible source maps to hidden', () => { + expect(decideSourceMapHandling('visible', options(sdkOptions), true).log).toEqual({ + level: 'info', + message: + 'Switching to hidden source maps, because the Sentry SDK removes them from the build output. ' + + 'Without the `sourceMappingURL` comment browsers do not request the removed map files.', }); }); @@ -180,41 +193,62 @@ describe('decideSourceMapHandling', () => { expect(decideSourceMapHandling(kind, options(sdkOptions), false)).toEqual(NO_CHANGE); }); - it.each([undefined, false])('keeps them when `deleteSourcemapsAfterUpload` is %s', deleteSourcemapsAfterUpload => { + it.each(['hidden', 'visible'])('keeps `%s` source maps when it is `false`', kind => { + expect(decideSourceMapHandling(kind, options({ sdkDeleteSourceMaps: false }), true)).toEqual(NO_CHANGE); + }); + + it('keeps the source maps the plugin turns on when it is `false`', () => { + expect(decideSourceMapHandling('unset', options({ sdkDeleteSourceMaps: false }), true)).toMatchObject({ + enableHidden: true, + deleteAfterUpload: false, + }); + }); + + it('lets the user-set `deleteSourcemapsAfterUpload` win', () => { expect( - decideSourceMapHandling('hidden', options({ deleteSourcemapsAfterUpload, sdkEnabledSourceMaps: true }), true), + decideSourceMapHandling( + 'hidden', + options({ deleteSourcemapsAfterUpload: false, sdkDeleteSourceMaps: true }), + true, + ), ).toEqual(NO_CHANGE); + expect( + decideSourceMapHandling( + 'hidden', + options({ deleteSourcemapsAfterUpload: true, sdkDeleteSourceMaps: false }), + true, + ), + ).toEqual({ enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: false }); }); - it('calls the function form when it decides', () => { - let value: boolean | undefined; - const normalized = options({ deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: () => value }); + it('names `deleteSourcemapsAfterUpload` in the logs when the user set it to `true`', () => { + const userOptions = options({ deleteSourcemapsAfterUpload: true, sdkDeleteSourceMaps: true }); - expect(decideSourceMapHandling('hidden', normalized, true)).toMatchObject({ removeAllSourceMaps: false }); - value = true; - expect(decideSourceMapHandling('hidden', normalized, true)).toMatchObject({ removeAllSourceMaps: true }); + expect(decideSourceMapHandling('hidden', userOptions, false).log).toEqual({ + level: 'warn', + message: + 'Source maps are not uploaded, but they are removed from the build output because `sourcemaps.deleteSourcemapsAfterUpload` is set.', + }); + expect(decideSourceMapHandling('visible', userOptions, true).log?.message).toMatch( + /^Switching to hidden source maps because `sourcemaps\.deleteSourcemapsAfterUpload` is set\./, + ); }); - }); - describe('with the internal function form', () => { - it('calls the function when it decides', () => { + it('calls the function form when it decides', () => { let value: boolean | undefined; - const normalized = options({ deleteSourcemapsAfterUpload: () => value }); + const normalized = options({ sdkDeleteSourceMaps: () => value }); expect(decideSourceMapHandling('hidden', normalized, true)).toEqual(NO_CHANGE); value = true; expect(decideSourceMapHandling('hidden', normalized, true)).toEqual({ enableHidden: false, deleteAfterUpload: true, - removeAllSourceMaps: false, + removeAllSourceMaps: true, }); }); - it('passes the environment to both functions', () => { - const normalized = options({ - deleteSourcemapsAfterUpload: environment => environment === 'client', - sdkEnabledSourceMaps: environment => environment === 'client', - }); + it('passes the environment to the function', () => { + const normalized = options({ sdkDeleteSourceMaps: environment => environment === 'client' || undefined }); expect(decideSourceMapHandling('hidden', normalized, true, 'client')).toMatchObject({ deleteAfterUpload: true, @@ -225,7 +259,7 @@ describe('decideSourceMapHandling', () => { }); it('treats `undefined` from the function like an unset option', () => { - expect(decideSourceMapHandling('unset', options({ deleteSourcemapsAfterUpload: () => undefined }), true)).toEqual( + expect(decideSourceMapHandling('unset', options({ sdkDeleteSourceMaps: () => undefined }), true)).toEqual( decideSourceMapHandling('unset', options(), true), ); }); @@ -286,9 +320,14 @@ describe('getDeleteOption', () => { it('reads `sourcemaps.deleteSourcemapsAfterUpload` when `sourcemaps.delete` is unset', () => { expect(getDeleteOption(options())).toBeUndefined(); expect(getDeleteOption(options({ deleteSourcemapsAfterUpload: true }))).toBe(true); - expect( - getDeleteOption(options({ deleteSourcemapsAfterUpload: environment => environment === 'client' }), 'client'), - ).toBe(true); + }); + + it('reads `sourcemaps.sdkDeleteSourceMaps` when both user options are unset', () => { + const sdkDeleteSourceMaps = (environment?: string): boolean | undefined => environment === 'client' || undefined; + + expect(getDeleteOption(options({ sdkDeleteSourceMaps }), 'client')).toBe(true); + expect(getDeleteOption(options({ sdkDeleteSourceMaps }), 'ssr')).toBeUndefined(); + expect(getDeleteOption(options({ deleteSourcemapsAfterUpload: false, sdkDeleteSourceMaps }), 'client')).toBe(false); }); it.each([true, false])('prefers `sourcemaps.delete: %s`', value => { @@ -409,7 +448,7 @@ describe('decideSourceMapHandling with `sourcemaps.delete`', () => { expect( decideSourceMapHandling( 'hidden', - options({ delete: false, deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }), + options({ delete: false, deleteSourcemapsAfterUpload: true, sdkDeleteSourceMaps: true }), true, ), ).toEqual(NO_CHANGE); diff --git a/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts index c82bd9a91bd0..bc7cd7477a4a 100644 --- a/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts @@ -181,7 +181,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (esbuild)', () => { 'deletes every map the SDK turned on, also those of chunks and CSS that were not uploaded (%s)', async (_, options) => { await build( - { ...options, sourcemaps: { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true } }, + { ...options, sourcemaps: { sdkDeleteSourceMaps: true } }, { ...writeSplitBuild(), sourcemap: 'external' }, ); diff --git a/packages/bundler-plugins/test/esbuild/disable-upload.test.ts b/packages/bundler-plugins/test/esbuild/disable-upload.test.ts index fb8801c69d65..2bfcba17926b 100644 --- a/packages/bundler-plugins/test/esbuild/disable-upload.test.ts +++ b/packages/bundler-plugins/test/esbuild/disable-upload.test.ts @@ -77,7 +77,7 @@ describe('sourcemaps.disable: "disable-upload"', () => { plugins: [ sentryEsbuildPlugin({ telemetry: false, - sourcemaps: { disable: 'disable-upload', deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }, + sourcemaps: { disable: 'disable-upload', sdkDeleteSourceMaps: true }, }), ], }); diff --git a/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts index 3418603b56d6..fe02efd16eee 100644 --- a/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts @@ -364,7 +364,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (rollup / rolldown)', () => { }, }; - const sdkSourcemaps = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true, ignore: ['**/vendor.js'] }; + const sdkSourcemaps = { sdkDeleteSourceMaps: true, ignore: ['**/vendor.js'] }; async function writeSdkBuild(options: InternalOptions): Promise { const vendor = path.join(tmpDir, 'vendor.js'); @@ -390,7 +390,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (rollup / rolldown)', () => { it('reads the function form when it decides', async () => { let sdkEnabled: boolean | undefined; - const plugins = sdkRollupPlugin({ sourcemaps: { ...sdkSourcemaps, sdkEnabledSourceMaps: () => sdkEnabled } }); + const plugins = sdkRollupPlugin({ sourcemaps: { ...sdkSourcemaps, sdkDeleteSourceMaps: () => sdkEnabled } }); sdkEnabled = true; const vendor = path.join(tmpDir, 'vendor.js'); fs.writeFileSync(vendor, 'console.log("vendor");\n'); @@ -400,8 +400,8 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (rollup / rolldown)', () => { expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'style.css', 'vendor.js', 'worker.js']); }); - it('keeps the maps when `deleteSourcemapsAfterUpload` is not true', async () => { - await writeSdkBuild({ sourcemaps: { sdkEnabledSourceMaps: true } }); + it('keeps the maps when the user sets `deleteSourcemapsAfterUpload: false`', async () => { + await writeSdkBuild({ sourcemaps: { deleteSourcemapsAfterUpload: false, sdkDeleteSourceMaps: true } }); expect( fs diff --git a/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts index 5a154ca8231a..ffd285e06dcd 100644 --- a/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts @@ -216,7 +216,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { it.each([true, 'hidden'] as const)( 'removes `%s` source maps an output enables when the SDK turned source maps on', async sourcemap => { - const config = viteConfig({ sourcemaps: { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true } }); + const config = viteConfig({ sourcemaps: { sdkDeleteSourceMaps: true } }); await build({ ...config, build: { ...config.build, rollupOptions: { input: entry, output: { sourcemap } } }, @@ -236,7 +236,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { expect(uploads).toHaveLength(0); }); - it('reads the option from the internal function form when it decides', async () => { + it('reads `sdkDeleteSourceMaps` from its function form when it decides', async () => { let deleteMaps: boolean | undefined; const sdkPlugin: Plugin = { name: 'sdk', @@ -250,7 +250,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { ...config, plugins: [ sdkPlugin, - ...sentryVitePlugin({ ...credentials, sourcemaps: { deleteSourcemapsAfterUpload: () => deleteMaps } }), + ...sentryVitePlugin({ ...credentials, sourcemaps: { sdkDeleteSourceMaps: () => deleteMaps } }), ], }); @@ -274,8 +274,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { const config = viteConfig( { sourcemaps: { - deleteSourcemapsAfterUpload: true, - sdkEnabledSourceMaps: () => sdkEnabled, + sdkDeleteSourceMaps: () => sdkEnabled, ignore: ['**/lazy-*'], }, }, @@ -419,7 +418,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { const builder = await createBuilder({ ...viteConfig({ sourcemaps: { - deleteSourcemapsAfterUpload: environment => { + sdkDeleteSourceMaps: environment => { askedFor.push(environment); return environment === undefined ? true : undefined; }, diff --git a/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts index 1982b1a34d9f..e592d4a7c04d 100644 --- a/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts @@ -459,7 +459,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (webpack)', () => { }); describe('with source maps the SDK turned on', () => { - const sdkSourcemaps = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }; + const sdkSourcemaps = { sdkDeleteSourceMaps: true }; function sdkConfig(pluginOptions: InternalOptions): Configuration { fs.writeFileSync(path.join(tmpDir, 'style.css'), 'body { color: red; }\n'); @@ -495,8 +495,8 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (webpack)', () => { expect(mkdtempSpy).not.toHaveBeenCalled(); }); - it('keeps the maps when `deleteSourcemapsAfterUpload` is not true', async () => { - await build(sdkConfig({ sourcemaps: { sdkEnabledSourceMaps: true } })); + it('keeps the maps when the user sets `deleteSourcemapsAfterUpload: false`', async () => { + await build(sdkConfig({ sourcemaps: { deleteSourcemapsAfterUpload: false, sdkDeleteSourceMaps: true } })); expect( fs diff --git a/packages/cloudflare/src/options.ts b/packages/cloudflare/src/options.ts index 7e38369d0c5c..b57baeaf7b17 100644 --- a/packages/cloudflare/src/options.ts +++ b/packages/cloudflare/src/options.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_captureOptionsSetByUser, isObjectLike, envToBool } from '@sentry/core'; +import { _INTERNAL_captureOptionsSetByUser, GLOBAL_OBJ, isObjectLike, envToBool } from '@sentry/core'; import type { CloudflareOptions } from './client'; /** @@ -31,7 +31,8 @@ function getEnvVar>(env: unknown, varName: key * Release is determined with the following priority (highest to lowest): * 1. User-provided release option * 2. SENTRY_RELEASE environment variable - * 3. CF_VERSION_METADATA.id binding (if configured in the wrangler config) + * 3. The release that a Sentry bundler plugin injected into the build (`globalThis.SENTRY_RELEASE.id`) + * 4. CF_VERSION_METADATA.id binding (if configured in the wrangler config) * * @param options - The options passed in from the user. * @param env - The environment variables. @@ -45,13 +46,14 @@ export function getFinalOptions(options: CloudflareOptions = {}, env: unknown): return userOptions; } - // Priority: userOptions.release > SENTRY_RELEASE > CF_VERSION_METADATA.id + // Priority: userOptions.release > SENTRY_RELEASE > injected release > CF_VERSION_METADATA.id const release = 'SENTRY_RELEASE' in env && typeof env.SENTRY_RELEASE === 'string' ? env.SENTRY_RELEASE - : 'CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA) - ? env.CF_VERSION_METADATA.id - : undefined; + : GLOBAL_OBJ.SENTRY_RELEASE?.id || + ('CF_VERSION_METADATA' in env && isVersionMetadata(env.CF_VERSION_METADATA) + ? env.CF_VERSION_METADATA.id + : undefined); const tracesSampleRate = userOptions.tracesSampleRate ?? parseFloat(getEnvVar(env, 'SENTRY_TRACES_SAMPLE_RATE') ?? ''); diff --git a/packages/cloudflare/src/vite/autoInstrument.ts b/packages/cloudflare/src/vite/autoInstrument.ts index bef38c6dc05e..ae16afc6b7d2 100644 --- a/packages/cloudflare/src/vite/autoInstrument.ts +++ b/packages/cloudflare/src/vite/autoInstrument.ts @@ -299,6 +299,11 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa buildOptionsImport(entryPath, instrumentFilePath, { absolute: !!virtualEntry }) : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined }; + // The TanStack Start server entry shim with a release wraps the default export of the entry it re-exports + // (`export default addReleaseMetaTag(serverEntry, release)`). That entry is wrapped already, and a second + // `withSentry` would start a second trace for each request. + const reexportsEntry = reexportsAllFromSameFile(ast, normalizedId); + // No registration import is injected here: the orchestrion plugin's // subscribe-injection makes each bundled package self-register its channel // subscriber on the global marker, so wrapping the entry with `withSentry` @@ -311,11 +316,12 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa sameWorkerBindings: wranglerConfig.sameWorkerBindings, sentryModule, workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate }, + wrapDefault: !reexportsEntry, }); const wrappedClasses = result?.wrappedClasses ?? new Set(); const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name)); - if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) { + if (missing.length > 0 && !reexportsEntry) { this.warn?.( `[sentry] Could not auto-instrument ${missing.join(', ')}. ` + 'The worker entry has no export matching them. ' + diff --git a/packages/cloudflare/test/options.test.ts b/packages/cloudflare/test/options.test.ts index 765768f37853..661bdff5527f 100644 --- a/packages/cloudflare/test/options.test.ts +++ b/packages/cloudflare/test/options.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from 'vitest'; +import { GLOBAL_OBJ } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; import { getFinalOptions } from '../src/options'; describe('getFinalOptions', () => { @@ -208,6 +209,35 @@ describe('getFinalOptions', () => { }); }); + describe('injected release', () => { + afterEach(() => { + delete GLOBAL_OBJ.SENTRY_RELEASE; + }); + + it('uses the release that a bundler plugin injected', () => { + GLOBAL_OBJ.SENTRY_RELEASE = { id: 'injected-release' }; + + const result = getFinalOptions({ dsn: 'test-dsn' }, {}); + + expect(result).toEqual(expect.objectContaining({ dsn: 'test-dsn', release: 'injected-release' })); + }); + + it('prefers the injected release over CF_VERSION_METADATA.id', () => { + GLOBAL_OBJ.SENTRY_RELEASE = { id: 'injected-release' }; + + const result = getFinalOptions({ dsn: 'test-dsn' }, { CF_VERSION_METADATA: { id: 'version-123' } }); + + expect(result).toEqual(expect.objectContaining({ dsn: 'test-dsn', release: 'injected-release' })); + }); + + it('prefers SENTRY_RELEASE and the user release over the injected release', () => { + GLOBAL_OBJ.SENTRY_RELEASE = { id: 'injected-release' }; + + expect(getFinalOptions({ dsn: 'test-dsn' }, { SENTRY_RELEASE: 'env-release' }).release).toBe('env-release'); + expect(getFinalOptions({ dsn: 'test-dsn', release: 'user-release' }, {}).release).toBe('user-release'); + }); + }); + describe('SENTRY_SPOTLIGHT', () => { it('reads SENTRY_SPOTLIGHT boolean "true" from env', () => { const result = getFinalOptions({}, { SENTRY_SPOTLIGHT: 'true' }); diff --git a/packages/cloudflare/test/vite/autoInstrument.test.ts b/packages/cloudflare/test/vite/autoInstrument.test.ts index 9603e9a33f9d..0ad992104d10 100644 --- a/packages/cloudflare/test/vite/autoInstrument.test.ts +++ b/packages/cloudflare/test/vite/autoInstrument.test.ts @@ -636,6 +636,35 @@ describe('sentryCloudflareAutoInstrumentPlugin', () => { expect(shimResult.code).toContain('_INTERNAL_wrapUnlessInstrumented('); expect(warnings).toEqual([]); }); + + it('wraps the default export only once when the shim wraps the default export of the entry', async () => { + const dir = writeTempDir({ 'wrangler.toml': 'main = "index.ts"' }); + const plugin = sentryCloudflareAutoInstrumentPlugin(); + plugin.configResolved({ root: dir }); + + const entry = join(dir, 'index.ts').replace(/\\/g, '/'); + const original = JSON.stringify(`${entry}?sentry-tunnel-original`); + const ctx = { parse: (c: string) => parseJS(c) }; + + const originalResult = await plugin.transform.call( + ctx, + 'export default { fetch() {} };', + `${entry}?sentry-tunnel-original`, + ); + const shimResult = await plugin.transform.call( + ctx, + [ + `import serverEntry from ${original};`, + `export * from ${original};`, + "export default addReleaseMetaTag(serverEntry, 'release');", + ].join('\n'), + entry, + ); + + expect(originalResult.code).toContain('__SENTRY__.withSentry('); + expect(shimResult?.code ?? '').not.toContain('withSentry'); + expect(shimResult?.code ?? '').not.toContain('_INTERNAL_wrapUnlessInstrumented'); + }); }); describe('wranglerConfigPath option', () => { diff --git a/packages/gatsby/gatsby-node.js b/packages/gatsby/gatsby-node.js index cb09716f4960..9834e87fdafb 100644 --- a/packages/gatsby/gatsby-node.js +++ b/packages/gatsby/gatsby-node.js @@ -64,9 +64,7 @@ exports.onCreateWebpackConfig = ({ getConfig, actions, stage }, options) => { assets: ['./public/**'], upload: options.sourcemaps?.upload, injectDebugIds: options.sourcemaps?.injectDebugIds, - deleteSourcemapsAfterUpload, - // Also removes CSS maps and maps of chunks that are not uploaded. - sdkEnabledSourceMaps: deleteSourcemapsAfterUpload, + sdkDeleteSourceMaps: deleteSourcemapsAfterUpload, // Ignore files that aren't users' source code related ignore: [ 'polyfill-*', // related to polyfills diff --git a/packages/gatsby/test/gatsby-node.test.ts b/packages/gatsby/test/gatsby-node.test.ts index ae2e769f3fc9..ca7d37dae041 100644 --- a/packages/gatsby/test/gatsby-node.test.ts +++ b/packages/gatsby/test/gatsby-node.test.ts @@ -230,8 +230,7 @@ describe('onCreateWebpackConfig', () => { expect.objectContaining({ sourcemaps: { assets: ['./public/**'], - deleteSourcemapsAfterUpload: expected.deleteOptions, - sdkEnabledSourceMaps: expected.deleteOptions, + sdkDeleteSourceMaps: expected.deleteOptions, ignore: ['polyfill-*', 'framework-*', 'webpack-runtime-*'], }, }), @@ -269,8 +268,7 @@ describe('onCreateWebpackConfig', () => { assets: ['./public/**'], upload: 'upload' in sourcemaps ? sourcemaps.upload : undefined, injectDebugIds: 'injectDebugIds' in sourcemaps ? sourcemaps.injectDebugIds : undefined, - deleteSourcemapsAfterUpload: deletes, - sdkEnabledSourceMaps: deletes, + sdkDeleteSourceMaps: deletes, ignore: ['polyfill-*', 'framework-*', 'webpack-runtime-*'], }, }), @@ -318,7 +316,7 @@ describe('onCreateWebpackConfig', () => { onCreateWebpackConfig({ actions, getConfig, stage: 'build-javascript' }, { ...flatOptions, sourcemaps }); expect(sentryWebpackPlugin).toHaveBeenCalledWith( - expect.objectContaining({ sourcemaps: expect.objectContaining({ deleteSourcemapsAfterUpload: deletes }) }), + expect.objectContaining({ sourcemaps: expect.objectContaining({ sdkDeleteSourceMaps: deletes }) }), ); }); }); diff --git a/packages/nextjs/src/config/getBuildPluginOptions.ts b/packages/nextjs/src/config/getBuildPluginOptions.ts index 715865f50eeb..21d4e1ac86dc 100644 --- a/packages/nextjs/src/config/getBuildPluginOptions.ts +++ b/packages/nextjs/src/config/getBuildPluginOptions.ts @@ -185,7 +185,7 @@ function createSourcemapUploadIgnorePattern( /** * Creates file patterns for deletion after the source map upload that runs after the production compile. - * The webpack plugin removes the maps of webpack builds itself (see `deleteSourcemapsAfterUpload`). + * The webpack plugin removes the maps of webpack builds itself (see `sdkDeleteSourceMaps`). */ function createFilesToDeleteAfterUploadPattern( normalizedDistPath: string, @@ -369,10 +369,9 @@ export function getBuildPluginOptions({ assets: sentryBuildOptions.sourcemaps?.assets ?? sourcemapUploadAssets, ignore: finalIgnorePatterns, filesToDeleteAfterUpload, - deleteSourcemapsAfterUpload: webpackPluginDeletesSourcemaps, // Every client map goes, also those the user turned on with `productionBrowserSourceMaps` or // `devtool`, and those of chunks the upload leaves out. - sdkEnabledSourceMaps: webpackPluginDeletesSourcemaps, + sdkDeleteSourceMaps: webpackPluginDeletesSourcemaps, resolveSourceMap: sentryBuildOptions.sourcemaps?.resolveSourceMap, }, release: createReleaseConfig(releaseName, sentryBuildOptions), diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts index 0d01bfa9bbc2..1ffbdf1773de 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts @@ -29,6 +29,10 @@ const MISSING_INSTRUMENTATION_FILE_WARNING_SHOWN = '__SENTRY_MISSING_INSTRUMENTA * With the default `'childProcesses'`, Next.js runs Turbopack loaders in `node` processes and puts `process.execArgv` * into their `NODE_OPTIONS`. On Bun, `execArgv` contains `--bun`, which Node.js does not accept, so the build fails or * hangs. `withSentryConfig` always adds loaders. + * + * `next dev` keeps the Next.js default. With worker threads, the loaders run in the dev server process, and Bun caches + * that `.next/dev` has no `node_modules` folder. The server then cannot load the externals that Turbopack links into + * `.next/dev/node_modules` later. */ export function maybeSetTurbopackPluginRuntimeStrategyOption( incomingUserNextConfigObject: NextConfigObject, @@ -36,7 +40,7 @@ export function maybeSetTurbopackPluginRuntimeStrategyOption( isTurbopack: boolean, silent?: boolean, ): void { - if (!process.versions.bun || !isTurbopack || !nextJsVersion) { + if (!process.versions.bun || !isTurbopack || !nextJsVersion || process.env.NODE_ENV === 'development') { return; } diff --git a/packages/nextjs/test/config/getBuildPluginOptions.test.ts b/packages/nextjs/test/config/getBuildPluginOptions.test.ts index 7f72a4abffd4..6b6f5b2d79cf 100644 --- a/packages/nextjs/test/config/getBuildPluginOptions.test.ts +++ b/packages/nextjs/test/config/getBuildPluginOptions.test.ts @@ -498,7 +498,7 @@ describe('getBuildPluginOptions', () => { expect(result.sourcemaps).toMatchObject({ filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: true, + sdkDeleteSourceMaps: true, }); }); @@ -516,7 +516,7 @@ describe('getBuildPluginOptions', () => { expect(result.sourcemaps).toMatchObject({ filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: false, + sdkDeleteSourceMaps: false, }); }); @@ -536,7 +536,7 @@ describe('getBuildPluginOptions', () => { // The upload runs after the compile, and the after-production-compile options delete the maps. expect(result.sourcemaps).toMatchObject({ filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: false, + sdkDeleteSourceMaps: false, }); }); @@ -556,14 +556,13 @@ describe('getBuildPluginOptions', () => { expect(result.sourcemaps).toMatchObject({ filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: false, - sdkEnabledSourceMaps: false, + sdkDeleteSourceMaps: false, }); }, ); it.each(['after-production-compile-webpack', 'after-production-compile-turbopack'] as const)( - 'leaves deleteSourcemapsAfterUpload unset for %s builds', + 'leaves sdkDeleteSourceMaps unset for %s builds', buildTool => { const result = getBuildPluginOptions({ sentryBuildOptions: { @@ -577,12 +576,12 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); - expect(result.sourcemaps?.sdkEnabledSourceMaps).toBeUndefined(); + expect(result.sourcemaps?.sdkDeleteSourceMaps).toBeUndefined(); }, ); it.each([true, false])( - 'sets sdkEnabledSourceMaps to the client delete option (deleteSourcemapsAfterUpload: %s)', + 'sets sdkDeleteSourceMaps to the client delete option (deleteSourcemapsAfterUpload: %s)', option => { const result = getBuildPluginOptions({ sentryBuildOptions: { @@ -595,7 +594,8 @@ describe('getBuildPluginOptions', () => { buildTool: 'webpack-client', }); - expect(result.sourcemaps).toMatchObject({ deleteSourcemapsAfterUpload: option, sdkEnabledSourceMaps: option }); + expect(result.sourcemaps).toMatchObject({ sdkDeleteSourceMaps: option }); + expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); }, ); @@ -616,7 +616,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); - expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBe(false); + expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); it('uses custom filesToDeleteAfterUpload array when provided', () => { @@ -656,7 +656,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); - expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBe(false); + expect(result.sourcemaps?.sdkDeleteSourceMaps).toBe(false); }); it('filesToDeleteAfterUpload bypasses server build guard', () => { @@ -816,7 +816,7 @@ describe('getBuildPluginOptions', () => { buildTool, }); - expect(result.sourcemaps).toMatchObject({ deleteSourcemapsAfterUpload: false, sdkEnabledSourceMaps: false }); + expect(result.sourcemaps).toMatchObject({ sdkDeleteSourceMaps: false }); expect(result.sourcemaps).not.toHaveProperty('delete'); }, ); diff --git a/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts b/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts index 3b32d2456c28..baabe647edeb 100644 --- a/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts +++ b/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts @@ -8,6 +8,7 @@ describe('maybeSetTurbopackPluginRuntimeStrategyOption', () => { afterEach(() => { Object.defineProperty(process, 'versions', originalVersions); vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); it.each(['16.2.0', '16.3.8', '17.0.0'])( @@ -46,6 +47,23 @@ describe('maybeSetTurbopackPluginRuntimeStrategyOption', () => { expect(warnSpy).not.toHaveBeenCalled(); }); + it('keeps the Next.js default in `next dev` on Bun', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.5' } }); + vi.stubEnv('NODE_ENV', 'development'); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const defaultConfig: NextConfigObject = {}; + const childProcessesConfig: NextConfigObject = { + experimental: { turbopackPluginRuntimeStrategy: 'childProcesses' }, + }; + + maybeSetTurbopackPluginRuntimeStrategyOption(defaultConfig, '16.4.6', true); + maybeSetTurbopackPluginRuntimeStrategyOption(childProcessesConfig, '16.4.6', true); + + expect(defaultConfig.experimental).toBeUndefined(); + expect(childProcessesConfig.experimental).toEqual({ turbopackPluginRuntimeStrategy: 'childProcesses' }); + expect(warnSpy).not.toHaveBeenCalled(); + }); + it('does not warn about `childProcesses` on Node.js', () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const config: NextConfigObject = { experimental: { turbopackPluginRuntimeStrategy: 'childProcesses' } }; diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index 5b9b3fb6bfed..fc230474312b 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -144,10 +144,7 @@ describe('constructWebpackConfigFunction()', () => { expect(sentryWebpackPlugin).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ - deleteSourcemapsAfterUpload: deletesAll, - sdkEnabledSourceMaps: deletesAll, - }), + sourcemaps: expect.objectContaining({ sdkDeleteSourceMaps: deletesAll }), }), ); }); @@ -180,8 +177,7 @@ describe('constructWebpackConfigFunction()', () => { expect(sentryWebpackPlugin).toHaveBeenCalledWith( expect.objectContaining({ sourcemaps: expect.objectContaining({ - deleteSourcemapsAfterUpload: deletesAll, - sdkEnabledSourceMaps: deletesAll, + sdkDeleteSourceMaps: deletesAll, upload: 'upload' in sourcemaps ? sourcemaps.upload : undefined, injectDebugIds: 'injectDebugIds' in sourcemaps ? sourcemaps.injectDebugIds : undefined, }), diff --git a/packages/nuxt/src/runtime/hooks/captureErrorHook.ts b/packages/nuxt/src/runtime/hooks/captureErrorHook.ts index 6d8adaf2ea77..f95beee94daa 100644 --- a/packages/nuxt/src/runtime/hooks/captureErrorHook.ts +++ b/packages/nuxt/src/runtime/hooks/captureErrorHook.ts @@ -1,4 +1,4 @@ -import { captureException, getClient, getCurrentScope } from '@sentry/core'; +import { captureException, getClient, stripUrlQueryAndFragment, withScope } from '@sentry/core'; import { flushIfServerless } from '@sentry/core/server'; import type { CapturedErrorContext } from 'nitropack/types'; import { extractErrorContext, getEventRequestInfo } from '../utils'; @@ -59,17 +59,20 @@ export async function sentryCaptureErrorHook(error: Error, errorContext: Capture } } - const { method = '', path } = getEventRequestInfo(errorContext.event); - - if (path) { - getCurrentScope().setTransactionName(`${method} ${path}`); - } - + const { method = '', path = '' } = getEventRequestInfo(errorContext.event); + const pathname = stripUrlQueryAndFragment(path); const structuredContext = extractErrorContext(errorContext); - captureException(error, { - captureContext: { contexts: { nuxt: structuredContext } }, - mechanism: { handled: false, type: 'auto.function.nuxt.nitro' }, + // On the current scope, the name would also apply to every later event of that scope. + withScope(scope => { + if (pathname) { + scope.setTransactionName(`${method} ${pathname}`); + } + + captureException(error, { + captureContext: { contexts: { nuxt: structuredContext } }, + mechanism: { handled: false, type: 'auto.function.nuxt.nitro' }, + }); }); await flushIfServerless(); diff --git a/packages/nuxt/src/runtime/utils.ts b/packages/nuxt/src/runtime/utils.ts index a5378fb430ac..b5533f5638ba 100644 --- a/packages/nuxt/src/runtime/utils.ts +++ b/packages/nuxt/src/runtime/utils.ts @@ -1,5 +1,5 @@ import type { ClientOptions, Context, SerializedTraceData } from '@sentry/core'; -import { captureException, debug, getClient, getTraceMetaTags, isObjectLike } from '@sentry/core'; +import { captureException, debug, filterCollectedUrl, getClient, getTraceMetaTags, isObjectLike } from '@sentry/core'; import type { CapturedErrorContext } from 'nitropack/types'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; import type { ComponentPublicInstance } from 'vue'; @@ -39,7 +39,8 @@ export function extractErrorContext(errorContext: CapturedErrorContext | undefin if (errorContext.event) { const { method, path } = getEventRequestInfo(errorContext.event); ctx.method = method; - ctx.path = path; + // The h3 v1 path has the query string. + ctx.path = filterCollectedUrl(path); } if (Array.isArray(errorContext.tags)) { diff --git a/packages/nuxt/src/vite/sourceMapDeletion.ts b/packages/nuxt/src/vite/sourceMapDeletion.ts index 12e7b7ab0cc7..7d1089d6986b 100644 --- a/packages/nuxt/src/vite/sourceMapDeletion.ts +++ b/packages/nuxt/src/vite/sourceMapDeletion.ts @@ -128,8 +128,9 @@ export function withClientSourceMapDeletion( ...options.sourcemaps, filesToDeleteAfterUpload: undefined, delete: undefined, - // The Vite plugin reads these in its `config` hook, after `modules:done` set the fallback. - deleteSourcemapsAfterUpload: environment => { + deleteSourcemapsAfterUpload: undefined, + // The Vite plugin reads this in its `config` hook, after `modules:done` set the fallback. + sdkDeleteSourceMaps: environment => { const side = getSide(environment); if (side === undefined) { return undefined; @@ -139,11 +140,6 @@ export function withClientSourceMapDeletion( } return fallback[side] && userSourcemaps?.filesToDeleteAfterUpload === undefined ? true : undefined; }, - // Makes the plugin remove every source map of the environment, not only those of uploaded chunks. - sdkEnabledSourceMaps: environment => { - const side = getSide(environment); - return side !== undefined && (userSourcemaps?.delete === true || fallback[side]); - }, }, }; } @@ -156,14 +152,15 @@ function isClientEnvironment(environment: string | undefined): boolean { return environment === undefined || environment === 'client'; } -export function withoutSourceMapDeletion(options: Options): Options { +export function withoutSourceMapDeletion(options: Options): InternalOptions { return { ...options, sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, delete: undefined, - deleteSourcemapsAfterUpload: false, + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: false, }, }; } diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index ded5a827068a..655f5768f148 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -308,7 +308,7 @@ function resolveFilesToDeleteAfterUpload( 3. users did not set source maps generation - we enable 'hidden' source maps generation when Sentry uploads the maps, or when `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - - client with the Vite builder: pass `deleteSourcemapsAfterUpload: true`, so the maps never reach the build output + - client with the Vite builder: pass `sdkDeleteSourceMaps: true`, so the maps never reach the build output - client with another builder: configure `filesToDeleteAfterUpload` for the .map files in Nitro's public dir - server: configure `filesToDeleteAfterUpload` to delete the .map files after the build (we emit a log about this) diff --git a/packages/nuxt/test/runtime/hooks/captureErrorHook.test.ts b/packages/nuxt/test/runtime/hooks/captureErrorHook.test.ts index bcf7f01690be..8812bea51cc3 100644 --- a/packages/nuxt/test/runtime/hooks/captureErrorHook.test.ts +++ b/packages/nuxt/test/runtime/hooks/captureErrorHook.test.ts @@ -6,15 +6,12 @@ import type { CapturedErrorContext } from 'nitropack/types'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { sentryCaptureErrorHook } from '../../../src/runtime/hooks/captureErrorHook'; -const setTransactionName = vi.fn(); - vi.mock('@sentry/core', async importOriginal => { const mod = await importOriginal(); return { ...(mod as any), captureException: vi.fn(), getClient: vi.fn(), - getCurrentScope: vi.fn(() => ({ setTransactionName })), }; }); @@ -41,12 +38,15 @@ const h3Majors = [ error.statusCode = statusCode; return error; }, - event: { method: 'GET', path: '/test-path' }, + event: { method: 'GET', path: '/users/42?include=profile' }, }, { name: 'h3 v2 (Nitro v3)', httpError: (message: string, statusCode: number): Error => new HTTPError({ message, status: statusCode }), - event: { req: new Request('http://localhost/test-path'), url: new URL('http://localhost/test-path') }, + event: { + req: new Request('http://localhost/users/42?include=profile'), + url: new URL('http://localhost/users/42?include=profile'), + }, }, ]; @@ -56,6 +56,16 @@ function withCause(error: Error, cause: unknown): Error { return Object.defineProperty(error, 'cause', { value: cause, configurable: true }); } +/** The transaction name that the next captured event gets from the scope that is current during the capture. */ +function recordTransactionNameOfNextCapture(): Array { + const transactionNames: Array = []; + vi.mocked(SentryCore.captureException).mockImplementationOnce(() => { + transactionNames.push(SentryCore.getCurrentScope().getScopeData().transactionName); + return '4c79f60c11214eb38604f4ae0781bfb2'; + }); + return transactionNames; +} + describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event }) => { const mockErrorContext = { event } as unknown as CapturedErrorContext; @@ -80,10 +90,18 @@ describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event }) ); }); - it('sets the transaction name from the request method and path', async () => { + it('names the captured event after the request method and path, without the query string', async () => { + const transactionNames = recordTransactionNameOfNextCapture(); + + await sentryCaptureErrorHook(new Error('Test error'), mockErrorContext); + + expect(transactionNames).toEqual(['GET /users/42']); + }); + + it('leaves the transaction name of the current scope unchanged', async () => { await sentryCaptureErrorHook(new Error('Test error'), mockErrorContext); - expect(setTransactionName).toHaveBeenCalledWith('GET /test-path'); + expect(SentryCore.getCurrentScope().getScopeData().transactionName).toBeUndefined(); }); it('should skip HTTP errors with 4xx status codes', async () => { @@ -174,6 +192,22 @@ describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event }) }); }); +describe('sentryCaptureErrorHook - request without a pathname', () => { + beforeEach(() => { + vi.clearAllMocks(); + (SentryCore.getClient as any).mockReturnValue({ getOptions: () => ({}) }); + }); + + it('does not name the event when the h3 v1 path has only a query string', async () => { + const transactionNames = recordTransactionNameOfNextCapture(); + const errorContext = { event: { method: 'GET', path: '?page=2' } } as unknown as CapturedErrorContext; + + await sentryCaptureErrorHook(new Error('Test error'), errorContext); + + expect(transactionNames).toEqual([undefined]); + }); +}); + describe('sentryCaptureErrorHook - errors that only look like h3 errors', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/packages/nuxt/test/runtime/utils.test.ts b/packages/nuxt/test/runtime/utils.test.ts index f5c9dfbe2b31..d96c0812087c 100644 --- a/packages/nuxt/test/runtime/utils.test.ts +++ b/packages/nuxt/test/runtime/utils.test.ts @@ -1,4 +1,5 @@ import { captureException, getClient } from '@sentry/core'; +import type { CapturedErrorContext } from 'nitropack/types'; import { afterEach, beforeEach, describe, expect, it, type Mock, test, vi } from 'vitest'; import type { ComponentPublicInstance } from 'vue'; import { extractErrorContext, reportNuxtError } from '../../src/runtime/utils'; @@ -37,6 +38,17 @@ describe('extractErrorContext', () => { expect(extractErrorContext(partialContext)).toEqual({ path: '/test' }); }); + it('filters sensitive query params in the path of an h3 v1 (Nitro v2) event', () => { + const context = { + event: { method: 'GET', path: '/users/42?include=profile&token=abc123' }, + } as unknown as CapturedErrorContext; + + expect(extractErrorContext(context)).toEqual({ + method: 'GET', + path: '/users/42?include=profile&token=[Filtered]', + }); + }); + it('reads method and path from an h3 v2 (Nitro v3) event, which has no `method`/`path` getters', () => { const context = { event: { diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index b0722f380fc3..c36ea805aea3 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -370,8 +370,8 @@ describe('setupSourceMaps hooks', () => { assets: undefined, ignore: undefined, filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: expect.any(Function), rewriteSources: expect.any(Function), }, }); @@ -401,12 +401,7 @@ describe('setupSourceMaps hooks', () => { describe('client source map deletion', () => { function getDeleteOption(environment?: string): boolean | undefined { - const value = capturedViteOptions.options?.sourcemaps?.deleteSourcemapsAfterUpload; - return typeof value === 'function' ? value(environment) : value; - } - - function getSdkEnabledSourceMaps(environment?: string): boolean | undefined { - const value = capturedViteOptions.options?.sourcemaps?.sdkEnabledSourceMaps; + const value = capturedViteOptions.options?.sourcemaps?.sdkDeleteSourceMaps; return typeof value === 'function' ? value(environment) : value; } @@ -423,7 +418,7 @@ describe('setupSourceMaps hooks', () => { }); // The plugin then also removes the maps of chunks that the user's `assets` or `ignore` leave out. - it('tells the Vite plugin that Sentry enabled the client source maps', async () => { + it('asks the Vite plugin to delete the client source maps Sentry enabled with a narrowed upload', async () => { const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); setupSourceMaps( @@ -434,40 +429,38 @@ describe('setupSourceMaps hooks', () => { await mockNuxt.triggerHook('modules:done'); expect(capturedViteOptions.options?.sourcemaps?.assets).toEqual(['.nuxt/dist/client/_nuxt/entry*']); - expect(getSdkEnabledSourceMaps()).toBe(true); + expect(getDeleteOption()).toBe(true); }); // With the Vite environment API, the plugin also decides for the server environments. it.each([ - { environment: undefined, sdkEnabled: true }, - { environment: 'client', sdkEnabled: true }, - { environment: 'ssr', sdkEnabled: false }, - { environment: 'nitro', sdkEnabled: false }, - ])('answers for the client only, in the $environment environment', async ({ environment, sdkEnabled }) => { + { environment: undefined, expected: true }, + { environment: 'client', expected: true }, + { environment: 'ssr', expected: undefined }, + { environment: 'nitro', expected: undefined }, + ])('answers for the client only, in the $environment environment', async ({ environment, expected }) => { const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); await mockNuxt.triggerHook('modules:done'); - expect(getDeleteOption(environment)).toBe(sdkEnabled ? true : undefined); - expect(getSdkEnabledSourceMaps(environment)).toBe(sdkEnabled); + expect(getDeleteOption(environment)).toBe(expected); }); it.each([ - { label: 'Sentry enabled', server: undefined, sourcemaps: {}, expected: true, sdkEnabled: true }, - { label: 'Nuxt enabled', server: true, sourcemaps: {}, expected: undefined, sdkEnabled: false }, - { label: 'Nuxt enabled', server: true, sourcemaps: { delete: true }, expected: true, sdkEnabled: true }, - { label: 'Sentry enabled', server: undefined, sourcemaps: { delete: false }, expected: false, sdkEnabled: true }, + { label: 'Sentry enabled', server: undefined, sourcemaps: {}, expected: true }, + { label: 'Nuxt enabled', server: true, sourcemaps: {}, expected: undefined }, + { label: 'Nuxt enabled', server: true, sourcemaps: { delete: true }, expected: true }, + { label: 'Sentry enabled', server: undefined, sourcemaps: { delete: false }, expected: false }, { label: 'Sentry enabled', server: undefined, sourcemaps: { filesToDeleteAfterUpload: 'x/**' }, expected: undefined, - sdkEnabled: true, }, ] as const)( 'on the Vite server, decides for the $label server maps in the ssr environment with $sourcemaps', - async ({ server, sourcemaps, expected, sdkEnabled }) => { + async ({ server, sourcemaps, expected }) => { const mockNuxt = createMockNuxt({ sourcemap: { client: true, server } }); setupSourceMaps({ sourcemaps }, mockNuxt as unknown as Nuxt, vi.fn(), false, true); @@ -475,7 +468,6 @@ describe('setupSourceMaps hooks', () => { for (const environment of ['ssr', undefined]) { expect(getDeleteOption(environment)).toBe(expected); - expect(getSdkEnabledSourceMaps(environment)).toBe(sdkEnabled); } }, ); @@ -489,7 +481,6 @@ describe('setupSourceMaps hooks', () => { await mockNuxt.triggerHook('modules:done'); expect(getDeleteOption()).toBeUndefined(); - expect(getSdkEnabledSourceMaps()).toBe(false); }, ); @@ -504,6 +495,7 @@ describe('setupSourceMaps hooks', () => { setupSourceMaps({ sourcemaps: { deleteSourcemapsAfterUpload } }, mockNuxt as unknown as Nuxt, vi.fn()); await mockNuxt.triggerHook('modules:done'); + expect(capturedViteOptions.options?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); expect(getDeleteOption()).toBe(expected); expect(getDeleteOption('client')).toBe(expected); expect(getDeleteOption('ssr')).toBeUndefined(); @@ -519,7 +511,6 @@ describe('setupSourceMaps hooks', () => { expect(capturedViteOptions.options?.sourcemaps?.disable).toBe('disable-upload'); expect(getDeleteOption()).toBe(true); - expect(getSdkEnabledSourceMaps()).toBe(true); }); describe('with the new source map options', () => { @@ -558,7 +549,6 @@ describe('setupSourceMaps hooks', () => { expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }), ); expect(getDeleteOption()).toBeUndefined(); - expect(getSdkEnabledSourceMaps()).toBe(false); expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled(); }, ); @@ -582,7 +572,6 @@ describe('setupSourceMaps hooks', () => { await runBuild({ delete: true }, { client: true, server: true }); expect(getDeleteOption()).toBe(true); - expect(getSdkEnabledSourceMaps()).toBe(true); expectFilesDeletedAfterBuild(['.output/server/**/*.map']); }); @@ -599,10 +588,13 @@ describe('setupSourceMaps hooks', () => { expect(capturedViteOptions.options?.sourcemaps?.delete).toBeUndefined(); expect(getDeleteOption('client')).toBe(value); expect(getDeleteOption('ssr')).toBeUndefined(); - expect(getSdkEnabledSourceMaps('ssr')).toBe(false); expect(mockSentryRollupPlugin).toHaveBeenCalledWith( expect.objectContaining({ - sourcemaps: expect.objectContaining({ delete: undefined, deleteSourcemapsAfterUpload: false }), + sourcemaps: expect.objectContaining({ + delete: undefined, + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: false, + }), }), ); }); diff --git a/packages/remix/package.json b/packages/remix/package.json index 9a22b959571a..736d317d2090 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -7,8 +7,8 @@ "author": "Sentry", "license": "MIT", "bin": { - "sentry-upload-sourcemaps": "scripts/sentry-upload-sourcemaps.js", - "sentry-remix-v3-upload-sourcemaps": "scripts/sentry-remix-v3-upload-sourcemaps.mjs" + "sentry-upload-sourcemaps": "scripts/cli.mjs", + "sentry-remix-v3-upload-sourcemaps": "scripts/cli.mjs" }, "engines": { "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" diff --git a/packages/remix/scripts/cli.mjs b/packages/remix/scripts/cli.mjs new file mode 100755 index 000000000000..e7067b9370c4 --- /dev/null +++ b/packages/remix/scripts/cli.mjs @@ -0,0 +1,15 @@ +#!/usr/bin/env node +// All bins have to point at this one file: `npx @sentry/remix` can only pick an executable if every bin has the same +// target (or if one is called `remix`, which would collide with the Remix CLI). +import * as path from 'node:path'; + +// Windows and pnpm bin shims don't preserve the bin name, so also detect Remix 3 by its required `--entry` option. +const isRemixV3 = + path.basename(process.argv[1]) === 'sentry-remix-v3-upload-sourcemaps' || + process.argv.slice(2).some(arg => arg === '--entry' || arg.startsWith('--entry=')); + +if (isRemixV3) { + await import('./sentry-remix-v3-upload-sourcemaps.mjs'); +} else { + await import('./sentry-upload-sourcemaps.js'); +} diff --git a/packages/remix/src/vite/sourceMaps.ts b/packages/remix/src/vite/sourceMaps.ts index 05f729af2b21..cd3cafc76f6e 100644 --- a/packages/remix/src/vite/sourceMaps.ts +++ b/packages/remix/src/vite/sourceMaps.ts @@ -60,11 +60,10 @@ export function makeAddSentryVitePlugin( // Without an upload the user uploads the maps by hand, so they stay. // The SDK never read the user's `deleteSourcemapsAfterUpload`. `delete` replaces it. // A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. - deleteSourcemapsAfterUpload: + sdkDeleteSourceMaps: sourcemaps?.delete === undefined && sourcemaps?.filesToDeleteAfterUpload === undefined ? () => (state.sdkEnabledSourceMaps && resolveSourceMapsFeatures(sourcemaps).upload ? true : undefined) : undefined, - sdkEnabledSourceMaps: () => state.sdkEnabledSourceMaps, }, telemetry: telemetry ?? true, url: sentryUrl, @@ -109,7 +108,7 @@ export function makeEnableSourceMapsPlugin( * 3. Users didn't set source maps generation * - we enable 'hidden' source maps generation when Sentry uploads the maps, or when * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - * - without `sourcemaps.delete` we pass `deleteSourcemapsAfterUpload: true`, so the maps never + * - without `sourcemaps.delete` we pass `sdkDeleteSourceMaps: true`, so the maps never * reach the build output * * --> only exported for testing diff --git a/packages/remix/test/scripts/cli.test.ts b/packages/remix/test/scripts/cli.test.ts new file mode 100644 index 000000000000..55409364b055 --- /dev/null +++ b/packages/remix/test/scripts/cli.test.ts @@ -0,0 +1,49 @@ +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bin } from '../../package.json'; + +const CLI = path.resolve(__dirname, '../../scripts/cli.mjs'); + +describe('cli', () => { + let binDir: string; + + beforeAll(() => { + binDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-remix-cli-')); + for (const name of Object.keys(bin)) { + fs.symlinkSync(CLI, path.join(binDir, name)); + } + }); + + afterAll(() => { + fs.rmSync(binDir, { recursive: true, force: true }); + }); + + function run(file: string, ...args: string[]): string { + const { stdout, stderr } = spawnSync(process.execPath, [file, ...args], { encoding: 'utf8', cwd: binDir }); + return stdout + stderr; + } + + it('has a single bin target so that `npx @sentry/remix` can resolve it', () => { + expect(new Set(Object.values(bin))).toEqual(new Set(['scripts/cli.mjs'])); + }); + + it('runs the classic script by default', () => { + expect(run(path.join(binDir, 'sentry-upload-sourcemaps'), '--upload-sourcemaps', '--help')).toContain( + 'Usage: npx @sentry/remix --upload-sourcemaps', + ); + }); + + it('runs the Remix 3 script through its bin name', () => { + expect(run(path.join(binDir, 'sentry-remix-v3-upload-sourcemaps'))).toContain('at least one --entry is required'); + }); + + it.each([['--entry', 'app/entry.ts'], ['--entry=app/entry.ts']])( + 'runs the Remix 3 script for `%s` when the bin name is lost', + (...args) => { + expect(run(CLI, ...args, '--unknown')).toContain("[sentry] Unknown option '--unknown'"); + }, + ); +}); diff --git a/packages/remix/test/vite/index.test.ts b/packages/remix/test/vite/index.test.ts index 9f4514061b86..ec78602bbfcd 100644 --- a/packages/remix/test/vite/index.test.ts +++ b/packages/remix/test/vite/index.test.ts @@ -32,14 +32,14 @@ type CapturedSentryOptions = { applicationKey?: string; bundleSizeOptimizations?: { excludeTracing?: boolean }; release?: { name?: string; inject?: boolean }; - sourcemaps?: { deleteSourcemapsAfterUpload?: boolean | (() => boolean | undefined) }; + sourcemaps?: { sdkDeleteSourceMaps?: boolean | (() => boolean | undefined) }; }; let capturedSentryOptions: CapturedSentryOptions | undefined; let deleteOptionInConfigHook: boolean | undefined | 'not called'; function getDeleteOption(): boolean | undefined { - const value = capturedSentryOptions?.sourcemaps?.deleteSourcemapsAfterUpload; + const value = capturedSentryOptions?.sourcemaps?.sdkDeleteSourceMaps; return typeof value === 'function' ? value() : value; } diff --git a/packages/remix/test/vite/sourceMaps.test.ts b/packages/remix/test/vite/sourceMaps.test.ts index 3e2dd7796461..98c43209b572 100644 --- a/packages/remix/test/vite/sourceMaps.test.ts +++ b/packages/remix/test/vite/sourceMaps.test.ts @@ -193,7 +193,7 @@ describe('makeAddSentryVitePlugin', () => { }); function getDeleteOption(): boolean | undefined { - const value = capturedOptions?.sourcemaps?.deleteSourcemapsAfterUpload; + const value = capturedOptions?.sourcemaps?.sdkDeleteSourceMaps; return typeof value === 'function' ? value() : value; } @@ -230,11 +230,12 @@ describe('makeAddSentryVitePlugin', () => { }); it.each([{ delete: true }, { delete: false, deleteSourcemapsAfterUpload: true }] as const)( - 'passes no `deleteSourcemapsAfterUpload` with %j', + 'passes no `deleteSourcemapsAfterUpload` and no `sdkDeleteSourceMaps` with %j', sourcemaps => { makeAddSentryVitePlugin({ sourcemaps }, { sdkEnabledSourceMaps: true }); expect(capturedOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); + expect(capturedOptions?.sourcemaps?.sdkDeleteSourceMaps).toBeUndefined(); }, ); @@ -246,6 +247,7 @@ describe('makeAddSentryVitePlugin', () => { (value, sdkEnabledSourceMaps, expected) => { makeAddSentryVitePlugin({ sourcemaps: { deleteSourcemapsAfterUpload: value } }, { sdkEnabledSourceMaps }); + expect(capturedOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); expect(getDeleteOption()).toBe(expected); }, ); @@ -259,14 +261,4 @@ describe('makeAddSentryVitePlugin', () => { expect(getDeleteOption()).toBeUndefined(); }, ); - - it('tells the bundler plugin whether the SDK enabled the source maps', () => { - const state: SourceMapState = { sdkEnabledSourceMaps: false }; - makeAddSentryVitePlugin({}, state); - const sdkEnabled = capturedOptions?.sourcemaps?.sdkEnabledSourceMaps as () => boolean; - - expect(sdkEnabled()).toBe(false); - state.sdkEnabledSourceMaps = true; - expect(sdkEnabled()).toBe(true); - }); }); diff --git a/packages/server-utils/src/ai/flue/types.ts b/packages/server-utils/src/ai/flue/types.ts index 651aaa730c84..3f5a896320e2 100644 --- a/packages/server-utils/src/ai/flue/types.ts +++ b/packages/server-utils/src/ai/flue/types.ts @@ -18,9 +18,9 @@ export interface FlueErrorInfo { } /** - * One event from Flue's observation stream. Only the fields we read are declared, but the index - * signature keeps the rest visible to `recordInputs`/`recordOutputs`. Flue emits more event types - * than are handled here, and unknown types are ignored. + * One event from Flue's observation stream. Only the fields we read are declared, and none of these + * types carry an index signature, because Flue's own types have none and would not be assignable. + * Flue emits more event types than are handled here, and unknown types are ignored. */ export interface FlueObservation { type: string; @@ -39,7 +39,6 @@ export interface FlueObservation { result?: unknown; /** The tool result as the model sees it, on successful `tool` events. */ effectiveResult?: unknown; - [key: string]: unknown; } /** The execution unit an interceptor wraps. */ @@ -48,7 +47,6 @@ export interface FlueExecutionOperation { operationId?: string; operationKind?: string; toolCallId?: string; - [key: string]: unknown; } /** Mirrors `FlueTraceCarrier` — the W3C headers Flue persists at admission. */ @@ -64,12 +62,10 @@ export interface FlueExecutionContext { conversationId?: string; session?: string; taskId?: string; - [key: string]: unknown; } export interface FlueEventContext { - agentName?: string; - [key: string]: unknown; + agentName?: string | undefined; } /** The object `instrument()` accepts. */ diff --git a/packages/solid/src/solid2/index.worker.ts b/packages/solid/src/solid2/index.worker.ts index c23682861c40..b9a10586c96d 100644 --- a/packages/solid/src/solid2/index.worker.ts +++ b/packages/solid/src/solid2/index.worker.ts @@ -2,3 +2,4 @@ export * from './client'; export { solidServerErrorsIntegration } from './server/errors'; export { solidServerTracePropagationIntegration } from './server/tracePropagation'; +export { solidServerObserveIntegration } from './server/observe'; diff --git a/packages/solid/src/solid2/server/cloudflare.ts b/packages/solid/src/solid2/server/cloudflare.ts index 88fcae00b71f..905b606e68af 100644 --- a/packages/solid/src/solid2/server/cloudflare.ts +++ b/packages/solid/src/solid2/server/cloudflare.ts @@ -3,6 +3,7 @@ import { addServerTimingTraceHeader, defineCloudflareOptions as defineCloudflare import type { Integration } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, defineIntegration } from '@sentry/core'; import { solidServerErrorsIntegration } from './errors'; +import { solidServerObserveIntegration } from './observe'; import { solidServerTracePropagationIntegration } from './tracePropagation'; // Sends the trace to the browser on every document response, so the pageload continues it, as `init` does on Node. @@ -48,6 +49,7 @@ export const defineCloudflareOptions: typeof defineCloudflareOptionsBase = ( ...defaults, solidServerErrorsIntegration(), solidServerTracePropagationIntegration(), + solidServerObserveIntegration(), serverTimingTraceHeaderIntegration(), ]; return typeof userIntegrations === 'function' diff --git a/packages/solid/src/solid2/server/index.ts b/packages/solid/src/solid2/server/index.ts index 665e85362c4b..88c082ff64f6 100644 --- a/packages/solid/src/solid2/server/index.ts +++ b/packages/solid/src/solid2/server/index.ts @@ -3,3 +3,4 @@ export * from '@sentry/node'; export { init, getDefaultIntegrations } from './sdk'; export { solidServerErrorsIntegration } from './errors'; export { solidServerTracePropagationIntegration } from './tracePropagation'; +export { solidServerObserveIntegration } from './observe'; diff --git a/packages/solid/src/solid2/server/observe.ts b/packages/solid/src/solid2/server/observe.ts new file mode 100644 index 000000000000..4740f1acfeef --- /dev/null +++ b/packages/solid/src/solid2/server/observe.ts @@ -0,0 +1,110 @@ +import { + CODE_FUNCTION_NAME, + HTTP_REQUEST_METHOD, + HTTP_ROUTE, + SENTRY_OP, + SENTRY_ORIGIN, + SENTRY_SEGMENT_NAME_SOURCE, + URL_PATH_PARAMETER_KEY_BASE, +} from '@sentry/conventions/attributes'; +import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op'; +import { + _INTERNAL_performanceTimeToSeconds as performanceTimeToSeconds, + defineIntegration, + getActiveSpan, + getDefaultIsolationScope, + getIsolationScope, + getRootSpan, + SPAN_STATUS_ERROR, + spanToJSON, + // The rule counts all of `@sentry/solid` as browser code, but this module only runs on the server. + // oxlint-disable-next-line sdk/no-unguarded-span-apis + startInactiveSpan, + updateSpanName, +} from '@sentry/core'; +import type { InvocationEvent, RenderEvent } from '@solidjs/web'; +import { OBSERVE } from 'solid-js'; + +const INTEGRATION_NAME = 'SolidServerObserve'; + +/** A span for a server function execution, under the span of the request or render that ran it. */ +function recordInvocationSpan({ id, at, durationMs, outcome }: InvocationEvent): void { + // Record times are `performance.now()` values. Without a usable time origin, the span cannot be placed. + const startTime = performanceTimeToSeconds(at); + const endTime = performanceTimeToSeconds(at + durationMs, at); + if (startTime === undefined || endTime === undefined) { + return; + } + + const span = startInactiveSpan({ + name: id, + startTime, + onlyIfParent: true, + attributes: { + [SENTRY_OP]: FUNCTION, + [SENTRY_ORIGIN]: 'auto.function.solid.server_function', + [CODE_FUNCTION_NAME]: id, + }, + }); + if (outcome === 'error') { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + } + span.end(endTime); +} + +/** + * Names the `http.server` span after the route the router declared for the render, e.g. `GET /user/:id`, unless it + * is named after a route already (by `withSentryRouterRouting`). + */ +function nameRequestAfterRenderRoute({ route }: RenderEvent): void { + const activeSpan = getActiveSpan(); + // Without a matching route, the router reports the raw path as `name` and no `params`. + if (!route?.name || !route.params || !activeSpan) { + return; + } + + const rootSpan = getRootSpan(activeSpan); + const { attributes } = spanToJSON(rootSpan); + if ( + attributes?.[SENTRY_OP] !== HTTP_SERVER || + attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || + !rootSpan.isRecording() + ) { + return; + } + + const method = attributes[HTTP_REQUEST_METHOD]; + const name = `${typeof method === 'string' ? method : 'GET'} ${route.name}`; + updateSpanName(rootSpan, name); + rootSpan.setAttributes({ + [HTTP_ROUTE]: route.name, + [SENTRY_SEGMENT_NAME_SOURCE]: 'route', + }); + for (const [key, value] of Object.entries(route.params ?? {})) { + if (typeof value === 'string') { + rootSpan.setAttribute(`${URL_PATH_PARAMETER_KEY_BASE}.${key}`, value); + } + } + + // Outside a request, the isolation scope is shared by the whole process. + const isolationScope = getIsolationScope(); + if (isolationScope !== getDefaultIsolationScope()) { + isolationScope.setTransactionName(name); + } +} + +/** + * Turns the records of Solid's observe and dev builds into Sentry data: a span for every server function execution, + * and the route of a render as the name of its request span, with any router. Production builds have no records, so + * this does nothing there. + */ +export const solidServerObserveIntegration = defineIntegration(() => { + return { + name: INTEGRATION_NAME, + setup() { + // Solid keeps one entry per listener function, so a client set up per request on Workers adds no duplicates. + OBSERVE?.records.subscribe('invocation', recordInvocationSpan); + OBSERVE?.records.subscribe('render', nameRequestAfterRenderRoute); + }, + }; +}); diff --git a/packages/solid/src/solid2/server/sdk.ts b/packages/solid/src/solid2/server/sdk.ts index 19b0bfd14569..6169f51f2b89 100644 --- a/packages/solid/src/solid2/server/sdk.ts +++ b/packages/solid/src/solid2/server/sdk.ts @@ -7,6 +7,7 @@ import { init as initNodeSdk, } from '@sentry/node'; import { solidServerErrorsIntegration } from './errors'; +import { solidServerObserveIntegration } from './observe'; import { solidServerTracePropagationIntegration } from './tracePropagation'; /** @@ -34,5 +35,6 @@ export function getDefaultIntegrations(options: NodeOptions): Integration[] { ...getNodeDefaultIntegrations(options), solidServerErrorsIntegration(), solidServerTracePropagationIntegration(), + solidServerObserveIntegration(), ]; } diff --git a/packages/solid/test/solid2/server/observe.test.ts b/packages/solid/test/solid2/server/observe.test.ts new file mode 100644 index 000000000000..c3bf0a388bfb --- /dev/null +++ b/packages/solid/test/solid2/server/observe.test.ts @@ -0,0 +1,179 @@ +import { + CODE_FUNCTION_NAME, + HTTP_REQUEST_METHOD, + HTTP_ROUTE, + SENTRY_OP, + SENTRY_ORIGIN, + SENTRY_SEGMENT_NAME_SOURCE, + URL_PATH_PARAMETER_KEY_BASE, +} from '@sentry/conventions/attributes'; +import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op'; +import type { StreamedSpanJSON } from '@sentry/core'; +import { + createTransport, + getIsolationScope, + setCurrentClient, + spanToJSON, + startSpan, + startSpanManual, + withIsolationScope, +} from '@sentry/core'; +import { NodeClient } from '@sentry/node'; +import type { InvocationEvent, RenderEvent } from '@solidjs/web'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { solidServerObserveIntegration } from '../../../src/solid2/server'; + +type Listener = (event: unknown, live: unknown) => void; + +const { listeners } = vi.hoisted(() => ({ listeners: new Map() })); + +// The production build has no `OBSERVE`; observe and dev builds do. +vi.mock('solid-js', async importOriginal => ({ + ...(await importOriginal()), + OBSERVE: { + records: { + subscribe: (type: string, listener: Listener) => { + listeners.set(type, listener); + return () => listeners.delete(type); + }, + }, + }, +})); + +function emit(type: 'invocation', event: InvocationEvent): void; +function emit(type: 'render', event: RenderEvent): void; +function emit(type: string, event: unknown): void { + listeners.get(type)?.(event, {}); +} + +describe('solidServerObserveIntegration', () => { + let ended: StreamedSpanJSON[]; + + beforeEach(() => { + listeners.clear(); + ended = []; + const client = new NodeClient({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + integrations: [], + transport: () => createTransport({ recordDroppedEvent: () => undefined }, _ => Promise.resolve({})), + stackParser: () => [], + }); + setCurrentClient(client); + client.init(); + client.on('spanEnd', span => { + ended.push(spanToJSON(span)); + }); + solidServerObserveIntegration().setup!(client); + }); + + describe('server function executions', () => { + it('adds a span under the active span, with the recorded timing', () => { + const at = performance.now() - 50; + + const parentSpanId = startSpan({ name: 'POST /_server' }, span => { + emit('invocation', { id: 'src/api.ts#getUser', direct: false, at, durationMs: 20, outcome: 'ok' }); + return span.spanContext().spanId; + }); + + const span = ended.find(one => one.name === 'src/api.ts#getUser'); + expect(span).toMatchObject({ + parent_span_id: parentSpanId, + status: 'ok', + attributes: expect.objectContaining({ + [SENTRY_OP]: FUNCTION, + [SENTRY_ORIGIN]: 'auto.function.solid.server_function', + [CODE_FUNCTION_NAME]: 'src/api.ts#getUser', + }), + }); + expect(span?.start_timestamp).toBeCloseTo((performance.timeOrigin + at) / 1000, 3); + expect(span?.end_timestamp).toBeCloseTo((performance.timeOrigin + at + 20) / 1000, 3); + }); + + it('marks a failed execution', () => { + startSpan({ name: 'POST /_server' }, () => { + emit('invocation', { id: 'fail', direct: false, at: performance.now(), durationMs: 1, outcome: 'error' }); + }); + + expect(ended.find(one => one.name === 'fail')?.status).toBe('error'); + }); + + it('adds no span outside a request', () => { + emit('invocation', { id: 'orphan', direct: false, at: performance.now(), durationMs: 1, outcome: 'ok' }); + + expect(ended).toEqual([]); + }); + }); + + describe('render routes', () => { + const render = (route?: RenderEvent['route']): RenderEvent => ({ + mode: 'stream', + at: performance.now(), + durationMs: 1, + boundaries: 0, + outcome: 'complete', + route, + }); + + it('names the request span after the route of the render', () => { + withIsolationScope(() => { + startSpanManual( + { name: 'GET /user/5', op: HTTP_SERVER, attributes: { [HTTP_REQUEST_METHOD]: 'GET' } }, + span => { + emit('render', render({ name: '/user/:id', to: '/user/5', params: { id: '5' } })); + + expect(spanToJSON(span)).toMatchObject({ + name: 'GET /user/:id', + attributes: expect.objectContaining({ + [HTTP_ROUTE]: '/user/:id', + [SENTRY_SEGMENT_NAME_SOURCE]: 'route', + [`${URL_PATH_PARAMETER_KEY_BASE}.id`]: '5', + }), + }); + expect(getIsolationScope().getScopeData().transactionName).toBe('GET /user/:id'); + span.end(); + }, + ); + }); + }); + + it('keeps a name the router wrapper set', () => { + startSpanManual( + { name: 'GET /user/:userId', op: HTTP_SERVER, attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: 'route' } }, + span => { + emit('render', render({ name: '/user/:id', params: {} })); + + expect(spanToJSON(span).name).toBe('GET /user/:userId'); + span.end(); + }, + ); + }); + + it('leaves other spans alone', () => { + startSpanManual({ name: 'some work', op: FUNCTION }, span => { + emit('render', render({ name: '/user/:id', params: {} })); + + expect(spanToJSON(span).name).toBe('some work'); + span.end(); + }); + }); + + it('keeps the name when no route matched', () => { + startSpanManual({ name: 'GET /missing', op: HTTP_SERVER }, span => { + emit('render', render({ name: '/missing', to: '/missing' })); + + expect(spanToJSON(span).name).toBe('GET /missing'); + span.end(); + }); + }); + + it('does nothing without a route', () => { + startSpanManual({ name: 'GET /user/5', op: HTTP_SERVER }, span => { + emit('render', render()); + + expect(spanToJSON(span).name).toBe('GET /user/5'); + span.end(); + }); + }); + }); +}); diff --git a/packages/solidstart/src/vite/sourceMaps.ts b/packages/solidstart/src/vite/sourceMaps.ts index ce621b78adb8..d57460ecf249 100644 --- a/packages/solidstart/src/vite/sourceMaps.ts +++ b/packages/solidstart/src/vite/sourceMaps.ts @@ -25,24 +25,21 @@ export type SourceMapState = { type SourceMapsOptions = SentrySolidStartPluginOptions['sourcemaps']; /** - * The bundler plugin calls these when it decides, after `makeEnableSourceMapsVitePlugin` ran. - * It passes the name of an environment with its own `build.sourcemap`, and `undefined` for the + * The bundler plugin calls `sdkDeleteSourceMaps` when it decides, after `makeEnableSourceMapsVitePlugin` + * ran. It passes the name of an environment with its own `build.sourcemap`, and `undefined` for the * top-level setting. The SDK only turns on the top-level maps: Nitro's environments get their * setting from Nitro, and `@sentry/nitro` handles their maps. * * With `keepWhenUploadDisabled`, maps the SDK turned on stay with `disable: 'disable-upload'`. * A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. - * - * With `sourcemaps.delete` the bundler plugin ignores `deleteSourcemapsAfterUpload` and warns if - * the user set it, so it only gets the user's value then. */ function makeSourceMapDeletionOptions( sourcemaps: SourceMapsOptions, state: SourceMapState, { keepWhenUploadDisabled }: { keepWhenUploadDisabled: boolean }, ): { - deleteSourcemapsAfterUpload: boolean | undefined | ((environment?: string) => boolean | undefined); - sdkEnabledSourceMaps: (environment?: string) => boolean; + deleteSourcemapsAfterUpload: boolean | undefined; + sdkDeleteSourceMaps: ((environment?: string) => boolean | undefined) | undefined; } { const sdkEnabledSourceMaps = (environment?: string): boolean => environment === undefined && state.sdkEnabledSourceMaps; @@ -51,17 +48,16 @@ function makeSourceMapDeletionOptions( const keepSdkEnabledSourceMaps = keepWhenUploadDisabled && !!resolveSourceMapsFeatures(sourcemaps).legacyDisable; return { - deleteSourcemapsAfterUpload: - sourcemaps?.delete !== undefined - ? sourcemaps.deleteSourcemapsAfterUpload - : environment => - sourcemaps?.deleteSourcemapsAfterUpload ?? - (sdkEnabledSourceMaps(environment) && + deleteSourcemapsAfterUpload: sourcemaps?.deleteSourcemapsAfterUpload, + sdkDeleteSourceMaps: + sourcemaps?.delete === undefined + ? environment => + sdkEnabledSourceMaps(environment) && !keepSdkEnabledSourceMaps && sourcemaps?.filesToDeleteAfterUpload === undefined ? true - : undefined), - sdkEnabledSourceMaps, + : undefined + : undefined, }; } @@ -243,7 +239,7 @@ export function makeEnableSourceMapsVitePlugin( * 3. Users didn't set source maps generation * - we enable 'hidden' source maps generation when Sentry uploads the maps, or when * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset - * - without `sourcemaps.delete` we pass `deleteSourcemapsAfterUpload: true`, so the maps never + * - without `sourcemaps.delete` we pass `sdkDeleteSourceMaps: true`, so the maps never * reach the build output * * --> only exported for testing diff --git a/packages/solidstart/test/vite/sourceMaps.test.ts b/packages/solidstart/test/vite/sourceMaps.test.ts index 05544278e713..80ce599feb83 100644 --- a/packages/solidstart/test/vite/sourceMaps.test.ts +++ b/packages/solidstart/test/vite/sourceMaps.test.ts @@ -15,7 +15,7 @@ import { let lastPluginOptions: SentryVitePluginInternalOptions | undefined; /** What the options returned when the mocked Sentry plugin's `config` hook ran. */ -let optionsAtSentryConfigHook: { deletion?: boolean; sdkEnabled?: boolean } | undefined; +let optionsAtSentryConfigHook: { deletion?: boolean; sdkDelete?: boolean } | undefined; const sentryVitePluginSpy = vi.fn((options: SentryVitePluginInternalOptions): Plugin[] => { lastPluginOptions = options; @@ -23,7 +23,7 @@ const sentryVitePluginSpy = vi.fn((options: SentryVitePluginInternalOptions): Pl { name: 'sentry-vite-debug-id-upload-plugin', config() { - optionsAtSentryConfigHook = { deletion: getDeleteOption(), sdkEnabled: getSdkEnabledOption() }; + optionsAtSentryConfigHook = { deletion: getDeleteOption(), sdkDelete: getSdkDeleteOption() }; }, }, ]; @@ -44,13 +44,13 @@ function runConfigHooks(plugins: Plugin[], config: UserConfig): UserConfig { return config; } +/** The plugin's delete value without `sourcemaps.delete`: the user's value wins over the SDK's. */ function getDeleteOption(environment?: string): boolean | undefined { - const value = lastPluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload; - return typeof value === 'function' ? value(environment) : value; + return lastPluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload ?? getSdkDeleteOption(environment); } -function getSdkEnabledOption(environment?: string): boolean | undefined { - const value = lastPluginOptions?.sourcemaps?.sdkEnabledSourceMaps; +function getSdkDeleteOption(environment?: string): boolean | undefined { + const value = lastPluginOptions?.sourcemaps?.sdkDeleteSourceMaps; return typeof value === 'function' ? value(environment) : value; } @@ -147,8 +147,8 @@ describe('makeAddSentryVitePlugin()', () => { moduleMetadata: { team: 'sdk' }, sourcemaps: { filesToDeleteAfterUpload: ['baz/*.js'], - deleteSourcemapsAfterUpload: expect.any(Function), - sdkEnabledSourceMaps: expect.any(Function), + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: expect.any(Function), }, bundleSizeOptimizations: { excludeTracing: true, @@ -305,14 +305,13 @@ describe.each([ // Nitro gives its environments their own `build.sourcemap`, and `@sentry/nitro` reads those // maps after the build. it.each([ - [undefined, true, true], - ['nitro', undefined, false], - ['ssr', undefined, false], - ])('answers for the `%s` environment', (environment, deletion, sdkEnabled) => { + [undefined, true], + ['nitro', undefined], + ['ssr', undefined], + ])('answers for the `%s` environment', (environment, deletion) => { makePlugin({}, { sdkEnabledSourceMaps: true }); - expect(getDeleteOption(environment)).toBe(deletion); - expect(getSdkEnabledOption(environment)).toBe(sdkEnabled); + expect(getSdkDeleteOption(environment)).toBe(deletion); }); it.each([undefined, 'nitro', 'ssr'])( @@ -329,10 +328,9 @@ describe.each([ const state: SourceMapState = { sdkEnabledSourceMaps: false }; makePlugin({ sourcemaps: { assets: ['./dist/client/**'] } }, state); - expect(getSdkEnabledOption()).toBe(false); + expect(getSdkDeleteOption()).toBeUndefined(); state.sdkEnabledSourceMaps = true; - expect(getSdkEnabledOption()).toBe(true); - expect(getDeleteOption()).toBe(true); + expect(getSdkDeleteOption()).toBe(true); }); }); @@ -368,8 +366,7 @@ describe.each([ it('makeAddSentryVitePlugin() asks for deletion when only the upload is disabled', () => { makeAddSentryVitePlugin({ sourcemaps: { disable: 'disable-upload' } }, { sdkEnabledSourceMaps: true }); - expect(getDeleteOption()).toBe(true); - expect(getSdkEnabledOption()).toBe(true); + expect(getSdkDeleteOption()).toBe(true); }); it('makeAddSentryVitePluginSolidStart2() keeps the source maps when only the upload is disabled', () => { @@ -395,14 +392,14 @@ describe.each([ const config = runConfigHooks(getPlugins(), { ...vinxiClientConfig }); expect(config.build?.sourcemap).toBe('hidden'); - expect(optionsAtSentryConfigHook).toEqual({ deletion: true, sdkEnabled: true }); + expect(optionsAtSentryConfigHook).toEqual({ deletion: true, sdkDelete: true }); }); it('keeps source maps the user enabled', () => { const config = runConfigHooks(getPlugins(), { ...vinxiClientConfig, build: { sourcemap: 'hidden' } }); expect(config.build?.sourcemap).toBe('hidden'); - expect(optionsAtSentryConfigHook).toEqual({ deletion: undefined, sdkEnabled: false }); + expect(optionsAtSentryConfigHook).toEqual({ deletion: undefined, sdkDelete: undefined }); }); }); diff --git a/packages/sveltekit/src/vite/sourceMaps.ts b/packages/sveltekit/src/vite/sourceMaps.ts index 573bbbad603c..b1f22b11a4b9 100644 --- a/packages/sveltekit/src/vite/sourceMaps.ts +++ b/packages/sveltekit/src/vite/sourceMaps.ts @@ -61,9 +61,7 @@ export async function makeCustomSentryVitePlugins( warnOnConflictingSourceMapOptions(options?.sourcemaps); const defaultPluginOptions: SentryVitePluginOptions = { - release: { - name: releaseName, - }, + release: { name: releaseName }, _metaOptions: { telemetry: { metaFramework: 'sveltekit', @@ -90,7 +88,8 @@ export async function makeCustomSentryVitePlugins( filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, // The adapter runs after the bundler and still needs the source maps, so // the SDK deletes them from disk afterwards instead of the plugin. - deleteSourcemapsAfterUpload: false, + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: false, delete: undefined, }, }; diff --git a/packages/sveltekit/test/vite/sourceMaps.test.ts b/packages/sveltekit/test/vite/sourceMaps.test.ts index f7d94632508d..f162821fc5ae 100644 --- a/packages/sveltekit/test/vite/sourceMaps.test.ts +++ b/packages/sveltekit/test/vite/sourceMaps.test.ts @@ -483,7 +483,11 @@ describe('source map deletion with `sourcemaps.delete`', () => { // @ts-expect-error this function exists! await deletionPlugin.configResolved(); - expect(mergedOptions.sourcemaps).toMatchObject({ deleteSourcemapsAfterUpload: false, delete: undefined }); + expect(mergedOptions.sourcemaps).toMatchObject({ + deleteSourcemapsAfterUpload: undefined, + sdkDeleteSourceMaps: false, + delete: undefined, + }); return mergedOptions.sourcemaps?.filesToDeleteAfterUpload; } @@ -620,7 +624,7 @@ describe('deleteFilesAfterUpload', () => { }, sourcemaps: { filesToDeleteAfterUpload: expect.any(Promise), - deleteSourcemapsAfterUpload: false, + sdkDeleteSourceMaps: false, }, }); @@ -700,7 +704,7 @@ describe('deleteFilesAfterUpload', () => { }, sourcemaps: { filesToDeleteAfterUpload: expect.any(Promise), - deleteSourcemapsAfterUpload: false, + sdkDeleteSourceMaps: false, }, }); diff --git a/packages/tanstackstart-react/src/vite/autoInstrumentMiddleware.ts b/packages/tanstackstart-react/src/vite/autoInstrumentMiddleware.ts index 266653f90a36..77126b86dec5 100644 --- a/packages/tanstackstart-react/src/vite/autoInstrumentMiddleware.ts +++ b/packages/tanstackstart-react/src/vite/autoInstrumentMiddleware.ts @@ -105,8 +105,8 @@ export function makeAutoInstrumentMiddlewarePlugin(options: AutoInstrumentMiddle return null; } - // Skip if not a TS/JS file - if (!/\.(ts|tsx|js|jsx|mjs|mts)$/.test(id)) { + // Skip if not a TS/JS file. The id can end in a query, e.g. the server function module `foo.tsx?tss-serverfn-split`. + if (!/\.(ts|tsx|js|jsx|mjs|mts)$/.test(id.split('?')[0] ?? id)) { return null; } diff --git a/packages/tanstackstart-react/src/vite/sourceMaps.ts b/packages/tanstackstart-react/src/vite/sourceMaps.ts index cc61338d7c5b..821747431589 100644 --- a/packages/tanstackstart-react/src/vite/sourceMaps.ts +++ b/packages/tanstackstart-react/src/vite/sourceMaps.ts @@ -109,11 +109,10 @@ export function makeAddSentryVitePlugin( // Called when the bundler plugin decides, after the SDK's enable plugins ran. // The SDK never read the user's `deleteSourcemapsAfterUpload`. `delete` replaces it. // A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. - deleteSourcemapsAfterUpload: + sdkDeleteSourceMaps: sourcemaps?.delete === undefined && sourcemaps?.filesToDeleteAfterUpload === undefined ? environment => hasSdkEnabledSourceMaps(state, environment) || undefined : undefined, - sdkEnabledSourceMaps: environment => hasSdkEnabledSourceMaps(state, environment), }, reactComponentAnnotation: { enabled: reactComponentAnnotation?.enabled ?? undefined, @@ -169,7 +168,7 @@ export function makeEnableSourceMapsVitePlugin( * 3. Users didn't set source maps generation * - we enable 'hidden' source maps generation when Sentry can upload them, or when `sourcemaps.delete: false` * keeps them for a manual upload - * - without `sourcemaps.delete` we pass `deleteSourcemapsAfterUpload: true`, so the bundler plugin removes + * - without `sourcemaps.delete` we pass `sdkDeleteSourceMaps: true`, so the bundler plugin removes * these .map files from the build output * * @internal Only exported for testing. diff --git a/packages/tanstackstart-react/test/vite/autoInstrumentMiddleware.test.ts b/packages/tanstackstart-react/test/vite/autoInstrumentMiddleware.test.ts index 7a58fa3237e4..27e1109c09c8 100644 --- a/packages/tanstackstart-react/test/vite/autoInstrumentMiddleware.test.ts +++ b/packages/tanstackstart-react/test/vite/autoInstrumentMiddleware.test.ts @@ -71,6 +71,25 @@ createStart(() => ({ requestMiddleware: wrapMiddlewaresWithSentry({ myMiddleware expect(result!.code).toContain("import { wrapMiddlewaresWithSentry } from '@sentry/tanstackstart-react'"); }); + it('instruments server function middlewares in a module whose id ends in a query', () => { + const plugin = makeAutoInstrumentMiddlewarePlugin() as PluginWithTransform; + const code = ` +import { createServerFn } from '@tanstack/react-start'; +const serverFn = createServerFn().middleware([authMiddleware]).handler(async () => ({})); +`; + const result = plugin.transform(code, '/app/routes/foo.tsx?tss-serverfn-split'); + + expect(result).not.toBeNull(); + expect(result!.code).toContain('.middleware(wrapMiddlewaresWithSentry({ authMiddleware }))'); + }); + + it('does not instrument non-TS/JS files whose id ends in a query', () => { + const plugin = makeAutoInstrumentMiddlewarePlugin() as PluginWithTransform; + const result = plugin.transform(createStartFile, '/app/start.css?direct'); + + expect(result).toBeNull(); + }); + it('instruments both start files and route files', () => { const plugin = makeAutoInstrumentMiddlewarePlugin() as PluginWithTransform; diff --git a/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts b/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts index 7d9230016013..8e10e0e62cca 100644 --- a/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts +++ b/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts @@ -120,18 +120,14 @@ function build({ /** * Mirrors the decision of the bundler plugin: it passes the name of an environment with its own `build.sourcemap` to - * the function options. It removes the maps of an output with its own `sourcemap` if they are hidden, or if - * `sdkEnabledSourceMaps` is true and they are not inline. + * `sdkDeleteSourceMaps`. It removes the maps of an output with its own `sourcemap` if they are hidden, or if + * `sdkDeleteSourceMaps` is true and they are not inline. */ function isDeletedByBundlerPlugin(userConfig: UserConfig, name: string, build: BuildEnvironmentOptions): boolean { const environment = userConfig.environments?.[name]?.build?.sourcemap !== undefined ? name : undefined; - const { deleteSourcemapsAfterUpload, sdkEnabledSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; - const deleteOption = - typeof deleteSourcemapsAfterUpload === 'function' - ? deleteSourcemapsAfterUpload(environment) - : deleteSourcemapsAfterUpload; - const sdkEnabled = - typeof sdkEnabledSourceMaps === 'function' ? sdkEnabledSourceMaps(environment) : sdkEnabledSourceMaps; + const { deleteSourcemapsAfterUpload, sdkDeleteSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; + const sdkDelete = typeof sdkDeleteSourceMaps === 'function' ? sdkDeleteSourceMaps(environment) : sdkDeleteSourceMaps; + const deleteOption = deleteSourcemapsAfterUpload ?? sdkDelete; const outputSourceMap = getOwnOutputSourceMapSetting(build); if (deleteOption !== true) { return false; @@ -139,7 +135,7 @@ function isDeletedByBundlerPlugin(userConfig: UserConfig, name: string, build: B if (outputSourceMap === undefined) { return build.sourcemap !== false; } - return outputSourceMap === 'hidden' || (sdkEnabled === true && outputSourceMap === true); + return outputSourceMap === 'hidden' || (sdkDelete === true && outputSourceMap === true); } describe('source map scenarios of a build with Nitro', () => { diff --git a/packages/tanstackstart-react/test/vite/sourceMaps.test.ts b/packages/tanstackstart-react/test/vite/sourceMaps.test.ts index a10bc169cc57..271651ebb24c 100644 --- a/packages/tanstackstart-react/test/vite/sourceMaps.test.ts +++ b/packages/tanstackstart-react/test/vite/sourceMaps.test.ts @@ -213,27 +213,20 @@ describe('makeAddSentryVitePlugin()', () => { }, ); - describe('deleteSourcemapsAfterUpload', () => { - /** Calls the function options like the bundler plugin, which passes an environment with its own setting. */ - function decide(environment?: string) { - const { deleteSourcemapsAfterUpload, sdkEnabledSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; - return { - delete: - typeof deleteSourcemapsAfterUpload === 'function' - ? deleteSourcemapsAfterUpload(environment) - : deleteSourcemapsAfterUpload, - sdkEnabled: - typeof sdkEnabledSourceMaps === 'function' ? sdkEnabledSourceMaps(environment) : sdkEnabledSourceMaps, - }; + describe('sdkDeleteSourceMaps', () => { + /** Calls the option like the bundler plugin, which passes an environment with its own setting. */ + function decide(environment?: string): boolean | undefined { + const { sdkDeleteSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; + return typeof sdkDeleteSourceMaps === 'function' ? sdkDeleteSourceMaps(environment) : sdkDeleteSourceMaps; } it('reads the state when the bundler plugin decides, not when the plugin is created', () => { const state = createSourceMapState(); makeAddSentryVitePlugin({}, state); - expect(decide()).toEqual({ delete: undefined, sdkEnabled: false }); + expect(decide()).toBeUndefined(); state.sdkEnabledSourceMaps = true; - expect(decide()).toEqual({ delete: true, sdkEnabled: true }); + expect(decide()).toBe(true); }); it.each([ @@ -260,19 +253,14 @@ describe('makeAddSentryVitePlugin()', () => { ])('asks for deletion of the source maps the SDK enabled when $label', ({ state, expected }) => { makeAddSentryVitePlugin({}, state); - expect({ top: decide().delete, ssr: decide('ssr').delete, nitro: decide('nitro').delete }).toEqual(expected); - expect({ - top: decide().sdkEnabled, - ssr: decide('ssr').sdkEnabled, - nitro: decide('nitro').sdkEnabled, - }).toEqual({ top: expected.top === true, ssr: false, nitro: expected.nitro === true }); + expect({ top: decide(), ssr: decide('ssr'), nitro: decide('nitro') }).toEqual(expected); }); // A client environment with its own setting was set by the user, because the SDK sets only the top level. it('keeps the source maps of an environment that the user configured', () => { makeAddSentryVitePlugin({}, { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }); - expect(decide('client')).toEqual({ delete: undefined, sdkEnabled: false }); + expect(decide('client')).toBeUndefined(); }); it.each([ @@ -286,11 +274,8 @@ describe('makeAddSentryVitePlugin()', () => { { sdkEnabledSourceMaps: sdkEnabled, sdkEnabledNitroSourceMaps: sdkEnabled }, ); - expect([decide().delete, decide('ssr').delete, decide('nitro').delete]).toEqual([ - expected, - undefined, - expected, - ]); + expect(sentryVitePluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); + expect([decide(), decide('ssr'), decide('nitro')]).toEqual([expected, undefined, expected]); }, ); @@ -303,11 +288,12 @@ describe('makeAddSentryVitePlugin()', () => { }); it.each([{ delete: true }, { delete: false, deleteSourcemapsAfterUpload: true }] as const)( - 'passes no `deleteSourcemapsAfterUpload` with %j', + 'passes no `deleteSourcemapsAfterUpload` and no `sdkDeleteSourceMaps` with %j', sourcemaps => { makeAddSentryVitePlugin({ sourcemaps }, { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }); expect(sentryVitePluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); + expect(sentryVitePluginOptions?.sourcemaps?.sdkDeleteSourceMaps).toBeUndefined(); }, ); @@ -320,11 +306,7 @@ describe('makeAddSentryVitePlugin()', () => { ); expect(sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(files); - expect([decide().delete, decide('ssr').delete, decide('nitro').delete]).toEqual([ - undefined, - undefined, - undefined, - ]); + expect([decide(), decide('ssr'), decide('nitro')]).toEqual([undefined, undefined, undefined]); }, ); }); diff --git a/scripts/ci-unit-tests.ts b/scripts/ci-unit-tests.ts index c8475fe2b506..4620eb69dc2e 100644 --- a/scripts/ci-unit-tests.ts +++ b/scripts/ci-unit-tests.ts @@ -4,6 +4,7 @@ import * as path from 'path'; const UNIT_TEST_ENV = process.env.UNIT_TEST_ENV as 'node' | 'browser' | undefined; const RUN_AFFECTED = process.argv.includes('--affected'); +const BUILD_ONLY = process.argv.includes('--build-only'); const UNIT_TEST_SHARD = process.env.UNIT_TEST_SHARD; // These packages are tested separately in CI, so no need to run them here @@ -97,7 +98,11 @@ function runAllTests(ignorePackages: Set): void { .map(dep => `--exclude="${dep}"`) .join(' '); - run(`pnpm run test ${excludeFlags}`); + run( + BUILD_ONLY + ? `pnpm exec nx run-many -t build:transpile build:types ${excludeFlags}` + : `pnpm run test ${excludeFlags}`, + ); } /** @@ -106,14 +111,18 @@ function runAllTests(ignorePackages: Set): void { function runAffectedTests(ignorePackages: Set): void { const additionalArgs = process.argv .slice(2) - .filter(arg => arg !== '--affected') + .filter(arg => arg !== '--affected' && arg !== '--build-only') .join(' '); const excludeFlags = Array.from(ignorePackages) .map(dep => `--exclude="${dep}"`) .join(' '); - run(`pnpm run test:pr ${excludeFlags} ${additionalArgs}`); + run( + BUILD_ONLY + ? `pnpm exec nx affected -t build:transpile build:types ${excludeFlags} ${additionalArgs}` + : `pnpm run test:pr ${excludeFlags} ${additionalArgs}`, + ); } runTests(); diff --git a/warden.toml b/warden.toml index f5d73443fd83..a91172beeabf 100644 --- a/warden.toml +++ b/warden.toml @@ -8,6 +8,11 @@ version = 1 failOn = "high" reportOn = "medium" +# Max parallel code chunks Warden reviews per run, across all skills (default: 5). +# Ignored if the org config (https://github.com/getsentry/.github/blob/main/warden.toml) sets one. +[runner] +concurrency = 12 + [[skills]] name = "gha-security-review" remote = "getsentry/skills"