diff --git a/.agents/skills/bump-conventions/SKILL.md b/.agents/skills/bump-conventions/SKILL.md index 02a2f8dbe1d6..181859b2ee0a 100644 --- a/.agents/skills/bump-conventions/SKILL.md +++ b/.agents/skills/bump-conventions/SKILL.md @@ -50,7 +50,6 @@ After fixing, re-run `pnpm run build:dev` and confirm it passes before verifying ## 5. Final verification ```bash -pnpm run circularDepCheck pnpm run fix pnpm run test ``` diff --git a/.agents/skills/upgrade-dep/SKILL.md b/.agents/skills/upgrade-dep/SKILL.md index e8c88d65ab86..883ff7d743a7 100644 --- a/.agents/skills/upgrade-dep/SKILL.md +++ b/.agents/skills/upgrade-dep/SKILL.md @@ -44,7 +44,6 @@ pnpm install pnpm run build:dev pnpm run dedupe-deps:fix pnpm run fix -pnpm run circularDepCheck ``` ## Useful commands diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d12cda804156..32fab6f55b39 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,23 +1,19 @@ -**Why:** +## What -**How to review:** + -**Unsure about:** +## Why -Closes # + - +Closes: # diff --git a/.github/CODEOWNERS b/.github/REVIEWERS similarity index 92% rename from .github/CODEOWNERS rename to .github/REVIEWERS index 148f6bbb4695..e534da992d3d 100644 --- a/.github/CODEOWNERS +++ b/.github/REVIEWERS @@ -1,5 +1,7 @@ -# Catch-all rule for shared packages -* @getsentry/team-javascript-sdks-browser @getsentry/team-javascript-sdks-server @getsentry/team-javascript-sdks-framework +# Reviewer routing for scripts/assign-reviewers.mjs, in CODEOWNERS syntax. +# This is deliberately not a CODEOWNERS file: GitHub requests every matching +# code owner team as soon as a PR opens, before the workflow requests anyone, +# so the whole team gets notified. # Browser, replay, feedback, and related packages /packages/browser/ @getsentry/team-javascript-sdks-browser diff --git a/.github/actions/install-dependencies/action.yml b/.github/actions/install-dependencies/action.yml index 052da6857343..098f48c191a5 100644 --- a/.github/actions/install-dependencies/action.yml +++ b/.github/actions/install-dependencies/action.yml @@ -22,9 +22,7 @@ runs: id: cache_dependencies with: path: ${{ env.CACHED_DEPENDENCY_PATHS }} - key: - ${{ steps.compute_lockfile_hash.outputs.hash }}${{ runner.arch != 'X64' && format('-{0}', runner.arch) || '' - }} + key: ${{ steps.compute_lockfile_hash.outputs.hash }}-${{ runner.arch }} - name: Install dependencies if: steps.cache_dependencies.outputs.cache-hit != 'true' diff --git a/.github/actions/prepare-e2e-test/action.yml b/.github/actions/prepare-e2e-test/action.yml index 417877403d90..e7576ac001fc 100644 --- a/.github/actions/prepare-e2e-test/action.yml +++ b/.github/actions/prepare-e2e-test/action.yml @@ -9,6 +9,9 @@ inputs: runtime: description: 'The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md.' default: '' + bun-version: + description: 'The Bun version to install, if the application needs Bun.' + default: '1.3.14' deno-version: description: 'The Deno version to install, if the application needs Deno.' default: 'v2.8.3' @@ -25,16 +28,14 @@ runs: # Uses the repo's root node pin for the steps before the app is copied (installing pnpm, `test:prepare`, # `test:validate`, `ci:copy-to-temp`). The app's own node version is set up after the copy below. - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun if: inputs.test-application == 'node-exports-test-app' || contains(inputs.test-application, 'bun') || inputs.runtime == 'bun' uses: oven-sh/setup-bun@v2 with: - bun-version: '1.3.14' + bun-version: ${{ inputs.bun-version || '1.4.2' }} - name: Set up AWS SAM if: contains(inputs.test-application, 'aws-serverless') uses: aws-actions/setup-sam@v3 diff --git a/.github/actions/restore-cache/action.yml b/.github/actions/restore-cache/action.yml index 372def6a0a7e..4112ad39ee54 100644 --- a/.github/actions/restore-cache/action.yml +++ b/.github/actions/restore-cache/action.yml @@ -17,7 +17,7 @@ runs: uses: actions/cache/restore@v6.1.0 with: path: ${{ env.CACHED_DEPENDENCY_PATHS }} - key: ${{ inputs.dependency_cache_key }}${{ runner.arch != 'X64' && format('-{0}', runner.arch) || '' }} + key: ${{ inputs.dependency_cache_key }}-${{ runner.arch }} - name: Restore build artifacts uses: actions/download-artifact@v7 diff --git a/.github/actions/setup-node/action.yml b/.github/actions/setup-node/action.yml new file mode 100644 index 000000000000..77a4f3eb8db3 --- /dev/null +++ b/.github/actions/setup-node/action.yml @@ -0,0 +1,32 @@ +name: 'Set up Node' +description: 'Sets up the Node.js version of `devEngines.runtime` in the root package.json.' + +runs: + using: 'composite' + steps: + - name: Resolve Node.js version + id: node + run: sh "$GITHUB_ACTION_PATH/resolve-node.sh" + shell: sh + + # The runner images don't ship this exact version. Without the cache, `actions/setup-node` fetches its version + # manifest through the GitHub API in every job, which uses up the repository's `GITHUB_TOKEN` rate limit. + - name: Restore Node.js install + id: node-cache + uses: actions/cache/restore@v6.1.0 + with: + path: ${{ steps.node.outputs.cache-path }} + key: ${{ steps.node.outputs.cache-key }} + + - name: Set up Node + uses: actions/setup-node@v7 + with: + node-version: ${{ steps.node.outputs.version }} + + # Only `develop` saves, so PRs share one entry per architecture instead of each creating their own. + - name: Save Node.js install + if: steps.node-cache.outputs.cache-hit != 'true' && github.ref == 'refs/heads/develop' + uses: actions/cache/save@v6.1.0 + with: + path: ${{ steps.node.outputs.cache-path }} + key: ${{ steps.node.outputs.cache-key }} diff --git a/.github/actions/setup-node/resolve-node.sh b/.github/actions/setup-node/resolve-node.sh new file mode 100755 index 000000000000..a611890c4023 --- /dev/null +++ b/.github/actions/setup-node/resolve-node.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +version=$(jq -e -r '.devEngines.runtime.version' package.json) +cache_path="$RUNNER_TOOL_CACHE/node/$version" +cache_key="node-toolcache-$RUNNER_OS-$RUNNER_ARCH-$version" + +printf 'version=%s\ncache-path=%s\ncache-key=%s\n' "$version" "$cache_path" "$cache_key" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/assign-junior-prs.yml b/.github/workflows/assign-junior-prs.yml new file mode 100644 index 000000000000..0b86f0577110 --- /dev/null +++ b/.github/workflows/assign-junior-prs.yml @@ -0,0 +1,38 @@ +name: 'PR: Assign Junior PRs to requester' + +on: + pull_request_target: + types: + - opened + +permissions: + contents: read + +jobs: + assign-requester: + name: Assign requester + runs-on: ubuntu-24.04 + if: github.event.pull_request.user.login == 'sentry-junior[bot]' + steps: + # Matching Slack names to GitHub users lists team members, which needs org `members: read`. + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.GITFLOW_APP_ID }} + private-key: ${{ secrets.GITFLOW_APP_PRIVATE_KEY }} + + - name: Checkout base branch + uses: actions/checkout@v7 + with: + sparse-checkout: | + scripts/junior-requesters.mjs + sparse-checkout-cone-mode: false + + - name: Assign requester + uses: actions/github-script@v9 + with: + github-token: ${{ steps.app-token.outputs.token }} + script: | + const { assignJuniorRequesters } = await import('${{ github.workspace }}/scripts/junior-requesters.mjs'); + await assignJuniorRequesters({ github, context, core }); diff --git a/.github/workflows/assign-reviewers.yml b/.github/workflows/assign-reviewers.yml new file mode 100644 index 000000000000..60e541dcb775 --- /dev/null +++ b/.github/workflows/assign-reviewers.yml @@ -0,0 +1,48 @@ +name: 'PR: Assign reviewers' + +on: + # pull_request_target so this also runs for fork PRs. It only checks out the base branch, + # never the PR's code. + pull_request_target: + types: + - opened + - reopened + - ready_for_review + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + assign-reviewers: + name: Assign reviewers + runs-on: ubuntu-24.04 + if: github.event.pull_request.draft == false + steps: + # Listing team members needs org `members: read`, which GITHUB_TOKEN can't have. + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.GITFLOW_APP_ID }} + private-key: ${{ secrets.GITFLOW_APP_PRIVATE_KEY }} + + - name: Checkout base branch + uses: actions/checkout@v7 + with: + sparse-checkout: | + .github/REVIEWERS + scripts/assign-reviewers.mjs + scripts/junior-requesters.mjs + sparse-checkout-cone-mode: false + + - name: Assign reviewers + uses: actions/github-script@v9 + with: + github-token: ${{ steps.app-token.outputs.token }} + script: | + const { assignReviewers } = await import('${{ github.workspace }}/scripts/assign-reviewers.mjs'); + await assignReviewers({ github, context, core }); diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59211cdc3d6d..53c2cf9ab6b4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,5 @@ name: 'CI: Build & Test' +# Full-CI baseline for the Nuxt production/development split benchmark. on: push: branches: @@ -92,9 +93,7 @@ jobs: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install Dependencies uses: ./.github/actions/install-dependencies @@ -155,6 +154,40 @@ jobs: $GITHUB_OUTPUT working-directory: dev-packages/e2e-tests + - name: Build tarballs and bundles + run: | + pnpm run clean:tarballs + pnpm exec nx run-many -t build:tarball build:bundle --parallel=4 + + - name: Upload tarball artifacts + uses: actions/upload-artifact@v7 + with: + name: build-tarball-output + path: ${{ env.TARBALL_ARTIFACT_GLOB }} + if-no-files-found: error + retention-days: 4 + compression-level: 6 + overwrite: true + + - name: Upload test-utils tarball artifact + uses: actions/upload-artifact@v7 + with: + name: build-test-utils-tarball-output + path: dev-packages/test-utils/*.tgz + if-no-files-found: error + retention-days: 4 + compression-level: 6 + overwrite: true + + - name: Upload bundle artifacts + uses: actions/upload-artifact@v7 + with: + name: build-bundle-output + path: ${{ env.BUNDLE_ARTIFACT_GLOB }} + retention-days: 4 + compression-level: 6 + overwrite: true + outputs: dependency_cache_key: ${{ steps.install_dependencies.outputs.cache_key }} changed_node_integration: @@ -206,9 +239,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore NX cache uses: actions/cache/restore@v6.1.0 with: @@ -234,45 +265,6 @@ jobs: compression-level: 6 overwrite: true - job_build_bundles: - name: Build bundles - needs: [job_get_metadata, job_build] - timeout-minutes: 10 - runs-on: ubuntu-24.04-arm - steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) - uses: actions/checkout@v7 - with: - ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' - - name: Restore NX cache - uses: actions/cache/restore@v6.1.0 - with: - path: | - .nx/cache - .nx/workspace-data - key: ${{ env.NX_CACHE_KEY }}-${{ runner.arch }} - - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - - name: Build bundles - run: pnpm run build:bundle - - - name: Upload build artifacts - uses: actions/upload-artifact@v7 - with: - name: build-bundle-output - path: ${{ env.BUNDLE_ARTIFACT_GLOB }} - retention-days: 4 - compression-level: 6 - overwrite: true - job_check_branches: name: Check PR branches needs: job_get_metadata @@ -290,7 +282,7 @@ jobs: job_size_check: name: Size Check - needs: [job_get_metadata, job_build, job_build_bundles] + needs: [job_get_metadata, job_build] timeout-minutes: 15 runs-on: ubuntu-24.04-arm if: @@ -302,9 +294,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -334,9 +324,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -348,8 +336,6 @@ jobs: run: pnpm run lint:es-compatibility - name: Lint types run: pnpm run lint:types - - name: Check for circular dependencies - run: pnpm run circularDepCheck - name: Check for dts files that reference stuff in the temporary build folder run: | if grep -r --include "*.d.ts" --exclude-dir ".nx" 'import("@sentry(-internal)?/[^/]*/build' .; then @@ -382,9 +368,7 @@ jobs: - name: Install pnpm uses: ./.github/actions/install-pnpm - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install dependencies run: pnpm install --no-frozen-lockfile - name: Check that pnpm-lock.yaml is stable @@ -408,9 +392,7 @@ jobs: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install Dependencies uses: ./.github/actions/install-dependencies @@ -420,7 +402,7 @@ jobs: job_artifacts: name: Upload Artifacts - needs: [job_get_metadata, job_build, job_build_layer, job_build_bundles, job_build_tarballs] + needs: [job_get_metadata, 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' @@ -430,9 +412,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -488,9 +468,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -521,9 +499,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: @@ -548,9 +524,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: @@ -616,7 +590,7 @@ 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, job_build_bundles] + needs: [job_get_metadata, job_build] if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' runs-on: ubuntu-24.04-large-js timeout-minutes: 25 @@ -634,8 +608,6 @@ jobs: - bundle_tracing - bundle_tracing_logs_metrics - bundle_tracing_replay - - bundle_tracing_replay_logs_metrics - - bundle_tracing_replay_feedback - bundle_tracing_replay_feedback_logs_metrics - bundle_tracing_replay_feedback_logs_metrics_min project: @@ -654,19 +626,51 @@ jobs: - bundle: esm project: chromium shard: 1 - shards: 4 + shards: 6 - bundle: esm project: chromium shard: 2 - shards: 4 + shards: 6 - bundle: esm project: chromium shard: 3 - shards: 4 + shards: 6 - bundle: esm project: chromium shard: 4 - shards: 4 + shards: 6 + - bundle: esm + project: chromium + shard: 5 + shards: 6 + - bundle: esm + project: chromium + shard: 6 + shards: 6 + - bundle: bundle_tracing_replay_feedback + project: chromium + shard: 1 + shards: 3 + - bundle: bundle_tracing_replay_feedback + project: chromium + shard: 2 + shards: 3 + - bundle: bundle_tracing_replay_feedback + project: chromium + shard: 3 + shards: 3 + - bundle: bundle_tracing_replay_logs_metrics + project: chromium + shard: 1 + shards: 3 + - bundle: bundle_tracing_replay_logs_metrics + project: chromium + shard: 2 + shards: 3 + - bundle: bundle_tracing_replay_logs_metrics + project: chromium + shard: 3 + shards: 3 steps: - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) @@ -674,9 +678,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -715,7 +717,7 @@ jobs: job_browser_loader_tests: name: PW ${{ matrix.bundle }} Tests - needs: [job_get_metadata, job_build, job_build_bundles] + needs: [job_get_metadata, job_build] if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' runs-on: ubuntu-24.04 timeout-minutes: 15 @@ -737,9 +739,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -773,6 +773,39 @@ jobs: overwrite: true retention-days: 7 + # 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' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Check out current commit (${{ needs.job_get_metadata.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 + with: + name: build-bundle-output + path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + + # Chromium itself isn't cached: `run.mjs` downloads the 127 MB zip on each run, which is about as quick as a + # cache restore. + - name: Install Chromium dependencies + run: dev-packages/browser-min-version-tests/install-deps.sh + + - name: Run tests + run: node dev-packages/browser-min-version-tests/run.mjs + job_node_integration_tests: name: Node (${{ matrix.node }}) Integration Tests (${{ matrix.shard }}/${{ matrix.shards }}) needs: [job_get_metadata, job_build] @@ -784,19 +817,9 @@ jobs: strategy: fail-fast: false matrix: - node: [20.19, 22, 24, 26] - shard: [1, 2, 3, 4] - shards: [4] - include: - - node: '^27.0.0-0' - shard: 1 - shards: 3 - - node: '^27.0.0-0' - shard: 2 - shards: 3 - - node: '^27.0.0-0' - shard: 3 - shards: 3 + node: [20.19, 22, 24, 26, '^27.0.0-0'] + shard: [1, 2, 3, 4, 5, 6] + shards: [6] steps: - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) uses: actions/checkout@v7 @@ -877,9 +900,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -948,7 +969,7 @@ jobs: run: pnpm run test job_bun_integration_tests: - name: Bun (${{ matrix.bun }}) Integration Tests (${{ matrix.shard }}/2) + name: Bun (${{ matrix.bun }}) Integration Tests (${{ matrix.shard }}/4) needs: [job_get_metadata, job_build] if: needs.job_build.outputs.changed_bun_integration == 'true' || github.event_name != 'pull_request' runs-on: ubuntu-24.04-arm @@ -958,16 +979,14 @@ jobs: matrix: # 1.3.14 is the oldest supported Bun version bun: ['1.3.14', '1.4'] - shard: [1, 2] + shard: [1, 2, 3, 4] steps: - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: @@ -979,10 +998,10 @@ jobs: - name: Run integration tests working-directory: dev-packages/bun-integration-tests - run: pnpm run test --shard=${{ matrix.shard }}/2 + run: pnpm run test --shard=${{ matrix.shard }}/4 job_deno_integration_tests: - name: Deno Integration Tests (${{ matrix.shard }}/2) + name: Deno Integration Tests (${{ matrix.shard }}/4) needs: [job_get_metadata, job_build] if: needs.job_build.outputs.changed_deno_integration == 'true' || github.event_name != 'pull_request' runs-on: ubuntu-24.04-arm @@ -990,16 +1009,14 @@ jobs: strategy: fail-fast: false matrix: - shard: [1, 2] + shard: [1, 2, 3, 4] steps: - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) uses: actions/checkout@v7 with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: @@ -1021,75 +1038,14 @@ jobs: - name: Run shared Node integration tests working-directory: dev-packages/deno-integration-tests # Tedious runs in the dedicated SQL Server job because its database container requires x86. - run: pnpm run test:node-suites --shard=${{ matrix.shard }}/2 --exclude '**/tracing/tedious/**' - - job_build_tarballs: - name: Build tarballs - # We want to run this if: - # - The build job was successful, not skipped - if: | - always() && - needs.job_build.result == 'success' - needs: [job_get_metadata, job_build] - runs-on: ubuntu-24.04-arm - timeout-minutes: 15 - steps: - - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) - uses: actions/checkout@v7 - with: - ref: ${{ env.HEAD_COMMIT }} - - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' - - name: Restore NX cache - uses: actions/cache/restore@v6.1.0 - with: - path: | - .nx/cache - .nx/workspace-data - key: ${{ env.NX_CACHE_KEY }}-${{ runner.arch }} - - - name: Restore caches - uses: ./.github/actions/restore-cache - with: - dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} - - - name: Build tarballs - run: | - pnpm run clean:tarballs - pnpm run build:tarballs --parallel=4 - - - name: Upload tarball artifacts - uses: actions/upload-artifact@v7 - with: - name: build-tarball-output - path: ${{ env.TARBALL_ARTIFACT_GLOB }} - if-no-files-found: error - retention-days: 4 - compression-level: 6 - overwrite: true - - - name: Upload test-utils tarball artifact - uses: actions/upload-artifact@v7 - with: - name: build-test-utils-tarball-output - path: dev-packages/test-utils/*.tgz - if-no-files-found: error - retention-days: 4 - compression-level: 6 - overwrite: true + run: pnpm run test:node-suites --shard=${{ matrix.shard }}/4 --exclude '**/tracing/tedious/**' # GitHub Actions allows at most 256 jobs in one matrix, so the E2E tests are split into two jobs that share `env` # and `steps`. job_e2e_tests_1: name: E2E ${{ matrix.label || matrix.test-application }} Test - # We need to add the `always()` check here because the previous step has this as well :( - # See: https://github.com/actions/runner/issues/2205 - if: - always() && needs.job_build_tarballs.result == 'success' && needs.job_build.outputs.e2e-matrix-1 != - '{"include":[]}' - needs: [job_get_metadata, job_build, job_build_tarballs] + if: always() && needs.job_build.result == 'success' && needs.job_build.outputs.e2e-matrix-1 != '{"include":[]}' + needs: [job_get_metadata, job_build] runs-on: ubuntu-24.04 timeout-minutes: 15 # We just use a dummy DSN here, only send to the tunnel anyhow @@ -1103,6 +1059,7 @@ jobs: E2E_TEST_SENTRY_PROJECT: 'sentry-javascript-e2e-tests' # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: @@ -1118,6 +1075,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} # Installs Playwright while the app builds. Keep it right before the build: the runner sets up a background @@ -1158,10 +1116,8 @@ jobs: job_e2e_tests_2: name: E2E ${{ matrix.label || matrix.test-application }} Test - if: - always() && needs.job_build_tarballs.result == 'success' && needs.job_build.outputs.e2e-matrix-2 != - '{"include":[]}' - needs: [job_get_metadata, job_build, job_build_tarballs] + if: always() && needs.job_build.result == 'success' && needs.job_build.outputs.e2e-matrix-2 != '{"include":[]}' + needs: [job_get_metadata, job_build] runs-on: ubuntu-24.04 timeout-minutes: 15 env: *e2e-env @@ -1172,9 +1128,9 @@ jobs: job_e2e_aws_layer_tests: name: E2E ${{ matrix.label || matrix.test-application }} Test - needs: [job_get_metadata, job_build, job_build_layer, job_build_tarballs] + needs: [job_get_metadata, job_build, job_build_layer] if: >- - always() && needs.job_build_tarballs.result == 'success' && needs.job_build_layer.result == 'success' && + always() && needs.job_build.result == 'success' && needs.job_build_layer.result == 'success' && needs.job_build.outputs.e2e-matrix-aws-layer != '{"include":[]}' runs-on: ubuntu-24.04 timeout-minutes: 15 @@ -1190,13 +1146,11 @@ jobs: job_optional_e2e_tests: name: E2E Tests (optional) # We only run E2E tests for non-fork PRs because the E2E tests require secrets to work and they can't be accessed from forks - # We need to add the `always()` check here because the previous step has this as well :( - # See: https://github.com/actions/runner/issues/2205 if: - always() && needs.job_get_metadata.outputs.is_release != 'true' && needs.job_build_tarballs.result == 'success' && + 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, job_build_tarballs] + needs: [job_get_metadata, job_build] # This job only waits for optional-e2e.yml, which can take most of an hour. runs-on: ubuntu-24.04 timeout-minutes: 60 @@ -1209,9 +1163,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install pnpm uses: ./.github/actions/install-pnpm # Only install what the action needs @@ -1229,9 +1181,7 @@ jobs: needs: [ job_build, - job_build_bundles, job_build_layer, - job_build_tarballs, job_browser_unit_tests, job_bun_unit_tests, job_deno_unit_tests, @@ -1244,6 +1194,7 @@ jobs: job_deno_integration_tests, job_browser_playwright_tests, job_browser_loader_tests, + job_browser_min_version_tests, job_e2e_tests_1, job_e2e_tests_2, job_e2e_aws_layer_tests, diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 422cecffa19c..f8ef50f4da66 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -85,6 +85,7 @@ jobs: E2E_TEST_SENTRY_PROJECT: 'sentry-javascript-e2e-tests' # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: @@ -101,6 +102,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} - name: Build E2E app diff --git a/.github/workflows/cleanup-e2e-workers.yml b/.github/workflows/cleanup-e2e-workers.yml index 69aae225e408..4b986b32805e 100644 --- a/.github/workflows/cleanup-e2e-workers.yml +++ b/.github/workflows/cleanup-e2e-workers.yml @@ -20,6 +20,7 @@ jobs: worker-prefix: - e2e-send-to-sentry - e2e-flue-send-to-sentry + - e2e-without-tracing-send-to-sentry steps: - name: Set up Node uses: actions/setup-node@v7 diff --git a/.github/workflows/optional-e2e.yml b/.github/workflows/optional-e2e.yml index 0fc020c9b327..48c469acacb1 100644 --- a/.github/workflows/optional-e2e.yml +++ b/.github/workflows/optional-e2e.yml @@ -63,6 +63,7 @@ jobs: E2E_PR_NUMBER: ${{ inputs.pr_number }} # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: @@ -79,6 +80,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} artifacts-run-id: ${{ inputs.build_run_id }} github-token: ${{ github.token }} @@ -125,9 +127,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install pnpm uses: ./.github/actions/install-pnpm - name: Install action dependencies diff --git a/.madgerc b/.madgerc deleted file mode 100644 index b407c6b4b14f..000000000000 --- a/.madgerc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "detectiveOptions": { - "ts": { - "skipTypeImports": true - } - } -} diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json index 3c42d69b4bb4..73a31b05f3b8 100644 --- a/.oxlintrc.base.json +++ b/.oxlintrc.base.json @@ -79,6 +79,13 @@ "sdk/no-unfiltered-url-attributes": "error" } }, + { + // Type-only imports are erased at build time, so they cannot cause load-order bugs. + "files": ["**/src/**"], + "rules": { + "import/no-cycle": ["error", { "ignoreTypes": true }] + } + }, { // The rule itself decides which files are browser-facing (see `no-unguarded-span-apis.js`); // oxlint resolves `files` globs relative to each package's own config, so scoping it to diff --git a/.vscode/launch.json b/.vscode/launch.json index 5c59e098d55e..750acd5f866f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -52,33 +52,6 @@ "internalConsoleOptions": "openOnSessionStart", "outputCapture": "std" }, - // Run a specific test file in watch mode (must have file in currently active tab when hitting the play button). - // NOTE: If you try to run this and VSCode complains that the command `shellCommand.execute` can't be found, go - // install the recommended extension Tasks Shell Input. - { - "name": "Debug playwright tests (just open file)", - "type": "pwa-node", - "cwd": "${workspaceFolder}/packages/${input:getPackageName}", - "request": "launch", - "runtimeExecutable": "pnpm", - "runtimeArgs": [ - // `nodemon` is basically `node --watch` - "nodemon", - // be default it only watches JS files, so have it watch TS files instead - "--ext", - "ts", - "${workspaceFolder}/node_modules/playwright/node_modules/.bin/playwright", - "test", - "${file}" - ], - "skipFiles": ["/**"], - "outFiles": ["${workspaceFolder}/**/*.js", "!**/node_modules/**"], - "sourceMaps": true, - "smartStep": true, - "internalConsoleOptions": "openOnSessionStart", - // show stdout and stderr output in the debug console - "outputCapture": "std" - }, // @sentry/nextjs - Run a specific integration test file // Must have test file in currently active tab when hitting the play button, and must already have run `pnpm install` in test app directory diff --git a/CHANGELOG.md b/CHANGELOG.md index cae8ddfbdbb1..1a2040fb3be8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,170 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +## 11.13.0 + +### Important Changes + +- **feat(sveltekit): Mark pageloads of prerendered and Vercel ISR pages ([#26301](https://github.com/getsentry/sentry-javascript/pull/26301), [#26307](https://github.com/getsentry/sentry-javascript/pull/26307))** + + When SvelteKit serves a page that it rendered earlier, the pageload now has the `page.server_rendering.type: static` attribute. This covers pages prerendered during `vite build` and pages that Vercel caches with ISR (`config.isr`). For an ISR page, the pageload also links to the request that rendered the page, if that request was sampled. + + Before, every visitor of a cached ISR page continued the trace of that one request. Now each pageload starts its own trace. Pages with `ssr = false` get no attribute, because the server rendered none of their content. + +- **feat(nuxt): Mark pageloads of cached pages ([#26305](https://github.com/getsentry/sentry-javascript/pull/26305))** + + When Nuxt serves a cached or prerendered page, for example with a `swr` or `isr` route rule, the pageload now has the `page.server_rendering.type: static` attribute and starts its own trace. If the request that rendered the cached page was sampled, the pageload also links to it. So visitors of a cached page no longer continue the trace of the request that rendered it. + +- **fix(core): Set `url.scheme` without colon and `url.port` as a number ([#26284](https://github.com/getsentry/sentry-javascript/pull/26284))** + + HTTP spans that the SDK builds from a `URL` now send `url.scheme` without the trailing colon (`https` instead of `https:`) and `url.port` as a number instead of a string, as the Sentry conventions define them and as Node `http.server` spans already do. This changes `http.server` spans from `@sentry/cloudflare`, `Bun.serve`, Deno and Nitro, and outgoing `node:http` client spans. Update saved queries, alerts and dashboards that filter on `url.scheme:"https:"` or on `url.port` as a string. + +- **feat(cloudflare): Continue the Cloudflare trace of the invocation ([#25613](https://github.com/getsentry/sentry-javascript/pull/25613))** + + When tracing is not set up (no `tracesSampleRate` or `tracesSampler`), errors and logs from fetch, scheduled, queue and email handlers and from `WorkerEntrypoint` RPC methods now get the trace id that Cloudflare gives the invocation. With this trace id, you can find the Cloudflare spans and logs of an error in Workers Observability. This needs workerd 1.20261009.1 or newer and Workers Observability turned on. An incoming Sentry trace still has precedence. + + The `parent_span_id` of these events is the id of a Cloudflare span. This span is in Sentry only when you export your Workers traces to Sentry. + +- **feat(server-utils): Record Bedrock prompts and responses ([#26249](https://github.com/getsentry/sentry-javascript/pull/26249), [#26362](https://github.com/getsentry/sentry-javascript/pull/26362), [#26414](https://github.com/getsentry/sentry-javascript/pull/26414))** + + Amazon Bedrock spans from `awsIntegration` now record prompts, system instructions, tool definitions and responses by default, as the other AI integrations do. This applies to the `Converse`, `ConverseStream`, `InvokeModel` and `InvokeModelWithResponseStream` commands. + + To stop recording prompts or responses for all AI integrations, set `dataCollection: { genAI: { inputs: false, outputs: false } }`. To stop it only for Bedrock, use the new `awsIntegration` options, which take precedence over `dataCollection.genAI`: + + ```js + Sentry.init({ + integrations: [Sentry.awsIntegration({ recordInputs: false, recordOutputs: false })], + }); + ``` + +### Other Changes + +- feat(aws-serverless): Add HTTP request and response attributes to function.aws spans ([#26226](https://github.com/getsentry/sentry-javascript/pull/26226)) +- feat(aws-serverless): Ignore static asset and preflight invocations by default ([#26228](https://github.com/getsentry/sentry-javascript/pull/26228)) +- feat(bundler-plugins): Delete source maps with `deleteSourcemapsAfterUpload: true` when no upload runs ([#26281](https://github.com/getsentry/sentry-javascript/pull/26281)) +- feat(bundler-plugins): Enable external source maps and delete them after upload in the esbuild plugin ([#25648](https://github.com/getsentry/sentry-javascript/pull/25648)) +- feat(cloudflare): Instrument `trace` and `tailStream` handlers ([#26250](https://github.com/getsentry/sentry-javascript/pull/26250)) +- feat(core): Add `getTraceServerTimingHeader` and `isSharedCacheable` ([#26325](https://github.com/getsentry/sentry-javascript/pull/26325)) +- feat(core): capture MCP OAuth client names per request ([#24508](https://github.com/getsentry/sentry-javascript/pull/24508)) +- feat(core): Support Zod 4 errors in zodErrorsIntegration ([#25756](https://github.com/getsentry/sentry-javascript/pull/25756)) +- feat(nextjs): Emit the tunnel route handler ([#25424](https://github.com/getsentry/sentry-javascript/pull/25424)) +- feat(nextjs): Send the render start of a cached page to the browser ([#26397](https://github.com/getsentry/sentry-javascript/pull/26397)) +- feat(nextjs): Send the trace in the `Server-Timing` header of document responses ([#26107](https://github.com/getsentry/sentry-javascript/pull/26107)) +- feat(nextjs): Use the Bun integrations when Next.js runs on Bun ([#26294](https://github.com/getsentry/sentry-javascript/pull/26294)) +- feat(nextjs): Use the Deno fetch integration when Next.js runs on Deno ([#26295](https://github.com/getsentry/sentry-javascript/pull/26295)) +- feat(node): Capture the original job error for failed BullMQ jobs ([#26352](https://github.com/getsentry/sentry-javascript/pull/26352)) +- feat(node): Instrument HTTP/2 servers that use the compat API ([#25992](https://github.com/getsentry/sentry-javascript/pull/25992)) +- feat(node): Publish flat CJS builds to cut `@sentry/node` startup time ([#25968](https://github.com/getsentry/sentry-javascript/pull/25968)) +- feat(nuxt): Instrument Nitro v3 cache storage ([#25951](https://github.com/getsentry/sentry-javascript/pull/25951)) +- feat(nuxt): Send the render start of a cached page to the browser ([#26399](https://github.com/getsentry/sentry-javascript/pull/26399)) +- feat(react-router): Export createSentryHandleError from the Cloudflare entry ([#26343](https://github.com/getsentry/sentry-javascript/pull/26343)) +- feat(server-utils): Add pi-ai integration ([#25937](https://github.com/getsentry/sentry-javascript/pull/25937)) +- feat(server-utils): Enable pi-ai by default & use it for Flue & pi-durable ([#25940](https://github.com/getsentry/sentry-javascript/pull/25940)) +- feat(sveltekit): Send the render start of a cached page to the browser ([#26398](https://github.com/getsentry/sentry-javascript/pull/26398)) +- feat(tanstackstart-react): Initialize the SDK when the Nitro server starts ([#26224](https://github.com/getsentry/sentry-javascript/pull/26224)) +- fix(anthropic): End and mark messages.stream() span as cancelled on abort ([#26236](https://github.com/getsentry/sentry-javascript/pull/26236)) +- fix(astro, cloudflare): Run the Cloudflare SDK on the server for Cloudflare Pages ([#26188](https://github.com/getsentry/sentry-javascript/pull/26188)) +- fix(browser): Accept managed tunnel options in the `BrowserClient` constructor ([#26313](https://github.com/getsentry/sentry-javascript/pull/26313)) +- fix(browser): Handle parentheses in function names in stack parsers ([#26233](https://github.com/getsentry/sentry-javascript/pull/26233)) +- fix(browser): Instrument empty-URL XHR and show the page URL in breadcrumbs ([#26201](https://github.com/getsentry/sentry-javascript/pull/26201)) +- fix(browser): Send same-origin string tunnels as `application/x-sentry-envelope` ([#26299](https://github.com/getsentry/sentry-javascript/pull/26299)) +- fix(browser): Skip CLS on browsers without Array.prototype.at ([#26347](https://github.com/getsentry/sentry-javascript/pull/26347)) +- fix(bundler-plugins): Keep uploading when a directory has no source maps ([#26092](https://github.com/getsentry/sentry-javascript/pull/26092)) +- fix(bundler-plugins): Skip default commit association on Vercel builds that --auto can't resolve ([#26320](https://github.com/getsentry/sentry-javascript/pull/26320)) +- fix(bundler-plugins): Stop defaulting `url` to sentry.io ([#26252](https://github.com/getsentry/sentry-javascript/pull/26252)) +- fix(cloudflare): Capture errors that fail a workflow run outside a step callback ([#26316](https://github.com/getsentry/sentry-javascript/pull/26316)) +- fix(cloudflare): Forward method, headers and body when a Request is passed as fetch init ([#26368](https://github.com/getsentry/sentry-javascript/pull/26368)) +- fix(cloudflare): Have `@flue/runtime` provide its own namespace ([#25935](https://github.com/getsentry/sentry-javascript/pull/25935)) +- fix(cloudflare): Skip auto-instrument warning for TanStack Start tunnel shim ([#26239](https://github.com/getsentry/sentry-javascript/pull/26239)) +- fix(core): Always return a string from `_enhanceErrorWithSentryInfo` ([#26349](https://github.com/getsentry/sentry-javascript/pull/26349)) +- fix(nextjs): Inject build values into instrumentation for an external server SDK ([#26292](https://github.com/getsentry/sentry-javascript/pull/26292)) +- fix(nextjs): Run Turbopack loaders in worker threads on Bun ([#26293](https://github.com/getsentry/sentry-javascript/pull/26293)) +- fix(opentelemetry): Keep live context link when passing a scope to withScope ([#26234](https://github.com/getsentry/sentry-javascript/pull/26234)) +- fix(replay): Minify the compression worker to ES2020 ([#26355](https://github.com/getsentry/sentry-javascript/pull/26355)) +- fix(server-runtime-injection): Register the CJS loader hook from the CJS build ([#26278](https://github.com/getsentry/sentry-javascript/pull/26278)) +- fix(server-utils): Count Google GenAI tool-use prompt tokens as input tokens ([#25834](https://github.com/getsentry/sentry-javascript/pull/25834)) +- fix(server-utils): Instrument deps excluded from the Vite dep optimizer ([#26264](https://github.com/getsentry/sentry-javascript/pull/26264)) +- fix(server-utils): Keep usage and tool errors when ai omits channel results ([#26150](https://github.com/getsentry/sentry-javascript/pull/26150)) +- fix(server-utils): Keep Workers AI streamed tool calls that have no index ([#25835](https://github.com/getsentry/sentry-javascript/pull/25835)) +- fix(server-utils): Mark AI spans as cancelled when the caller aborts ([#26297](https://github.com/getsentry/sentry-javascript/pull/26297)) +- fix(server-utils): Read GLOBAL_OBJ at call time in Nitro integration ([#26300](https://github.com/getsentry/sentry-javascript/pull/26300)) +- fix(server-utils): Record Anthropic chat spans for thread and tool-runner streams on 1.2+ ([#25931](https://github.com/getsentry/sentry-javascript/pull/25931)) +- fix(server-utils): Record output of Workers AI chat-completion responses ([#26175](https://github.com/getsentry/sentry-javascript/pull/26175)) +- fix(server-utils): Trace Vercel AI streamObject on ai v4-v6 ([#26382](https://github.com/getsentry/sentry-javascript/pull/26382)) +- fix(server-utils): Use the client's provider name for Anthropic platform clients ([#26119](https://github.com/getsentry/sentry-javascript/pull/26119)) +- fix(solidstart): Keep build-time tooling out of SolidStart 2 server bundles ([#26277](https://github.com/getsentry/sentry-javascript/pull/26277)) +- ref(server-runtime-injection): Say when hook registration fails because the deployment is missing a file ([#26272](https://github.com/getsentry/sentry-javascript/pull/26272)) + +
+ Internal Changes + +- chore(build): Remove build:watch scripts ([#26350](https://github.com/getsentry/sentry-javascript/pull/26350)) +- chore(build): Replace es-check with an acorn-based script ([#26321](https://github.com/getsentry/sentry-javascript/pull/26321)) +- chore(bundler-plugins): Type-check tests via lint:types ([#26345](https://github.com/getsentry/sentry-javascript/pull/26345)) +- chore(ci): Add Warden gha-security-review and skill-scanner ([#26269](https://github.com/getsentry/sentry-javascript/pull/26269)) +- chore(ci): Align Node 27 integration test sharding ([#26375](https://github.com/getsentry/sentry-javascript/pull/26375)) +- chore(ci): Assign 3 PR reviewers via workflow ([#26268](https://github.com/getsentry/sentry-javascript/pull/26268)) +- chore(ci): Assign Junior PRs to their requester and skip them as reviewer ([#26304](https://github.com/getsentry/sentry-javascript/pull/26304)) +- chore(ci): Move reviewer routing out of CODEOWNERS ([#26346](https://github.com/getsentry/sentry-javascript/pull/26346)) +- chore(ci): Never auto-request HazAT as reviewer ([#26353](https://github.com/getsentry/sentry-javascript/pull/26353)) +- chore(ci): Prefer reviewers with fewer recent review requests ([#26407](https://github.com/getsentry/sentry-javascript/pull/26407)) +- chore(ci): Skip busy users when assigning PR reviewers ([#26358](https://github.com/getsentry/sentry-javascript/pull/26358)) +- chore(deno): Note that OTel setup defaulting to on is unintentional ([#26310](https://github.com/getsentry/sentry-javascript/pull/26310)) +- chore(deps): Bump `@sentry/conventions` to 0.33.0 ([#26374](https://github.com/getsentry/sentry-javascript/pull/26374)) +- chore(deps): Record the `node-abort-controller` deprecation in the lockfile ([#26270](https://github.com/getsentry/sentry-javascript/pull/26270)) +- chore(deps): Record the postcss-selector-parser 7.2.0 deprecation in the lockfile ([#26339](https://github.com/getsentry/sentry-javascript/pull/26339)) +- chore(deps): Run yalc via pnpm dlx instead of a root devDependency ([#26318](https://github.com/getsentry/sentry-javascript/pull/26318)) +- chore(deps-dev): Bump @nuxt/schema from 3.21.11 to 4.6.4 ([#26370](https://github.com/getsentry/sentry-javascript/pull/26370)) +- chore(deps-dev): Bump hono from 4.13.11 to 4.13.16 ([#26340](https://github.com/getsentry/sentry-javascript/pull/26340)) +- chore(dev-deps): Replace madge with oxlint import/no-cycle ([#26317](https://github.com/getsentry/sentry-javascript/pull/26317)) +- chore(dev-deps): Replace nodemon with tsx watch ([#26322](https://github.com/getsentry/sentry-javascript/pull/26322)) +- chore(dev-deps): Replace npm-run-all2 with pnpm script selectors ([#26319](https://github.com/getsentry/sentry-javascript/pull/26319)) +- chore: Exempt Sentry packages from release-age checks ([#26274](https://github.com/getsentry/sentry-javascript/pull/26274)) +- chore: Revert add catch-all rule for shared packages in CODEOWNERS ([#25789](https://github.com/getsentry/sentry-javascript/pull/25789)) (#26255) +- chore: Switch to rolldown ([#20775](https://github.com/getsentry/sentry-javascript/pull/20775)) +- chore: Use What/Why structure in PR template ([#26348](https://github.com/getsentry/sentry-javascript/pull/26348)) +- ci: Cache the Node.js install instead of fetching it in every job ([#26287](https://github.com/getsentry/sentry-javascript/pull/26287)) +- docs(aws-serverless): Use Lambda Event Functions naming in README ([#26354](https://github.com/getsentry/sentry-javascript/pull/26354)) +- docs(browser): Fix `enableLongAnimationFrame` default in JSDoc ([#26256](https://github.com/getsentry/sentry-javascript/pull/26256)) +- feat(deps): Bump @hono/node-server from 2.1.5 to 2.1.7 ([#26331](https://github.com/getsentry/sentry-javascript/pull/26331)) +- feat(deps): Bump node-forge from 1.4.2 to 1.4.3 ([#26267](https://github.com/getsentry/sentry-javascript/pull/26267)) +- fix(ci): separate x64 and ARM64 dependency cache keys ([#26282](https://github.com/getsentry/sentry-javascript/pull/26282)) +- perf(ci): Build CDN bundles in the main build job ([#26379](https://github.com/getsentry/sentry-javascript/pull/26379)) +- perf(ci): Increase integration test sharding ([#26378](https://github.com/getsentry/sentry-javascript/pull/26378)) +- perf(ci): Pack tarballs in the build job ([#26377](https://github.com/getsentry/sentry-javascript/pull/26377)) +- perf(ci): Separate Nuxt production and development E2E jobs ([#26396](https://github.com/getsentry/sentry-javascript/pull/26396)) +- perf(ci): Shard slow Nuxt and Next.js E2E variants ([#26376](https://github.com/getsentry/sentry-javascript/pull/26376)) +- ref(remix): Use the core Server-Timing and shared-cache helpers ([#26326](https://github.com/getsentry/sentry-javascript/pull/26326)) +- ref(server-utils): Extract pi-ai chat span helpers from pi-durable ([#25932](https://github.com/getsentry/sentry-javascript/pull/25932)) +- ref(tanstackstart-react): Forward request options in the server entry example ([#26408](https://github.com/getsentry/sentry-javascript/pull/26408)) +- ref: Share the cache origin helpers of Next.js, Nuxt and SvelteKit ([#26363](https://github.com/getsentry/sentry-javascript/pull/26363)) +- test(astro): Cover server island trace connection in E2E tests ([#26405](https://github.com/getsentry/sentry-javascript/pull/26405)) +- test(astro): Move tunnel e2e tests into a dedicated astro tunnel app ([#26392](https://github.com/getsentry/sentry-javascript/pull/26392)) +- test(cloudflare): Add e2e test for the Cloudflare trace id without tracing ([#25643](https://github.com/getsentry/sentry-javascript/pull/25643)) +- test(cloudflare): Run the SDK on the new module registry ([#26212](https://github.com/getsentry/sentry-javascript/pull/26212)) +- test(e2e): Assert source map stripping for Next.js and TanStack Start ([#26265](https://github.com/getsentry/sentry-javascript/pull/26265)) +- test(e2e): Pin pi to 1.4.0 for node-flue (latest) ([#26237](https://github.com/getsentry/sentry-javascript/pull/26237)) +- test(e2e): Run nestjs-12 on Bun, Deno and Cloudflare ([#26283](https://github.com/getsentry/sentry-javascript/pull/26283)) +- test(e2e): Run OTel SDK E2E apps on SDK v3 with an SDK v2 variant ([#25703](https://github.com/getsentry/sentry-javascript/pull/25703)) +- test(e2e): Trim tracer provider variants down to node-express ([#26385](https://github.com/getsentry/sentry-javascript/pull/26385)) +- test(nextjs): Cover the server request link of a late trace meta tag ([#26357](https://github.com/getsentry/sentry-javascript/pull/26357)) +- test(nextjs): Run the source map upload e2e test on Bun ([#26344](https://github.com/getsentry/sentry-javascript/pull/26344)) +- test(nitro): Move tunnel e2e tests into a dedicated nitro-3-tunnel app ([#26384](https://github.com/getsentry/sentry-javascript/pull/26384)) +- test(nuxt): Add vue-router to Nuxt 5 E2E apps ([#26323](https://github.com/getsentry/sentry-javascript/pull/26323)) +- test(nuxt): Move tunnel e2e tests into dedicated nuxt tunnel apps ([#26393](https://github.com/getsentry/sentry-javascript/pull/26393)) +- test(nuxt): Remove redundant full-suite import compatibility variant ([#26406](https://github.com/getsentry/sentry-javascript/pull/26406)) +- test(react-router): Move tunnel e2e tests into a dedicated react-router-8-tunnel app ([#26388](https://github.com/getsentry/sentry-javascript/pull/26388)) +- test(remix): Move tunnel e2e tests into a dedicated remix-v3-tunnel app ([#26391](https://github.com/getsentry/sentry-javascript/pull/26391)) +- test(scripts): Pass compare fn to sort in assign-reviewers tests ([#26303](https://github.com/getsentry/sentry-javascript/pull/26303)) +- test(solidstart): Move tunnel e2e tests into dedicated solidstart tunnel apps ([#26390](https://github.com/getsentry/sentry-javascript/pull/26390)) +- test(sveltekit): Move tunnel e2e tests into a dedicated sveltekit-3-tunnel app ([#26386](https://github.com/getsentry/sentry-javascript/pull/26386)) +- test(tanstackstart-react): Move tunnel e2e tests into a dedicated tanstackstart-react-tunnel app ([#26389](https://github.com/getsentry/sentry-javascript/pull/26389)) +- test(tanstackstart-react): Run the e2e fixtures on TanStack Start stable ([#26402](https://github.com/getsentry/sentry-javascript/pull/26402)) + +
+ +Work in this release was contributed by @kunal649, @bardrop, @DomWane, @Vivek1898, @mvanhorn, and @pcbeingused333. Thank you for your contributions! + ## 11.12.0 ### Important Changes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 79a1beab5799..dfad37a4c049 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,13 +46,12 @@ doesn't match the repo, see [Node.js and pnpm Versions](#nodejs-and-pnpm-version ## Building Packages Since we are using [`TypeScript`](https://www.typescriptlang.org/), you need to transpile the code to JavaScript to be -able to use it. From the top level of the repo, there are three commands available: +able to use it. From the top level of the repo, there are two commands available: - `pnpm run build:dev`, which runs a one-time build of every package - `pnpm run build:dev:filter `, which runs `pnpm run build:dev` only in projects relevant to the given package (so, for example, running `pnpm run build:dev:filter @sentry/react` will build the `react` package, all of its dependencies (`utils`, `core`, `browser`, etc), and all packages which depend on it (currently `gatsby` and `nextjs`)) -- `pnpm run build:dev:watch`, which runs `pnpm run build:dev` in watch mode (recommended) Note: Due to package incompatibilities between Python versions, building native binaries currently requires a Python version <3.12. diff --git a/README.md b/README.md index 0d82b7f93172..dc97eaf54018 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ package. Please refer to the README and instructions of those SDKs for more deta - [`@sentry/remix`](https://github.com/getsentry/sentry-javascript/tree/master/packages/remix): SDK for Remix - [`@sentry/tanstackstart-react`](https://github.com/getsentry/sentry-javascript/tree/master/packages/tanstackstart-react): SDK for TanStack Start React - [`@sentry/aws-serverless`](https://github.com/getsentry/sentry-javascript/tree/master/packages/aws-serverless): SDK - for AWS Lambda Functions + for AWS Lambda Event Functions - [`@sentry/google-cloud-serverless`](https://github.com/getsentry/sentry-javascript/tree/master/packages/google-cloud-serverless): SDK for Google Cloud Functions - [`@sentry/electron`](https://github.com/getsentry/sentry-electron): SDK for Electron with support for native crashes diff --git a/dev-packages/browser-integration-tests/package.json b/dev-packages/browser-integration-tests/package.json index 2eeff5ed3129..6809d901a3e2 100644 --- a/dev-packages/browser-integration-tests/package.json +++ b/dev-packages/browser-integration-tests/package.json @@ -61,7 +61,7 @@ "@playwright/test": "1.64.1", "@sentry/browser": "11.12.0", "@sentry/browser-utils": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "11.12.0", "@sentry/replay": "11.12.0", "@sentry/replay-canvas": "11.12.0", diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js new file mode 100644 index 000000000000..acf8b119a5e8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js @@ -0,0 +1,5 @@ +// Called from a served script so the synthetic stacktrace keeps a frame with a URL. Frames from +// `page.evaluate` have none, and the SDK's own `captureMessage` frames are stripped. +window.captureTestMessage = () => { + window.Sentry.captureMessage('Some message'); +}; diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts index 90b867c117e3..fd63b05b4207 100644 --- a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts @@ -16,7 +16,7 @@ sentryTest( await waitForReplayRunning(page); const errorRequestPromise = waitForErrorRequest(page); - await page.evaluate(() => (window as any).Sentry.captureMessage('Some message')); + await page.evaluate(() => (window as any).captureTestMessage()); const event = envelopeRequestParser(await errorRequestPromise); await forceFlushReplay(); diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js new file mode 100644 index 000000000000..acf8b119a5e8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js @@ -0,0 +1,5 @@ +// Called from a served script so the synthetic stacktrace keeps a frame with a URL. Frames from +// `page.evaluate` have none, and the SDK's own `captureMessage` frames are stripped. +window.captureTestMessage = () => { + window.Sentry.captureMessage('Some message'); +}; diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts index d89371695436..c047f0fcaa7d 100644 --- a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts @@ -22,7 +22,7 @@ sentryTest( const errorRequestPromise = waitForErrorRequest(page); const replayRequestPromise = waitForReplayRequest(page, 0); - await page.evaluate(() => (window as any).Sentry.captureMessage('Some message')); + await page.evaluate(() => (window as any).captureTestMessage()); const event = envelopeRequestParser(await errorRequestPromise); await replayRequestPromise; diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js new file mode 100644 index 000000000000..24397a4f6f66 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js @@ -0,0 +1,3 @@ +import { simulateCLS } from '../../../../utils/web-vitals/cls.ts'; + +simulateCLS(0.15).then(() => window.dispatchEvent(new Event('cls-done'))); diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html new file mode 100644 index 000000000000..10e2e22f7d6a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html @@ -0,0 +1,10 @@ + + + + + + +
+

Some content

+ + diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts new file mode 100644 index 000000000000..68be3f8f7063 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts @@ -0,0 +1,34 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { hidePage, shouldSkipTracingTest } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest.beforeEach(async ({ browserName, page }) => { + if (shouldSkipTracingTest() || browserName !== 'chromium') { + sentryTest.skip(); + } + + await page.setViewportSize({ width: 800, height: 1200 }); +}); + +// Chromium 80-91 is within our supported range and reports layout shifts, but has no `Array.prototype.at`, +// which web-vitals' CLS code relies on. +sentryTest('does not throw on layout shifts without Array.prototype.at', async ({ getLocalTestUrl, page }) => { + const pageErrors: string[] = []; + page.on('pageerror', error => pageErrors.push(error.message)); + + await page.addInitScript(() => { + // @ts-expect-error - emulating Chromium < 92 + delete Array.prototype.at; + }); + + const url = await getLocalTestUrl({ testDir: __dirname }); + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + await page.evaluate(() => new Promise(resolve => window.addEventListener('cls-done', resolve))); + await hidePage(page); + await pageloadSpanPromise; + + expect(pageErrors).toEqual([]); +}); diff --git a/dev-packages/browser-min-version-tests/.gitignore b/dev-packages/browser-min-version-tests/.gitignore new file mode 100644 index 000000000000..36e1248d6bd9 --- /dev/null +++ b/dev-packages/browser-min-version-tests/.gitignore @@ -0,0 +1 @@ +.chromium/ diff --git a/dev-packages/browser-min-version-tests/install-deps.sh b/dev-packages/browser-min-version-tests/install-deps.sh new file mode 100755 index 000000000000..8316317a7d05 --- /dev/null +++ b/dev-packages/browser-min-version-tests/install-deps.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Old Chromium links against libXss, which current runner images don't ship. Installing from the image's +# package lists is fast; only refresh them when they are too stale to resolve the package. +set -eu + +if ! sudo apt-get install -y --no-install-recommends libxss1; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends libxss1 +fi diff --git a/dev-packages/browser-min-version-tests/package.json b/dev-packages/browser-min-version-tests/package.json new file mode 100644 index 000000000000..172040f165b6 --- /dev/null +++ b/dev-packages/browser-min-version-tests/package.json @@ -0,0 +1,13 @@ +{ + "name": "@sentry-internal/browser-min-version-tests", + "version": "11.12.0", + "license": "MIT", + "private": true, + "type": "module", + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + }, + "devDependencies": { + "@sentry-internal/test-utils": "11.12.0" + } +} diff --git a/dev-packages/browser-min-version-tests/page.html b/dev-packages/browser-min-version-tests/page.html new file mode 100644 index 000000000000..c918731ca689 --- /dev/null +++ b/dev-packages/browser-min-version-tests/page.html @@ -0,0 +1,29 @@ + + + + + + + + +

Largest contentful paint

+

Shifting

+ + + + diff --git a/dev-packages/browser-min-version-tests/run.mjs b/dev-packages/browser-min-version-tests/run.mjs new file mode 100644 index 000000000000..64d3b686010c --- /dev/null +++ b/dev-packages/browser-min-version-tests/run.mjs @@ -0,0 +1,275 @@ +// Loads the CDN bundles in the oldest Chromium we support and checks that the web vitals it can +// measure are sent, and that nothing throws. Playwright only drives the Chromium it ships with, so +// this talks to the browser over the DevTools protocol directly. Run it after `pnpm build:bundle` in +// `packages/browser`. +import { execFileSync, spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { CDPClient, createBasicSentryServer, getSpanOp } from '@sentry-internal/test-utils'; + +// Chromium 80.0.3987.0, the minimum Chrome version in our supported browsers docs. +const CHROMIUM_REVISION = '722234'; +const CHROMIUM_ZIP_SHA256 = '2a7f1d1cf4fd933f4090739667f86b52187431a5a22e5f33a4a2be158d4574dc'; +const DIR = path.dirname(fileURLToPath(import.meta.url)); +const CHROMIUM_DIR = path.join(DIR, '.chromium', CHROMIUM_REVISION); +const CHROME = path.join(CHROMIUM_DIR, 'chrome-linux', 'chrome'); +const BUNDLES_DIR = path.join(DIR, '../../packages/browser/build/bundles'); +const BUNDLES = [ + 'bundle.tracing.min.js', + // The debug build logs errors the SDK catches internally, which would otherwise go unnoticed. + 'bundle.tracing.replay.feedback.logs.metrics.debug.min.js', +]; +const PAGE = readFileSync(path.join(DIR, 'page.html'), 'utf8'); + +// What Chromium 80 can report. CLS is skipped there because web-vitals' CLS code needs +// `Array.prototype.at` (Chromium 92), and INP needs `PerformanceEventTiming.interactionId` (Chromium 96). +const EXPECTED_PAGELOAD_VITALS = ['fcp', 'fp', 'ttfb']; +const UNEXPECTED_SPAN_OPS = ['ui.webvital.cls', 'ui.interaction.click']; + +async function ensureChromium() { + if (existsSync(CHROME)) { + return; + } + const url = `https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/${CHROMIUM_REVISION}/chrome-linux.zip`; + const response = await fetch(url, { signal: AbortSignal.timeout(120_000) }); + if (!response.ok) { + throw new Error(`Downloading Chromium failed: ${response.status} ${url}`); + } + const data = Buffer.from(await response.arrayBuffer()); + const sha256 = createHash('sha256').update(data).digest('hex'); + if (sha256 !== CHROMIUM_ZIP_SHA256) { + throw new Error(`Chromium download has SHA-256 ${sha256}, expected ${CHROMIUM_ZIP_SHA256}`); + } + mkdirSync(CHROMIUM_DIR, { recursive: true }); + const zip = `${CHROMIUM_DIR}.zip`; + writeFileSync(zip, data); + execFileSync('unzip', ['-q', zip, '-d', CHROMIUM_DIR]); + rmSync(zip); +} + +// The page and the DSN are on different ports, so envelopes are sent cross-origin like they are to sentry.io. +function startPageServer(bundlePath, sentryPort) { + const page = PAGE.replace('__DSN__', `http://public@localhost:${sentryPort}/1337`); + const server = createServer((req, res) => { + if (req.url === '/bundle.js') { + res.setHeader('content-type', 'text/javascript'); + res.end(readFileSync(bundlePath)); + return; + } + res.setHeader('content-type', 'text/html'); + res.end(page); + }); + return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve(server))); +} + +function launchChrome(userDataDir) { + const chrome = spawn(CHROME, [ + '--headless', + '--no-sandbox', + '--disable-gpu', + '--remote-debugging-port=0', + '--window-size=800,1200', + `--user-data-dir=${userDataDir}`, + 'about:blank', + ]); + const port = new Promise((resolve, reject) => { + let stderr = ''; + chrome.stderr.on('data', chunk => { + stderr += chunk; + const match = stderr.match(/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//); + if (match) { + resolve(match[1]); + } + }); + chrome.on('exit', code => reject(new Error(`Chromium exited with ${code}:\n${stderr}`))); + }); + return { chrome, port }; +} + +async function connect(port) { + // The DevTools server can come up before the initial page target exists. + let page; + for (let attempt = 0; !page && attempt < 50; attempt++) { + const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + page = targets.find(target => target.type === 'page'); + if (!page) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + } + if (!page) { + throw new Error('Chromium has no page target'); + } + const cdp = new CDPClient({ url: page.webSocketDebuggerUrl, retries: 1 }); + await cdp.connect(); + return cdp; +} + +function waitForEvent(cdp, method) { + return new Promise(resolve => { + const off = cdp.on(method, () => { + off(); + resolve(); + }); + }); +} + +async function evaluate(cdp, expression) { + const { result, exceptionDetails } = await cdp.send('Runtime.evaluate', { + expression, + awaitPromise: true, + returnByValue: true, + }); + if (exceptionDetails) { + throw new Error(`Evaluating failed: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`); + } + return result.value; +} + +function collectItems(spans, events) { + return ([, items]) => { + for (const [header, payload] of items) { + if (header.type === 'span') { + spans.push(...payload.items); + } else if (header.type === 'event') { + events.push(payload); + } + } + }; +} + +const isPageload = span => span.is_segment && getSpanOp(span) === 'pageload'; + +async function runBundle(bundle) { + const spans = []; + const events = []; + const errors = []; + const [sentryPort, closeSentryServer] = await createBasicSentryServer(collectItems(spans, events)); + const server = await startPageServer(path.join(BUNDLES_DIR, bundle), sentryPort); + const userDataDir = mkdtempSync(path.join(tmpdir(), 'chromium-profile-')); + const { chrome, port } = launchChrome(userDataDir); + let cdp; + + try { + cdp = await connect(await port); + cdp.on('Runtime.exceptionThrown', ({ exceptionDetails }) => { + errors.push(exceptionDetails.exception?.description ?? exceptionDetails.text); + }); + cdp.on('Runtime.consoleAPICalled', ({ type, args }) => { + if (type === 'error') { + errors.push(args.map(arg => arg.value ?? arg.description).join(' ')); + } + }); + cdp.on('Log.entryAdded', ({ entry }) => { + if (entry.level === 'error') { + errors.push(entry.text); + } + }); + await Promise.all([cdp.send('Runtime.enable'), cdp.send('Log.enable'), cdp.send('Page.enable')]); + + const loaded = waitForEvent(cdp, 'Page.loadEventFired'); + await cdp.send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/` }); + await loaded; + + // Layout shifts, then a click: shifts within 500ms after an input don't count towards CLS. + await evaluate( + cdp, + `(async () => { + const element = document.getElementById('shift'); + for (let i = 1; i <= 10; i++) { + element.style.top = 200 + i * 40 + 'px'; + await new Promise(resolve => setTimeout(resolve, 50)); + } + })()`, + ); + const { x, y } = await evaluate( + cdp, + `(() => { + const rect = document.getElementById('button').getBoundingClientRect(); + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; + })()`, + ); + for (const type of ['mousePressed', 'mouseReleased']) { + await cdp.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 }); + } + await new Promise(resolve => setTimeout(resolve, 300)); + + // Without these, the checks that CLS and INP are not sent would pass without testing anything. + const { layoutShifts, clicked } = await evaluate( + cdp, + `new Promise(resolve => { + const done = layoutShifts => resolve({ layoutShifts, clicked: document.getElementById('button').dataset.clicked === 'true' }); + new PerformanceObserver(list => done(list.getEntries().length)).observe({ type: 'layout-shift', buffered: true }); + setTimeout(() => done(0), 500); + })`, + ); + if (!layoutShifts || !clicked) { + throw new Error(`Page did not shift (${layoutShifts} layout shifts) or was not clicked (${clicked})`); + } + + // Hiding the page is what makes the SDK finalize LCP and CLS. + await evaluate( + cdp, + `(() => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }); + document.dispatchEvent(new Event('visibilitychange')); + })()`, + ); + // The pageload span, which carries FCP, FP and TTFB, ends once the page has been idle for a second. + const deadline = Date.now() + 10_000; + while (!spans.some(isPageload) && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + } finally { + await cdp?.close(); + chrome.kill(); + server.close(); + closeSentryServer(); + rmSync(userDataDir, { recursive: true, force: true }); + } + + const pageload = spans.find(isPageload); + const ops = new Set(spans.map(getSpanOp)); + const failures = [...new Set(errors)].map(error => `page error: ${error}`); + + for (const event of events) { + failures.push(`error event sent: ${event.exception?.values?.[0]?.value ?? event.message}`); + } + if (!pageload) { + failures.push('no pageload span sent'); + } else { + if (!pageload.attributes['user_agent.original']?.value.includes('Chrome/80.')) { + failures.push(`not running in Chrome 80: ${pageload.attributes['user_agent.original']?.value}`); + } + for (const vital of EXPECTED_PAGELOAD_VITALS) { + if (typeof pageload.attributes[`browser.web_vital.${vital}.value`]?.value !== 'number') { + failures.push(`pageload span has no ${vital.toUpperCase()}`); + } + } + } + const lcp = spans.find(span => getSpanOp(span) === 'ui.webvital.lcp'); + if (typeof lcp?.attributes['browser.web_vital.lcp.value']?.value !== 'number') { + failures.push('no LCP span sent'); + } + for (const unexpected of UNEXPECTED_SPAN_OPS) { + if (ops.has(unexpected)) { + failures.push(`unexpected ${unexpected} span sent`); + } + } + + return failures; +} + +await ensureChromium(); + +const results = await Promise.all(BUNDLES.map(runBundle)); +results.forEach((failures, index) => { + // eslint-disable-next-line no-console + console.log( + `${failures.length ? '✘' : '✓'} ${BUNDLES[index]}${failures.map(failure => `\n ${failure}`).join('')}`, + ); +}); +process.exitCode = results.some(failures => failures.length) ? 1 : 0; diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts index 60d47967bd65..ff7e526ad3db 100644 --- a/dev-packages/bun-integration-tests/node-suites/excludes.ts +++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts @@ -120,6 +120,7 @@ export const NO_AUTO_INSTRUMENTATION = [ 'suites/tracing/openai/v6/test.ts', 'suites/tracing/openai/v7/test.ts', 'suites/tracing/orchestrion-lazy-registration/test.ts', + 'suites/tracing/pi-ai/test.ts', 'suites/tracing/pi-durable/test.ts', 'suites/tracing/postgres/test.ts', 'suites/tracing/postgresjs/test.ts', diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts index e91fb5ed133b..f07edbcb8c58 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts @@ -35,6 +35,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { "sentry-cli-mock.json": "["release","create","CURRENT_SHA","--project","fake-project"], ["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts index e91fb5ed133b..f07edbcb8c58 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts @@ -35,6 +35,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { "sentry-cli-mock.json": "["release","create","CURRENT_SHA","--project","fake-project"], ["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts index 64fdb039b963..7aac92da1976 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts @@ -34,6 +34,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { ", "sentry-cli-mock.json": "["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js new file mode 100644 index 000000000000..588483bf6eea --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js @@ -0,0 +1,14 @@ +import * as esbuild from "esbuild"; +import { sentryEsbuildPlugin } from "@sentry/bundler-plugins/esbuild"; +import { sentryConfig } from "../configs/sourcemaps-assets-auto.config.js"; + +await esbuild.build({ + entryPoints: ["./src/entry1.js", "./src/entry2.js"], + bundle: true, + outdir: "./out/sourcemaps-assets-auto", + minify: false, + format: "esm", + splitting: true, + chunkNames: "[name]", + plugins: [sentryEsbuildPlugin(sentryConfig)], +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts new file mode 100644 index 000000000000..4751e8acc361 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts @@ -0,0 +1,33 @@ +import { expect } from "vitest"; +import { test } from "./utils"; + +test(import.meta.url, ({ runBundler, readOutputFiles }) => { + runBundler({ SENTRY_TEST_RECORD_UPLOADED_SOURCES: "1" }); + const files = readOutputFiles(); + + expect(Object.keys(files).sort()).toMatchInlineSnapshot(` + [ + "chunk.js", + "entry1.js", + "entry2.js", + "sentry-cli-mock.json", + "sentry-uploaded-sources.json", + ] + `); + expect(JSON.parse(files["sentry-uploaded-sources.json"]!)).toMatchInlineSnapshot(` + [ + [ + "sentry-debug-id-stub:_sentry-debug-id-injection-stub?sentry-module-id=00000000-0000-0000-0000-000000000000", + "../../src/entry1.js", + "../../src/entry1.js", + ], + ] + `); + expect(files["sentry-cli-mock.json"]).toMatchInlineSnapshot(` + "["release","create","CURRENT_SHA","--project","fake-project"], + ["release","set-commits","CURRENT_SHA","--auto"], + ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], + " + `); +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js new file mode 100644 index 000000000000..8737a7c03287 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js @@ -0,0 +1,14 @@ +import * as esbuild from "esbuild"; +import { sentryEsbuildPlugin } from "@sentry/bundler-plugins/esbuild"; +import { sentryConfig } from "../configs/sourcemaps-ignore-auto.config.js"; + +await esbuild.build({ + entryPoints: ["./src/entry1.js", "./src/entry2.js"], + bundle: true, + outdir: "./out/sourcemaps-ignore-auto", + minify: false, + format: "esm", + splitting: true, + chunkNames: "[name]", + plugins: [sentryEsbuildPlugin(sentryConfig)], +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts new file mode 100644 index 000000000000..4751e8acc361 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts @@ -0,0 +1,33 @@ +import { expect } from "vitest"; +import { test } from "./utils"; + +test(import.meta.url, ({ runBundler, readOutputFiles }) => { + runBundler({ SENTRY_TEST_RECORD_UPLOADED_SOURCES: "1" }); + const files = readOutputFiles(); + + expect(Object.keys(files).sort()).toMatchInlineSnapshot(` + [ + "chunk.js", + "entry1.js", + "entry2.js", + "sentry-cli-mock.json", + "sentry-uploaded-sources.json", + ] + `); + expect(JSON.parse(files["sentry-uploaded-sources.json"]!)).toMatchInlineSnapshot(` + [ + [ + "sentry-debug-id-stub:_sentry-debug-id-injection-stub?sentry-module-id=00000000-0000-0000-0000-000000000000", + "../../src/entry1.js", + "../../src/entry1.js", + ], + ] + `); + expect(files["sentry-cli-mock.json"]).toMatchInlineSnapshot(` + "["release","create","CURRENT_SHA","--project","fake-project"], + ["release","set-commits","CURRENT_SHA","--auto"], + ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], + " + `); +}); diff --git a/dev-packages/bundler-plugin-integration-tests/package.json b/dev-packages/bundler-plugin-integration-tests/package.json index 9c61edd0b2f5..9f42dcc5fd21 100644 --- a/dev-packages/bundler-plugin-integration-tests/package.json +++ b/dev-packages/bundler-plugin-integration-tests/package.json @@ -6,8 +6,8 @@ "scripts": { "test": "node setup.mjs && vitest run --pool threads --test-timeout=10000", "check:types": "tsc --project ./tsconfig.json --noEmit", - "clean": "run-s clean:build", - "clean:all": "run-p clean clean:deps", + "clean": "pnpm run clean:build", + "clean:all": "pnpm run \"/^(clean|clean:deps)$/\"", "clean:build": "node ../../scripts/rm.mjs ./fixtures/*/out", "clean:deps": "node ../../scripts/rm.mjs node_modules" }, diff --git a/dev-packages/bundler-tests/tests/runtime-entries.test.ts b/dev-packages/bundler-tests/tests/runtime-entries.test.ts index 156102cc6765..90dcb2833f8c 100644 --- a/dev-packages/bundler-tests/tests/runtime-entries.test.ts +++ b/dev-packages/bundler-tests/tests/runtime-entries.test.ts @@ -17,24 +17,33 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '../../..'); const FIXTURE_DIR = path.join(__dirname, '..', 'dist', 'runtime-entries'); +/** Third-party build tools. No Sentry code is reachable through them. */ +const BUILD_TOOL_PATTERNS: RegExp[] = [ + /(^|\/)node_modules\/(vite|webpack|rollup|esbuild|oxc-parser)\//, + /(^|\/)node_modules\/@(babel|rollup|oxc-parser)\//, + /\.wasm$/, +]; + const BUILD_TIME_PATTERNS: RegExp[] = [ /(^|\/)packages\/bundler-plugins\//, /(^|\/)node_modules\/@sentry\/bundler-plugins(\/|$)/, /(^|\/)packages\/server-utils\/build\/[^/]+\/orchestrion\/bundler\//, - /(^|\/)node_modules\/(vite|webpack|rollup|esbuild|oxc-parser)\//, - /(^|\/)node_modules\/@(babel|rollup|oxc-parser)\//, - /\.wasm$/, + ...BUILD_TOOL_PATTERNS, +]; + +const RUNTIME_INJECTION_PATTERNS: RegExp[] = [ + /(^|\/)packages\/server-runtime-injection\//, + /(^|\/)node_modules\/@sentry\/server-runtime-injection(\/|$)/, ]; -const KNOWN_VIOLATIONS = new Set([ - // These root entries also re-export config-time code (`sentryAstro`, - // `withSentry`). They must keep it until v12 for backwards compatibility. - '@sentry/astro', - '@sentry/solidstart', - // Remix 3 has no bundler. Its asset server runs the orchestrion - // transform on browser modules at request time. - '@sentry/remix/v3', - '@sentry/remix/v3/node', +// These config entries import the `@sentry/node` root, which installs +// runtime injection when a client is made. +const KNOWN_RUNTIME_INJECTION_VIOLATIONS = new Set([ + // `getSentryRelease` + '@sentry/nextjs/config', + '@sentry/sveltekit/vite', + // `setupSentryNitroModule`, through the `@sentry/nitro` root + '@sentry/solidstart/vite', ]); type Format = 'esm' | 'cjs'; @@ -43,6 +52,8 @@ interface Case { specifier: string; conditions: string[]; formats: Format[]; + /** The entry reaches build-time tooling on purpose. Drop this when the test fails. */ + knownViolation?: true; } const NODE = ['node']; @@ -81,7 +92,11 @@ const CASES: Case[] = [ { specifier: '@sentry/sveltekit', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/sveltekit/opentelemetry-api', conditions: NODE, formats: BOTH }, - { specifier: '@sentry/astro', conditions: NODE, formats: BOTH }, + // The Node root entry also re-exports config-time code (`sentryAstro`). It must keep it until v12 + // for backwards compatibility. + { specifier: '@sentry/astro', conditions: NODE, formats: BOTH, knownViolation: true }, + { specifier: '@sentry/astro', conditions: WORKERD, formats: BOTH }, + { specifier: '@sentry/astro', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/astro/middleware', conditions: NODE, formats: BOTH }, { specifier: '@sentry/astro/import', conditions: NODE, formats: ESM }, @@ -93,10 +108,14 @@ const CASES: Case[] = [ { specifier: '@sentry/remix', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/remix/cloudflare', conditions: WORKERD, formats: BOTH }, { specifier: '@sentry/remix/import', conditions: NODE, formats: ESM }, - { specifier: '@sentry/remix/v3', conditions: NODE, formats: ESM }, - { specifier: '@sentry/remix/v3/node', conditions: NODE, formats: ESM }, + // Remix 3 has no bundler. Its asset server runs the orchestrion transform on browser modules at + // request time. + { specifier: '@sentry/remix/v3', conditions: NODE, formats: ESM, knownViolation: true }, + { specifier: '@sentry/remix/v3/node', conditions: NODE, formats: ESM, knownViolation: true }, - { specifier: '@sentry/solidstart', conditions: NODE, formats: BOTH }, + // The root entry also re-exports config-time code (`withSentry`). It must keep it until v12 for + // backwards compatibility. + { specifier: '@sentry/solidstart', conditions: NODE, formats: BOTH, knownViolation: true }, { specifier: '@sentry/tanstackstart-react', conditions: NODE, formats: BOTH }, { specifier: '@sentry/tanstackstart-react/import', conditions: NODE, formats: ESM }, @@ -138,8 +157,8 @@ function writeFixture(specifier: string, conditions: string[], format: Format): return file; } -function isBuildTime(file: string): boolean { - return BUILD_TIME_PATTERNS.some(pattern => pattern.test(file)); +function matches(file: string, patterns: RegExp[]): boolean { + return patterns.some(pattern => pattern.test(file)); } type Reasons = Awaited>['reasons']; @@ -173,10 +192,10 @@ function importChain(reasons: Reasons, entry: string, file: string): string[] { } /** - * Each place where a runtime module imports a build-time module, as the - * import chain from the entry. + * Each place where a module imports a module that matches `targets`, as + * the import chain from the entry. */ -async function findBuildTimeImports(fixture: string, conditions: string[]): Promise { +async function findImports(fixture: string, conditions: string[], targets: RegExp[]): Promise { const imports: [importer: string, file: string][] = []; const { fileList, reasons } = await nodeFileTrace([fixture], { @@ -186,14 +205,14 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom // A dynamic `fs` path in config code makes nft glob the whole repo. // That is slow and finds user files, not package code. analysis: { emitGlobs: false }, - // Stop at the first build-time module, instead of tracing all of Vite - // or Babel. `.wasm` files are assets, so they stay in the trace with - // their importer. - ignore: file => isBuildTime(file) && !file.endsWith('.wasm'), + // Stop at the first target, and do not trace all of Vite or Babel. + // `.wasm` files are assets, so they stay in the trace with their + // importer. + ignore: file => matches(file, [...targets, ...BUILD_TOOL_PATTERNS]) && !file.endsWith('.wasm'), async resolve(id, parent, job, cjsResolve) { const resolved = await resolve(id, parent, job, cjsResolve); for (const file of [resolved].flat()) { - if (isBuildTime(file)) { + if (matches(file, targets)) { imports.push([path.relative(ROOT_DIR, parent), path.relative(ROOT_DIR, file)]); } } @@ -202,7 +221,7 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom }); for (const file of fileList) { - if (file.endsWith('.wasm')) { + if (file.endsWith('.wasm') && matches(file, targets)) { for (const parent of reasons.get(file)?.parents ?? []) { imports.push([parent, file]); } @@ -217,19 +236,26 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom } describe('server runtime entries do not reach build-time tooling', () => { - for (const { specifier, conditions, formats } of CASES) { + for (const { specifier, conditions, formats, knownViolation } of CASES) { for (const format of formats) { const name = `${specifier} (${format}, conditions: ${conditions.join(', ')})`; - if (KNOWN_VIOLATIONS.has(specifier)) { + if (knownViolation) { test(`${name} is a known violation`, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); - // Remove the entry from KNOWN_VIOLATIONS when this fails. + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).not.toEqual([]); }); } else { test(name, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).toEqual([]); }); } @@ -241,13 +267,38 @@ describe('build-time entries reach build-time tooling', () => { for (const { specifier, conditions, formats } of BUILD_TIME_CASES) { for (const format of formats) { test(`${specifier} (${format}, conditions: ${conditions.join(', ')})`, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).not.toEqual([]); }); } } }); +describe('build-time entries do not reach runtime injection', () => { + for (const { specifier, conditions, formats } of BUILD_TIME_CASES) { + for (const format of formats) { + const name = `${specifier} (${format}, conditions: ${conditions.join(', ')})`; + const find = (): Promise => + findImports(writeFixture(specifier, conditions, format), conditions, RUNTIME_INJECTION_PATTERNS); + + if (KNOWN_RUNTIME_INJECTION_VIOLATIONS.has(specifier)) { + test(`${name} is a known violation`, async () => { + // Remove the entry from KNOWN_RUNTIME_INJECTION_VIOLATIONS when this fails. + expect(await find()).not.toEqual([]); + }); + } else { + test(name, async () => { + expect(await find()).toEqual([]); + }); + } + } + } +}); + test('every export of a tested package is classified', () => { const classified = new Set([...CASES, ...BUILD_TIME_CASES].map(({ specifier }) => specifier)); for (const specifier of CLIENT_ENTRIES) { diff --git a/dev-packages/bundler-tests/tests/startup.test.ts b/dev-packages/bundler-tests/tests/startup.test.ts new file mode 100644 index 000000000000..2a94028e2663 --- /dev/null +++ b/dev-packages/bundler-tests/tests/startup.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * Node resolves, reads and evaluates each published file on its own, so + * the number of files that `@sentry/node` loads sets most of its startup + * cost. Our CJS builds publish flat entry files with a few shared chunks. + * The ESM builds keep one file per module, because bundlers use them and + * drop unused files. A count is stable in CI, where a timing is not. + */ + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE_DIR = path.join(__dirname, '..', 'dist', 'startup'); + +// One entry file and its shared chunks. +const MAX_FILES_PER_PACKAGE = 10; + +const COUNTER = `import { writeSync } from 'node:fs'; +import { registerHooks } from 'node:module'; +const files = new Set(); +registerHooks({ + load(url, context, nextLoad) { + if (url.startsWith('file:')) files.add(url); + return nextLoad(url, context); + }, +}); +// A pipe write from an exit handler must be sync, or Node cuts it off. +process.on('exit', () => writeSync(1, JSON.stringify([...files]))); +`; + +function loadedFiles(specifier: string): string[] { + fs.mkdirSync(FIXTURE_DIR, { recursive: true }); + const counter = path.join(FIXTURE_DIR, 'counter.mjs'); + fs.writeFileSync(counter, COUNTER); + const fixture = path.join(FIXTURE_DIR, `${specifier.replace(/[@/]/g, '_')}.cjs`); + fs.writeFileSync(fixture, `require('${specifier}');\n`); + + const output = execFileSync(process.execPath, ['--import', counter, fixture], { encoding: 'utf8' }); + return (JSON.parse(output) as string[]).map(url => fileURLToPath(url)).filter(file => file !== fixture); +} + +/** The package that `file` belongs to, for workspace and installed packages. */ +function packageOf(file: string): string { + const installed = file.split('/node_modules/').at(-1) as string; + if (installed !== file) { + const [scope, name] = installed.split('/'); + return scope?.startsWith('@') ? `${scope}/${name}` : (scope as string); + } + const workspace = file.match(/\/packages\/([^/]+)\//); + return workspace ? `@sentry/${workspace[1]}` : file; +} + +describe('@sentry/node startup', () => { + test(`each Sentry package loads at most ${MAX_FILES_PER_PACKAGE} files`, () => { + const counts: Record = {}; + for (const file of loadedFiles('@sentry/node')) { + const pkg = packageOf(file); + if (pkg.startsWith('@sentry/')) { + counts[pkg] = (counts[pkg] ?? 0) + 1; + } + } + + const tooMany = Object.fromEntries(Object.entries(counts).filter(([, count]) => count > MAX_FILES_PER_PACKAGE)); + expect(tooMany).toEqual({}); + }); +}); diff --git a/dev-packages/cloudflare-integration-tests/expect.ts b/dev-packages/cloudflare-integration-tests/expect.ts index 71eb5c9963c4..5d7699e70367 100644 --- a/dev-packages/cloudflare-integration-tests/expect.ts +++ b/dev-packages/cloudflare-integration-tests/expect.ts @@ -1,6 +1,7 @@ import type { Contexts, Envelope, Event, SdkInfo } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; import { expect } from 'vitest'; +import { supports } from './runtime'; export const UUID_MATCHER = expect.stringMatching(/^[\da-f]{32}$/); export const UUID_V4_MATCHER = expect.stringMatching( @@ -39,6 +40,7 @@ function defaultContexts(eventContexts: Contexts = {}): Contexts { trace: { trace_id: UUID_MATCHER, span_id: SHORT_UUID_MATCHER, + parent_span_id: supports({ minWorkerd: '1.20261009.1' }) ? SHORT_UUID_MATCHER : undefined, }, cloud_resource: { 'cloud.provider': 'cloudflare' }, culture: { timezone: expect.any(String) }, diff --git a/dev-packages/cloudflare-integration-tests/package.json b/dev-packages/cloudflare-integration-tests/package.json index 869263da78bb..a1ddbfeaaac4 100644 --- a/dev-packages/cloudflare-integration-tests/package.json +++ b/dev-packages/cloudflare-integration-tests/package.json @@ -28,7 +28,7 @@ "@prisma/client": "6.15.0", "@sentry-internal/test-utils": "11.12.0", "@sentry/cloudflare": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "11.12.0", "@sentry/hono": "11.12.0", "ai": "^6.0.0", diff --git a/dev-packages/cloudflare-integration-tests/runtime.ts b/dev-packages/cloudflare-integration-tests/runtime.ts new file mode 100644 index 000000000000..9f175f0c94be --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/runtime.ts @@ -0,0 +1,31 @@ +import { parseSemver } from '@sentry/core'; +import { createRequire } from 'module'; + +// `wrangler dev` runs the workerd that its own miniflare depends on. +const wranglerRequire = createRequire(createRequire(__filename).resolve('wrangler/package.json')); +const miniflareRequire = createRequire(wranglerRequire.resolve('miniflare/package.json')); +const WORKERD_VERSION = parseSemver((miniflareRequire('workerd/package.json') as { version: string }).version); + +export type Requirements = { + /** Lowest workerd version that runs the tests, for example `1.20261009.1`. */ + minWorkerd?: string; +}; + +/** + * Whether the workerd that runs the Workers meets the requirements of the tests, for use in `it.runIf` and + * `it.skipIf`. The pinned wrangler of the required CI job runs an older workerd than the latest wrangler of the + * optional CI job. + */ +export function supports({ minWorkerd }: Requirements): boolean { + if (!minWorkerd) { + return true; + } + + const required = parseSemver(minWorkerd); + const difference = + (WORKERD_VERSION.major || 0) - (required.major || 0) || + (WORKERD_VERSION.minor || 0) - (required.minor || 0) || + (WORKERD_VERSION.patch || 0) - (required.patch || 0); + + return difference >= 0; +} diff --git a/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts b/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts index 33ba266ed7cc..ebf929489edd 100644 --- a/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { eventEnvelope } from '../../expect'; +import { eventEnvelope, SHORT_UUID_MATCHER, UUID_MATCHER } from '../../expect'; import { createRunner } from '../../runner'; import { getSpanOp, getSpansFromEnvelope } from '../../spanUtils'; @@ -28,6 +28,12 @@ it('Hono app captures parametrized errors (Hono SDK)', async ({ signal }) => { method: 'GET', url: expect.stringContaining('/error/param-123'), }, + contexts: { + trace: { + trace_id: UUID_MATCHER, + span_id: SHORT_UUID_MATCHER, + }, + }, breadcrumbs: [ { timestamp: expect.any(Number), diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts new file mode 100644 index 000000000000..21cd5c7e529e --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts @@ -0,0 +1,36 @@ +import * as Sentry from '@sentry/cloudflare'; +import { DurableObject } from 'cloudflare:workers'; + +interface Env { + SENTRY_DSN: string; + TEST_DURABLE_OBJECT: DurableObjectNamespace; +} + +export class TestDurableObject extends DurableObject { + async sayHello(name: string): Promise { + return `Hello, ${name}`; + } +} + +export default { + async fetch(request: Request, env: Env): Promise { + const { pathname } = new URL(request.url); + + // `import.meta.resolve` only exists with the new module registry. + if (pathname === '/import-meta-resolve') { + return new Response(typeof import.meta.resolve); + } + + if (pathname === '/error') { + throw new Error('Error with the new module registry'); + } + + if (pathname === '/durable-object') { + const stub = env.TEST_DURABLE_OBJECT.get(env.TEST_DURABLE_OBJECT.idFromName('test')); + return new Response(await stub.sayHello('world')); + } + + Sentry.startSpan({ name: 'test-span', op: 'test' }, () => {}); + return new Response('OK'); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts new file mode 100644 index 000000000000..e577550ae0b8 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts @@ -0,0 +1,6 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({ + dsn: env.SENTRY_DSN, + tracesSampleRate: 1.0, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts new file mode 100644 index 000000000000..295e7d7aac10 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts @@ -0,0 +1,60 @@ +import type { Event } from '@sentry/core'; +import { HTTP_SERVER, RPC } from '@sentry/conventions/op'; +import { expect, it } from 'vitest'; +import { createRunner } from '../../runner'; +import { getSpanOp, getSpansFromEnvelope } from '../../spanUtils'; + +it('runs the worker with the new module registry', async ({ signal }) => { + const runner = createRunner(__dirname).start(signal); + expect(await runner.makeRequest('get', '/import-meta-resolve')).toBe('function'); +}); + +it('captures errors thrown by the fetch handler', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect(envelope => { + const event = envelope[1]?.[0]?.[1] as Event; + expect(event.exception?.values?.[0]).toEqual({ + type: 'Error', + value: 'Error with the new module registry', + stacktrace: { frames: expect.any(Array) }, + mechanism: { type: 'auto.http.cloudflare', handled: false }, + }); + }) + .unordered() + .start(signal); + + await runner.makeRequest('get', '/error', { expectError: true }); + await runner.completed(); +}); + +it('sends the spans of the fetch handler', async ({ signal }) => { + const runner = createRunner(__dirname).start(signal); + const spansPromise = runner.collectStreamedSpans(spansOfTrace => spansOfTrace.length === 2); + + await runner.makeRequest('get', '/'); + + const spans = await spansPromise; + const segmentSpan = spans.find(span => span.is_segment); + const childSpan = spans.find(span => span.name === 'test-span'); + + expect(segmentSpan?.name).toBe('GET /'); + expect(getSpanOp(segmentSpan!)).toBe(HTTP_SERVER); + expect(childSpan?.parent_span_id).toBe(segmentSpan?.span_id); + expect(getSpanOp(childSpan!)).toBe('test'); +}); + +it('traces Durable Object RPC calls', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect(envelope => { + const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment); + expect(segmentSpan?.name).toBe('sayHello'); + expect(getSpanOp(segmentSpan!)).toBe(RPC); + }) + .unordered() + .start(signal); + + const response = await runner.makeRequest('get', '/durable-object'); + expect(response).toBe('Hello, world'); + + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc new file mode 100644 index 000000000000..85ceb154ea5c --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc @@ -0,0 +1,12 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "new-module-registry", + "main": "index.ts", + "compatibility_date": "2025-06-17", + // `new_module_registry` becomes the default for compatibility dates from 2026-11-17 on. + "compatibility_flags": ["nodejs_compat", "new_module_registry"], + "durable_objects": { + "bindings": [{ "name": "TEST_DURABLE_OBJECT", "class_name": "TestDurableObject" }], + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["TestDurableObject"] }], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts b/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts index adf52419022f..430e5baf0487 100644 --- a/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts @@ -224,12 +224,12 @@ it('sends a streamed span envelope with correct spans for a manually started spa value: '/', }, 'url.port': { - type: 'string', - value: expect.stringMatching(/^\d{4,5}$/), + type: 'integer', + value: expect.any(Number), }, 'url.scheme': { type: 'string', - value: 'http:', + value: 'http', }, 'user_agent.original': { type: 'string', diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts new file mode 100644 index 000000000000..4bc14ed89a89 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts @@ -0,0 +1,5 @@ +export default { + async fetch() { + return new Response('ok'); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts new file mode 100644 index 000000000000..70632becce3a --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts @@ -0,0 +1,19 @@ +interface Env { + PRODUCER: Fetcher; +} + +// Nothing is wrapped manually, the Vite plugin wraps the default export. +export default { + async fetch(_request, env) { + return env.PRODUCER.fetch('http://fake-host/'); + }, + // workerd calls `tailStream()` with the producer's onset event, then calls + // the returned object for the later events of that invocation. + tailStream() { + return { + outcome() { + throw new Error('Error from the tailStream outcome handler'); + }, + }; + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts new file mode 100644 index 000000000000..9de8aec879bb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts @@ -0,0 +1,5 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({ + dsn: env.SENTRY_DSN, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts new file mode 100644 index 000000000000..3d906ace27bb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts @@ -0,0 +1,25 @@ +import type { Event } from '@sentry/core'; +import { join } from 'path'; +import { expect, it } from 'vitest'; +import { createRunner } from '../../runner'; + +it('captures errors thrown by the handler that tailStream returns', async ({ signal }) => { + const runner = createRunner(__dirname) + // A tail consumer in another `wrangler dev` process does not receive + // streaming tail events, so the producer runs in the same process. + .withWranglerArgs('-c', join(__dirname, 'dist/cloudflare_tail_stream_producer/wrangler.json')) + .expect(envelope => { + const event = envelope[1][0]?.[1] as Event; + expect(event.exception?.values?.[0]).toEqual( + expect.objectContaining({ + type: 'Error', + value: 'Error from the tailStream outcome handler', + mechanism: { type: 'auto.faas.cloudflare.tail_stream', handled: false }, + }), + ); + }) + .start(signal); + + await runner.makeRequest('get', '/'); + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts new file mode 100644 index 000000000000..71ebb6c3e6fa --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts @@ -0,0 +1,10 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [ + cloudflare({ auxiliaryWorkers: [{ configPath: './wrangler-producer.jsonc' }] }), + sentryCloudflareVitePlugin(), + ], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc new file mode 100644 index 000000000000..97e22bd98f7d --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "cloudflare-tail-stream-producer", + "main": "index-producer.ts", + "compatibility_date": "2025-06-17", + "compatibility_flags": ["nodejs_compat"], + "streaming_tail_consumers": [{ "service": "cloudflare-tail-stream-consumer" }], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc new file mode 100644 index 000000000000..0f4b2e593c3c --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "cloudflare-tail-stream-consumer", + "main": "index.ts", + "compatibility_date": "2025-06-17", + "compatibility_flags": ["nodejs_compat"], + "services": [{ "binding": "PRODUCER", "service": "cloudflare-tail-stream-producer" }], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts new file mode 100644 index 000000000000..4da39ebf2b88 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/cloudflare'; + +// `getActiveSpan` and `Span.spanContext` are newer than the installed workers types, and older runtimes do not have +// them. +interface CloudflareTracing { + getActiveSpan?(): { isTraced?: boolean; spanContext?(): { traceId: string; spanId: string } } | undefined; +} + +export default { + async fetch(_request, _env, ctx) { + const span = (ctx.tracing as unknown as CloudflareTracing | undefined)?.getActiveSpan?.(); + const spanContext = span?.isTraced ? span.spanContext?.() : undefined; + + Sentry.captureException(new Error('Error in a Cloudflare trace')); + + return Response.json(spanContext ? { traceId: spanContext.traceId, spanId: spanContext.spanId } : null); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts new file mode 100644 index 000000000000..0d33b7bb23d0 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts @@ -0,0 +1,6 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string; TRACES_SAMPLE_RATE: string }) => ({ + dsn: env.SENTRY_DSN, + tracesSampleRate: env.TRACES_SAMPLE_RATE ? Number(env.TRACES_SAMPLE_RATE) : undefined, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts new file mode 100644 index 000000000000..2f6323969634 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts @@ -0,0 +1,104 @@ +import type { Event, SerializedStreamedSpanContainer } from '@sentry/core'; +import { expect, it } from 'vitest'; +import { SHORT_UUID_MATCHER, UUID_MATCHER } from '../../../expect'; +import { createRunner } from '../../../runner'; +import { supports } from '../../../runtime'; + +// `Span.spanContext()` ships in workerd 1.20261009.1. Without it, the Worker responds with `null`. +it.runIf(supports({ minWorkerd: '1.20261009.1' }))( + 'uses the Cloudflare trace for the error event when tracing is not set up', + async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + expect(cloudflareSpan).toEqual({ traceId: UUID_MATCHER, spanId: SHORT_UUID_MATCHER }); + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace).toEqual({ + trace_id: cloudflareSpan?.traceId, + span_id: SHORT_UUID_MATCHER, + parent_span_id: cloudflareSpan?.spanId, + }); + }, +); + +it.runIf(supports({ minWorkerd: '1.20261009.1' }))( + 'starts its own trace when tracing is set up', + async ({ signal }) => { + const errorEvents: Event[] = []; + const spanContainers: SerializedStreamedSpanContainer[] = []; + + const runner = createRunner(__dirname) + .withWranglerArgs('--var', 'TRACES_SAMPLE_RATE:1') + .unordered() + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('span'); + spanContainers.push(envelope[1][0][1] as SerializedStreamedSpanContainer); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + const segmentSpans = spanContainers.flatMap(container => container.items).filter(span => span.is_segment); + expect(cloudflareSpan).toEqual({ traceId: UUID_MATCHER, spanId: SHORT_UUID_MATCHER }); + expect(errorEvents).toHaveLength(1); + expect(segmentSpans).toHaveLength(1); + expect(segmentSpans[0]?.trace_id).not.toBe(cloudflareSpan?.traceId); + expect(segmentSpans[0]?.parent_span_id).toBeUndefined(); + expect(errorEvents[0]?.contexts?.trace?.trace_id).toBe(segmentSpans[0]?.trace_id); + }, +); + +it.skipIf(supports({ minWorkerd: '1.20261009.1' }))( + 'starts its own trace on runtimes without `Span.spanContext()`', + async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + expect(cloudflareSpan).toBeNull(); + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace).toEqual({ trace_id: UUID_MATCHER, span_id: SHORT_UUID_MATCHER }); + }, +); + +it('continues an incoming Sentry trace instead of the Cloudflare trace', async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + await runner.makeRequest('get', '/', { + headers: { 'sentry-trace': '12345678901234567890123456789012-1234567890123456-1' }, + }); + await runner.completed(); + + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace?.trace_id).toBe('12345678901234567890123456789012'); + expect(errorEvents[0]?.contexts?.trace?.parent_span_id).toBe('1234567890123456'); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc new file mode 100644 index 000000000000..37b1010b07a7 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc @@ -0,0 +1,9 @@ +{ + "name": "cloudflare-trace-worker", + "compatibility_date": "2025-06-17", + "main": "index.ts", + "compatibility_flags": ["nodejs_compat"], + "vars": { + "TRACES_SAMPLE_RATE": "", + }, +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts index f9916e5c03c7..fb98b6ed2bc5 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { eventEnvelope } from '../../../expect'; +import { eventEnvelope, SHORT_UUID_MATCHER, UUID_MATCHER } from '../../../expect'; import { createRunner } from '../../../runner'; import { getSpanOp, getSpansFromEnvelope } from '../../../spanUtils'; @@ -29,6 +29,12 @@ it('omits the span name from the DSC for url-source spans when tracing is enable method: 'GET', url: expect.any(String), }, + contexts: { + trace: { + trace_id: UUID_MATCHER, + span_id: SHORT_UUID_MATCHER, + }, + }, }, { includeSamplingFields: true, includeSampleRand: true, includeTransaction: false }, ), diff --git a/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/index.ts b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/index.ts new file mode 100644 index 000000000000..4f77c798e2e2 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/index.ts @@ -0,0 +1,105 @@ +import * as Sentry from '@sentry/cloudflare'; +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { NonRetryableError } from 'cloudflare:workflows'; + +interface Env { + SENTRY_DSN: string; + RUN_ERRORS_WORKFLOW: Workflow; +} + +interface WorkflowParams { + mode: string; +} + +export class RunErrorsTestWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent, step: WorkflowStep): Promise { + const { mode } = event.payload; + + if (mode === 'throw-before-step') { + throw new TypeError('Thrown before any step'); + } + + if (mode === 'non-retryable-before-step') { + throw new NonRetryableError('Non-retryable before any step'); + } + + if (mode === 'throw-after-step') { + await step.do('successful-step', async () => 'done'); + throw new Error('Thrown after a successful step'); + } + + if (mode === 'wait-for-event-timeout') { + await step.waitForEvent('wait-for-event', { type: 'never-sent', timeout: '1 second' }); + } + + if (mode === 'step-timeout') { + await step.do('slow-step', { timeout: '1 second', retries: { limit: 0, delay: 100 } }, async () => { + await new Promise(resolve => setTimeout(resolve, 5000)); + }); + } + + if (mode === 'non-serializable') { + await step.do( + 'non-serializable-step', + { retries: { limit: 0, delay: 100 } }, + (async () => () => 'function') as () => Promise, + ); + } + + if (mode === 'throw-in-step') { + await step.do('failing-step', { retries: { limit: 0, delay: 100 } }, async () => { + throw new Error('Thrown inside the step callback'); + }); + } + + if (mode === 'caught-step-error') { + try { + await step.do('failing-step', { retries: { limit: 0, delay: 100 } }, async () => { + throw new Error('Thrown inside the step callback'); + }); + } catch { + // The workflow goes on after the failed step + } + } + + if (mode === 'rethrow-new-error') { + try { + await step.do('failing-step', { retries: { limit: 0, delay: 100 } }, async () => { + throw new Error('Thrown inside the step callback'); + }); + } catch { + throw new Error('Thrown by run() after the failed step'); + } + } + } +} + +export default { + async fetch(request, env, _ctx) { + const url = new URL(request.url); + + if (url.pathname === '/trigger-workflow') { + const instance = await env.RUN_ERRORS_WORKFLOW.create({ + params: { mode: url.searchParams.get('mode') || '' }, + }); + + return Response.json({ id: instance.id }); + } + + if (url.pathname === '/flush-marker') { + Sentry.captureMessage('flush-marker'); + return Response.json({ ok: true }); + } + + const statusMatch = url.pathname.match(/^\/workflow-status\/(.+)$/); + + if (statusMatch) { + const instance = await env.RUN_ERRORS_WORKFLOW.get(statusMatch[1]!); + + return Response.json({ id: statusMatch[1], status: await instance.status() }); + } + + return new Response('Not found', { status: 404 }); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/instrument.server.ts new file mode 100644 index 000000000000..9de8aec879bb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/instrument.server.ts @@ -0,0 +1,5 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({ + dsn: env.SENTRY_DSN, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/test.ts b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/test.ts new file mode 100644 index 000000000000..6913c1f133b2 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/test.ts @@ -0,0 +1,161 @@ +import type { Envelope } from '@sentry/core'; +import { expect, it } from 'vitest'; +import { createRunner } from '../../../runner'; + +interface TriggerResponse { + id: string; +} + +interface StatusResponse { + id: string; + status: { status: string }; +} + +interface SentException { + type?: string; + value?: string; + mechanism?: { handled?: boolean; type?: string }; +} + +async function waitForWorkflowStatus( + makeRequest: (method: 'get' | 'post', path: string) => Promise, + workflowId: string, +): Promise { + for (let i = 0; i < 30; i++) { + const status = await makeRequest('get', `/workflow-status/${workflowId}`); + if (status?.status?.status === 'errored' || status?.status?.status === 'complete') { + return status; + } + await new Promise(r => setTimeout(r, 200)); + } + return undefined; +} + +// The flush marker is sent after the instance has ended and must arrive directly after the expected +// error event. A second error event for the same failure would arrive in its place and fail the test. +const flushMarkerMatcher = (envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, Record]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.message).toBe('flush-marker'); +}; + +it.for([ + { mode: 'throw-before-step', type: 'TypeError', value: 'Thrown before any step' }, + { mode: 'non-retryable-before-step', type: 'NonRetryableError', value: 'Non-retryable before any step' }, + { mode: 'throw-after-step', type: 'Error', value: 'Thrown after a successful step' }, + { mode: 'wait-for-event-timeout', type: 'Error', value: expect.stringContaining('timed out') }, + { mode: 'step-timeout', type: 'Error', value: expect.stringContaining('timed out') }, + { mode: 'non-serializable', type: 'Error', value: expect.stringContaining('not serialisable') }, +])( + 'captures one unhandled error when run() fails outside a step callback ($mode)', + async ({ mode, type, value }, { signal }) => { + const runner = createRunner(__dirname) + .expect((envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, { exception?: { values?: SentException[] } }]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.exception?.values?.[0]).toMatchObject({ + type, + value, + mechanism: { handled: false, type: 'auto.faas.cloudflare.workflow' }, + }); + }) + .expect(flushMarkerMatcher) + .start(signal); + + const trigger = await runner.makeRequest('get', `/trigger-workflow?mode=${mode}`); + expect(trigger?.id).toBeDefined(); + + const status = await waitForWorkflowStatus(runner.makeRequest.bind(runner), trigger!.id); + expect(status?.status?.status).toBe('errored'); + + await runner.makeRequest('get', '/flush-marker'); + await runner.completed(); + }, +); + +it('captures an error thrown inside a step callback only one time', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect((envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, { exception?: { values?: SentException[] } }]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.exception?.values?.[0]).toMatchObject({ + type: 'Error', + value: 'Thrown inside the step callback', + mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' }, + }); + }) + .expect(flushMarkerMatcher) + .start(signal); + + const trigger = await runner.makeRequest('get', '/trigger-workflow?mode=throw-in-step'); + expect(trigger?.id).toBeDefined(); + + const status = await waitForWorkflowStatus(runner.makeRequest.bind(runner), trigger!.id); + expect(status?.status?.status).toBe('errored'); + + await runner.makeRequest('get', '/flush-marker'); + await runner.completed(); +}); + +it('captures no second error when run() catches a failed step', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect((envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, { exception?: { values?: SentException[] } }]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.exception?.values?.[0]?.value).toBe('Thrown inside the step callback'); + }) + .expect(flushMarkerMatcher) + .start(signal); + + const trigger = await runner.makeRequest('get', '/trigger-workflow?mode=caught-step-error'); + expect(trigger?.id).toBeDefined(); + + const status = await waitForWorkflowStatus(runner.makeRequest.bind(runner), trigger!.id); + expect(status?.status?.status).toBe('complete'); + + await runner.makeRequest('get', '/flush-marker'); + await runner.completed(); +}); + +it('captures the step error and the new error when run() replaces a failed step error', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect((envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, { exception?: { values?: SentException[] } }]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.exception?.values?.[0]).toMatchObject({ + value: 'Thrown inside the step callback', + mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' }, + }); + }) + .expect((envelope: Envelope): void => { + const [, items] = envelope; + const [itemHeader, itemBody] = items[0] as [{ type: string }, { exception?: { values?: SentException[] } }]; + + expect(itemHeader.type).toBe('event'); + expect(itemBody.exception?.values?.[0]).toMatchObject({ + value: 'Thrown by run() after the failed step', + mechanism: { handled: false, type: 'auto.faas.cloudflare.workflow' }, + }); + }) + .expect(flushMarkerMatcher) + .start(signal); + + const trigger = await runner.makeRequest('get', '/trigger-workflow?mode=rethrow-new-error'); + expect(trigger?.id).toBeDefined(); + + const status = await waitForWorkflowStatus(runner.makeRequest.bind(runner), trigger!.id); + expect(status?.status?.status).toBe('errored'); + + await runner.makeRequest('get', '/flush-marker'); + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/vite.config.mts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/vite.config.mts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/wrangler.jsonc new file mode 100644 index 000000000000..c70373ceb803 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/workflows/run-errors/wrangler.jsonc @@ -0,0 +1,13 @@ +{ + "name": "workflow-run-errors-test", + "compatibility_date": "2026-05-01", + "main": "index.ts", + "compatibility_flags": ["nodejs_compat"], + "workflows": [ + { + "name": "run-errors-test-workflow", + "binding": "RUN_ERRORS_WORKFLOW", + "class_name": "RunErrorsTestWorkflow", + }, + ], +} diff --git a/dev-packages/deno-integration-tests/package.json b/dev-packages/deno-integration-tests/package.json index f91826f278bc..36221d8d7d38 100644 --- a/dev-packages/deno-integration-tests/package.json +++ b/dev-packages/deno-integration-tests/package.json @@ -17,7 +17,7 @@ }, "devDependencies": { "@sentry-internal/node-integration-tests": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/deno": "11.12.0", "mysql": "^2.18.1", diff --git a/dev-packages/e2e-tests/.env.example b/dev-packages/e2e-tests/.env.example index 17326f227680..4417292a006c 100644 --- a/dev-packages/e2e-tests/.env.example +++ b/dev-packages/e2e-tests/.env.example @@ -23,5 +23,7 @@ E2E_OPENAI_DECISIONS_API_KEY= # Cloudflare credentials for E2E tests that deploy a real Worker (e.g. cloudflare-workers-send-to-sentry). # The API token needs "Workers Scripts: Edit" on the account; "Workers KV Storage: Read" additionally silences a # warning when a worker is deleted. Leave it empty to use a `wrangler login` session instead. +# Apps that read Workers Logs (e.g. cloudflare-workers-without-tracing-send-to-sentry) need an API token with +# "Workers Observability: Edit". CLOUDFLARE_API_TOKEN= CLOUDFLARE_ACCOUNT_ID= diff --git a/dev-packages/e2e-tests/README.md b/dev-packages/e2e-tests/README.md index be2b94586ece..49f3db499220 100644 --- a/dev-packages/e2e-tests/README.md +++ b/dev-packages/e2e-tests/README.md @@ -152,6 +152,9 @@ Apps like `cloudflare-workers-send-to-sentry` deploy the built app as a real Wor `cloudflare-flue-send-to-sentry/src/auth.ts`. - Add the `workerPrefix` to `.github/workflows/cleanup-e2e-workers.yml`, which deletes the Worker of a PR when the PR closes. +- To check what Cloudflare stored for a request (for example its Cloudflare trace id), read Workers Logs with + `fetchWorkersLogsEvents`. `CLOUDFLARE_API_TOKEN` then also needs "Workers Observability: Edit". See + `cloudflare-workers-without-tracing-send-to-sentry`. - Set `"sentryTest": { "optional": true }` in `package.json`, because only the optional CI job has the Cloudflare secrets. @@ -173,9 +176,9 @@ is the reference setup. (`instrument.mjs`), Bun `@sentry/bun` (`instrument.bun.mjs`), Deno `@sentry/deno` (`instrument.deno.mjs`) and Cloudflare `@sentry/cloudflare`. The framework SDK only provides the framework wrappers on the other runtimes, so values that come from its `init()` (`sdk.name`, default integrations) are Node-only. Next.js is different: it loads - `instrumentation.ts` on every runtime, so `nextjs-16` calls `init()` of `@sentry/nextjs` on Bun and Deno too, and - adds the integrations of `@sentry/bun` or `@sentry/deno` that replace the Node instrumentation those runtimes do not - trigger. + `instrumentation.ts` on every runtime, so `nextjs-16` calls `init()` of `@sentry/nextjs` on Bun and Deno too. Its + Bun and Deno variants build the app on that runtime, so `@sentry/nextjs` loads its `bun` or `deno` entry, which adds + the integrations of `@sentry/bun` or `@sentry/deno`. - **Start commands**: `playwright.config.mjs` selects the start command with `getRuntime()`. Bun and Deno use the same build as Node and only change the start command, for example `bun --bun --preload ./instrument.bun.mjs ./node_modules/@react-router/serve/bin.cjs ./build/server/index.js` and @@ -207,10 +210,13 @@ is the reference setup. replaces `vite.config.ts`. For a variant with `runtime`, the runner copies these files over the others in the temporary copy of the app, before the build. This needs no framework or bundler config. A build in the app folder itself does not get these files, so run a variant with `pnpm run test:run --variant `. -- **Deno version**: a variant can pin the Deno version, for example `"deno-version": "v2.9.0"`. +- **Bun and Deno versions**: a variant can pin the Bun or Deno version, for example `"bun-version": "1.4.4"` or + `"deno-version": "v2.9.0"`. - **Bun**: under `bun run` the SDK cannot inject diagnostics channels into packages that stay outside the build (for example Express behind `react-router-serve`), so those produce no spans on Bun. Where a test depends on them, branch - on `RUNTIME` and say why in a comment. + on `RUNTIME` and say why in a comment. An app that starts its own server can instead bundle it with + `@sentry/bun/plugin`, as `nestjs-12/bun-build.mjs` does. Bun 1.3 renames classes in bundles (`class Foo2`), which + changes span names taken from class names, so `nestjs-12` pins Bun 1.4 (see #26289). ```json "sentryTest": { @@ -296,6 +302,10 @@ of a test application. set its `assert-command` to run production tests and add a development variant to run both environments in parallel. The local `test:assert` script can still run both; select the base variant locally with `--variant