From 5c4221c27cf2a0d7eb29a77b8b424255c6c2bd6e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 09:49:47 +0100 Subject: [PATCH 01/29] build(deps): bump actions/create-github-app-token from 1.11.7 to 1.12.0 (#2450) Bumps [actions/create-github-app-token](https://github.com/actions/create-github-app-token) from 1.11.7 to 1.12.0.
Release notes

Sourced from actions/create-github-app-token's releases.

v1.12.0

1.12.0 (2025-03-27)

Features

Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/create-github-app-token&package-manager=github_actions&previous-version=1.11.7&new-version=1.12.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2b1fd6aea2..9bebf6d7c2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: steps: - name: Get auth token id: token - uses: actions/create-github-app-token@af35edadc00be37caa72ed9f3e6d5f7801bfdf09 # v1.11.7 + uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1.12.0 with: app-id: ${{ vars.SENTRY_RELEASE_BOT_CLIENT_ID }} private-key: ${{ secrets.SENTRY_RELEASE_BOT_PRIVATE_KEY }} From 0341eb5c85fae1711710af29a41fc8de3ce1bb23 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 08:51:14 +0000 Subject: [PATCH 02/29] build(deps): bump actions/setup-python from 5.4.0 to 5.5.0 (#2449) --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d8c85c39e6..a865cfc67d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -241,7 +241,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2 - name: Add Rustup Target run: rustup target add x86_64-unknown-linux-musl - - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # 5.4.0 + - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # 5.5.0 with: python-version: '3.11' - run: python3 -m pip install build && python3 -m build @@ -257,7 +257,7 @@ jobs: needs: [linux, sign-macos-binaries, windows, python-base] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2 - - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # 5.4.0 + - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # 5.5.0 with: python-version: '3.11' - uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # 4.2.1 From f15f80d4eb10e3c76f2a33b09b1ee7e6ade5d12d Mon Sep 17 00:00:00 2001 From: Sebastian Zivota Date: Tue, 22 Apr 2025 15:28:53 +0200 Subject: [PATCH 03/29] chore: Fix nightly clippy lints (#2469) One of them appears to be a false positive, though. --------- Co-authored-by: Daniel Szoke <7881302+szokeasaurusrex@users.noreply.github.com> --- src/commands/sourcemaps/explain.rs | 2 +- src/utils/appcenter.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/sourcemaps/explain.rs b/src/commands/sourcemaps/explain.rs index ab129ec4d5..aeeebb6b48 100644 --- a/src/commands/sourcemaps/explain.rs +++ b/src/commands/sourcemaps/explain.rs @@ -140,7 +140,7 @@ fn find_matching_artifact(artifacts: &[Artifact], path: &str) -> Result Result { let history = get_appcenter_deployment_history(app, deployment)?; - if let Some(latest) = history.into_iter().last() { + if let Some(latest) = history.into_iter().next_back() { Ok(latest) } else { bail!("Could not find deployment {} for {}", deployment, app); From 1f29870bbecccea3cfed54f2a4f2d369f3a08364 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 09:07:51 +0000 Subject: [PATCH 04/29] build(deps): bump actions/create-github-app-token from 1.12.0 to 2.0.2 (#2452) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9bebf6d7c2..dd0f065f31 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: steps: - name: Get auth token id: token - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1.12.0 + uses: actions/create-github-app-token@3ff1caaa28b64c9cc276ce0a02e2ff584f3900c5 # v2.0.2 with: app-id: ${{ vars.SENTRY_RELEASE_BOT_CLIENT_ID }} private-key: ${{ secrets.SENTRY_RELEASE_BOT_PRIVATE_KEY }} From 34ba636ebe50b3f56a06f45161a5e8030bd05d9a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 09:20:54 +0000 Subject: [PATCH 05/29] build(deps): bump github/codeql-action from 3.28.13 to 3.28.15 (#2453) --- .github/workflows/codeql-analysis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 43dc67e847..f2b8581631 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -37,7 +37,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # 3.28.13 + uses: github/codeql-action/init@45775bd8235c68ba998cffa5171334d58593da47 # 3.28.15 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -48,7 +48,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # 3.28.13 + uses: github/codeql-action/autobuild@45775bd8235c68ba998cffa5171334d58593da47 # 3.28.15 # â„šī¸ Command-line programs to run using the OS shell. # 📚 https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions @@ -59,4 +59,4 @@ jobs: # make bootstrap # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # 3.28.13 + uses: github/codeql-action/analyze@45775bd8235c68ba998cffa5171334d58593da47 # 3.28.15 From e981e750877e13dfb74e0cfc6c2ebd87e08ea803 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 09:23:49 +0000 Subject: [PATCH 06/29] build(deps): bump actions/setup-node from 4.3.0 to 4.4.0 (#2465) --- .github/workflows/build.yml | 4 ++-- .github/workflows/ci.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a865cfc67d..43d502fbae 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -210,7 +210,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # 4.4.0 with: node-version: '20.10.0' @@ -283,7 +283,7 @@ jobs: needs: [linux, sign-macos-binaries, windows] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # 4.4.0 with: node-version: '20.10.0' - uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # 4.2.1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa848c0741..5e2ae4f042 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,7 +79,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2 - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # 4.3.0 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # 4.4.0 with: node-version: ${{ matrix.node-version }} From 94329027a7126fd49ec4bdb1ac676c7f83d6b7f8 Mon Sep 17 00:00:00 2001 From: Stephanie Anderson Date: Fri, 25 Apr 2025 15:12:58 +0200 Subject: [PATCH 07/29] Update GH issue templates for Linear compatibility (#2471) --- .github/ISSUE_TEMPLATE/BUG_REPORT.yml | 2 +- .github/ISSUE_TEMPLATE/FEATURE_REQUEST.md | 1 + .github/ISSUE_TEMPLATE/QUESTION.md | 8 +------- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml index ad33bd104d..86541c5c26 100644 --- a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml +++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml @@ -1,6 +1,6 @@ name: 🐞 Bug Report description: Report a bug in this repo - +labels: ["CLI", "Bug"] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md index 795e31ac98..0b40ef148b 100644 --- a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md +++ b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md @@ -1,6 +1,7 @@ --- name: 🧠 Feature Request about: Suggest an idea for improving this repo +labels: ["CLI", "Feature"] --- From 41f7db9565b7509a44fddb6380cb1064976c75b2 Mon Sep 17 00:00:00 2001 From: Daniel Szoke <7881302+szokeasaurusrex@users.noreply.github.com> Date: Mon, 28 Apr 2025 09:34:17 +0200 Subject: [PATCH 09/29] build: Bump `tokio` to `1.44.2` (#2474) --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f11905d2ce..a55c5637b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1674,9 +1674,9 @@ checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" [[package]] name = "libc" -version = "0.2.155" +version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libgit2-sys" @@ -3325,9 +3325,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.41.1" +version = "1.44.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" dependencies = [ "backtrace", "bytes", From 6aef1581c3b70a1f56091cc04816bdb9d102fa57 Mon Sep 17 00:00:00 2001 From: getsentry-bot Date: Mon, 28 Apr 2025 07:55:04 +0000 Subject: [PATCH 10/29] release: 2.43.1 --- CHANGELOG.md | 14 ++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- npm-binary-distributions/darwin/package.json | 2 +- .../linux-arm/package.json | 2 +- .../linux-arm64/package.json | 2 +- .../linux-i686/package.json | 2 +- .../linux-x64/package.json | 2 +- .../win32-arm64/package.json | 2 +- .../win32-i686/package.json | 2 +- .../win32-x64/package.json | 2 +- package.json | 18 +++++++++--------- 12 files changed, 33 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4589306534..c92717b8d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ "You know what they say. Fool me once, strike one, but fool me twice... strike three." — Michael Scott +## 2.43.1 + +### Various fixes & improvements + +- build: Bump `tokio` to `1.44.2` (#2474) by @szokeasaurusrex +- meta: Delete "question" issue template (#2473) by @szokeasaurusrex +- Update GH issue templates for Linear compatibility (#2471) by @stephanie-anderson +- build(deps): bump actions/setup-node from 4.3.0 to 4.4.0 (#2465) by @dependabot +- build(deps): bump github/codeql-action from 3.28.13 to 3.28.15 (#2453) by @dependabot +- build(deps): bump actions/create-github-app-token from 1.12.0 to 2.0.2 (#2452) by @dependabot +- chore: Fix nightly clippy lints (#2469) by @loewenheim +- build(deps): bump actions/setup-python from 5.4.0 to 5.5.0 (#2449) by @dependabot +- build(deps): bump actions/create-github-app-token from 1.11.7 to 1.12.0 (#2450) by @dependabot + ## 2.43.0 This release explicitly deprecates the `sentry-cli debug-files upload` command's `--info-plist` argument, since the argument does nothing. If you are using the `--info-plist` argument, you should stop using it. diff --git a/Cargo.lock b/Cargo.lock index a55c5637b9..05f264632c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2728,7 +2728,7 @@ dependencies = [ [[package]] name = "sentry-cli" -version = "2.43.0" +version = "2.43.1" dependencies = [ "anyhow", "anylog", diff --git a/Cargo.toml b/Cargo.toml index 1519b7dacb..b3e076c085 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ authors = ["Armin Ronacher "] build = "build.rs" name = "sentry-cli" -version = "2.43.0" +version = "2.43.1" edition = "2021" rust-version = "1.80" diff --git a/npm-binary-distributions/darwin/package.json b/npm-binary-distributions/darwin/package.json index a2fe2b6f4e..ab013fbb0a 100644 --- a/npm-binary-distributions/darwin/package.json +++ b/npm-binary-distributions/darwin/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-darwin", - "version": "2.43.0", + "version": "2.43.1", "description": "The darwin distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/linux-arm/package.json b/npm-binary-distributions/linux-arm/package.json index 2d20d1e89a..f36e45de3a 100644 --- a/npm-binary-distributions/linux-arm/package.json +++ b/npm-binary-distributions/linux-arm/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-linux-arm", - "version": "2.43.0", + "version": "2.43.1", "description": "The linux arm distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/linux-arm64/package.json b/npm-binary-distributions/linux-arm64/package.json index 3ec8f601dc..48c39fb54f 100644 --- a/npm-binary-distributions/linux-arm64/package.json +++ b/npm-binary-distributions/linux-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-linux-arm64", - "version": "2.43.0", + "version": "2.43.1", "description": "The linux arm64 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/linux-i686/package.json b/npm-binary-distributions/linux-i686/package.json index f398f6039e..ae7131f6bc 100644 --- a/npm-binary-distributions/linux-i686/package.json +++ b/npm-binary-distributions/linux-i686/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-linux-i686", - "version": "2.43.0", + "version": "2.43.1", "description": "The linux x86 and ia32 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/linux-x64/package.json b/npm-binary-distributions/linux-x64/package.json index 0d6387f5b1..5e80d3a3a2 100644 --- a/npm-binary-distributions/linux-x64/package.json +++ b/npm-binary-distributions/linux-x64/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-linux-x64", - "version": "2.43.0", + "version": "2.43.1", "description": "The linux x64 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/win32-arm64/package.json b/npm-binary-distributions/win32-arm64/package.json index 0c39f12c3f..b756247734 100644 --- a/npm-binary-distributions/win32-arm64/package.json +++ b/npm-binary-distributions/win32-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-win32-arm64", - "version": "2.43.0", + "version": "2.43.1", "description": "The windows arm64 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/win32-i686/package.json b/npm-binary-distributions/win32-i686/package.json index e92c545c11..e1b542e60c 100644 --- a/npm-binary-distributions/win32-i686/package.json +++ b/npm-binary-distributions/win32-i686/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-win32-i686", - "version": "2.43.0", + "version": "2.43.1", "description": "The windows x86 and ia32 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/npm-binary-distributions/win32-x64/package.json b/npm-binary-distributions/win32-x64/package.json index 364d98b26c..9d178715b2 100644 --- a/npm-binary-distributions/win32-x64/package.json +++ b/npm-binary-distributions/win32-x64/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli-win32-x64", - "version": "2.43.0", + "version": "2.43.1", "description": "The windows x64 distribution of the Sentry CLI binary.", "repository": "https://github.com/getsentry/sentry-cli", "license": "BSD-3-Clause", diff --git a/package.json b/package.json index d2fde70dcf..01ec0e3295 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sentry/cli", - "version": "2.43.0", + "version": "2.43.1", "description": "A command line utility to work with Sentry. https://docs.sentry.io/hosted/learn/cli/", "repository": "git://github.com/getsentry/sentry-cli.git", "homepage": "https://docs.sentry.io/hosted/learn/cli/", @@ -30,14 +30,14 @@ "prettier": "2.8.8" }, "optionalDependencies": { - "@sentry/cli-darwin": "2.43.0", - "@sentry/cli-linux-arm": "2.43.0", - "@sentry/cli-linux-arm64": "2.43.0", - "@sentry/cli-linux-i686": "2.43.0", - "@sentry/cli-linux-x64": "2.43.0", - "@sentry/cli-win32-i686": "2.43.0", - "@sentry/cli-win32-x64": "2.43.0", - "@sentry/cli-win32-arm64": "2.43.0" + "@sentry/cli-darwin": "2.43.1", + "@sentry/cli-linux-arm": "2.43.1", + "@sentry/cli-linux-arm64": "2.43.1", + "@sentry/cli-linux-i686": "2.43.1", + "@sentry/cli-linux-x64": "2.43.1", + "@sentry/cli-win32-i686": "2.43.1", + "@sentry/cli-win32-x64": "2.43.1", + "@sentry/cli-win32-arm64": "2.43.1" }, "scripts": { "postinstall": "node ./scripts/install.js", From efad25ef61f262d856c8c950ee77fe0c2fe56943 Mon Sep 17 00:00:00 2001 From: Daniel Szoke <7881302+szokeasaurusrex@users.noreply.github.com> Date: Mon, 28 Apr 2025 09:57:41 +0200 Subject: [PATCH 11/29] meta: Update CHANGELOG.md --- CHANGELOG.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c92717b8d8..2f438a60fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,14 +7,7 @@ ### Various fixes & improvements - build: Bump `tokio` to `1.44.2` (#2474) by @szokeasaurusrex -- meta: Delete "question" issue template (#2473) by @szokeasaurusrex -- Update GH issue templates for Linear compatibility (#2471) by @stephanie-anderson -- build(deps): bump actions/setup-node from 4.3.0 to 4.4.0 (#2465) by @dependabot -- build(deps): bump github/codeql-action from 3.28.13 to 3.28.15 (#2453) by @dependabot -- build(deps): bump actions/create-github-app-token from 1.12.0 to 2.0.2 (#2452) by @dependabot - chore: Fix nightly clippy lints (#2469) by @loewenheim -- build(deps): bump actions/setup-python from 5.4.0 to 5.5.0 (#2449) by @dependabot -- build(deps): bump actions/create-github-app-token from 1.11.7 to 1.12.0 (#2450) by @dependabot ## 2.43.0 From 102820b738d43489d2fee1e8fe165b837af75675 Mon Sep 17 00:00:00 2001 From: Daniel Szoke Date: Wed, 30 Apr 2025 14:25:22 +0200 Subject: [PATCH 12/29] test(sourcemaps): Assert injection outputs --- .../esbuild/cjs.js} | 0 .../esbuild/cjs.js.map} | 0 .../esbuild/iife.js} | 0 .../esbuild/iife.js.map} | 0 .../sourcemaps-inject-bundlers/rollup/cjs.js} | 0 .../rollup/cjs.js.map} | 0 .../rollup/iife.js} | 0 .../rollup/iife.js.map} | 0 .../rspack/iife.js} | 0 .../rspack/iife.js.map} | 0 .../sourcemaps-inject-bundlers/vite/cjs.js} | 0 .../vite/cjs.js.map} | 0 .../sourcemaps-inject-bundlers/vite/iife.js} | 0 .../vite/iife.js.map} | 0 .../webpack/cjs.js} | 0 .../webpack/cjs.js.map} | 0 .../webpack/iife.js} | 0 .../webpack/iife.js.map} | 0 .../dummy_embedded.js | 4 + .../sourcemaps-inject-indexed/index.js | 13 ++ .../sourcemaps-inject-indexed/index.js.map | 1 + .../nonexisting/.gitkeep | 0 .../server/app/page.min.js | 3 + .../server/chunks/1.js.map | 1 + .../server/chunks/1.min.js | 5 + .../chunks/flight-server-css-manifest.js | 3 + .../server/edge-runtime-webpack.js.map | 1 + .../server/edge-runtime-webpack.min.js | 1 + .../server/flight-manifest.js | 3 + .../server/pages/_document.js.map | 1 + .../server/pages/_document.min.js | 4 + .../server/pages/api/hello.min.js | 3 + .../server/pages/asdf.js.map | 1 + .../static/chunks/575-bb7d7e0e6de8d623.js.map | 1 + .../static/chunks/575-bb7d7e0e6de8d623.min.js | 4 + .../app/client/layout-ba9c3036fc0dba78.js | 3 + .../app/client/page-d5742c254d9533f8.js.map | 1 + .../app/client/page-d5742c254d9533f8.min.js | 1 + .../chunks/app/head-172ad45600676c06.js | 3 + .../chunks/pages/asdf-05b39167abbe433b.js.map | 1 + .../chunks/pages/asdf-05b39167abbe433b.min.js | 4 + .../not-compiled.js | 7 + .../code/foo/index.js | 3 + .../code/index.js | 4 + .../maps/foo/index.js.map | 1 + .../maps/index.js.map | 1 + .../maps2/foo/index.js.map | 1 + .../sourcemaps-inject-split/code/foo/index.js | 4 + .../sourcemaps-inject-split/code/index.js | 4 + .../maps/foo/index.js.map | 1 + .../sourcemaps-inject-split/maps/index.js.map | 1 + .../sourcemaps-inject/server/app/page.js | 3 + .../sourcemaps-inject/server/chunks/1.js | 4 + .../sourcemaps-inject/server/chunks/1.js.map | 1 + .../chunks/flight-server-css-manifest.js | 3 + .../server/dummy_embedded.js | 4 + .../sourcemaps-inject/server/dummy_hosted.js | 5 + .../server/dummy_hosted.js.map | 1 + .../server/dummy_hosted_full.js | 5 + .../server/dummy_hosted_full.js.map | 1 + .../server/edge-runtime-webpack.js | 2 + .../server/edge-runtime-webpack.js.map | 1 + .../server/flight-manifest.js | 3 + .../server/pages/_document.js | 4 + .../server/pages/_document.js.map | 1 + .../server/pages/api/hello.js | 3 + .../server/pages/asdf.js.map | 1 + .../static/chunks/575-bb7d7e0e6de8d623.js | 4 + .../static/chunks/575-bb7d7e0e6de8d623.js.map | 1 + .../app/client/layout-ba9c3036fc0dba78.js | 3 + .../app/client/page-d5742c254d9533f8.js | 2 + .../app/client/page-d5742c254d9533f8.js.map | 1 + .../chunks/app/head-172ad45600676c06.js | 3 + .../chunks/pages/asdf-05b39167abbe433b.js | 4 + .../chunks/pages/asdf-05b39167abbe433b.js.map | 1 + .../static/chunks/whatever.svg | 6 + tests/integration/sourcemaps/inject.rs | 161 +++++++++++++----- 77 files changed, 276 insertions(+), 41 deletions(-) rename tests/integration/{_fixtures/inject_bundlers/esbuild/cjs.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/esbuild/cjs.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/esbuild/iife.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/esbuild/iife.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/rollup/cjs.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/rollup/cjs.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/rollup/iife.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/rollup/iife.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/rspack/iife.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/rspack/iife.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/vite/cjs.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/vite/cjs.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/vite/iife.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/vite/iife.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/webpack/cjs.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/webpack/cjs.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js.map} (100%) rename tests/integration/{_fixtures/inject_bundlers/webpack/iife.js.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js} (100%) rename tests/integration/{_fixtures/inject_bundlers/webpack/iife.js.map.expected => _expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js.map} (100%) create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-embedded/dummy_embedded.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nofiles/nonexisting/.gitkeep create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/app/page.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/flight-server-css-manifest.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/flight-manifest.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/api/hello.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/asdf.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/575-bb7d7e0e6de8d623.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/575-bb7d7e0e6de8d623.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/app/client/layout-ba9c3036fc0dba78.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/app/client/page-d5742c254d9533f8.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/app/client/page-d5742c254d9533f8.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/app/head-172ad45600676c06.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/pages/asdf-05b39167abbe433b.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/pages/asdf-05b39167abbe433b.min.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-not-compiled/not-compiled.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split-ambiguous/code/foo/index.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split-ambiguous/code/index.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split-ambiguous/maps/foo/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split-ambiguous/maps/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split-ambiguous/maps2/foo/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split/code/foo/index.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split/code/index.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split/maps/foo/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-split/maps/index.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/app/page.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/chunks/1.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/chunks/1.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/chunks/flight-server-css-manifest.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/dummy_embedded.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/dummy_hosted.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/dummy_hosted.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/dummy_hosted_full.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/dummy_hosted_full.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/edge-runtime-webpack.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/edge-runtime-webpack.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/flight-manifest.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/pages/_document.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/pages/_document.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/pages/api/hello.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/server/pages/asdf.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/575-bb7d7e0e6de8d623.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/575-bb7d7e0e6de8d623.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/app/client/layout-ba9c3036fc0dba78.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/app/client/page-d5742c254d9533f8.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/app/client/page-d5742c254d9533f8.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/app/head-172ad45600676c06.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/pages/asdf-05b39167abbe433b.js create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/pages/asdf-05b39167abbe433b.js.map create mode 100644 tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject/static/chunks/whatever.svg diff --git a/tests/integration/_fixtures/inject_bundlers/esbuild/cjs.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/esbuild/cjs.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js diff --git a/tests/integration/_fixtures/inject_bundlers/esbuild/cjs.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/esbuild/cjs.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/cjs.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/esbuild/iife.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/esbuild/iife.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js diff --git a/tests/integration/_fixtures/inject_bundlers/esbuild/iife.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/esbuild/iife.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/esbuild/iife.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/rollup/cjs.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rollup/cjs.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js diff --git a/tests/integration/_fixtures/inject_bundlers/rollup/cjs.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rollup/cjs.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/cjs.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/rollup/iife.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rollup/iife.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js diff --git a/tests/integration/_fixtures/inject_bundlers/rollup/iife.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rollup/iife.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rollup/iife.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/rspack/iife.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rspack/iife.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js diff --git a/tests/integration/_fixtures/inject_bundlers/rspack/iife.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/rspack/iife.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/rspack/iife.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/vite/cjs.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/vite/cjs.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js diff --git a/tests/integration/_fixtures/inject_bundlers/vite/cjs.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/vite/cjs.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/cjs.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/vite/iife.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/vite/iife.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js diff --git a/tests/integration/_fixtures/inject_bundlers/vite/iife.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/vite/iife.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/vite/iife.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/webpack/cjs.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/webpack/cjs.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js diff --git a/tests/integration/_fixtures/inject_bundlers/webpack/cjs.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/webpack/cjs.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/cjs.js.map diff --git a/tests/integration/_fixtures/inject_bundlers/webpack/iife.js.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/webpack/iife.js.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js diff --git a/tests/integration/_fixtures/inject_bundlers/webpack/iife.js.map.expected b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js.map similarity index 100% rename from tests/integration/_fixtures/inject_bundlers/webpack/iife.js.map.expected rename to tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-bundlers/webpack/iife.js.map diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-embedded/dummy_embedded.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-embedded/dummy_embedded.js new file mode 100644 index 0000000000..d691d9b09e --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-embedded/dummy_embedded.js @@ -0,0 +1,4 @@ + +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="387af3ce-423a-5792-8d09-194d56a0ac3f")}catch(e){}}(); +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMS5qcyIsInNvdXJjZXMiOltdLCJzb3VyY2VSb290IjoiIiwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImRlYnVnX2lkIjoiMzg3YWYzY2UtNDIzYS01NzkyLThkMDktMTk0ZDU2YTBhYzNmIn0= +//# debugId=387af3ce-423a-5792-8d09-194d56a0ac3f diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js new file mode 100644 index 0000000000..429d6601f0 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +"use strict";!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="85ee593b-6278-5da3-8f05-e762f00b888d")}catch(e){}}(); +// this is a comment +/*and +another +comment*/ +"use strict"; +function greet(name) { + return `Hello, ${name}!`; +} +console.log(greet("World")); +//# sourceMappingURL=index.js.map +//# debugId=85ee593b-6278-5da3-8f05-e762f00b888d diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js.map new file mode 100644 index 0000000000..1a9a836259 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-indexed/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":null,"sections":[{"offset":{"line":1,"column":0},"url":null,"map":{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourceRoot":"","sourcesContent":["#!/usr/bin/env node\n// this is a comment\n/*and \nanother \ncomment*/\n\"use strict\";\n\nfunction greet(name: string): string {\n return `Hello, ${name}!`;\n}\n\nconsole.log(greet(\"World\")); "],"names":[],"mappings":";AACA,oBAAoB;AACpB;;SAES;AACT,YAAY,CAAC;AAEb,SAAS,KAAK,CAAC,IAAY;IACvB,OAAO,UAAU,IAAI,GAAG,CAAC;AAC7B,CAAC;AAED,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC"}}],"debugId":"85ee593b-6278-5da3-8f05-e762f00b888d"} \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nofiles/nonexisting/.gitkeep b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nofiles/nonexisting/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/app/page.min.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/app/page.min.js new file mode 100644 index 0000000000..30155b8392 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/app/page.min.js @@ -0,0 +1,3 @@ + +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="adc83b19-e793-591b-9c6e-a0fd8b46cd9f")}catch(e){}}(); +//# debugId=adc83b19-e793-591b-9c6e-a0fd8b46cd9f diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.js.map new file mode 100644 index 0000000000..9c5a0ef099 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"1.js","sources":["webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/api.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/baseclient.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/envelope.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/exports.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/hub.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/integration.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/integrations/functiontostring.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/integrations/inboundfilters.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/integrations/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/scope.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/sdk.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/session.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/sessionflusher.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/transports/base.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/transports/offline.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/utils/prepareEvent.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/core/build/cjs/version.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/captureconsole.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/debug.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/dedupe.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/extraerrordata.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/httpclient.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/offline.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/reportingobserver.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/rewriteframes.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/sessiontiming.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/integrations/build/npm/cjs/transaction.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/common/_error.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/common/metadata.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/common/userIntegrations.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/index.server.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/utils/isBuild.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/utils/platformSupportsStreaming.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/utils/responseEnd.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/utils/wrapperUtils.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapApiHandlerWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapAppDirComponentWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapAppGetInitialPropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapDocumentGetInitialPropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapErrorGetInitialPropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapGetInitialPropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapGetServerSidePropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/nextjs/build/cjs/server/wrapGetStaticPropsWithSentry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/client.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/eventbuilder.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/handlers.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/console.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/context.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/contextlines.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/http.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/linkederrors.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/localvariables.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/modules.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/onuncaughtexception.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/onunhandledrejection.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/requestdata.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/utils/errorhandling.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/integrations/utils/http.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/module.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/requestDataDeprecated.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/requestdata.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/sdk.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/transports/http.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/node/build/cjs/utils.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/backgroundtab.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/browsertracing.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/metrics/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/metrics/utils.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/request.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/router.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/types.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/getCLS.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/getFID.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/getLCP.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/bindReporter.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/generateUniqueID.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/getActivationStart.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/getNavigationEntry.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/getVisibilityWatcher.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/initMetric.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/observe.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/browser/web-vitals/lib/onHidden.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/errors.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/hubextensions.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/idletransaction.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/apollo.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/express.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/graphql.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/mongo.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/mysql.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/postgres.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/prisma.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/integrations/node/utils/node-utils.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/span.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/spanstatus.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/transaction.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/tracing/build/npm/cjs/utils.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/baggage.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/browser.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_asyncNullishCoalesce.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_asyncOptionalChain.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_asyncOptionalChainDelete.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_createNamedExportFrom.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_createStarExport.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_interopDefault.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_interopNamespace.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_interopNamespaceDefaultOnly.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_interopRequireDefault.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_interopRequireWildcard.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_nullishCoalesce.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_optionalChain.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/_optionalChainDelete.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/buildPolyfills/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/clientreport.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/dsn.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/env.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/envelope.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/error.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/instrument.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/is.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/logger.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/memo.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/misc.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/node.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/normalize.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/object.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/path.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/promisebuffer.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/ratelimit.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/requestdata.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/severity.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/stacktrace.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/string.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/supports.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/syncpromise.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/time.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/tracing.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/url.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/@sentry/utils/build/cjs/worldwide.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/agent-base/dist/src/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/agent-base/dist/src/promisify.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/cookie/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/debug/src/browser.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/debug/src/common.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/debug/src/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/debug/src/node.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/has-flag/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/https-proxy-agent/dist/agent.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/https-proxy-agent/dist/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/https-proxy-agent/dist/parse-proxy-response.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/localforage/dist/localforage.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/lru_map/lru.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/ms/index.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/next/constants.js","webpack://sentry-nextjs-vercel-testproject/./node_modules/supports-color/index.js"],"sourceRoot":"","sourcesContent":["Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n return utils.urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(\n dsn,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions = {} ,\n) {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\n const dsn = utils.makeDsn(dsnLike);\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${utils.dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexports.getEnvelopeEndpointWithUrlEncodedAuth = getEnvelopeEndpointWithUrlEncodedAuth;\nexports.getReportDialogEndpoint = getReportDialogEndpoint;\n//# sourceMappingURL=api.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst api = require('./api.js');\nconst envelope = require('./envelope.js');\nconst integration = require('./integration.js');\nconst session = require('./session.js');\nconst prepareEvent = require('./utils/prepareEvent.js');\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n __init() {this._integrations = {};}\n\n /** Indicates whether this client's integrations have been set up. */\n __init2() {this._integrationsInitialized = false;}\n\n /** Number of calls being processed */\n __init3() {this._numProcessing = 0;}\n\n /** Holds flushable */\n __init4() {this._outcomes = {};}\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this);\n this._options = options;\n if (options.dsn) {\n this._dsn = utils.makeDsn(options.dsn);\n const url = api.getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('No DSN provided, client will not do anything.');\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint, scope) {\n // ensure we haven't captured this very object before\n if (utils.checkOrSetAlreadyCaught(exception)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n scope,\n ) {\n let eventId = hint && hint.event_id;\n\n const promisedEvent = utils.isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && utils.checkOrSetAlreadyCaught(hint.originalException)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session$1) {\n if (!this._isEnabled()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session$1.release === 'string')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session$1);\n // After sending, we set init false to indicate it's not the first occurrence\n session.updateSession(session$1, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return utils.resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n setupIntegrations() {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = integration.setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n try {\n return (this._integrations[integration.id] ) || null;\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration$1) {\n integration.setupIntegration(integration$1, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint = {}) {\n if (this._dsn) {\n let env = envelope.createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = utils.addItemToEnvelope(\n env,\n utils.createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendSession(session) {\n if (this._dsn) {\n const env = envelope.createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, _event) {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session$1, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session$1.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session$1.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.updateSession(session$1, {\n ...(crashed && { status: 'crashed' }),\n errors: session$1.errors || Number(errored || crashed),\n });\n this.captureSession(session$1);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new utils.SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(event, hint, scope) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent.prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n utils.logger.log(sentryError.message);\n } else {\n utils.logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(event, hint, scope) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return utils.rejectedSyncPromise(new utils.SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return utils.rejectedSyncPromise(\n new utils.SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new utils.SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new utils.SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n changes: [\n ...transactionInfo.changes,\n {\n source,\n // use the same timestamp as the processed event.\n timestamp: processedEvent.timestamp ,\n propagations: transactionInfo.propagations,\n },\n ],\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof utils.SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason ,\n });\n throw new utils.SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n _sendEnvelope(envelope) {\n if (this._transport && this._dsn) {\n this._transport.send(envelope).then(null, reason => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Error while sending event:', reason);\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (utils.isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!utils.isPlainObject(event) && event !== null) {\n throw new utils.SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new utils.SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!utils.isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new utils.SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexports.BaseClient = BaseClient;\n//# sourceMappingURL=baseclient.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: utils.dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session];\n\n return utils.createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjut a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = utils.createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return utils.createEnvelope(envelopeHeaders, [eventItem]);\n}\n\nexports.createEventEnvelope = createEventEnvelope;\nexports.createSessionEnvelope = createSessionEnvelope;\n//# sourceMappingURL=envelope.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst hub = require('./hub.js');\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction captureException(exception, captureContext) {\n return hub.getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nfunction captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n captureContext,\n) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return hub.getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nfunction captureEvent(event, hint) {\n return hub.getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nfunction configureScope(callback) {\n hub.getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nfunction addBreadcrumb(breadcrumb) {\n hub.getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setContext(name, context) {\n hub.getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n hub.getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n hub.getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n hub.getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n hub.getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n hub.getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nfunction withScope(callback) {\n hub.getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nfunction startTransaction(\n context,\n customSamplingContext,\n) {\n return hub.getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\nexports.addBreadcrumb = addBreadcrumb;\nexports.captureEvent = captureEvent;\nexports.captureException = captureException;\nexports.captureMessage = captureMessage;\nexports.configureScope = configureScope;\nexports.setContext = setContext;\nexports.setExtra = setExtra;\nexports.setExtras = setExtras;\nexports.setTag = setTag;\nexports.setTags = setTags;\nexports.setUser = setUser;\nexports.startTransaction = startTransaction;\nexports.withScope = withScope;\n//# sourceMappingURL=exports.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst scope = require('./scope.js');\nconst session = require('./session.js');\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nconst API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * A layer in the process stack.\n * @hidden\n */\n\n/**\n * @inheritDoc\n */\nclass Hub {\n /** Is a {@link Layer}[] containing the client and scope */\n __init() {this._stack = [{}];}\n\n /** Contains the last event id of a captured event. */\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n constructor(client, scope$1 = new scope.Scope(), _version = API_VERSION) {this._version = _version;Hub.prototype.__init.call(this);\n this.getStackTop().scope = scope$1;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n isOlderThan(version) {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n bindClient(client) {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n pushScope() {\n // We want to clone the content of prev scope\n const scope$1 = scope.Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope: scope$1,\n });\n return scope$1;\n }\n\n /**\n * @inheritDoc\n */\n popScope() {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n withScope(callback) {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /** Returns the scope of the top stack. */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n getStack() {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n getStackTop() {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n ) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, hint) {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = utils.dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (utils.consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) )\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setContext(name, context) {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n configureScope(callback) {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n run(callback) {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n startTransaction(context, customSamplingContext) {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n traceHeaders() {\n return this._callExtensionMethod('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n captureSession(endSession = false) {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n endSession() {\n const layer = this.getStackTop();\n const scope = layer && layer.scope;\n const session$1 = scope && scope.getSession();\n if (session$1) {\n session.closeSession(session$1);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n if (scope) {\n scope.setSession();\n }\n }\n\n /**\n * @inheritDoc\n */\n startSession(context) {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = utils.GLOBAL_OBJ.navigator || {};\n\n const session$1 = session.makeSession({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n session.updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session$1);\n }\n\n return session$1;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n shouldSendDefaultPii() {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n _sendSessionUpdate() {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n _withClient(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _callExtensionMethod(method, ...args) {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n utils.GLOBAL_OBJ.__SENTRY__ = utils.GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return utils.GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nfunction makeMain(hub) {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nfunction getCurrentHub() {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (utils.isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry) {\n try {\n const sentry = getMainCarrier().__SENTRY__;\n const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope.Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier) {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nfunction getHubFromCarrier(carrier) {\n return utils.getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nfunction setHubOnCarrier(carrier, hub) {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n\nexports.API_VERSION = API_VERSION;\nexports.Hub = Hub;\nexports.getCurrentHub = getCurrentHub;\nexports.getHubFromCarrier = getHubFromCarrier;\nexports.getMainCarrier = getMainCarrier;\nexports.makeMain = makeMain;\nexports.setHubOnCarrier = setHubOnCarrier;\n//# sourceMappingURL=hub.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst exports$1 = require('./exports.js');\nconst hub = require('./hub.js');\nconst session = require('./session.js');\nconst sessionflusher = require('./sessionflusher.js');\nconst scope = require('./scope.js');\nconst api = require('./api.js');\nconst baseclient = require('./baseclient.js');\nconst sdk = require('./sdk.js');\nconst base = require('./transports/base.js');\nconst offline = require('./transports/offline.js');\nconst version = require('./version.js');\nconst integration = require('./integration.js');\nconst index = require('./integrations/index.js');\nconst prepareEvent = require('./utils/prepareEvent.js');\nconst functiontostring = require('./integrations/functiontostring.js');\nconst inboundfilters = require('./integrations/inboundfilters.js');\n\n\n\nexports.addBreadcrumb = exports$1.addBreadcrumb;\nexports.captureEvent = exports$1.captureEvent;\nexports.captureException = exports$1.captureException;\nexports.captureMessage = exports$1.captureMessage;\nexports.configureScope = exports$1.configureScope;\nexports.setContext = exports$1.setContext;\nexports.setExtra = exports$1.setExtra;\nexports.setExtras = exports$1.setExtras;\nexports.setTag = exports$1.setTag;\nexports.setTags = exports$1.setTags;\nexports.setUser = exports$1.setUser;\nexports.startTransaction = exports$1.startTransaction;\nexports.withScope = exports$1.withScope;\nexports.Hub = hub.Hub;\nexports.getCurrentHub = hub.getCurrentHub;\nexports.getHubFromCarrier = hub.getHubFromCarrier;\nexports.getMainCarrier = hub.getMainCarrier;\nexports.makeMain = hub.makeMain;\nexports.setHubOnCarrier = hub.setHubOnCarrier;\nexports.closeSession = session.closeSession;\nexports.makeSession = session.makeSession;\nexports.updateSession = session.updateSession;\nexports.SessionFlusher = sessionflusher.SessionFlusher;\nexports.Scope = scope.Scope;\nexports.addGlobalEventProcessor = scope.addGlobalEventProcessor;\nexports.getEnvelopeEndpointWithUrlEncodedAuth = api.getEnvelopeEndpointWithUrlEncodedAuth;\nexports.getReportDialogEndpoint = api.getReportDialogEndpoint;\nexports.BaseClient = baseclient.BaseClient;\nexports.initAndBind = sdk.initAndBind;\nexports.createTransport = base.createTransport;\nexports.makeOfflineTransport = offline.makeOfflineTransport;\nexports.SDK_VERSION = version.SDK_VERSION;\nexports.getIntegrationsToSetup = integration.getIntegrationsToSetup;\nexports.Integrations = index;\nexports.prepareEvent = prepareEvent.prepareEvent;\nexports.FunctionToString = functiontostring.FunctionToString;\nexports.InboundFilters = inboundfilters.InboundFilters;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst hub = require('./hub.js');\nconst scope = require('./scope.js');\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = utils.arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(integrations) {\n const integrationIndex = {};\n\n integrations.forEach(integration => {\n setupIntegration(integration, integrationIndex);\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(integration, integrationIndex) {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(scope.addGlobalEventProcessor, hub.getCurrentHub);\n installedIntegrations.push(integration.name);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\nexports.getIntegrationsToSetup = getIntegrationsToSetup;\nexports.installedIntegrations = installedIntegrations;\nexports.setupIntegration = setupIntegration;\nexports.setupIntegrations = setupIntegrations;\n//# sourceMappingURL=integration.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nlet originalFunctionToString;\n\n/** Patch toString calls to return proper name for wrapped functions */\nclass FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'FunctionToString';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = FunctionToString.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function ( ...args) {\n const context = utils.getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n} FunctionToString.__initStatic();\n\nexports.FunctionToString = FunctionToString;\n//# sourceMappingURL=functiontostring.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** Options for the InboundFilters integration */\n\n/** Inbound filters configurable by the user */\nclass InboundFilters {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'InboundFilters';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = InboundFilters.id;}\n\n constructor( _options = {}) {this._options = _options;InboundFilters.prototype.__init.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcess = (event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n} InboundFilters.__initStatic();\n\n/** JSDoc */\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${utils.getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${utils.getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${utils.getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${utils.getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n if (!ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => utils.stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : utils.stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : utils.stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(`Cannot extract message for event ${utils.getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(`Cannot extract url for event ${utils.getEventDescription(event)}`);\n return null;\n }\n}\n\nexports.InboundFilters = InboundFilters;\nexports._mergeOptions = _mergeOptions;\nexports._shouldDropEvent = _shouldDropEvent;\n//# sourceMappingURL=inboundfilters.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst functiontostring = require('./functiontostring.js');\nconst inboundfilters = require('./inboundfilters.js');\n\n\n\nexports.FunctionToString = functiontostring.FunctionToString;\nexports.InboundFilters = inboundfilters.InboundFilters;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst session = require('./session.js');\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nclass Scope {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called after {@link applyToEvent}. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n\n /** Transaction Name */\n\n /** Span */\n\n /** Session */\n\n /** Request Mode Session Status */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n static clone(scope) {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this._user = user || {};\n if (this._session) {\n session.updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level,\n ) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setSpan(span) {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSpan() {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n getTransaction() {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext )(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (utils.isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext ;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: utils.dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getAttachments() {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n applyToEvent(event, hint = {}) {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction && this._span.transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n _notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n ) {\n return new utils.SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n processor.id &&\n result === null &&\n utils.logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (utils.isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n _applyFingerprint(event) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? utils.arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors() {\n return utils.getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nfunction addGlobalEventProcessor(callback) {\n getGlobalEventProcessors().push(callback);\n}\n\nexports.Scope = Scope;\nexports.addGlobalEventProcessor = addGlobalEventProcessor;\n//# sourceMappingURL=scope.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst hub = require('./hub.js');\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n utils.logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub$1 = hub.getCurrentHub();\n const scope = hub$1.getScope();\n if (scope) {\n scope.update(options.initialScope);\n }\n\n const client = new clientClass(options);\n hub$1.bindClient(client);\n}\n\nexports.initAndBind = initAndBind;\n//# sourceMappingURL=sdk.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = utils.timestampInSeconds();\n\n const session = {\n sid: utils.uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || utils.timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : utils.uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return utils.dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexports.closeSession = closeSession;\nexports.makeSession = makeSession;\nexports.updateSession = updateSession;\n//# sourceMappingURL=session.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst hub = require('./hub.js');\n\n/**\n * @inheritdoc\n */\nclass SessionFlusher {\n __init() {this.flushTimeout = 60;}\n __init2() {this._pendingAggregates = {};}\n\n __init3() {this._isEnabled = true;}\n\n constructor(client, attrs) {SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this);\n this._client = client;\n // Call to setInterval, so that flush is called every 60 seconds\n this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);\n this._sessionAttrs = attrs;\n }\n\n /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */\n flush() {\n const sessionAggregates = this.getSessionAggregates();\n if (sessionAggregates.aggregates.length === 0) {\n return;\n }\n this._pendingAggregates = {};\n this._client.sendSession(sessionAggregates);\n }\n\n /** Massages the entries in `pendingAggregates` and returns aggregated sessions */\n getSessionAggregates() {\n const aggregates = Object.keys(this._pendingAggregates).map((key) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return utils.dropUndefinedKeys(sessionAggregates);\n }\n\n /** JSDoc */\n close() {\n clearInterval(this._intervalId);\n this._isEnabled = false;\n this.flush();\n }\n\n /**\n * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then\n * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to\n * `_incrementSessionStatusCount` along with the start date\n */\n incrementSessionStatusCount() {\n if (!this._isEnabled) {\n return;\n }\n const scope = hub.getCurrentHub().getScope();\n const requestSession = scope && scope.getRequestSession();\n\n if (requestSession && requestSession.status) {\n this._incrementSessionStatusCount(requestSession.status, new Date());\n // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in\n // case captureRequestSession is called more than once to prevent double count\n if (scope) {\n scope.setRequestSession(undefined);\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n }\n }\n\n /**\n * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of\n * the session received\n */\n _incrementSessionStatusCount(status, date) {\n // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys\n const sessionStartedTrunc = new Date(date).setSeconds(0, 0);\n this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};\n\n // corresponds to aggregated sessions in one specific minute bucket\n // for example, {\"started\":\"2021-03-16T08:00:00.000Z\",\"exited\":4, \"errored\": 1}\n const aggregationCounts = this._pendingAggregates[sessionStartedTrunc];\n if (!aggregationCounts.started) {\n aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();\n }\n\n switch (status) {\n case 'errored':\n aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;\n return aggregationCounts.errored;\n case 'ok':\n aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;\n return aggregationCounts.exited;\n default:\n aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;\n return aggregationCounts.crashed;\n }\n }\n}\n\nexports.SessionFlusher = SessionFlusher;\n//# sourceMappingURL=sessionflusher.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = utils.makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n utils.forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = utils.envelopeItemTypeToDataCategory(type);\n if (utils.isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return utils.resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope = utils.createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n utils.forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, utils.envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: utils.serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = utils.updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof utils.SentryError) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return utils.resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexports.DEFAULT_TRANSPORT_BUFFER_SIZE = DEFAULT_TRANSPORT_BUFFER_SIZE;\nexports.createTransport = createTransport;\n//# sourceMappingURL=base.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nconst MIN_DELAY = 100; // 100 ms\nconst START_DELAY = 5000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\nfunction isReplayEnvelope(envelope) {\n let isReplay = false;\n\n utils.forEachEnvelopeItem(envelope, (_, type) => {\n if (type === 'replay_event') {\n isReplay = true;\n }\n });\n\n return isReplay;\n}\n\nfunction log(msg, error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.info(`[Offline]: ${msg}`, error);\n}\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nfunction makeOfflineTransport(\n createTransport,\n) {\n return options => {\n const transport = createTransport(options);\n const store = options.createStore ? options.createStore(options) : undefined;\n\n let retryDelay = START_DELAY;\n let flushTimer;\n\n function shouldQueue(env, error, retryDelay) {\n // We don't queue Session Replay envelopes because they are:\n // - Ordered and Replay relies on the response status to know when they're successfully sent.\n // - Likely to fill the queue quickly and block other events from being sent.\n if (isReplayEnvelope(env)) {\n return false;\n }\n\n if (options.shouldStore) {\n return options.shouldStore(env, error, retryDelay);\n }\n\n return true;\n }\n\n function flushIn(delay) {\n if (!store) {\n return;\n }\n\n if (flushTimer) {\n clearTimeout(flushTimer );\n }\n\n flushTimer = setTimeout(async () => {\n flushTimer = undefined;\n\n const found = await store.pop();\n if (found) {\n log('Attempting to send previously queued event');\n void send(found).catch(e => {\n log('Failed to retry sending', e);\n });\n }\n }, delay) ;\n\n // We need to unref the timer in node.js, otherwise the node process never exit.\n if (typeof flushTimer !== 'number' && flushTimer.unref) {\n flushTimer.unref();\n }\n }\n\n function flushWithBackOff() {\n if (flushTimer) {\n return;\n }\n\n flushIn(retryDelay);\n\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n }\n\n async function send(envelope) {\n try {\n const result = await transport.send(envelope);\n\n let delay = MIN_DELAY;\n\n if (result) {\n // If there's a retry-after header, use that as the next delay.\n if (result.headers && result.headers['retry-after']) {\n delay = utils.parseRetryAfterHeader(result.headers['retry-after']);\n } // If we have a server error, return now so we don't flush the queue.\n else if ((result.statusCode || 0) >= 400) {\n return result;\n }\n }\n\n flushIn(delay);\n retryDelay = START_DELAY;\n return result;\n } catch (e) {\n if (store && (await shouldQueue(envelope, e, retryDelay))) {\n await store.insert(envelope);\n flushWithBackOff();\n log('Error sending. Event queued', e);\n return {};\n } else {\n throw e;\n }\n }\n }\n\n if (options.flushAtStartup) {\n flushWithBackOff();\n }\n\n return {\n send,\n flush: t => transport.flush(t),\n };\n };\n}\n\nexports.MIN_DELAY = MIN_DELAY;\nexports.START_DELAY = START_DELAY;\nexports.makeOfflineTransport = makeOfflineTransport;\n//# sourceMappingURL=offline.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst scope = require('../scope.js');\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope$1,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || utils.uuid4(),\n timestamp: event.timestamp || utils.dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope$1;\n if (hint.captureContext) {\n finalScope = scope.Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = utils.resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = utils.truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = utils.truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = utils.truncate(request.url, maxValueLength);\n }\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: utils.normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: utils.normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: utils.normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: utils.normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = utils.normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = utils.normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n\nexports.prepareEvent = prepareEvent;\n//# sourceMappingURL=prepareEvent.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst SDK_VERSION = '7.37.0';\n\nexports.SDK_VERSION = SDK_VERSION;\n//# sourceMappingURL=version.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** Send Console API calls as Sentry Events */\nclass CaptureConsole {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'CaptureConsole';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = CaptureConsole.id;}\n\n /**\n * @inheritDoc\n */\n __init2() {this._levels = utils.CONSOLE_LEVELS;}\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {CaptureConsole.prototype.__init.call(this);CaptureConsole.prototype.__init2.call(this);\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (!('console' in utils.GLOBAL_OBJ)) {\n return;\n }\n\n this._levels.forEach((level) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (!(level in (utils.GLOBAL_OBJ ).console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n utils.fill((utils.GLOBAL_OBJ ).console, level, (originalConsoleMethod) => (...args) => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(utils.severityLevelFromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = utils.safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${utils.safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(utils.GLOBAL_OBJ.console, args);\n }\n });\n });\n }\n} CaptureConsole.__initStatic();\n\nexports.CaptureConsole = CaptureConsole;\n//# sourceMappingURL=captureconsole.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/**\n * Integration to debug sent Sentry events.\n * This integration should not be used in production\n */\nclass Debug {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Debug';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Debug.id;}\n\n constructor(options) {Debug.prototype.__init.call(this);\n this._options = {\n debugger: false,\n stringify: false,\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor((event, hint) => {\n const self = getCurrentHub().getIntegration(Debug);\n if (self) {\n if (self._options.debugger) {\n // eslint-disable-next-line no-debugger\n debugger;\n }\n\n /* eslint-disable no-console */\n utils.consoleSandbox(() => {\n if (self._options.stringify) {\n console.log(JSON.stringify(event, null, 2));\n if (Object.keys(hint).length) {\n console.log(JSON.stringify(hint, null, 2));\n }\n } else {\n console.log(event);\n if (Object.keys(hint).length) {\n console.log(hint);\n }\n }\n });\n /* eslint-enable no-console */\n }\n return event;\n });\n }\n} Debug.__initStatic();\n\nexports.Debug = Debug;\n//# sourceMappingURL=debug.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** Deduplication filter */\nclass Dedupe {constructor() { Dedupe.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Dedupe';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Dedupe.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcessor = currentEvent => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n} Dedupe.__initStatic();\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexports.Dedupe = Dedupe;\nexports._shouldDropEvent = _shouldDropEvent;\n//# sourceMappingURL=dedupe.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** JSDoc */\n\n/** Patch toString calls to return proper name for wrapped functions */\nclass ExtraErrorData {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'ExtraErrorData';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = ExtraErrorData.id;}\n\n /** JSDoc */\n\n /**\n * @inheritDoc\n */\n constructor(options) {ExtraErrorData.prototype.__init.call(this);\n this._options = {\n depth: 3,\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor((event, hint) => {\n const self = getCurrentHub().getIntegration(ExtraErrorData);\n if (!self) {\n return event;\n }\n return self.enhanceEventWithErrorData(event, hint);\n });\n }\n\n /**\n * Attaches extracted information from the Error object to extra field in the Event\n */\n enhanceEventWithErrorData(event, hint = {}) {\n if (!hint.originalException || !utils.isError(hint.originalException)) {\n return event;\n }\n const exceptionName = (hint.originalException ).name || hint.originalException.constructor.name;\n\n const errorData = this._extractErrorData(hint.originalException );\n\n if (errorData) {\n const contexts = {\n ...event.contexts,\n };\n\n const normalizedErrorData = utils.normalize(errorData, this._options.depth);\n\n if (utils.isPlainObject(normalizedErrorData)) {\n // We mark the error data as \"already normalized\" here, because we don't want other normalization procedures to\n // potentially truncate the data we just already normalized, with a certain depth setting.\n utils.addNonEnumerableProperty(normalizedErrorData, '__sentry_skip_normalization__', true);\n contexts[exceptionName] = normalizedErrorData;\n }\n\n return {\n ...event,\n contexts,\n };\n }\n\n return event;\n }\n\n /**\n * Extract extra information from the Error object\n */\n _extractErrorData(error) {\n // We are trying to enhance already existing event, so no harm done if it won't succeed\n try {\n const nativeKeys = [\n 'name',\n 'message',\n 'stack',\n 'line',\n 'column',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'toJSON',\n ];\n\n const extraErrorInfo = {};\n\n // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n for (const key of Object.keys(error)) {\n if (nativeKeys.indexOf(key) !== -1) {\n continue;\n }\n const value = error[key];\n extraErrorInfo[key] = utils.isError(value) ? value.toString() : value;\n }\n\n // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n if (typeof error.toJSON === 'function') {\n const serializedError = error.toJSON() ;\n\n for (const key of Object.keys(serializedError)) {\n const value = serializedError[key];\n extraErrorInfo[key] = utils.isError(value) ? value.toString() : value;\n }\n }\n\n return extraErrorInfo;\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Unable to extract extra data from the Error object:', oO);\n }\n\n return null;\n }\n} ExtraErrorData.__initStatic();\n\nexports.ExtraErrorData = ExtraErrorData;\n//# sourceMappingURL=extraerrordata.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** HTTPClient integration creates events for failed client side HTTP requests. */\nclass HttpClient {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'HttpClient';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = HttpClient.id;}\n\n /**\n * Returns current hub.\n */\n\n /**\n * @inheritDoc\n *\n * @param options\n */\n constructor(options) {HttpClient.prototype.__init.call(this);\n this._options = {\n failedRequestStatusCodes: [[500, 599]],\n failedRequestTargets: [/.*/],\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n *\n * @param options\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n this._wrapFetch();\n this._wrapXHR();\n }\n\n /**\n * Interceptor function for fetch requests\n *\n * @param requestInfo The Fetch API request info\n * @param response The Fetch API response\n * @param requestInit The request init object\n */\n _fetchResponseHandler(requestInfo, response, requestInit) {\n if (this._getCurrentHub && this._shouldCaptureResponse(response.status, response.url)) {\n const request = new Request(requestInfo, requestInit);\n const hub = this._getCurrentHub();\n\n let requestHeaders, responseHeaders, requestCookies, responseCookies;\n\n if (hub.shouldSendDefaultPii()) {\n [{ headers: requestHeaders, cookies: requestCookies }, { headers: responseHeaders, cookies: responseCookies }] =\n [\n { cookieHeader: 'Cookie', obj: request },\n { cookieHeader: 'Set-Cookie', obj: response },\n ].map(({ cookieHeader, obj }) => {\n const headers = this._extractFetchHeaders(obj.headers);\n let cookies;\n\n try {\n const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || undefined;\n\n if (cookieString) {\n cookies = this._parseCookieString(cookieString);\n }\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`Could not extract cookies from header ${cookieHeader}`);\n }\n\n return {\n headers,\n cookies,\n };\n });\n }\n\n const event = this._createEvent({\n url: request.url,\n method: request.method,\n status: response.status,\n requestHeaders,\n responseHeaders,\n requestCookies,\n responseCookies,\n });\n\n hub.captureEvent(event);\n }\n }\n\n /**\n * Interceptor function for XHR requests\n *\n * @param xhr The XHR request\n * @param method The HTTP method\n * @param headers The HTTP headers\n */\n _xhrResponseHandler(xhr, method, headers) {\n if (this._getCurrentHub && this._shouldCaptureResponse(xhr.status, xhr.responseURL)) {\n let requestHeaders, responseCookies, responseHeaders;\n const hub = this._getCurrentHub();\n\n if (hub.shouldSendDefaultPii()) {\n try {\n const cookieString = xhr.getResponseHeader('Set-Cookie') || xhr.getResponseHeader('set-cookie') || undefined;\n\n if (cookieString) {\n responseCookies = this._parseCookieString(cookieString);\n }\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Could not extract cookies from response headers');\n }\n\n try {\n responseHeaders = this._getXHRResponseHeaders(xhr);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Could not extract headers from response');\n }\n\n requestHeaders = headers;\n }\n\n const event = this._createEvent({\n url: xhr.responseURL,\n method: method,\n status: xhr.status,\n requestHeaders,\n // Can't access request cookies from XHR\n responseHeaders,\n responseCookies,\n });\n\n hub.captureEvent(event);\n }\n }\n\n /**\n * Extracts response size from `Content-Length` header when possible\n *\n * @param headers\n * @returns The response size in bytes or undefined\n */\n _getResponseSizeFromHeaders(headers) {\n if (headers) {\n const contentLength = headers['Content-Length'] || headers['content-length'];\n\n if (contentLength) {\n return parseInt(contentLength, 10);\n }\n }\n\n return undefined;\n }\n\n /**\n * Creates an object containing cookies from the given cookie string\n *\n * @param cookieString The cookie string to parse\n * @returns The parsed cookies\n */\n _parseCookieString(cookieString) {\n return cookieString.split('; ').reduce((acc, cookie) => {\n const [key, value] = cookie.split('=');\n acc[key] = value;\n return acc;\n }, {});\n }\n\n /**\n * Extracts the headers as an object from the given Fetch API request or response object\n *\n * @param headers The headers to extract\n * @returns The extracted headers as an object\n */\n _extractFetchHeaders(headers) {\n const result = {};\n\n headers.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n }\n\n /**\n * Extracts the response headers as an object from the given XHR object\n *\n * @param xhr The XHR object to extract the response headers from\n * @returns The response headers as an object\n */\n _getXHRResponseHeaders(xhr) {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ');\n acc[key] = value;\n return acc;\n }, {});\n }\n\n /**\n * Checks if the given target url is in the given list of targets\n *\n * @param target The target url to check\n * @returns true if the target url is in the given list of targets, false otherwise\n */\n _isInGivenRequestTargets(target) {\n if (!this._options.failedRequestTargets) {\n return false;\n }\n\n return this._options.failedRequestTargets.some((givenRequestTarget) => {\n if (typeof givenRequestTarget === 'string') {\n return target.includes(givenRequestTarget);\n }\n\n return givenRequestTarget.test(target);\n });\n }\n\n /**\n * Checks if the given status code is in the given range\n *\n * @param status The status code to check\n * @returns true if the status code is in the given range, false otherwise\n */\n _isInGivenStatusRanges(status) {\n if (!this._options.failedRequestStatusCodes) {\n return false;\n }\n\n return this._options.failedRequestStatusCodes.some((range) => {\n if (typeof range === 'number') {\n return range === status;\n }\n\n return status >= range[0] && status <= range[1];\n });\n }\n\n /**\n * Wraps `fetch` function to capture request and response data\n */\n _wrapFetch() {\n if (!utils.supportsNativeFetch()) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n utils.fill(utils.GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function ( ...args) {\n const [requestInfo, requestInit] = args ;\n const responsePromise = originalFetch.apply(this, args);\n\n responsePromise\n .then((response) => {\n self._fetchResponseHandler(requestInfo, response, requestInit);\n return response;\n })\n .catch((error) => {\n throw error;\n });\n\n return responsePromise;\n };\n });\n }\n\n /**\n * Wraps XMLHttpRequest to capture request and response data\n */\n _wrapXHR() {\n if (!('XMLHttpRequest' in utils.GLOBAL_OBJ)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n utils.fill(XMLHttpRequest.prototype, 'open', function (originalOpen) {\n return function ( ...openArgs) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const method = openArgs[0] ;\n const headers = {};\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n utils.fill(\n xhr,\n 'setRequestHeader',\n // eslint-disable-next-line @typescript-eslint/ban-types\n function (originalSetRequestHeader) {\n return function (...setRequestHeaderArgs) {\n const [header, value] = setRequestHeaderArgs ;\n\n headers[header] = value;\n\n return originalSetRequestHeader.apply(xhr, setRequestHeaderArgs);\n };\n },\n );\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n utils.fill(xhr, 'onloadend', function (original) {\n return function (...onloadendArgs) {\n try {\n self._xhrResponseHandler(xhr, method, headers);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Error while extracting response event form XHR response', e);\n }\n\n if (original) {\n return original.apply(xhr, onloadendArgs);\n }\n };\n });\n\n return originalOpen.apply(this, openArgs);\n };\n });\n }\n\n /**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\n _isSentryRequest(url) {\n const client = this._getCurrentHub && this._getCurrentHub().getClient();\n\n if (!client) {\n return false;\n }\n\n const dsn = client.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n }\n\n /**\n * Checks whether to capture given response as an event\n *\n * @param status response status code\n * @param url response url\n */\n _shouldCaptureResponse(status, url) {\n return this._isInGivenStatusRanges(status) && this._isInGivenRequestTargets(url) && !this._isSentryRequest(url);\n }\n\n /**\n * Creates a synthetic Sentry event from given response data\n *\n * @param data response data\n * @returns event\n */\n _createEvent(data\n\n) {\n const message = `HTTP Client Error with status code: ${data.status}`;\n\n const event = {\n message,\n exception: {\n values: [\n {\n type: 'Error',\n value: message,\n },\n ],\n },\n request: {\n url: data.url,\n method: data.method,\n headers: data.requestHeaders,\n cookies: data.requestCookies,\n },\n contexts: {\n response: {\n status_code: data.status,\n headers: data.responseHeaders,\n cookies: data.responseCookies,\n body_size: this._getResponseSizeFromHeaders(data.responseHeaders),\n },\n },\n };\n\n utils.addExceptionMechanism(event, {\n type: 'http.client',\n });\n\n return event;\n }\n} HttpClient.__initStatic();\n\nexports.HttpClient = HttpClient;\n//# sourceMappingURL=httpclient.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst captureconsole = require('./captureconsole.js');\nconst debug = require('./debug.js');\nconst dedupe = require('./dedupe.js');\nconst extraerrordata = require('./extraerrordata.js');\nconst offline = require('./offline.js');\nconst reportingobserver = require('./reportingobserver.js');\nconst rewriteframes = require('./rewriteframes.js');\nconst sessiontiming = require('./sessiontiming.js');\nconst transaction = require('./transaction.js');\nconst httpclient = require('./httpclient.js');\n\n\n\nexports.CaptureConsole = captureconsole.CaptureConsole;\nexports.Debug = debug.Debug;\nexports.Dedupe = dedupe.Dedupe;\nexports.ExtraErrorData = extraerrordata.ExtraErrorData;\nexports.Offline = offline.Offline;\nexports.ReportingObserver = reportingobserver.ReportingObserver;\nexports.RewriteFrames = rewriteframes.RewriteFrames;\nexports.SessionTiming = sessiontiming.SessionTiming;\nexports.Transaction = transaction.Transaction;\nexports.HttpClient = httpclient.HttpClient;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst localForage = require('localforage');\n\nconst WINDOW = utils.GLOBAL_OBJ ;\n\n/**\n * cache offline errors and send when connected\n */\nclass Offline {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Offline';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Offline.id;}\n\n /**\n * the current hub instance\n */\n\n /**\n * maximum number of events to store while offline\n */\n\n /**\n * event cache\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {Offline.prototype.__init.call(this);\n this.maxStoredEvents = options.maxStoredEvents || 30; // set a reasonable default\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this.offlineEventStore = localForage.default.createInstance({\n name: 'sentry/offlineEventStore',\n });\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n this.hub = getCurrentHub();\n\n if ('addEventListener' in WINDOW) {\n WINDOW.addEventListener('online', () => {\n void this._sendEvents().catch(() => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('could not send cached events');\n });\n });\n }\n\n const eventProcessor = event => {\n if (this.hub && this.hub.getIntegration(Offline)) {\n // cache if we are positively offline\n if ('navigator' in WINDOW && 'onLine' in WINDOW.navigator && !WINDOW.navigator.onLine) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Event dropped due to being a offline - caching instead');\n\n void this._cacheEvent(event)\n .then((_event) => this._enforceMaxEvents())\n .catch((_error) => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('could not cache event while offline');\n });\n\n // return null on success or failure, because being offline will still result in an error\n return null;\n }\n }\n\n return event;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n\n // if online now, send any events stored in a previous offline session\n if ('navigator' in WINDOW && 'onLine' in WINDOW.navigator && WINDOW.navigator.onLine) {\n void this._sendEvents().catch(() => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('could not send cached events');\n });\n }\n }\n\n /**\n * cache an event to send later\n * @param event an event\n */\n async _cacheEvent(event) {\n return this.offlineEventStore.setItem(utils.uuid4(), utils.normalize(event));\n }\n\n /**\n * purge excess events if necessary\n */\n async _enforceMaxEvents() {\n const events = [];\n\n return this.offlineEventStore\n .iterate((event, cacheKey, _index) => {\n // aggregate events\n events.push({ cacheKey, event });\n })\n .then(\n () =>\n // this promise resolves when the iteration is finished\n this._purgeEvents(\n // purge all events past maxStoredEvents in reverse chronological order\n events\n .sort((a, b) => (b.event.timestamp || 0) - (a.event.timestamp || 0))\n .slice(this.maxStoredEvents < events.length ? this.maxStoredEvents : events.length)\n .map(event => event.cacheKey),\n ),\n )\n .catch((_error) => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('could not enforce max events');\n });\n }\n\n /**\n * purge event from cache\n */\n async _purgeEvent(cacheKey) {\n return this.offlineEventStore.removeItem(cacheKey);\n }\n\n /**\n * purge events from cache\n */\n async _purgeEvents(cacheKeys) {\n // trail with .then to ensure the return type as void and not void|void[]\n return Promise.all(cacheKeys.map(cacheKey => this._purgeEvent(cacheKey))).then();\n }\n\n /**\n * send all events\n */\n async _sendEvents() {\n return this.offlineEventStore.iterate((event, cacheKey, _index) => {\n if (this.hub) {\n this.hub.captureEvent(event);\n\n void this._purgeEvent(cacheKey).catch((_error) => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('could not purge event from cache');\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('no hub found - could not send cached event');\n }\n });\n }\n} Offline.__initStatic();\n\nexports.Offline = Offline;\n//# sourceMappingURL=offline.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nconst WINDOW = utils.GLOBAL_OBJ ;\n\n/** Reporting API integration - https://w3c.github.io/reporting/ */\nclass ReportingObserver {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'ReportingObserver';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = ReportingObserver.id;}\n\n /**\n * Returns current hub.\n */\n\n /**\n * @inheritDoc\n */\n constructor(\n _options\n\n = {\n types: ['crash', 'deprecation', 'intervention'],\n },\n ) {this._options = _options;ReportingObserver.prototype.__init.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (!utils.supportsReportingObserver()) {\n return;\n }\n\n this._getCurrentHub = getCurrentHub;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n const observer = new (WINDOW ).ReportingObserver(this.handler.bind(this), {\n buffered: true,\n types: this._options.types,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n observer.observe();\n }\n\n /**\n * @inheritDoc\n */\n handler(reports) {\n const hub = this._getCurrentHub && this._getCurrentHub();\n if (!hub || !hub.getIntegration(ReportingObserver)) {\n return;\n }\n for (const report of reports) {\n hub.withScope(scope => {\n scope.setExtra('url', report.url);\n\n const label = `ReportingObserver [${report.type}]`;\n let details = 'No details available';\n\n if (report.body) {\n // Object.keys doesn't work on ReportBody, as all properties are inheirted\n const plainBody\n\n = {};\n\n // eslint-disable-next-line guard-for-in\n for (const prop in report.body) {\n plainBody[prop] = report.body[prop];\n }\n\n scope.setExtra('body', plainBody);\n\n if (report.type === 'crash') {\n const body = report.body ;\n // A fancy way to create a message out of crashId OR reason OR both OR fallback\n details = [body.crashId || '', body.reason || ''].join(' ').trim() || details;\n } else {\n const body = report.body ;\n details = body.message || details;\n }\n }\n\n hub.captureMessage(`${label}: ${details}`);\n });\n }\n }\n} ReportingObserver.__initStatic();\n\nexports.ReportingObserver = ReportingObserver;\n//# sourceMappingURL=reportingobserver.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** Rewrite event frames paths */\nclass RewriteFrames {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'RewriteFrames';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = RewriteFrames.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n __init2() {this._prefix = 'app:///';}\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {RewriteFrames.prototype.__init.call(this);RewriteFrames.prototype.__init2.call(this);RewriteFrames.prototype.__init3.call(this);\n if (options.root) {\n this._root = options.root;\n }\n if (options.prefix) {\n this._prefix = options.prefix;\n }\n if (options.iteratee) {\n this._iteratee = options.iteratee;\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(RewriteFrames);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /** JSDoc */\n process(originalEvent) {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = this._processExceptionsEvent(processedEvent);\n }\n\n return processedEvent;\n }\n\n /**\n * @inheritDoc\n */\n __init3() {this._iteratee = (frame) => {\n if (!frame.filename) {\n return frame;\n }\n // Check if the frame filename begins with `/` or a Windows-style prefix such as `C:\\`\n const isWindowsFrame = /^[A-Z]:\\\\/.test(frame.filename);\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = this._root ? utils.relative(this._root, filename) : utils.basename(filename);\n frame.filename = `${this._prefix}${base}`;\n }\n return frame;\n };}\n\n /** JSDoc */\n _processExceptionsEvent(event) {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception.values.map(value => ({\n ...value,\n ...(value.stacktrace && { stacktrace: this._processStacktrace(value.stacktrace) }),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n _processStacktrace(stacktrace) {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => this._iteratee(f)),\n };\n }\n} RewriteFrames.__initStatic();\n\nexports.RewriteFrames = RewriteFrames;\n//# sourceMappingURL=rewriteframes.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/** This function adds duration since Sentry was initialized till the time event was sent */\nclass SessionTiming {constructor() { SessionTiming.prototype.__init.call(this);SessionTiming.prototype.__init2.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'SessionTiming';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = SessionTiming.id;}\n\n /** Exact time Client was initialized expressed in milliseconds since Unix Epoch. */\n __init2() {this._startTime = Date.now();}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(SessionTiming);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n process(event) {\n const now = Date.now();\n\n return {\n ...event,\n extra: {\n ...event.extra,\n ['session:start']: this._startTime,\n ['session:duration']: now - this._startTime,\n ['session:end']: now,\n },\n };\n }\n} SessionTiming.__initStatic();\n\nexports.SessionTiming = SessionTiming;\n//# sourceMappingURL=sessiontiming.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/** Add node transaction to the event */\nclass Transaction {constructor() { Transaction.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Transaction';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Transaction.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(Transaction);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n process(event) {\n const frames = this._getFramesFromEvent(event);\n\n // use for loop so we don't have to reverse whole frames array\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame.in_app === true) {\n event.transaction = this._getTransaction(frame);\n break;\n }\n }\n\n return event;\n }\n\n /** JSDoc */\n _getFramesFromEvent(event) {\n const exception = event.exception && event.exception.values && event.exception.values[0];\n return (exception && exception.stacktrace && exception.stacktrace.frames) || [];\n }\n\n /** JSDoc */\n _getTransaction(frame) {\n return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '';\n }\n} Transaction.__initStatic();\n\nexports.Transaction = Transaction;\n//# sourceMappingURL=transaction.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\n\n/** Platform-agnostic version of `flush` */\nfunction flush(timeout) {\n const client = core.getCurrentHub().getClient();\n return client ? client.flush(timeout) : Promise.resolve(false);\n}\n\n/**\n * Capture the exception passed by nextjs to the `_error` page, adding context data as appropriate.\n *\n * @param contextOrProps The data passed to either `getInitialProps` or `render` by nextjs\n */\nasync function captureUnderscoreErrorException(contextOrProps) {\n const { req, res, err } = contextOrProps;\n\n // 404s (and other 400-y friends) can trigger `_error`, but we don't want to send them to Sentry\n const statusCode = (res && res.statusCode) || contextOrProps.statusCode;\n if (statusCode && statusCode < 500) {\n return Promise.resolve();\n }\n\n // In previous versions of the suggested `_error.js` page in which this function is meant to be used, there was a\n // workaround for https://github.com/vercel/next.js/issues/8592 which involved an extra call to this function, in the\n // custom error component's `render` method, just in case it hadn't been called by `getInitialProps`. Now that that\n // issue has been fixed, the second call is unnecessary, but since it lives in user code rather than our code, users\n // have to be the ones to get rid of it, and guaraneteedly, not all of them will. So, rather than capture the error\n // twice, we just bail if we sense we're in that now-extraneous second call. (We can tell which function we're in\n // because Nextjs passes `pathname` to `getInitialProps` but not to `render`.)\n if (!contextOrProps.pathname) {\n return Promise.resolve();\n }\n\n core.withScope(scope => {\n scope.addEventProcessor(event => {\n utils.addExceptionMechanism(event, {\n type: 'instrument',\n handled: true,\n data: {\n function: '_error.getInitialProps',\n },\n });\n return event;\n });\n\n if (req) {\n scope.setSDKProcessingMetadata({ request: req });\n }\n\n // If third-party libraries (or users themselves) throw something falsy, we want to capture it as a message (which\n // is what passing a string to `captureException` will wind up doing)\n core.captureException(err || `_error.js called with falsy error (${err})`);\n });\n\n // In case this is being run as part of a serverless function (as is the case with the server half of nextjs apps\n // deployed to vercel), make sure the error gets sent to Sentry before the lambda exits.\n await flush(2000);\n}\n\nexports.captureUnderscoreErrorException = captureUnderscoreErrorException;\n//# sourceMappingURL=_error.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\n\nconst PACKAGE_NAME_PREFIX = 'npm:@sentry/';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n * @param options sdk options object that gets mutated\n * @param names list of package names\n */\nfunction buildMetadata(options, names) {\n options._metadata = options._metadata || {};\n options._metadata.sdk =\n options._metadata.sdk ||\n ({\n name: 'sentry.javascript.nextjs',\n packages: names.map(name => ({\n name: `${PACKAGE_NAME_PREFIX}${name}`,\n version: core.SDK_VERSION,\n })),\n version: core.SDK_VERSION,\n } );\n}\n\nexports.buildMetadata = buildMetadata;\n//# sourceMappingURL=metadata.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Recursively traverses an object to update an existing nested key.\n * Note: The provided key path must include existing properties,\n * the function will not create objects while traversing.\n *\n * @param obj An object to update\n * @param value The value to update the nested key with\n * @param keyPath The path to the key to update ex. fizz.buzz.foo\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setNestedKey(obj, keyPath, value) {\n // Ex. foo.bar.zoop will extract foo and bar.zoop\n const match = keyPath.match(/([a-z_]+)\\.(.*)/i);\n // The match will be null when there's no more recursing to do, i.e., when we've reached the right level of the object\n if (match === null) {\n obj[keyPath] = value;\n } else {\n // `match[1]` is the initial segment of the path, and `match[2]` is the remainder of the path\n const innerObj = obj[match[1]];\n setNestedKey(innerObj, match[2], value);\n }\n}\n\n/**\n * Enforces inclusion of a given integration with specified options in an integration array originally determined by the\n * user, by either including the given default instance or by patching an existing user instance with the given options.\n *\n * Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging\n * options from a default integration instance with those from a user-provided instance of the same integration, only\n * for allowing the user to override a default instance entirely. (TODO: Fix that.)\n *\n * @param defaultIntegrationInstance An instance of the integration with the correct options already set\n * @param userIntegrations Integrations defined by the user.\n * @param forcedOptions Options with which to patch an existing user-derived instance on the integration.\n * @returns A final integrations array.\n */\nfunction addOrUpdateIntegration(\n defaultIntegrationInstance,\n userIntegrations,\n forcedOptions = {},\n) {\n return (\n Array.isArray(userIntegrations)\n ? addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions)\n : addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance,\n // Somehow TS can't figure out that not being an array makes this necessarily a function\n userIntegrations ,\n forcedOptions,\n )\n ) ;\n}\n\nfunction addOrUpdateIntegrationInArray(\n defaultIntegrationInstance,\n userIntegrations,\n forcedOptions,\n) {\n const userInstance = userIntegrations.find(integration => integration.name === defaultIntegrationInstance.name);\n\n if (userInstance) {\n for (const [keyPath, value] of Object.entries(forcedOptions)) {\n setNestedKey(userInstance, keyPath, value);\n }\n\n return userIntegrations;\n }\n\n return [...userIntegrations, defaultIntegrationInstance];\n}\n\nfunction addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance,\n userIntegrationsFunc,\n forcedOptions,\n) {\n const wrapper = defaultIntegrations => {\n const userFinalIntegrations = userIntegrationsFunc(defaultIntegrations);\n\n // There are instances where we want the user to be able to prevent an integration from appearing at all, which they\n // would do by providing a function which filters out the integration in question. If that's happened in one of\n // those cases, don't add our default back in.\n if (defaultIntegrationInstance.allowExclusionByUser) {\n const userFinalInstance = userFinalIntegrations.find(\n integration => integration.name === defaultIntegrationInstance.name,\n );\n if (!userFinalInstance) {\n return userFinalIntegrations;\n }\n }\n\n return addOrUpdateIntegrationInArray(defaultIntegrationInstance, userFinalIntegrations, forcedOptions);\n };\n\n return wrapper;\n}\n\nexports.addOrUpdateIntegration = addOrUpdateIntegration;\n//# sourceMappingURL=userIntegrations.js.map\n","export * from \"./server\";","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst integrations = require('@sentry/integrations');\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst domain$1 = require('domain');\nconst path = require('path');\nconst metadata = require('../common/metadata.js');\nconst userIntegrations = require('../common/userIntegrations.js');\nconst isBuild = require('./utils/isBuild.js');\nconst _error = require('../common/_error.js');\nconst wrapGetStaticPropsWithSentry = require('./wrapGetStaticPropsWithSentry.js');\nconst wrapGetInitialPropsWithSentry = require('./wrapGetInitialPropsWithSentry.js');\nconst wrapAppGetInitialPropsWithSentry = require('./wrapAppGetInitialPropsWithSentry.js');\nconst wrapDocumentGetInitialPropsWithSentry = require('./wrapDocumentGetInitialPropsWithSentry.js');\nconst wrapErrorGetInitialPropsWithSentry = require('./wrapErrorGetInitialPropsWithSentry.js');\nconst wrapGetServerSidePropsWithSentry = require('./wrapGetServerSidePropsWithSentry.js');\nconst wrapApiHandlerWithSentry = require('./wrapApiHandlerWithSentry.js');\nconst wrapAppDirComponentWithSentry = require('./wrapAppDirComponentWithSentry.js');\n\n/**\n * A passthrough error boundary for the server that doesn't depend on any react. Error boundaries don't catch SSR errors\n * so they should simply be a passthrough.\n */\nconst ErrorBoundary = (props) => {\n if (!props.children) {\n return null;\n }\n\n if (typeof props.children === 'function') {\n return (props.children )();\n }\n\n // since Next.js >= 10 requires React ^16.6.0 we are allowed to return children like this here\n return props.children ;\n};\n\n/**\n * A passthrough error boundary wrapper for the server that doesn't depend on any react. Error boundaries don't catch\n * SSR errors so they should simply be a passthrough.\n */\nfunction withErrorBoundary(\n WrappedComponent,\n) {\n return WrappedComponent ;\n}\n\n/**\n * Just a passthrough since we're on the server and showing the report dialog on the server doesn't make any sense.\n */\nfunction showReportDialog() {\n return;\n}\n\nconst globalWithInjectedValues = global\n\n;\n\nconst domain = domain$1 ;\n\n// TODO (v8): Remove this\n/**\n * @deprecated This constant will be removed in the next major update.\n */\nconst IS_BUILD = isBuild.isBuild();\n\nconst IS_VERCEL = !!process.env.VERCEL;\n\n/** Inits the Sentry NextJS SDK on node. */\nfunction init(options) {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && options.debug) {\n utils.logger.enable();\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Initializing SDK...');\n\n if (sdkAlreadyInitialized()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('SDK already initialized');\n return;\n }\n\n metadata.buildMetadata(options, ['nextjs', 'node']);\n options.environment = options.environment || process.env.NODE_ENV;\n addServerIntegrations(options);\n // Right now we only capture frontend sessions for Next.js\n options.autoSessionTracking = false;\n\n // In an ideal world, this init function would be called before any requests are handled. That way, every domain we\n // use to wrap a request would inherit its scope and client from the global hub. In practice, however, handling the\n // first request is what causes us to initialize the SDK, as the init code is injected into `_app` and all API route\n // handlers, and those are only accessed in the course of handling a request. As a result, we're already in a domain\n // when `init` is called. In order to compensate for this and mimic the ideal world scenario, we stash the active\n // domain, run `init` as normal, and then restore the domain afterwards, copying over data from the main hub as if we\n // really were inheriting.\n const activeDomain = domain.active;\n domain.active = null;\n\n node.init(options);\n\n const filterTransactions = event => {\n return event.type === 'transaction' && event.transaction === '/404' ? null : event;\n };\n\n filterTransactions.id = 'NextServer404TransactionFilter';\n\n node.configureScope(scope => {\n scope.setTag('runtime', 'node');\n if (IS_VERCEL) {\n scope.setTag('vercel', true);\n }\n\n scope.addEventProcessor(filterTransactions);\n });\n\n if (activeDomain) {\n const globalHub = core.getHubFromCarrier(core.getMainCarrier());\n const domainHub = core.getHubFromCarrier(activeDomain);\n\n // apply the changes made by `nodeInit` to the domain's hub also\n domainHub.bindClient(globalHub.getClient());\n _optionalChain([domainHub, 'access', _ => _.getScope, 'call', _2 => _2(), 'optionalAccess', _3 => _3.update, 'call', _4 => _4(globalHub.getScope())]);\n // `scope.update()` doesn’t copy over event processors, so we have to add it manually\n _optionalChain([domainHub, 'access', _5 => _5.getScope, 'call', _6 => _6(), 'optionalAccess', _7 => _7.addEventProcessor, 'call', _8 => _8(filterTransactions)]);\n\n // restore the domain hub as the current one\n domain.active = activeDomain;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('SDK successfully initialized');\n}\n\nfunction sdkAlreadyInitialized() {\n const hub = node.getCurrentHub();\n return !!hub.getClient();\n}\n\nfunction addServerIntegrations(options) {\n let integrations$1 = options.integrations || [];\n\n // This value is injected at build time, based on the output directory specified in the build config. Though a default\n // is set there, we set it here as well, just in case something has gone wrong with the injection.\n const distDirName = globalWithInjectedValues.__rewriteFramesDistDir__ || '.next';\n // nextjs always puts the build directory at the project root level, which is also where you run `next start` from, so\n // we can read in the project directory from the currently running process\n const distDirAbsPath = path.resolve(process.cwd(), distDirName);\n const SOURCEMAP_FILENAME_REGEX = new RegExp(utils.escapeStringForRegex(distDirAbsPath));\n\n const defaultRewriteFramesIntegration = new integrations.RewriteFrames({\n iteratee: frame => {\n frame.filename = _optionalChain([frame, 'access', _9 => _9.filename, 'optionalAccess', _10 => _10.replace, 'call', _11 => _11(SOURCEMAP_FILENAME_REGEX, 'app:///_next')]);\n return frame;\n },\n });\n integrations$1 = userIntegrations.addOrUpdateIntegration(defaultRewriteFramesIntegration, integrations$1);\n\n const defaultOnUncaughtExceptionIntegration = new node.Integrations.OnUncaughtException({\n exitEvenIfOtherHandlersAreRegistered: false,\n });\n defaultOnUncaughtExceptionIntegration.allowExclusionByUser = true;\n integrations$1 = userIntegrations.addOrUpdateIntegration(defaultOnUncaughtExceptionIntegration, integrations$1, {\n _options: { exitEvenIfOtherHandlersAreRegistered: false },\n });\n\n if (tracing.hasTracingEnabled(options)) {\n const defaultHttpTracingIntegration = new node.Integrations.Http({ tracing: true });\n integrations$1 = userIntegrations.addOrUpdateIntegration(defaultHttpTracingIntegration, integrations$1, {\n _tracing: {},\n });\n }\n\n options.integrations = integrations$1;\n}\n\n// TODO (v8): Remove this\n/**\n * @deprecated This constant will be removed in the next major update.\n */\nconst deprecatedIsBuild = () => isBuild.isBuild();\n\nexports.captureUnderscoreErrorException = _error.captureUnderscoreErrorException;\nexports.withSentryGetStaticProps = wrapGetStaticPropsWithSentry.withSentryGetStaticProps;\nexports.wrapGetStaticPropsWithSentry = wrapGetStaticPropsWithSentry.wrapGetStaticPropsWithSentry;\nexports.withSentryServerSideGetInitialProps = wrapGetInitialPropsWithSentry.withSentryServerSideGetInitialProps;\nexports.wrapGetInitialPropsWithSentry = wrapGetInitialPropsWithSentry.wrapGetInitialPropsWithSentry;\nexports.withSentryServerSideAppGetInitialProps = wrapAppGetInitialPropsWithSentry.withSentryServerSideAppGetInitialProps;\nexports.wrapAppGetInitialPropsWithSentry = wrapAppGetInitialPropsWithSentry.wrapAppGetInitialPropsWithSentry;\nexports.withSentryServerSideDocumentGetInitialProps = wrapDocumentGetInitialPropsWithSentry.withSentryServerSideDocumentGetInitialProps;\nexports.wrapDocumentGetInitialPropsWithSentry = wrapDocumentGetInitialPropsWithSentry.wrapDocumentGetInitialPropsWithSentry;\nexports.withSentryServerSideErrorGetInitialProps = wrapErrorGetInitialPropsWithSentry.withSentryServerSideErrorGetInitialProps;\nexports.wrapErrorGetInitialPropsWithSentry = wrapErrorGetInitialPropsWithSentry.wrapErrorGetInitialPropsWithSentry;\nexports.withSentryGetServerSideProps = wrapGetServerSidePropsWithSentry.withSentryGetServerSideProps;\nexports.wrapGetServerSidePropsWithSentry = wrapGetServerSidePropsWithSentry.wrapGetServerSidePropsWithSentry;\nexports.withSentry = wrapApiHandlerWithSentry.withSentry;\nexports.withSentryAPI = wrapApiHandlerWithSentry.withSentryAPI;\nexports.wrapApiHandlerWithSentry = wrapApiHandlerWithSentry.wrapApiHandlerWithSentry;\nexports.wrapAppDirComponentWithSentry = wrapAppDirComponentWithSentry.wrapAppDirComponentWithSentry;\nexports.ErrorBoundary = ErrorBoundary;\nexports.IS_BUILD = IS_BUILD;\nexports.init = init;\nexports.isBuild = deprecatedIsBuild;\nexports.showReportDialog = showReportDialog;\nexports.withErrorBoundary = withErrorBoundary;\nfor (const k in node) {\n if (k !== 'default' && !exports.hasOwnProperty(k)) exports[k] = node[k];\n}\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst constants = require('next/constants');\n\n/**\n * Decide if the currently running process is part of the build phase or happening at runtime.\n */\nfunction isBuild() {\n return process.env.NEXT_PHASE === constants.PHASE_PRODUCTION_BUILD;\n}\n\nexports.isBuild = isBuild;\n//# sourceMappingURL=isBuild.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst platformSupportsStreaming = () => !process.env.LAMBDA_TASK_ROOT && !process.env.VERCEL;\n\nexports.platformSupportsStreaming = platformSupportsStreaming;\n//# sourceMappingURL=platformSupportsStreaming.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst utils = require('@sentry/utils');\n\n/**\n * Wrap `res.end()` so that it closes the transaction and flushes events before letting the request finish.\n *\n * Note: This wraps a sync method with an async method. While in general that's not a great idea in terms of keeping\n * things in the right order, in this case it's safe, because the native `.end()` actually *is* (effectively) async, and\n * its run actually *is* (literally) awaited, just manually so (which reflects the fact that the core of the\n * request/response code in Node by far predates the introduction of `async`/`await`). When `.end()` is done, it emits\n * the `prefinish` event, and only once that fires does request processing continue. See\n * https://github.com/nodejs/node/commit/7c9b607048f13741173d397795bac37707405ba7.\n *\n * Also note: `res.end()` isn't called until *after* all response data and headers have been sent, so blocking inside of\n * `end` doesn't delay data getting to the end user. See\n * https://nodejs.org/api/http.html#responseenddata-encoding-callback.\n *\n * @param transaction The transaction tracing request handling\n * @param res: The request's corresponding response\n */\nfunction autoEndTransactionOnResponseEnd(transaction, res) {\n const wrapEndMethod = (origEnd) => {\n return function sentryWrappedEnd( ...args) {\n void finishTransaction(transaction, this);\n return origEnd.call(this, ...args);\n };\n };\n\n // Prevent double-wrapping\n // res.end may be undefined during build when using `next export` to statically export a Next.js app\n if (res.end && !(res.end ).__sentry_original__) {\n utils.fill(res, 'end', wrapEndMethod);\n }\n}\n\n/** Finish the given response's transaction and set HTTP status data */\nasync function finishTransaction(transaction, res) {\n if (transaction) {\n transaction.setHttpStatus(res.statusCode);\n\n // If any open spans are set to finish when the response ends, it sets up a race condition between their `finish`\n // calls and the transaction's `finish` call - and any spans which lose the race will get dropped from the\n // transaction. To prevent this, push `transaction.finish` to the next event loop so that it's guaranteed to lose\n // the race, and wait for it to be done before flushing events.\n const transactionFinished = new Promise(resolve => {\n setImmediate(() => {\n transaction.finish();\n resolve();\n });\n });\n await transactionFinished;\n }\n}\n\n/** Flush the event queue to ensure that events get sent to Sentry before the response is finished and the lambda ends */\nasync function flushQueue() {\n try {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Flushing events...');\n await node.flush(2000);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Done flushing events');\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Error while flushing events:\\n', e);\n }\n}\n\nexports.autoEndTransactionOnResponseEnd = autoEndTransactionOnResponseEnd;\nexports.finishTransaction = finishTransaction;\nexports.flushQueue = flushQueue;\n//# sourceMappingURL=responseEnd.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst domain = require('domain');\nconst platformSupportsStreaming = require('./platformSupportsStreaming.js');\nconst responseEnd = require('./responseEnd.js');\n\n/**\n * Grabs a transaction off a Next.js datafetcher request object, if it was previously put there via\n * `setTransactionOnRequest`.\n *\n * @param req The Next.js datafetcher request object\n * @returns the Transaction on the request object if there is one, or `undefined` if the request object didn't have one.\n */\nfunction getTransactionFromRequest(req) {\n return req._sentryTransaction;\n}\n\nfunction setTransactionOnRequest(transaction, req) {\n req._sentryTransaction = transaction;\n}\n\n/**\n * Wraps a function that potentially throws. If it does, the error is passed to `captureException` and rethrown.\n *\n * Note: This function turns the wrapped function into an asynchronous one.\n */\nfunction withErrorInstrumentation(\n origFunction,\n) {\n return async function ( ...origFunctionArguments) {\n try {\n return await origFunction.apply(this, origFunctionArguments);\n } catch (e) {\n // TODO: Extract error logic from `withSentry` in here or create a new wrapper with said logic or something like that.\n core.captureException(e);\n throw e;\n }\n };\n}\n\n/**\n * Calls a server-side data fetching function (that takes a `req` and `res` object in its context) with tracing\n * instrumentation. A transaction will be created for the incoming request (if it doesn't already exist) in addition to\n * a span for the wrapped data fetching function.\n *\n * All of the above happens in an isolated domain, meaning all thrown errors will be associated with the correct span.\n *\n * @param origDataFetcher The data fetching method to call.\n * @param origFunctionArguments The arguments to call the data fetching method with.\n * @param req The data fetching function's request object.\n * @param res The data fetching function's response object.\n * @param options Options providing details for the created transaction and span.\n * @returns what the data fetching method call returned.\n */\nfunction withTracedServerSideDataFetcher(\n origDataFetcher,\n req,\n res,\n options\n\n,\n) {\n return async function ( ...args) {\n return domain.create().bind(async () => {\n let requestTransaction = getTransactionFromRequest(req);\n let dataFetcherSpan;\n\n const sentryTraceHeader = req.headers['sentry-trace'];\n const rawBaggageString = req.headers && req.headers.baggage;\n const traceparentData =\n typeof sentryTraceHeader === 'string' ? utils.extractTraceparentData(sentryTraceHeader) : undefined;\n\n const dynamicSamplingContext = utils.baggageHeaderToDynamicSamplingContext(rawBaggageString);\n\n if (platformSupportsStreaming.platformSupportsStreaming()) {\n if (requestTransaction === undefined) {\n const newTransaction = core.startTransaction(\n {\n op: 'http.server',\n name: options.requestedRouteName,\n ...traceparentData,\n status: 'ok',\n metadata: {\n request: req,\n source: 'route',\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n },\n { request: req },\n );\n\n requestTransaction = newTransaction;\n\n if (platformSupportsStreaming.platformSupportsStreaming()) {\n // On platforms that don't support streaming, doing things after res.end() is unreliable.\n responseEnd.autoEndTransactionOnResponseEnd(newTransaction, res);\n }\n\n // Link the transaction and the request together, so that when we would normally only have access to one, it's\n // still possible to grab the other.\n setTransactionOnRequest(newTransaction, req);\n }\n\n dataFetcherSpan = requestTransaction.startChild({\n op: 'function.nextjs',\n description: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,\n status: 'ok',\n });\n } else {\n dataFetcherSpan = core.startTransaction({\n op: 'function.nextjs',\n name: `${options.dataFetchingMethodName} (${options.dataFetcherRouteName})`,\n ...traceparentData,\n status: 'ok',\n metadata: {\n request: req,\n source: 'route',\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n });\n }\n\n const currentScope = core.getCurrentHub().getScope();\n if (currentScope) {\n currentScope.setSpan(dataFetcherSpan);\n currentScope.setSDKProcessingMetadata({ request: req });\n }\n\n try {\n return await origDataFetcher.apply(this, args);\n } catch (e) {\n // Since we finish the span before the error can bubble up and trigger the handlers in `registerErrorInstrumentation`\n // that set the transaction status, we need to manually set the status of the span & transaction\n dataFetcherSpan.setStatus('internal_error');\n _optionalChain([requestTransaction, 'optionalAccess', _ => _.setStatus, 'call', _2 => _2('internal_error')]);\n throw e;\n } finally {\n dataFetcherSpan.finish();\n if (!platformSupportsStreaming.platformSupportsStreaming()) {\n await responseEnd.flushQueue();\n }\n }\n })();\n };\n}\n\n/**\n * Call a data fetcher and trace it. Only traces the function if there is an active transaction on the scope.\n *\n * We only do the following until we move transaction creation into this function: When called, the wrapped function\n * will also update the name of the active transaction with a parameterized route provided via the `options` argument.\n */\nasync function callDataFetcherTraced(\n origFunction,\n origFunctionArgs,\n options\n\n,\n) {\n const { parameterizedRoute, dataFetchingMethodName } = options;\n\n const transaction = tracing.getActiveTransaction();\n\n if (!transaction) {\n return origFunction(...origFunctionArgs);\n }\n\n // TODO: Make sure that the given route matches the name of the active transaction (to prevent background data\n // fetching from switching the name to a completely other route) -- We'll probably switch to creating a transaction\n // right here so making that check will probabably not even be necessary.\n // Logic will be: If there is no active transaction, start one with correct name and source. If there is an active\n // transaction, create a child span with correct name and source.\n transaction.name = parameterizedRoute;\n transaction.metadata.source = 'route';\n\n // Capture the route, since pre-loading, revalidation, etc might mean that this span may happen during another\n // route's transaction\n const span = transaction.startChild({\n op: 'function.nextjs',\n description: `${dataFetchingMethodName} (${parameterizedRoute})`,\n status: 'ok',\n });\n\n try {\n return await origFunction(...origFunctionArgs);\n } catch (err) {\n // Since we finish the span before the error can bubble up and trigger the handlers in `registerErrorInstrumentation`\n // that set the transaction status, we need to manually set the status of the span & transaction\n transaction.setStatus('internal_error');\n span.setStatus('internal_error');\n span.finish();\n\n // TODO Copy more robust error handling over from `withSentry`\n core.captureException(err);\n throw err;\n }\n}\n\nexports.callDataFetcherTraced = callDataFetcherTraced;\nexports.getTransactionFromRequest = getTransactionFromRequest;\nexports.withErrorInstrumentation = withErrorInstrumentation;\nexports.withTracedServerSideDataFetcher = withTracedServerSideDataFetcher;\n//# sourceMappingURL=wrapperUtils.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst domain = require('domain');\nconst platformSupportsStreaming = require('./utils/platformSupportsStreaming.js');\nconst responseEnd = require('./utils/responseEnd.js');\n\n/**\n * Wrap the given API route handler for tracing and error capturing. Thin wrapper around `withSentry`, which only\n * applies it if it hasn't already been applied.\n *\n * @param apiHandler The handler exported from the user's API page route file, which may or may not already be\n * wrapped with `withSentry`\n * @param parameterizedRoute The page's route, passed in via the proxy loader\n * @returns The wrapped handler\n */\nfunction wrapApiHandlerWithSentry(apiHandler, parameterizedRoute) {\n return new Proxy(apiHandler, {\n apply: async (wrappingTarget, thisArg, args) => {\n // eslint-disable-next-line deprecation/deprecation\n return withSentry(wrappingTarget, parameterizedRoute).apply(thisArg, args);\n },\n });\n}\n\n/**\n * @deprecated Use `wrapApiHandlerWithSentry()` instead\n */\nconst withSentryAPI = wrapApiHandlerWithSentry;\n\n/**\n * Legacy function for manually wrapping API route handlers, now used as the innards of `wrapApiHandlerWithSentry`.\n *\n * @param apiHandler The user's original API route handler\n * @param parameterizedRoute The route whose handler is being wrapped. Meant for internal use only.\n * @returns A wrapped version of the handler\n *\n * @deprecated Use `wrapApiWithSentry()` instead\n */\nfunction withSentry(apiHandler, parameterizedRoute) {\n return new Proxy(apiHandler, {\n apply: async (wrappingTarget, thisArg, args) => {\n const [req, res] = args;\n\n // We're now auto-wrapping API route handlers using `wrapApiHandlerWithSentry` (which uses `withSentry` under the hood), but\n // users still may have their routes manually wrapped with `withSentry`. This check makes `sentryWrappedHandler`\n // idempotent so that those cases don't break anything.\n if (req.__withSentry_applied__) {\n return wrappingTarget.apply(thisArg, args);\n }\n req.__withSentry_applied__ = true;\n\n // use a domain in order to prevent scope bleed between requests\n const local = domain.create();\n local.add(req);\n local.add(res);\n\n // `local.bind` causes everything to run inside a domain, just like `local.run` does, but it also lets the callback\n // return a value. In our case, all any of the codepaths return is a promise of `void`, but nextjs still counts on\n // getting that before it will finish the response.\n // eslint-disable-next-line complexity\n const boundHandler = local.bind(async () => {\n let transaction;\n const hub = node.getCurrentHub();\n const currentScope = hub.getScope();\n const options = _optionalChain([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]);\n\n if (currentScope) {\n currentScope.setSDKProcessingMetadata({ request: req });\n\n if (tracing.hasTracingEnabled(options) && _optionalChain([options, 'optionalAccess', _5 => _5.instrumenter]) === 'sentry') {\n // If there is a trace header set, extract the data from it (parentSpanId, traceId, and sampling decision)\n let traceparentData;\n if (req.headers && utils.isString(req.headers['sentry-trace'])) {\n traceparentData = tracing.extractTraceparentData(req.headers['sentry-trace']);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] Continuing trace ${_optionalChain([traceparentData, 'optionalAccess', _6 => _6.traceId])}.`);\n }\n\n const baggageHeader = req.headers && req.headers.baggage;\n const dynamicSamplingContext = utils.baggageHeaderToDynamicSamplingContext(baggageHeader);\n\n // prefer the parameterized route, if we have it (which we will if we've auto-wrapped the route handler)\n let reqPath = parameterizedRoute;\n\n // If not, fake it by just replacing parameter values with their names, hoping that none of them match either\n // each other or any hard-coded parts of the path\n if (!reqPath) {\n const url = `${req.url}`;\n // pull off query string, if any\n reqPath = utils.stripUrlQueryAndFragment(url);\n // Replace with placeholder\n if (req.query) {\n for (const [key, value] of Object.entries(req.query)) {\n reqPath = reqPath.replace(`${value}`, `[${key}]`);\n }\n }\n }\n\n const reqMethod = `${(req.method || 'GET').toUpperCase()} `;\n\n transaction = node.startTransaction(\n {\n name: `${reqMethod}${reqPath}`,\n op: 'http.server',\n ...traceparentData,\n metadata: {\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n source: 'route',\n request: req,\n },\n },\n // extra context passed to the `tracesSampler`\n { request: req },\n );\n currentScope.setSpan(transaction);\n if (platformSupportsStreaming.platformSupportsStreaming() && !wrappingTarget.__sentry_test_doesnt_support_streaming__) {\n responseEnd.autoEndTransactionOnResponseEnd(transaction, res);\n } else {\n // If we're not on a platform that supports streaming, we're blocking res.end() until the queue is flushed.\n // res.json() and res.send() will implicitly call res.end(), so it is enough to wrap res.end().\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const origResEnd = res.end;\n res.end = async function ( ...args) {\n if (transaction) {\n await responseEnd.finishTransaction(transaction, res);\n await responseEnd.flushQueue();\n }\n\n origResEnd.apply(this, args);\n };\n }\n }\n }\n\n try {\n const handlerResult = await wrappingTarget.apply(thisArg, args);\n\n if (\n process.env.NODE_ENV === 'development' &&\n !process.env.SENTRY_IGNORE_API_RESOLUTION_ERROR &&\n !res.finished\n // This can only happen (not always) when the user is using `withSentry` manually, which we're deprecating.\n // Warning suppression on Next.JS is only necessary in that case.\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n `[sentry] If Next.js logs a warning \"API resolved without sending a response\", it's a false positive, which may happen when you use \\`withSentry\\` manually to wrap your routes.\n To suppress this warning, set \\`SENTRY_IGNORE_API_RESOLUTION_ERROR\\` to 1 in your env.\n To suppress the nextjs warning, use the \\`externalResolver\\` API route option (see https://nextjs.org/docs/api-routes/api-middlewares#custom-config for details).`,\n );\n }\n\n return handlerResult;\n } catch (e) {\n // In case we have a primitive, wrap it in the equivalent wrapper class (string -> String, etc.) so that we can\n // store a seen flag on it. (Because of the one-way-on-Vercel-one-way-off-of-Vercel approach we've been forced\n // to take, it can happen that the same thrown object gets caught in two different ways, and flagging it is a\n // way to prevent it from actually being reported twice.)\n const objectifiedErr = utils.objectify(e);\n\n if (currentScope) {\n currentScope.addEventProcessor(event => {\n utils.addExceptionMechanism(event, {\n type: 'instrument',\n handled: true,\n data: {\n wrapped_handler: wrappingTarget.name,\n function: 'withSentry',\n },\n });\n return event;\n });\n\n node.captureException(objectifiedErr);\n }\n\n // Because we're going to finish and send the transaction before passing the error onto nextjs, it won't yet\n // have had a chance to set the status to 500, so unless we do it ourselves now, we'll incorrectly report that\n // the transaction was error-free\n res.statusCode = 500;\n res.statusMessage = 'Internal Server Error';\n\n // Make sure we have a chance to finish the transaction and flush events to Sentry before the handler errors\n // out. (Apps which are deployed on Vercel run their API routes in lambdas, and those lambdas will shut down the\n // moment they detect an error, so it's important to get this done before rethrowing the error. Apps not\n // deployed serverlessly will run into this cleanup code again in `res.end(), but the transaction will already\n // be finished and the queue will already be empty, so effectively it'll just no-op.)\n if (platformSupportsStreaming.platformSupportsStreaming() && !wrappingTarget.__sentry_test_doesnt_support_streaming__) {\n void responseEnd.finishTransaction(transaction, res);\n } else {\n await responseEnd.finishTransaction(transaction, res);\n await responseEnd.flushQueue();\n }\n\n // We rethrow here so that nextjs can do with the error whatever it would normally do. (Sometimes \"whatever it\n // would normally do\" is to allow the error to bubble up to the global handlers - another reason we need to mark\n // the error as already having been captured.)\n throw objectifiedErr;\n }\n });\n\n // Since API route handlers are all async, nextjs always awaits the return value (meaning it's fine for us to return\n // a promise here rather than a real result, and it saves us the overhead of an `await` call.)\n return boundHandler();\n },\n });\n}\n\nexports.withSentry = withSentry;\nexports.withSentryAPI = withSentryAPI;\nexports.wrapApiHandlerWithSentry = wrapApiHandlerWithSentry;\n//# sourceMappingURL=wrapApiHandlerWithSentry.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\n\n/**\n * Wraps an `app` directory server component with Sentry error instrumentation.\n */\nfunction wrapAppDirComponentWithSentry(appDirComponent) {\n // Even though users may define server components as async functions, for the client bundles\n // Next.js will turn them into synchronous functions and it will transform any`await`s into instances of the`use`\n // hook. đŸ¤¯\n return new Proxy(appDirComponent, {\n apply: (originalFunction, thisArg, args) => {\n let maybePromiseResult;\n\n try {\n maybePromiseResult = originalFunction.apply(thisArg, args);\n } catch (e) {\n core.captureException(e);\n throw e;\n }\n\n if (typeof maybePromiseResult === 'object' && maybePromiseResult !== null && 'then' in maybePromiseResult) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return maybePromiseResult.then(null, (e) => {\n core.captureException(e);\n throw e;\n });\n } else {\n return maybePromiseResult;\n }\n },\n });\n}\n\nexports.wrapAppDirComponentWithSentry = wrapAppDirComponentWithSentry;\n//# sourceMappingURL=wrapAppDirComponentWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getInitialProps` function in\n * a custom app (\"_app.js\").\n *\n * @param origAppGetInitialProps The user's `getInitialProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapAppGetInitialPropsWithSentry(origAppGetInitialProps) {\n return new Proxy(origAppGetInitialProps, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const [context] = args;\n const { req, res } = context.ctx;\n\n const errorWrappedAppGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n // Generally we can assume that `req` and `res` are always defined on the server:\n // https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object\n // This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher\n // span with each other when there are no req or res objects, we simply do not trace them at all here.\n if (tracing.hasTracingEnabled() && req && res && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedAppGetInitialProps, req, res, {\n dataFetcherRouteName: '/_app',\n requestedRouteName: context.ctx.pathname,\n dataFetchingMethodName: 'getInitialProps',\n });\n\n const appGetInitialProps\n\n = await tracedGetInitialProps.apply(thisArg, args);\n\n const requestTransaction = wrapperUtils.getTransactionFromRequest(req);\n\n // Per definition, `pageProps` is not optional, however an increased amount of users doesn't seem to call\n // `App.getInitialProps(appContext)` in their custom `_app` pages which is required as per\n // https://nextjs.org/docs/advanced-features/custom-app - resulting in missing `pageProps`.\n // For this reason, we just handle the case where `pageProps` doesn't exist explicitly.\n if (!appGetInitialProps.pageProps) {\n appGetInitialProps.pageProps = {};\n }\n\n if (requestTransaction) {\n appGetInitialProps.pageProps._sentryTraceData = requestTransaction.toTraceparent();\n\n const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();\n appGetInitialProps.pageProps._sentryBaggage =\n utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n }\n\n return appGetInitialProps;\n } else {\n return errorWrappedAppGetInitialProps.apply(thisArg, args);\n }\n },\n });\n}\n\n/**\n * @deprecated Use `wrapAppGetInitialPropsWithSentry` instead.\n */\nconst withSentryServerSideAppGetInitialProps = wrapAppGetInitialPropsWithSentry;\n\nexports.withSentryServerSideAppGetInitialProps = withSentryServerSideAppGetInitialProps;\nexports.wrapAppGetInitialPropsWithSentry = wrapAppGetInitialPropsWithSentry;\n//# sourceMappingURL=wrapAppGetInitialPropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getInitialProps` function in\n * a custom document (\"_document.js\").\n *\n * @param origDocumentGetInitialProps The user's `getInitialProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapDocumentGetInitialPropsWithSentry(\n origDocumentGetInitialProps,\n) {\n return new Proxy(origDocumentGetInitialProps, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const [context] = args;\n const { req, res } = context;\n\n const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n // Generally we can assume that `req` and `res` are always defined on the server:\n // https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object\n // This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher\n // span with each other when there are no req or res objects, we simply do not trace them at all here.\n if (tracing.hasTracingEnabled() && req && res && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {\n dataFetcherRouteName: '/_document',\n requestedRouteName: context.pathname,\n dataFetchingMethodName: 'getInitialProps',\n });\n\n return await tracedGetInitialProps.apply(thisArg, args);\n } else {\n return errorWrappedGetInitialProps.apply(thisArg, args);\n }\n },\n });\n}\n\n/**\n * @deprecated Use `wrapDocumentGetInitialPropsWithSentry` instead.\n */\nconst withSentryServerSideDocumentGetInitialProps = wrapDocumentGetInitialPropsWithSentry;\n\nexports.withSentryServerSideDocumentGetInitialProps = withSentryServerSideDocumentGetInitialProps;\nexports.wrapDocumentGetInitialPropsWithSentry = wrapDocumentGetInitialPropsWithSentry;\n//# sourceMappingURL=wrapDocumentGetInitialPropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getInitialProps` function in\n * a custom error page (\"_error.js\").\n *\n * @param origErrorGetInitialProps The user's `getInitialProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapErrorGetInitialPropsWithSentry(\n origErrorGetInitialProps,\n) {\n return new Proxy(origErrorGetInitialProps, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const [context] = args;\n const { req, res } = context;\n\n const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n // Generally we can assume that `req` and `res` are always defined on the server:\n // https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object\n // This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher\n // span with each other when there are no req or res objects, we simply do not trace them at all here.\n if (tracing.hasTracingEnabled() && req && res && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {\n dataFetcherRouteName: '/_error',\n requestedRouteName: context.pathname,\n dataFetchingMethodName: 'getInitialProps',\n });\n\n const errorGetInitialProps\n\n = await tracedGetInitialProps.apply(thisArg, args);\n\n const requestTransaction = wrapperUtils.getTransactionFromRequest(req);\n if (requestTransaction) {\n errorGetInitialProps._sentryTraceData = requestTransaction.toTraceparent();\n\n const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();\n errorGetInitialProps._sentryBaggage = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n }\n\n return errorGetInitialProps;\n } else {\n return errorWrappedGetInitialProps.apply(thisArg, args);\n }\n },\n });\n}\n\n/**\n * @deprecated Use `wrapErrorGetInitialPropsWithSentry` instead.\n */\nconst withSentryServerSideErrorGetInitialProps = wrapErrorGetInitialPropsWithSentry;\n\nexports.withSentryServerSideErrorGetInitialProps = withSentryServerSideErrorGetInitialProps;\nexports.wrapErrorGetInitialPropsWithSentry = wrapErrorGetInitialPropsWithSentry;\n//# sourceMappingURL=wrapErrorGetInitialPropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getInitialProps` function\n *\n * @param origGetInitialProps The user's `getInitialProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapGetInitialPropsWithSentry(origGetInitialProps) {\n return new Proxy(origGetInitialProps, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const [context] = args;\n const { req, res } = context;\n\n const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n // Generally we can assume that `req` and `res` are always defined on the server:\n // https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object\n // This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher\n // span with each other when there are no req or res objects, we simply do not trace them at all here.\n if (tracing.hasTracingEnabled() && req && res && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {\n dataFetcherRouteName: context.pathname,\n requestedRouteName: context.pathname,\n dataFetchingMethodName: 'getInitialProps',\n });\n\n const initialProps\n\n = await tracedGetInitialProps.apply(thisArg, args);\n\n const requestTransaction = wrapperUtils.getTransactionFromRequest(req);\n if (requestTransaction) {\n initialProps._sentryTraceData = requestTransaction.toTraceparent();\n\n const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();\n initialProps._sentryBaggage = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n }\n\n return initialProps;\n } else {\n return errorWrappedGetInitialProps.apply(thisArg, args);\n }\n },\n });\n}\n\n/**\n * @deprecated Use `wrapGetInitialPropsWithSentry` instead.\n */\nconst withSentryServerSideGetInitialProps = wrapGetInitialPropsWithSentry;\n\nexports.withSentryServerSideGetInitialProps = withSentryServerSideGetInitialProps;\nexports.wrapGetInitialPropsWithSentry = wrapGetInitialPropsWithSentry;\n//# sourceMappingURL=wrapGetInitialPropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst utils = require('@sentry/utils');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getServerSideProps` function\n *\n * @param origGetServerSideProps The user's `getServerSideProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapGetServerSidePropsWithSentry(\n origGetServerSideProps,\n parameterizedRoute,\n) {\n return new Proxy(origGetServerSideProps, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const [context] = args;\n const { req, res } = context;\n\n const errorWrappedGetServerSideProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n if (tracing.hasTracingEnabled() && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n const tracedGetServerSideProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetServerSideProps, req, res, {\n dataFetcherRouteName: parameterizedRoute,\n requestedRouteName: parameterizedRoute,\n dataFetchingMethodName: 'getServerSideProps',\n });\n\n const serverSideProps = await (tracedGetServerSideProps.apply(thisArg, args)\n\n);\n\n if ('props' in serverSideProps) {\n const requestTransaction = wrapperUtils.getTransactionFromRequest(req);\n if (requestTransaction) {\n serverSideProps.props._sentryTraceData = requestTransaction.toTraceparent();\n\n const dynamicSamplingContext = requestTransaction.getDynamicSamplingContext();\n serverSideProps.props._sentryBaggage = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n }\n }\n\n return serverSideProps;\n } else {\n return errorWrappedGetServerSideProps.apply(thisArg, args);\n }\n },\n });\n}\n\n/**\n * @deprecated Use `withSentryGetServerSideProps` instead.\n */\nconst withSentryGetServerSideProps = wrapGetServerSidePropsWithSentry;\n\nexports.withSentryGetServerSideProps = withSentryGetServerSideProps;\nexports.wrapGetServerSidePropsWithSentry = wrapGetServerSidePropsWithSentry;\n//# sourceMappingURL=wrapGetServerSidePropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('@sentry/node');\nconst tracing = require('@sentry/tracing');\nconst isBuild = require('./utils/isBuild.js');\nconst wrapperUtils = require('./utils/wrapperUtils.js');\n\n/**\n * Create a wrapped version of the user's exported `getStaticProps` function\n *\n * @param origGetStaticProps The user's `getStaticProps` function\n * @param parameterizedRoute The page's parameterized route\n * @returns A wrapped version of the function\n */\nfunction wrapGetStaticPropsWithSentry(\n origGetStaticPropsa,\n parameterizedRoute,\n) {\n return new Proxy(origGetStaticPropsa, {\n apply: async (wrappingTarget, thisArg, args) => {\n if (isBuild.isBuild()) {\n return wrappingTarget.apply(thisArg, args);\n }\n\n const errorWrappedGetStaticProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);\n const options = _optionalChain([node.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n if (tracing.hasTracingEnabled() && _optionalChain([options, 'optionalAccess', _6 => _6.instrumenter]) === 'sentry') {\n return wrapperUtils.callDataFetcherTraced(errorWrappedGetStaticProps, args, {\n parameterizedRoute,\n dataFetchingMethodName: 'getStaticProps',\n });\n }\n\n return errorWrappedGetStaticProps.apply(thisArg, args);\n },\n });\n}\n\n/**\n * @deprecated Use `wrapGetStaticPropsWithSentry` instead.\n */\nconst withSentryGetStaticProps = wrapGetStaticPropsWithSentry;\n\nexports.withSentryGetStaticProps = withSentryGetStaticProps;\nexports.wrapGetStaticPropsWithSentry = wrapGetStaticPropsWithSentry;\n//# sourceMappingURL=wrapGetStaticPropsWithSentry.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst os = require('os');\nconst util = require('util');\nconst eventbuilder = require('./eventbuilder.js');\n\n/**\n * The Sentry Node SDK Client.\n *\n * @see NodeClientOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass NodeClient extends core.BaseClient {\n\n /**\n * Creates a new Node SDK instance.\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.node',\n packages: [\n {\n name: 'npm:@sentry/node',\n version: core.SDK_VERSION,\n },\n ],\n version: core.SDK_VERSION,\n };\n\n // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util\n options.transportOptions = {\n textEncoder: new util.TextEncoder(),\n ...options.transportOptions,\n };\n\n super(options);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint, scope) {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const requestSession = scope.getRequestSession();\n\n // Necessary checks to ensure this is code block is executed only within a request\n // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const eventType = event.type || 'exception';\n const isException =\n eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;\n\n // If the event is of type Exception, then a request session should be captured\n if (isException) {\n const requestSession = scope.getRequestSession();\n\n // Ensure that this is happening within the bounds of a request, and make sure not to override\n // Session Status if Errored / Crashed\n if (requestSession && requestSession.status === 'ok') {\n requestSession.status = 'errored';\n }\n }\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n *\n * @inheritdoc\n */\n close(timeout) {\n _optionalChain([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]);\n return super.close(timeout);\n }\n\n /** Method that initialises an instance of SessionFlusher on Client */\n initSessionFlusher() {\n const { release, environment } = this._options;\n if (!release) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');\n } else {\n this._sessionFlusher = new core.SessionFlusher(this, {\n release,\n environment,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n eventFromException(exception, hint) {\n return utils.resolvedSyncPromise(eventbuilder.eventFromUnknownInput(this._options.stackParser, exception, hint));\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n ) {\n return utils.resolvedSyncPromise(\n eventbuilder.eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n );\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'node';\n event.contexts = {\n ...event.contexts,\n runtime: _optionalChain([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || {\n name: 'node',\n version: global.process.version,\n },\n };\n event.server_name =\n event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os.hostname();\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment\n * appropriate session aggregates bucket\n */\n _captureRequestSession() {\n if (!this._sessionFlusher) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Discarded request mode session because autoSessionTracking option was disabled');\n } else {\n this._sessionFlusher.incrementSessionStatusCount();\n }\n }\n}\n\nexports.NodeClient = NodeClient;\n//# sourceMappingURL=client.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\n\n/**\n * Extracts stack frames from the error.stack string\n */\nfunction parseStackFrames(stackParser, error) {\n return stackParser(error.stack || '', 1);\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nfunction exceptionFromError(stackParser, error) {\n const exception = {\n type: error.name || error.constructor.name,\n value: error.message,\n };\n\n const frames = parseStackFrames(stackParser, error);\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n return exception;\n}\n\n/**\n * Builds and Event from a Exception\n * @hidden\n */\nfunction eventFromUnknownInput(stackParser, exception, hint) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ex = exception;\n const providedMechanism =\n hint && hint.data && (hint.data ).mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n if (!utils.isError(exception)) {\n if (utils.isPlainObject(exception)) {\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n const message = `Non-Error exception captured with keys: ${utils.extractExceptionKeysForMessage(exception)}`;\n\n const hub = core.getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n hub.configureScope(scope => {\n scope.setExtra('__serialized__', utils.normalizeToSize(exception, normalizeDepth));\n });\n\n ex = (hint && hint.syntheticException) || new Error(message);\n (ex ).message = message;\n } else {\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n ex = (hint && hint.syntheticException) || new Error(exception );\n (ex ).message = exception ;\n }\n mechanism.synthetic = true;\n }\n\n const event = {\n exception: {\n values: [exceptionFromError(stackParser, ex )],\n },\n };\n\n utils.addExceptionTypeValue(event, undefined, undefined);\n utils.addExceptionMechanism(event, mechanism);\n\n return {\n ...event,\n event_id: hint && hint.event_id,\n };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const event = {\n event_id: hint && hint.event_id,\n level,\n message,\n };\n\n if (attachStacktrace && hint && hint.syntheticException) {\n const frames = parseStackFrames(stackParser, hint.syntheticException);\n if (frames.length) {\n event.exception = {\n values: [\n {\n value: message,\n stacktrace: { frames },\n },\n ],\n };\n }\n }\n\n return event;\n}\n\nexports.eventFromMessage = eventFromMessage;\nexports.eventFromUnknownInput = eventFromUnknownInput;\nexports.exceptionFromError = exceptionFromError;\nexports.parseStackFrames = parseStackFrames;\n//# sourceMappingURL=eventbuilder.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst domain = require('domain');\nconst requestdata = require('./requestdata.js');\nconst sdk = require('./sdk.js');\nconst requestDataDeprecated = require('./requestDataDeprecated.js');\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Express-compatible tracing handler.\n * @see Exposed as `Handlers.tracingHandler`\n */\nfunction tracingHandler()\n\n {\n return function sentryTracingMiddleware(\n req,\n res,\n next,\n ) {\n const hub = core.getCurrentHub();\n const options = _optionalChain([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]);\n\n if (\n !options ||\n options.instrumenter !== 'sentry' ||\n _optionalChain([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' ||\n _optionalChain([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD'\n ) {\n return next();\n }\n\n // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a\n // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub.\n if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' +\n 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.',\n );\n return next();\n }\n\n // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)\n const traceparentData =\n req.headers && utils.isString(req.headers['sentry-trace']) && utils.extractTraceparentData(req.headers['sentry-trace']);\n const incomingBaggageHeaders = _optionalChain([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]);\n const dynamicSamplingContext = utils.baggageHeaderToDynamicSamplingContext(incomingBaggageHeaders);\n\n const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true });\n const transaction = core.startTransaction(\n {\n name,\n op: 'http.server',\n ...traceparentData,\n metadata: {\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become\n // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the\n // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to\n // be sure\n request: req,\n source,\n },\n },\n // extra context passed to the tracesSampler\n { request: requestdata.extractRequestData(req) },\n );\n\n // We put the transaction on the scope so users can attach children to it\n hub.configureScope(scope => {\n scope.setSpan(transaction);\n });\n\n // We also set __sentry_transaction on the response so people can grab the transaction there to add\n // spans to it later.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res ).__sentry_transaction = transaction;\n\n res.once('finish', () => {\n // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction\n // closes\n setImmediate(() => {\n utils.addRequestDataToTransaction(transaction, req);\n transaction.setHttpStatus(res.statusCode);\n transaction.finish();\n });\n });\n\n next();\n };\n}\n\n/**\n * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the\n * `AddRequestDataToEventOptions` interface.\n *\n * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`.\n */\nfunction convertReqHandlerOptsToAddReqDataOpts(\n reqHandlerOptions = {},\n) {\n let addRequestDataOptions;\n\n if ('include' in reqHandlerOptions) {\n addRequestDataOptions = { include: reqHandlerOptions.include };\n } else {\n // eslint-disable-next-line deprecation/deprecation\n const { ip, request, transaction, user } = reqHandlerOptions ;\n\n if (ip || request || transaction || user) {\n addRequestDataOptions = { include: utils.dropUndefinedKeys({ ip, request, transaction, user }) };\n }\n }\n\n return addRequestDataOptions;\n}\n\n/**\n * Express compatible request handler.\n * @see Exposed as `Handlers.requestHandler`\n */\nfunction requestHandler(\n options,\n) {\n // TODO (v8): Get rid of this\n const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options);\n\n const currentHub = core.getCurrentHub();\n const client = currentHub.getClient();\n // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the\n // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode\n if (client && sdk.isAutoSessionTrackingEnabled(client)) {\n client.initSessionFlusher();\n\n // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode\n const scope = currentHub.getScope();\n if (scope && scope.getSession()) {\n scope.setSession();\n }\n }\n\n return function sentryRequestMiddleware(\n req,\n res,\n next,\n ) {\n if (options && options.flushTimeout && options.flushTimeout > 0) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _end = res.end;\n res.end = function (chunk, encoding, cb) {\n void sdk.flush(options.flushTimeout)\n .then(() => {\n _end.call(this, chunk, encoding, cb);\n })\n .then(null, e => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(e);\n _end.call(this, chunk, encoding, cb);\n });\n };\n }\n const local = domain.create();\n local.add(req);\n local.add(res);\n\n local.run(() => {\n const currentHub = core.getCurrentHub();\n\n currentHub.configureScope(scope => {\n scope.setSDKProcessingMetadata({\n request: req,\n // TODO (v8): Stop passing this\n requestDataOptionsFromExpressHandler: requestDataOptions,\n });\n\n const client = currentHub.getClient();\n if (sdk.isAutoSessionTrackingEnabled(client)) {\n const scope = currentHub.getScope();\n if (scope) {\n // Set `status` of `RequestSession` to Ok, at the beginning of the request\n scope.setRequestSession({ status: 'ok' });\n }\n }\n });\n\n res.once('finish', () => {\n const client = currentHub.getClient();\n if (sdk.isAutoSessionTrackingEnabled(client)) {\n setImmediate(() => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (client && (client )._captureRequestSession) {\n // Calling _captureRequestSession to capture request session at the end of the request by incrementing\n // the correct SessionAggregates bucket i.e. crashed, errored or exited\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (client )._captureRequestSession();\n }\n });\n }\n });\n next();\n });\n };\n}\n\n/** JSDoc */\n\n/** JSDoc */\nfunction getStatusCodeFromResponse(error) {\n const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);\n return statusCode ? parseInt(statusCode , 10) : 500;\n}\n\n/** Returns true if response code is internal server error */\nfunction defaultShouldHandleError(error) {\n const status = getStatusCodeFromResponse(error);\n return status >= 500;\n}\n\n/**\n * Express compatible error handler.\n * @see Exposed as `Handlers.errorHandler`\n */\nfunction errorHandler(options\n\n)\n\n {\n return function sentryErrorMiddleware(\n error,\n _req,\n res,\n next,\n ) {\n const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;\n\n if (shouldHandleError(error)) {\n core.withScope(_scope => {\n // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`,\n // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't\n // hurt to be sure\n _scope.setSDKProcessingMetadata({ request: _req });\n\n // For some reason we need to set the transaction on the scope again\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const transaction = (res ).__sentry_transaction ;\n if (transaction && _scope.getSpan() === undefined) {\n _scope.setSpan(transaction);\n }\n\n const client = core.getCurrentHub().getClient();\n if (client && sdk.isAutoSessionTrackingEnabled(client)) {\n // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the\n // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only\n // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be\n // running in SessionAggregates mode\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const isSessionAggregatesMode = (client )._sessionFlusher !== undefined;\n if (isSessionAggregatesMode) {\n const requestSession = _scope.getRequestSession();\n // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a\n // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within\n // the bounds of a request, and if so the status is updated\n if (requestSession && requestSession.status !== undefined) {\n requestSession.status = 'crashed';\n }\n }\n }\n\n const eventId = core.captureException(error);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res ).sentry = eventId;\n next(error);\n });\n\n return;\n }\n\n next(error);\n };\n}\n\nexports.extractRequestData = requestDataDeprecated.extractRequestData;\nexports.parseRequest = requestDataDeprecated.parseRequest;\nexports.errorHandler = errorHandler;\nexports.requestHandler = requestHandler;\nexports.tracingHandler = tracingHandler;\n//# sourceMappingURL=handlers.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst client = require('./client.js');\nconst http = require('./transports/http.js');\nconst sdk = require('./sdk.js');\nconst requestdata = require('./requestdata.js');\nconst utils = require('./utils.js');\nconst domain = require('domain');\nconst handlers = require('./handlers.js');\nconst index = require('./integrations/index.js');\n\nconst INTEGRATIONS = {\n ...core.Integrations,\n ...index,\n};\n\n// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like\n// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.\nconst carrier = core.getMainCarrier();\nif (carrier.__SENTRY__) {\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain;\n}\n\nexports.Hub = core.Hub;\nexports.SDK_VERSION = core.SDK_VERSION;\nexports.Scope = core.Scope;\nexports.addBreadcrumb = core.addBreadcrumb;\nexports.addGlobalEventProcessor = core.addGlobalEventProcessor;\nexports.captureEvent = core.captureEvent;\nexports.captureException = core.captureException;\nexports.captureMessage = core.captureMessage;\nexports.configureScope = core.configureScope;\nexports.createTransport = core.createTransport;\nexports.getCurrentHub = core.getCurrentHub;\nexports.getHubFromCarrier = core.getHubFromCarrier;\nexports.makeMain = core.makeMain;\nexports.setContext = core.setContext;\nexports.setExtra = core.setExtra;\nexports.setExtras = core.setExtras;\nexports.setTag = core.setTag;\nexports.setTags = core.setTags;\nexports.setUser = core.setUser;\nexports.startTransaction = core.startTransaction;\nexports.withScope = core.withScope;\nexports.NodeClient = client.NodeClient;\nexports.makeNodeTransport = http.makeNodeTransport;\nexports.close = sdk.close;\nexports.defaultIntegrations = sdk.defaultIntegrations;\nexports.defaultStackParser = sdk.defaultStackParser;\nexports.flush = sdk.flush;\nexports.getSentryRelease = sdk.getSentryRelease;\nexports.init = sdk.init;\nexports.lastEventId = sdk.lastEventId;\nexports.DEFAULT_USER_INCLUDES = requestdata.DEFAULT_USER_INCLUDES;\nexports.addRequestDataToEvent = requestdata.addRequestDataToEvent;\nexports.extractRequestData = requestdata.extractRequestData;\nexports.deepReadDirSync = utils.deepReadDirSync;\nexports.Handlers = handlers;\nexports.Integrations = INTEGRATIONS;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst util = require('util');\n\n/** Console module integration */\nclass Console {constructor() { Console.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Console';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Console.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n for (const level of ['debug', 'info', 'warn', 'error', 'log']) {\n utils.fill(console, level, createConsoleWrapper(level));\n }\n }\n} Console.__initStatic();\n\n/**\n * Wrapper function that'll be used for every console level\n */\nfunction createConsoleWrapper(level) {\n return function consoleWrapper(originalConsoleMethod) {\n const sentryLevel = utils.severityLevelFromString(level);\n\n /* eslint-disable prefer-rest-params */\n return function () {\n if (core.getCurrentHub().getIntegration(Console)) {\n core.getCurrentHub().addBreadcrumb(\n {\n category: 'console',\n level: sentryLevel,\n message: util.format.apply(undefined, arguments),\n },\n {\n input: [...arguments],\n level,\n },\n );\n }\n\n originalConsoleMethod.apply(this, arguments);\n };\n /* eslint-enable prefer-rest-params */\n };\n}\n\nexports.Console = Console;\n//# sourceMappingURL=console.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst child_process = require('child_process');\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\nconst util = require('util');\n\n// TODO: Required until we drop support for Node v8\nconst readFileAsync = util.promisify(fs.readFile);\nconst readDirAsync = util.promisify(fs.readdir);\n\n/** Add node modules / packages to the event */\nclass Context {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Context';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Context.id;}\n\n /**\n * Caches context so it's only evaluated once\n */\n\n constructor( _options = { app: true, os: true, device: true, culture: true }) {this._options = _options;Context.prototype.__init.call(this);\n //\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor) {\n addGlobalEventProcessor(event => this.addContext(event));\n }\n\n /** Processes an event and adds context */\n async addContext(event) {\n if (this._cachedContext === undefined) {\n this._cachedContext = this._getContexts();\n }\n\n const updatedContext = this._updateContext(await this._cachedContext);\n\n event.contexts = {\n ...event.contexts,\n app: { ...updatedContext.app, ..._optionalChain([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) },\n os: { ...updatedContext.os, ..._optionalChain([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) },\n device: { ...updatedContext.device, ..._optionalChain([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) },\n culture: { ...updatedContext.culture, ..._optionalChain([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) },\n };\n\n return event;\n }\n\n /**\n * Updates the context with dynamic values that can change\n */\n _updateContext(contexts) {\n // Only update properties if they exist\n if (_optionalChain([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) {\n contexts.app.app_memory = process.memoryUsage().rss;\n }\n\n if (_optionalChain([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) {\n contexts.device.free_memory = os.freemem();\n }\n\n return contexts;\n }\n\n /**\n * Gets the contexts for the current environment\n */\n async _getContexts() {\n const contexts = {};\n\n if (this._options.os) {\n contexts.os = await getOsContext();\n }\n\n if (this._options.app) {\n contexts.app = getAppContext();\n }\n\n if (this._options.device) {\n contexts.device = getDeviceContext(this._options.device);\n }\n\n if (this._options.culture) {\n const culture = getCultureContext();\n\n if (culture) {\n contexts.culture = culture;\n }\n }\n\n return contexts;\n }\n}Context.__initStatic();\n\n/**\n * Returns the operating system context.\n *\n * Based on the current platform, this uses a different strategy to provide the\n * most accurate OS information. Since this might involve spawning subprocesses\n * or accessing the file system, this should only be executed lazily and cached.\n *\n * - On macOS (Darwin), this will execute the `sw_vers` utility. The context\n * has a `name`, `version`, `build` and `kernel_version` set.\n * - On Linux, this will try to load a distribution release from `/etc` and set\n * the `name`, `version` and `kernel_version` fields.\n * - On all other platforms, only a `name` and `version` will be returned. Note\n * that `version` might actually be the kernel version.\n */\nasync function getOsContext() {\n const platformId = os.platform();\n switch (platformId) {\n case 'darwin':\n return getDarwinInfo();\n case 'linux':\n return getLinuxInfo();\n default:\n return {\n name: PLATFORM_NAMES[platformId] || platformId,\n version: os.release(),\n };\n }\n}\n\nfunction getCultureContext() {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (typeof (process.versions ).icu !== 'string') {\n // Node was built without ICU support\n return;\n }\n\n // Check that node was built with full Intl support. Its possible it was built without support for non-English\n // locales which will make resolvedOptions inaccurate\n //\n // https://nodejs.org/api/intl.html#detecting-internationalization-support\n const january = new Date(9e8);\n const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n if (spanish.format(january) === 'enero') {\n const options = Intl.DateTimeFormat().resolvedOptions();\n\n return {\n locale: options.locale,\n timezone: options.timeZone,\n };\n }\n } catch (err) {\n //\n }\n\n return;\n}\n\nfunction getAppContext() {\n const app_memory = process.memoryUsage().rss;\n const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();\n\n return { app_start_time, app_memory };\n}\n\n/**\n * Gets device information from os\n */\nfunction getDeviceContext(deviceOpt) {\n const device = {};\n\n // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).\n // Hence, we only set boot time, if we get a valid uptime value.\n // @see https://github.com/getsentry/sentry-javascript/issues/5856\n const uptime = os.uptime && os.uptime();\n if (typeof uptime === 'number') {\n device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();\n }\n\n device.arch = os.arch();\n\n if (deviceOpt === true || deviceOpt.memory) {\n device.memory_size = os.totalmem();\n device.free_memory = os.freemem();\n }\n\n if (deviceOpt === true || deviceOpt.cpu) {\n const cpuInfo = os.cpus();\n if (cpuInfo && cpuInfo.length) {\n const firstCpu = cpuInfo[0];\n\n device.processor_count = cpuInfo.length;\n device.cpu_description = firstCpu.model;\n device.processor_frequency = firstCpu.speed;\n }\n }\n\n return device;\n}\n\n/** Mapping of Node's platform names to actual OS names. */\nconst PLATFORM_NAMES = {\n aix: 'IBM AIX',\n freebsd: 'FreeBSD',\n openbsd: 'OpenBSD',\n sunos: 'SunOS',\n win32: 'Windows',\n};\n\n/** Linux version file to check for a distribution. */\n\n/** Mapping of linux release files located in /etc to distributions. */\nconst LINUX_DISTROS = [\n { name: 'fedora-release', distros: ['Fedora'] },\n { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },\n { name: 'redhat_version', distros: ['Red Hat Linux'] },\n { name: 'SuSE-release', distros: ['SUSE Linux'] },\n { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },\n { name: 'debian_version', distros: ['Debian'] },\n { name: 'debian_release', distros: ['Debian'] },\n { name: 'arch-release', distros: ['Arch Linux'] },\n { name: 'gentoo-release', distros: ['Gentoo Linux'] },\n { name: 'novell-release', distros: ['SUSE Linux'] },\n { name: 'alpine-release', distros: ['Alpine Linux'] },\n];\n\n/** Functions to extract the OS version from Linux release files. */\nconst LINUX_VERSIONS\n\n = {\n alpine: content => content,\n arch: content => matchFirst(/distrib_release=(.*)/, content),\n centos: content => matchFirst(/release ([^ ]+)/, content),\n debian: content => content,\n fedora: content => matchFirst(/release (..)/, content),\n mint: content => matchFirst(/distrib_release=(.*)/, content),\n red: content => matchFirst(/release ([^ ]+)/, content),\n suse: content => matchFirst(/VERSION = (.*)\\n/, content),\n ubuntu: content => matchFirst(/distrib_release=(.*)/, content),\n};\n\n/**\n * Executes a regular expression with one capture group.\n *\n * @param regex A regular expression to execute.\n * @param text Content to execute the RegEx on.\n * @returns The captured string if matched; otherwise undefined.\n */\nfunction matchFirst(regex, text) {\n const match = regex.exec(text);\n return match ? match[1] : undefined;\n}\n\n/** Loads the macOS operating system context. */\nasync function getDarwinInfo() {\n // Default values that will be used in case no operating system information\n // can be loaded. The default version is computed via heuristics from the\n // kernel version, but the build ID is missing.\n const darwinInfo = {\n kernel_version: os.release(),\n name: 'Mac OS X',\n version: `10.${Number(os.release().split('.')[0]) - 4}`,\n };\n\n try {\n // We try to load the actual macOS version by executing the `sw_vers` tool.\n // This tool should be available on every standard macOS installation. In\n // case this fails, we stick with the values computed above.\n\n const output = await new Promise((resolve, reject) => {\n child_process.execFile('/usr/bin/sw_vers', (error, stdout) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n\n darwinInfo.name = matchFirst(/^ProductName:\\s+(.*)$/m, output);\n darwinInfo.version = matchFirst(/^ProductVersion:\\s+(.*)$/m, output);\n darwinInfo.build = matchFirst(/^BuildVersion:\\s+(.*)$/m, output);\n } catch (e) {\n // ignore\n }\n\n return darwinInfo;\n}\n\n/** Returns a distribution identifier to look up version callbacks. */\nfunction getLinuxDistroId(name) {\n return name.split(' ')[0].toLowerCase();\n}\n\n/** Loads the Linux operating system context. */\nasync function getLinuxInfo() {\n // By default, we cannot assume anything about the distribution or Linux\n // version. `os.release()` returns the kernel version and we assume a generic\n // \"Linux\" name, which will be replaced down below.\n const linuxInfo = {\n kernel_version: os.release(),\n name: 'Linux',\n };\n\n try {\n // We start guessing the distribution by listing files in the /etc\n // directory. This is were most Linux distributions (except Knoppix) store\n // release files with certain distribution-dependent meta data. We search\n // for exactly one known file defined in `LINUX_DISTROS` and exit if none\n // are found. In case there are more than one file, we just stick with the\n // first one.\n const etcFiles = await readDirAsync('/etc');\n const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));\n if (!distroFile) {\n return linuxInfo;\n }\n\n // Once that file is known, load its contents. To make searching in those\n // files easier, we lowercase the file contents. Since these files are\n // usually quite small, this should not allocate too much memory and we only\n // hold on to it for a very short amount of time.\n const distroPath = path.join('/etc', distroFile.name);\n const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase();\n\n // Some Linux distributions store their release information in the same file\n // (e.g. RHEL and Centos). In those cases, we scan the file for an\n // identifier, that basically consists of the first word of the linux\n // distribution name (e.g. \"red\" for Red Hat). In case there is no match, we\n // just assume the first distribution in our list.\n const { distros } = distroFile;\n linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];\n\n // Based on the found distribution, we can now compute the actual version\n // number. This is different for every distribution, so several strategies\n // are computed in `LINUX_VERSIONS`.\n const id = getLinuxDistroId(linuxInfo.name);\n linuxInfo.version = LINUX_VERSIONS[id](contents);\n } catch (e) {\n // ignore\n }\n\n return linuxInfo;\n}\n\nexports.Context = Context;\nexports.getDeviceContext = getDeviceContext;\nexports.readDirAsync = readDirAsync;\nexports.readFileAsync = readFileAsync;\n//# sourceMappingURL=context.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst fs = require('fs');\nconst lru_map = require('lru_map');\n\nconst FILE_CONTENT_CACHE = new lru_map.LRUMap(100);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\n\n// TODO: Replace with promisify when minimum supported node >= v8\nfunction readTextFileAsync(path) {\n return new Promise((resolve, reject) => {\n fs.readFile(path, 'utf8', (err, data) => {\n if (err) reject(err);\n else resolve(data);\n });\n });\n}\n\n/** Add node modules / packages to the event */\nclass ContextLines {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'ContextLines';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = ContextLines.id;}\n\n constructor( _options = {}) {this._options = _options;ContextLines.prototype.__init.call(this);}\n\n /** Get's the number of context lines to add */\n get _contextLines() {\n return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor) {\n addGlobalEventProcessor(event => this.addSourceContext(event));\n }\n\n /** Processes an event and adds context lines */\n async addSourceContext(event) {\n if (this._contextLines > 0 && _optionalChain([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) {\n for (const exception of event.exception.values) {\n if (_optionalChain([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) {\n await this.addSourceContextToFrames(exception.stacktrace.frames);\n }\n }\n }\n\n return event;\n }\n\n /** Adds context lines to frames */\n async addSourceContextToFrames(frames) {\n const contextLines = this._contextLines;\n\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined) {\n const sourceFile = await _readSourceFile(frame.filename);\n\n if (sourceFile) {\n try {\n const lines = sourceFile.split('\\n');\n utils.addContextToFrame(lines, frame, contextLines);\n } catch (e) {\n // anomaly, being defensive in case\n // unlikely to ever happen in practice but can definitely happen in theory\n }\n }\n }\n }\n }\n}ContextLines.__initStatic();\n\n/**\n * Reads file contents and caches them in a global LRU cache.\n *\n * @param filename filepath to read content from.\n */\nasync function _readSourceFile(filename) {\n const cachedFile = FILE_CONTENT_CACHE.get(filename);\n // We have a cache hit\n if (cachedFile !== undefined) {\n return cachedFile;\n }\n\n let content = null;\n try {\n content = await readTextFileAsync(filename);\n } catch (_) {\n //\n }\n\n FILE_CONTENT_CACHE.set(filename, content);\n return content;\n}\n\nexports.ContextLines = ContextLines;\n//# sourceMappingURL=contextlines.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst lru_map = require('lru_map');\nconst http = require('./utils/http.js');\n\nconst NODE_VERSION = utils.parseSemver(process.versions.node);\n\n/**\n * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing\n * http requests and attaches trace data when tracing is enabled via its `tracing` option.\n */\nclass Http {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Http';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Http.id;}\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {Http.prototype.__init.call(this);\n this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;\n this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(\n _addGlobalEventProcessor,\n setupOnceGetCurrentHub,\n ) {\n // No need to instrument if we don't want to track anything\n if (!this._breadcrumbs && !this._tracing) {\n return;\n }\n\n const clientOptions = _optionalChain([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n\n // Do not auto-instrument for other instrumenter\n if (clientOptions && clientOptions.instrumenter !== 'sentry') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('HTTP Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions\n // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly.\n const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpModule = require('http');\n const wrappedHttpHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions, httpModule);\n utils.fill(httpModule, 'get', wrappedHttpHandlerMaker);\n utils.fill(httpModule, 'request', wrappedHttpHandlerMaker);\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // If we do, we'd get double breadcrumbs and double spans for `https` calls.\n // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpsModule = require('https');\n const wrappedHttpsHandlerMaker = _createWrappedRequestMethodFactory(\n this._breadcrumbs,\n tracingOptions,\n httpsModule,\n );\n utils.fill(httpsModule, 'get', wrappedHttpsHandlerMaker);\n utils.fill(httpsModule, 'request', wrappedHttpsHandlerMaker);\n }\n }\n}Http.__initStatic();\n\n// for ease of reading below\n\n/**\n * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http`\n * and `https` modules. (NB: Not a typo - this is a creator^2!)\n *\n * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs\n * @param tracingEnabled Whether or not to record outgoing requests as tracing spans\n *\n * @returns A function which accepts the exiting handler and returns a wrapped handler\n */\nfunction _createWrappedRequestMethodFactory(\n breadcrumbsEnabled,\n tracingOptions,\n httpModule,\n) {\n // We're caching results so we don't have to recompute regexp every time we create a request.\n const createSpanUrlMap = new lru_map.LRUMap(100);\n const headersUrlMap = {};\n\n const shouldCreateSpan = (url) => {\n if (_optionalChain([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) {\n return true;\n }\n\n const cachedDecision = createSpanUrlMap.get(url);\n if (cachedDecision !== undefined) {\n return cachedDecision;\n }\n\n const decision = tracingOptions.shouldCreateSpanForRequest(url);\n createSpanUrlMap.set(url, decision);\n return decision;\n };\n\n const shouldAttachTraceData = (url) => {\n if (_optionalChain([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) {\n return true;\n }\n\n if (headersUrlMap[url]) {\n return headersUrlMap[url];\n }\n\n headersUrlMap[url] = utils.stringMatchesSomePattern(url, tracingOptions.tracePropagationTargets);\n\n return headersUrlMap[url];\n };\n\n return function wrappedRequestMethodFactory(originalRequestMethod) {\n return function wrappedMethod( ...args) {\n const requestArgs = http.normalizeRequestArgs(httpModule, args);\n const requestOptions = requestArgs[0];\n const requestUrl = http.extractUrl(requestOptions);\n\n // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method\n if (http.isSentryRequest(requestUrl)) {\n return originalRequestMethod.apply(httpModule, requestArgs);\n }\n\n let requestSpan;\n let parentSpan;\n\n const scope = core.getCurrentHub().getScope();\n\n if (scope && tracingOptions && shouldCreateSpan(requestUrl)) {\n parentSpan = scope.getSpan();\n\n if (parentSpan) {\n requestSpan = parentSpan.startChild({\n description: `${requestOptions.method || 'GET'} ${requestUrl}`,\n op: 'http.client',\n });\n\n if (shouldAttachTraceData(requestUrl)) {\n const sentryTraceHeader = requestSpan.toTraceparent();\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to \"${requestUrl}\": `,\n );\n\n requestOptions.headers = {\n ...requestOptions.headers,\n 'sentry-trace': sentryTraceHeader,\n };\n\n if (parentSpan.transaction) {\n const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext();\n const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n let newBaggageHeaderField;\n if (!requestOptions.headers || !requestOptions.headers.baggage) {\n newBaggageHeaderField = sentryBaggageHeader;\n } else if (!sentryBaggageHeader) {\n newBaggageHeaderField = requestOptions.headers.baggage;\n } else if (Array.isArray(requestOptions.headers.baggage)) {\n newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader];\n } else {\n // Type-cast explanation:\n // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity\n // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this.\n newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ;\n }\n\n requestOptions.headers = {\n ...requestOptions.headers,\n // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined\n ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }),\n };\n }\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`,\n );\n }\n\n const transaction = parentSpan.transaction;\n if (transaction) {\n transaction.metadata.propagations++;\n }\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalRequestMethod\n .apply(httpModule, requestArgs)\n .once('response', function ( res) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('response', requestUrl, req, res);\n }\n if (requestSpan) {\n if (res.statusCode) {\n requestSpan.setHttpStatus(res.statusCode);\n }\n requestSpan.description = http.cleanSpanDescription(requestSpan.description, requestOptions, req);\n requestSpan.finish();\n }\n })\n .once('error', function () {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('error', requestUrl, req);\n }\n if (requestSpan) {\n requestSpan.setHttpStatus(500);\n requestSpan.description = http.cleanSpanDescription(requestSpan.description, requestOptions, req);\n requestSpan.finish();\n }\n });\n };\n };\n}\n\n/**\n * Captures Breadcrumb based on provided request/response pair\n */\nfunction addRequestBreadcrumb(event, url, req, res) {\n if (!core.getCurrentHub().getIntegration(Http)) {\n return;\n }\n\n core.getCurrentHub().addBreadcrumb(\n {\n category: 'http',\n data: {\n method: req.method,\n status_code: res && res.statusCode,\n url,\n },\n type: 'http',\n },\n {\n event,\n request: req,\n response: res,\n },\n );\n}\n\nexports.Http = Http;\n//# sourceMappingURL=http.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst console = require('./console.js');\nconst http = require('./http.js');\nconst onuncaughtexception = require('./onuncaughtexception.js');\nconst onunhandledrejection = require('./onunhandledrejection.js');\nconst linkederrors = require('./linkederrors.js');\nconst modules = require('./modules.js');\nconst contextlines = require('./contextlines.js');\nconst context = require('./context.js');\nconst requestdata = require('./requestdata.js');\nconst localvariables = require('./localvariables.js');\n\n\n\nexports.Console = console.Console;\nexports.Http = http.Http;\nexports.OnUncaughtException = onuncaughtexception.OnUncaughtException;\nexports.OnUnhandledRejection = onunhandledrejection.OnUnhandledRejection;\nexports.LinkedErrors = linkederrors.LinkedErrors;\nexports.Modules = modules.Modules;\nexports.ContextLines = contextlines.ContextLines;\nexports.Context = context.Context;\nexports.RequestData = requestdata.RequestData;\nexports.LocalVariables = localvariables.LocalVariables;\n//# sourceMappingURL=index.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst eventbuilder = require('../eventbuilder.js');\nconst contextlines = require('./contextlines.js');\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nclass LinkedErrors {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'LinkedErrors';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = LinkedErrors.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {LinkedErrors.prototype.__init.call(this);\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n core.addGlobalEventProcessor(async (event, hint) => {\n const hub = core.getCurrentHub();\n const self = hub.getIntegration(LinkedErrors);\n const client = hub.getClient();\n if (client && self && self._handler && typeof self._handler === 'function') {\n await self._handler(client.getOptions().stackParser, event, hint);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n _handler(stackParser, event, hint) {\n if (!event.exception || !event.exception.values || !utils.isInstanceOf(hint.originalException, Error)) {\n return utils.resolvedSyncPromise(event);\n }\n\n return new utils.SyncPromise(resolve => {\n void this._walkErrorTree(stackParser, hint.originalException , this._key)\n .then((linkedErrors) => {\n if (event && event.exception && event.exception.values) {\n event.exception.values = [...linkedErrors, ...event.exception.values];\n }\n resolve(event);\n })\n .then(null, () => {\n resolve(event);\n });\n });\n }\n\n /**\n * @inheritDoc\n */\n async _walkErrorTree(\n stackParser,\n error,\n key,\n stack = [],\n ) {\n if (!utils.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {\n return Promise.resolve(stack);\n }\n\n const exception = eventbuilder.exceptionFromError(stackParser, error[key]);\n\n // If the ContextLines integration is enabled, we add source code context to linked errors\n // because we can't guarantee the order that integrations are run.\n const contextLines = core.getCurrentHub().getIntegration(contextlines.ContextLines);\n if (contextLines && _optionalChain([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) {\n await contextLines.addSourceContextToFrames(exception.stacktrace.frames);\n }\n\n return new Promise((resolve, reject) => {\n void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack])\n .then(resolve)\n .then(null, () => {\n reject();\n });\n });\n }\n}LinkedErrors.__initStatic();\n\nexports.LinkedErrors = LinkedErrors;\n//# sourceMappingURL=linkederrors.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst lru_map = require('lru_map');\n\n/**\n * Promise API is available as `Experimental` and in Node 19 only.\n *\n * Callback-based API is `Stable` since v14 and `Experimental` since v8.\n * Because of that, we are creating our own `AsyncSession` class.\n *\n * https://nodejs.org/docs/latest-v19.x/api/inspector.html#promises-api\n * https://nodejs.org/docs/latest-v14.x/api/inspector.html\n */\nclass AsyncSession {\n\n /** Throws is inspector API is not available */\n constructor() {\n // Node can be build without inspector support so this can throw\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Session } = require('inspector');\n this._session = new Session();\n }\n\n /** @inheritdoc */\n configureAndConnect(\n onPause,\n captureAll,\n ) {\n this._session.connect();\n this._session.on('Debugger.paused', onPause);\n this._session.post('Debugger.enable');\n // We only want to pause on uncaught exceptions\n this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' });\n }\n\n /** @inheritdoc */\n async getLocalVariables(objectId) {\n const props = await this._getProperties(objectId);\n const unrolled = {};\n\n for (const prop of props) {\n if (_optionalChain([prop, 'optionalAccess', _ => _.value, 'optionalAccess', _2 => _2.objectId]) && _optionalChain([prop, 'optionalAccess', _3 => _3.value, 'access', _4 => _4.className]) === 'Array') {\n unrolled[prop.name] = await this._unrollArray(prop.value.objectId);\n } else if (_optionalChain([prop, 'optionalAccess', _5 => _5.value, 'optionalAccess', _6 => _6.objectId]) && _optionalChain([prop, 'optionalAccess', _7 => _7.value, 'optionalAccess', _8 => _8.className]) === 'Object') {\n unrolled[prop.name] = await this._unrollObject(prop.value.objectId);\n } else if (_optionalChain([prop, 'optionalAccess', _9 => _9.value, 'optionalAccess', _10 => _10.value]) || _optionalChain([prop, 'optionalAccess', _11 => _11.value, 'optionalAccess', _12 => _12.description])) {\n unrolled[prop.name] = prop.value.value || `<${prop.value.description}>`;\n }\n }\n\n return unrolled;\n }\n\n /**\n * Gets all the PropertyDescriptors of an object\n */\n _getProperties(objectId) {\n return new Promise((resolve, reject) => {\n this._session.post(\n 'Runtime.getProperties',\n {\n objectId,\n ownProperties: true,\n },\n (err, params) => {\n if (err) {\n reject(err);\n } else {\n resolve(params.result);\n }\n },\n );\n });\n }\n\n /**\n * Unrolls an array property\n */\n async _unrollArray(objectId) {\n const props = await this._getProperties(objectId);\n return props\n .filter(v => v.name !== 'length' && !isNaN(parseInt(v.name, 10)))\n .sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10))\n .map(v => _optionalChain([v, 'optionalAccess', _13 => _13.value, 'optionalAccess', _14 => _14.value]));\n }\n\n /**\n * Unrolls an object property\n */\n async _unrollObject(objectId) {\n const props = await this._getProperties(objectId);\n return props\n .map(v => [v.name, _optionalChain([v, 'optionalAccess', _15 => _15.value, 'optionalAccess', _16 => _16.value])])\n .reduce((obj, [key, val]) => {\n obj[key] = val;\n return obj;\n }, {} );\n }\n}\n\n/**\n * When using Vercel pkg, the inspector module is not available.\n * https://github.com/getsentry/sentry-javascript/issues/6769\n */\nfunction tryNewAsyncSession() {\n try {\n return new AsyncSession();\n } catch (e) {\n return undefined;\n }\n}\n\n// Add types for the exception event data\n\n/** Could this be an anonymous function? */\nfunction isAnonymous(name) {\n return name !== undefined && ['', '?', ''].includes(name);\n}\n\n/** Do the function names appear to match? */\nfunction functionNamesMatch(a, b) {\n return a === b || (isAnonymous(a) && isAnonymous(b));\n}\n\n/** Creates a unique hash from stack frames */\nfunction hashFrames(frames) {\n if (frames === undefined) {\n return;\n }\n\n // Only hash the 10 most recent frames (ie. the last 10)\n return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, '');\n}\n\n/**\n * We use the stack parser to create a unique hash from the exception stack trace\n * This is used to lookup vars when the exception passes through the event processor\n */\nfunction hashFromStack(stackParser, stack) {\n if (stack === undefined) {\n return undefined;\n }\n\n return hashFrames(stackParser(stack, 1));\n}\n\n/**\n * Adds local variables to exception frames\n */\nclass LocalVariables {\n static __initStatic() {this.id = 'LocalVariables';}\n\n __init() {this.name = LocalVariables.id;}\n\n __init2() {this._cachedFrames = new lru_map.LRUMap(20);}\n\n constructor(\n _options = {},\n _session = tryNewAsyncSession(),\n ) {this._options = _options;this._session = _session;LocalVariables.prototype.__init.call(this);LocalVariables.prototype.__init2.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n this._setup(addGlobalEventProcessor, _optionalChain([getCurrentHub, 'call', _17 => _17(), 'access', _18 => _18.getClient, 'call', _19 => _19(), 'optionalAccess', _20 => _20.getOptions, 'call', _21 => _21()]));\n }\n\n /** Setup in a way that's easier to call from tests */\n _setup(\n addGlobalEventProcessor,\n clientOptions,\n ) {\n if (this._session && _optionalChain([clientOptions, 'optionalAccess', _22 => _22.includeLocalVariables])) {\n this._session.configureAndConnect(\n ev => this._handlePaused(clientOptions.stackParser, ev ),\n !!this._options.captureAllExceptions,\n );\n\n addGlobalEventProcessor(async event => this._addLocalVariables(event));\n }\n }\n\n /**\n * Handle the pause event\n */\n async _handlePaused(\n stackParser,\n { params: { reason, data, callFrames } },\n ) {\n if (reason !== 'exception' && reason !== 'promiseRejection') {\n return;\n }\n\n // data.description contains the original error.stack\n const exceptionHash = hashFromStack(stackParser, _optionalChain([data, 'optionalAccess', _23 => _23.description]));\n\n if (exceptionHash == undefined) {\n return;\n }\n\n const framePromises = callFrames.map(async ({ scopeChain, functionName, this: obj }) => {\n const localScope = scopeChain.find(scope => scope.type === 'local');\n\n // obj.className is undefined in ESM modules\n const fn = obj.className === 'global' || !obj.className ? functionName : `${obj.className}.${functionName}`;\n\n if (_optionalChain([localScope, 'optionalAccess', _24 => _24.object, 'access', _25 => _25.objectId]) === undefined) {\n return { function: fn };\n }\n\n const vars = await _optionalChain([this, 'access', _26 => _26._session, 'optionalAccess', _27 => _27.getLocalVariables, 'call', _28 => _28(localScope.object.objectId)]);\n\n return { function: fn, vars };\n });\n\n // We add the un-awaited promise to the cache rather than await here otherwise the event processor\n // can be called before we're finished getting all the vars\n this._cachedFrames.set(exceptionHash, Promise.all(framePromises));\n }\n\n /**\n * Adds local variables event stack frames.\n */\n async _addLocalVariables(event) {\n for (const exception of _optionalChain([event, 'optionalAccess', _29 => _29.exception, 'optionalAccess', _30 => _30.values]) || []) {\n await this._addLocalVariablesToException(exception);\n }\n\n return event;\n }\n\n /**\n * Adds local variables to the exception stack frames.\n */\n async _addLocalVariablesToException(exception) {\n const hash = hashFrames(_optionalChain([exception, 'optionalAccess', _31 => _31.stacktrace, 'optionalAccess', _32 => _32.frames]));\n\n if (hash === undefined) {\n return;\n }\n\n // Check if we have local variables for an exception that matches the hash\n // delete is identical to get but also removes the entry from the cache\n const cachedFrames = await this._cachedFrames.delete(hash);\n\n if (cachedFrames === undefined) {\n return;\n }\n\n const frameCount = _optionalChain([exception, 'access', _33 => _33.stacktrace, 'optionalAccess', _34 => _34.frames, 'optionalAccess', _35 => _35.length]) || 0;\n\n for (let i = 0; i < frameCount; i++) {\n // Sentry frames are in reverse order\n const frameIndex = frameCount - i - 1;\n\n // Drop out if we run out of frames to match up\n if (!_optionalChain([exception, 'optionalAccess', _36 => _36.stacktrace, 'optionalAccess', _37 => _37.frames, 'optionalAccess', _38 => _38[frameIndex]]) || !cachedFrames[i]) {\n break;\n }\n\n if (\n // We need to have vars to add\n cachedFrames[i].vars === undefined ||\n // We're not interested in frames that are not in_app because the vars are not relevant\n exception.stacktrace.frames[frameIndex].in_app === false ||\n // The function names need to match\n !functionNamesMatch(exception.stacktrace.frames[frameIndex].function, cachedFrames[i].function)\n ) {\n continue;\n }\n\n exception.stacktrace.frames[frameIndex].vars = cachedFrames[i].vars;\n }\n }\n}LocalVariables.__initStatic();\n\nexports.LocalVariables = LocalVariables;\n//# sourceMappingURL=localvariables.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst fs = require('fs');\nconst path = require('path');\n\nlet moduleCache;\n\n/** Extract information about paths */\nfunction getPaths() {\n try {\n return require.cache ? Object.keys(require.cache ) : [];\n } catch (e) {\n return [];\n }\n}\n\n/** Extract information about package.json modules */\nfunction collectModules()\n\n {\n const mainPaths = (require.main && require.main.paths) || [];\n const paths = getPaths();\n const infos\n\n = {};\n const seen\n\n = {};\n\n paths.forEach(path$1 => {\n let dir = path$1;\n\n /** Traverse directories upward in the search of package.json file */\n const updir = () => {\n const orig = dir;\n dir = path.dirname(orig);\n\n if (!dir || orig === dir || seen[orig]) {\n return undefined;\n }\n if (mainPaths.indexOf(dir) < 0) {\n return updir();\n }\n\n const pkgfile = path.join(orig, 'package.json');\n seen[orig] = true;\n\n if (!fs.existsSync(pkgfile)) {\n return updir();\n }\n\n try {\n const info = JSON.parse(fs.readFileSync(pkgfile, 'utf8'))\n\n;\n infos[info.name] = info.version;\n } catch (_oO) {\n // no-empty\n }\n };\n\n updir();\n });\n\n return infos;\n}\n\n/** Add node modules / packages to the event */\nclass Modules {constructor() { Modules.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Modules';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Modules.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(event => {\n if (!getCurrentHub().getIntegration(Modules)) {\n return event;\n }\n return {\n ...event,\n modules: {\n ...event.modules,\n ...this._getModules(),\n },\n };\n });\n }\n\n /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */\n _getModules() {\n if (!moduleCache) {\n moduleCache = collectModules();\n }\n return moduleCache;\n }\n} Modules.__initStatic();\n\nexports.Modules = Modules;\n//# sourceMappingURL=modules.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst errorhandling = require('./utils/errorhandling.js');\n\n/** Global Exception handler */\nclass OnUncaughtException {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'OnUncaughtException';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = OnUncaughtException.id;}\n\n /**\n * @inheritDoc\n */\n __init2() {this.handler = this._makeErrorHandler();}\n\n // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts`\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this);\n this._options = {\n exitEvenIfOtherHandlersAreRegistered: true,\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n global.process.on('uncaughtException', this.handler);\n }\n\n /**\n * @hidden\n */\n _makeErrorHandler() {\n const timeout = 2000;\n let caughtFirstError = false;\n let caughtSecondError = false;\n let calledFatalError = false;\n let firstError;\n\n return (error) => {\n let onFatalError = errorhandling.logAndExitProcess;\n const client = core.getCurrentHub().getClient();\n\n if (this._options.onFatalError) {\n onFatalError = this._options.onFatalError;\n } else if (client && client.getOptions().onFatalError) {\n onFatalError = client.getOptions().onFatalError ;\n }\n\n // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not\n // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust\n // exit behaviour of the SDK accordingly:\n // - If other listeners are attached, do not exit.\n // - If the only listener attached is ours, exit.\n const userProvidedListenersCount = global.process\n .listeners('uncaughtException')\n .reduce((acc, listener) => {\n if (\n listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself\n listener === this.handler // filter the handler we registered ourselves)\n ) {\n return acc;\n } else {\n return acc + 1;\n }\n }, 0);\n\n const processWouldExit = userProvidedListenersCount === 0;\n const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;\n\n if (!caughtFirstError) {\n const hub = core.getCurrentHub();\n\n // this is the first uncaught error and the ultimate reason for shutting down\n // we want to do absolutely everything possible to ensure it gets captured\n // also we want to make sure we don't go recursion crazy if more errors happen after this one\n firstError = error;\n caughtFirstError = true;\n\n if (hub.getIntegration(OnUncaughtException)) {\n hub.withScope((scope) => {\n scope.setLevel('fatal');\n hub.captureException(error, {\n originalException: error,\n data: { mechanism: { handled: false, type: 'onuncaughtexception' } },\n });\n if (!calledFatalError && shouldApplyFatalHandlingLogic) {\n calledFatalError = true;\n onFatalError(error);\n }\n });\n } else {\n if (!calledFatalError && shouldApplyFatalHandlingLogic) {\n calledFatalError = true;\n onFatalError(error);\n }\n }\n } else {\n if (shouldApplyFatalHandlingLogic) {\n if (calledFatalError) {\n // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown',\n );\n errorhandling.logAndExitProcess(error);\n } else if (!caughtSecondError) {\n // two cases for how we can hit this branch:\n // - capturing of first error blew up and we just caught the exception from that\n // - quit trying to capture, proceed with shutdown\n // - a second independent error happened while waiting for first error to capture\n // - want to avoid causing premature shutdown before first error capture finishes\n // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff\n // so let's instead just delay a bit before we proceed with our action here\n // in case 1, we just wait a bit unnecessarily but ultimately do the same thing\n // in case 2, the delay hopefully made us wait long enough for the capture to finish\n // two potential nonideal outcomes:\n // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError\n // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error\n // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError)\n // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish\n caughtSecondError = true;\n setTimeout(() => {\n if (!calledFatalError) {\n // it was probably case 1, let's treat err as the sendErr and call onFatalError\n calledFatalError = true;\n onFatalError(firstError, error);\n }\n }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc\n }\n }\n }\n };\n }\n} OnUncaughtException.__initStatic();\n\nexports.OnUncaughtException = OnUncaughtException;\n//# sourceMappingURL=onuncaughtexception.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst errorhandling = require('./utils/errorhandling.js');\n\n/** Global Promise Rejection handler */\nclass OnUnhandledRejection {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'OnUnhandledRejection';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = OnUnhandledRejection.id;}\n\n /**\n * @inheritDoc\n */\n constructor(\n _options\n\n = { mode: 'warn' },\n ) {this._options = _options;OnUnhandledRejection.prototype.__init.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this));\n }\n\n /**\n * Send an exception with reason\n * @param reason string\n * @param promise promise\n */\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\n sendUnhandledPromise(reason, promise) {\n const hub = core.getCurrentHub();\n if (hub.getIntegration(OnUnhandledRejection)) {\n hub.withScope((scope) => {\n scope.setExtra('unhandledPromiseRejection', true);\n hub.captureException(reason, {\n originalException: promise,\n data: { mechanism: { handled: false, type: 'onunhandledrejection' } },\n });\n });\n }\n this._handleRejection(reason);\n }\n\n /**\n * Handler for `mode` option\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _handleRejection(reason) {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (this._options.mode === 'warn') {\n utils.consoleSandbox(() => {\n console.warn(rejectionWarning);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.error(reason && reason.stack ? reason.stack : reason);\n });\n } else if (this._options.mode === 'strict') {\n utils.consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n errorhandling.logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n }\n} OnUnhandledRejection.__initStatic();\n\nexports.OnUnhandledRejection = OnUnhandledRejection;\n//# sourceMappingURL=onunhandledrejection.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst requestdata = require('../requestdata.js');\n\nconst DEFAULT_OPTIONS = {\n include: {\n cookies: true,\n data: true,\n headers: true,\n ip: false,\n query_string: true,\n url: true,\n user: {\n id: true,\n username: true,\n email: true,\n },\n },\n transactionNamingScheme: 'methodPath',\n};\n\n/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations`\n * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */\nclass RequestData {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'RequestData';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = RequestData.id;}\n\n /**\n * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but\n * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use\n * something similar in browser-based SDKs in the future.\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {RequestData.prototype.__init.call(this);\n this._addRequestData = requestdata.addRequestDataToEvent;\n this._options = {\n ...DEFAULT_OPTIONS,\n ...options,\n include: {\n // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in\n // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.)\n method: true,\n ...DEFAULT_OPTIONS.include,\n ...options.include,\n user:\n options.include && typeof options.include.user === 'boolean'\n ? options.include.user\n : {\n ...DEFAULT_OPTIONS.include.user,\n // Unclear why TS still thinks `options.include.user` could be a boolean at this point\n ...((options.include || {}).user ),\n },\n },\n };\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n // Note: In the long run, most of the logic here should probably move into the request data utility functions. For\n // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed.\n // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once\n // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.)\n const { transactionNamingScheme } = this._options;\n\n addGlobalEventProcessor(event => {\n const hub = getCurrentHub();\n const self = hub.getIntegration(RequestData);\n\n const { sdkProcessingMetadata = {} } = event;\n const req = sdkProcessingMetadata.request;\n\n // If the globally installed instance of this integration isn't associated with the current hub, `self` will be\n // undefined\n if (!self || !req) {\n return event;\n }\n\n // The Express request handler takes a similar `include` option to that which can be passed to this integration.\n // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this\n // integration, so that all of this passing and conversion isn't necessary\n const addRequestDataOptions =\n sdkProcessingMetadata.requestDataOptionsFromExpressHandler ||\n sdkProcessingMetadata.requestDataOptionsFromGCPWrapper ||\n convertReqDataIntegrationOptsToAddReqDataOpts(this._options);\n\n const processedEvent = this._addRequestData(event, req, addRequestDataOptions);\n\n // Transaction events already have the right `transaction` value\n if (event.type === 'transaction' || transactionNamingScheme === 'handler') {\n return processedEvent;\n }\n\n // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction`\n // value with a high-quality one\n const reqWithTransaction = req ;\n const transaction = reqWithTransaction._sentryTransaction;\n if (transaction) {\n // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to\n // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential\n // to break things like alert rules.)\n const shouldIncludeMethodInTransactionName =\n getSDKName(hub) === 'sentry.javascript.nextjs'\n ? transaction.name.startsWith('/api')\n : transactionNamingScheme !== 'path';\n\n const [transactionValue] = utils.extractPathForTransaction(req, {\n path: true,\n method: shouldIncludeMethodInTransactionName,\n customRoute: transaction.name,\n });\n\n processedEvent.transaction = transactionValue;\n }\n\n return processedEvent;\n });\n }\n} RequestData.__initStatic();\n\n/** Convert this integration's options to match what `addRequestDataToEvent` expects */\n/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */\nfunction convertReqDataIntegrationOptsToAddReqDataOpts(\n integrationOptions,\n) {\n const {\n transactionNamingScheme,\n include: { ip, user, ...requestOptions },\n } = integrationOptions;\n\n const requestIncludeKeys = [];\n for (const [key, value] of Object.entries(requestOptions)) {\n if (value) {\n requestIncludeKeys.push(key);\n }\n }\n\n let addReqDataUserOpt;\n if (user === undefined) {\n addReqDataUserOpt = true;\n } else if (typeof user === 'boolean') {\n addReqDataUserOpt = user;\n } else {\n const userIncludeKeys = [];\n for (const [key, value] of Object.entries(user)) {\n if (value) {\n userIncludeKeys.push(key);\n }\n }\n addReqDataUserOpt = userIncludeKeys;\n }\n\n return {\n include: {\n ip,\n user: addReqDataUserOpt,\n request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined,\n transaction: transactionNamingScheme,\n },\n };\n}\n\nfunction getSDKName(hub) {\n try {\n // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to\n // write out a long chain of `a && a.b && a.b.c && ...`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return hub.getClient().getOptions()._metadata.sdk.name;\n } catch (err) {\n // In theory we should never get here\n return undefined;\n }\n}\n\nexports.RequestData = RequestData;\n//# sourceMappingURL=requestdata.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\n/**\n * @hidden\n */\nfunction logAndExitProcess(error) {\n // eslint-disable-next-line no-console\n console.error(error && error.stack ? error.stack : error);\n\n const client = core.getCurrentHub().getClient();\n\n if (client === undefined) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n }\n\n const options = client.getOptions();\n const timeout =\n (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||\n DEFAULT_SHUTDOWN_TIMEOUT;\n client.close(timeout).then(\n (result) => {\n if (!result) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n },\n error => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(error);\n },\n );\n}\n\nexports.logAndExitProcess = logAndExitProcess;\n//# sourceMappingURL=errorhandling.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst url = require('url');\n\nconst NODE_VERSION = utils.parseSemver(process.versions.node);\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n */\nfunction isSentryRequest(url) {\n const dsn = _optionalChain([core.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]);\n return dsn ? url.includes(dsn.host) : false;\n}\n\n/**\n * Assemble a URL to be used for breadcrumbs and spans.\n *\n * @param requestOptions RequestOptions object containing the component parts for a URL\n * @returns Fully-formed URL\n */\nfunction extractUrl(requestOptions) {\n const protocol = requestOptions.protocol || '';\n const hostname = requestOptions.hostname || requestOptions.host || '';\n // Don't log standard :80 (http) and :443 (https) ports to reduce the noise\n const port =\n !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`;\n const path = requestOptions.path ? requestOptions.path : '/';\n\n return `${protocol}//${hostname}${port}${path}`;\n}\n\n/**\n * Handle various edge cases in the span description (for spans representing http(s) requests).\n *\n * @param description current `description` property of the span representing the request\n * @param requestOptions Configuration data for the request\n * @param Request Request object\n *\n * @returns The cleaned description\n */\nfunction cleanSpanDescription(\n description,\n requestOptions,\n request,\n) {\n // nothing to clean\n if (!description) {\n return description;\n }\n\n // eslint-disable-next-line prefer-const\n let [method, requestUrl] = description.split(' ');\n\n // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing,\n // we're likely dealing with an internal route and this doesn't apply)\n if (requestOptions.host && !requestOptions.protocol) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n requestOptions.protocol = _optionalChain([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes\n requestUrl = extractUrl(requestOptions);\n }\n\n // internal routes can end up starting with a triple slash rather than a single one\n if (_optionalChain([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) {\n requestUrl = requestUrl.slice(2);\n }\n\n return `${method} ${requestUrl}`;\n}\n\n// the node types are missing a few properties which node's `urlToOptions` function spits out\n\n/**\n * Convert a URL object into a RequestOptions object.\n *\n * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the\n * RequestOptions type above.\n *\n * See https://github.com/nodejs/node/blob/master/lib/internal/url.js.\n */\nfunction urlToOptions(url) {\n const options = {\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `${url.pathname || ''}${url.search || ''}`,\n href: url.href,\n };\n if (url.port !== '') {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`;\n }\n return options;\n}\n\n/**\n * Normalize inputs to `http(s).request()` and `http(s).get()`.\n *\n * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms:\n * [ RequestOptions | string | URL ],\n * [ RequestOptions | string | URL, RequestCallback ],\n * [ string | URL, RequestOptions ], and\n * [ string | URL, RequestOptions, RequestCallback ].\n *\n * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is\n * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact\n * with the args in a standard way.\n *\n * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array.\n *\n * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ].\n */\nfunction normalizeRequestArgs(\n httpModule,\n requestArgs,\n) {\n let callback, requestOptions;\n\n // pop off the callback, if there is one\n if (typeof requestArgs[requestArgs.length - 1] === 'function') {\n callback = requestArgs.pop() ;\n }\n\n // create a RequestOptions object of whatever's at index 0\n if (typeof requestArgs[0] === 'string') {\n requestOptions = urlToOptions(new url.URL(requestArgs[0]));\n } else if (requestArgs[0] instanceof url.URL) {\n requestOptions = urlToOptions(requestArgs[0]);\n } else {\n requestOptions = requestArgs[0];\n }\n\n // if the options were given separately from the URL, fold them in\n if (requestArgs.length === 2) {\n requestOptions = { ...requestOptions, ...requestArgs[1] };\n }\n\n // Figure out the protocol if it's currently missing\n if (requestOptions.protocol === undefined) {\n // Worst case we end up populating protocol with undefined, which it already is\n /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // Because of that, we cannot rely on `httpModule` to provide us with valid protocol,\n // as it will always return `http`, even when using `https` module.\n //\n // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n requestOptions.protocol =\n _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) ||\n _optionalChain([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) ||\n _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]);\n } else {\n requestOptions.protocol =\n _optionalChain([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) ||\n _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) ||\n _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]);\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n }\n\n // return args in standardized form\n if (callback) {\n return [requestOptions, callback];\n } else {\n return [requestOptions];\n }\n}\n\nexports.cleanSpanDescription = cleanSpanDescription;\nexports.extractUrl = extractUrl;\nexports.isSentryRequest = isSentryRequest;\nexports.normalizeRequestArgs = normalizeRequestArgs;\nexports.urlToOptions = urlToOptions;\n//# sourceMappingURL=http.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/** normalizes Windows paths */\nfunction normalizePath(path) {\n return path\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/'); // replace all `\\` instances with `/`\n}\n\n/** Gets the module from a filename */\nfunction getModule(filename) {\n if (!filename) {\n return;\n }\n\n const normalizedFilename = normalizePath(filename);\n\n // We could use optional chaining here but webpack does like that mixed with require\n const base = normalizePath(\n `${(require && require.main && require.main.filename && utils.dirname(require.main.filename)) || global.process.cwd()}/`,\n );\n\n // It's specifically a module\n const file = utils.basename(normalizedFilename, '.js');\n\n const path = utils.dirname(normalizedFilename);\n let n = path.lastIndexOf('/node_modules/');\n if (n > -1) {\n // /node_modules/ is 14 chars\n return `${path.slice(n + 14).replace(/\\//g, '.')}:${file}`;\n }\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n n = `${path}/`.lastIndexOf(base, 0);\n\n if (n === 0) {\n let moduleName = path.slice(base.length).replace(/\\//g, '.');\n if (moduleName) {\n moduleName += ':';\n }\n moduleName += file;\n return moduleName;\n }\n return file;\n}\n\nexports.getModule = getModule;\n//# sourceMappingURL=module.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst requestdata = require('./requestdata.js');\n\n/**\n * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead.\n */\n\n/**\n * Normalizes data from the request object, accounting for framework differences.\n *\n * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead.\n *\n * @param req The request object from which to extract data\n * @param keys An optional array of keys to include in the normalized data.\n * @returns An object containing normalized request data\n */\nfunction extractRequestData(req, keys) {\n return requestdata.extractRequestData(req, { include: keys });\n}\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n *\n * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use\n * `AddRequestDataToEventOptions` in `@sentry/utils` instead.\n */\n\n/**\n * Enriches passed event with request data.\n *\n * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead.\n *\n * @param event Will be mutated and enriched with req data\n * @param req Request object\n * @param options object containing flags to enable functionality\n * @hidden\n */\nfunction parseRequest(event, req, options = {}) {\n return requestdata.addRequestDataToEvent(event, req, { include: options });\n}\n\nexports.extractRequestData = extractRequestData;\nexports.parseRequest = parseRequest;\n//# sourceMappingURL=requestDataDeprecated.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst cookie = require('cookie');\nconst url = require('url');\n\nconst DEFAULT_INCLUDES = {\n ip: false,\n request: true,\n transaction: true,\n user: true,\n};\nconst DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\nconst DEFAULT_USER_INCLUDES = ['id', 'username', 'email'];\n\n/**\n * Extracts a complete and parameterized path from the request object and uses it to construct transaction name.\n * If the parameterized transaction name cannot be extracted, we fall back to the raw URL.\n *\n * Additionally, this function determines and returns the transaction name source\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req A request object\n * @param options What to include in the transaction name (method, path, or a custom route name to be\n * used instead of the request's route)\n *\n * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')\n */\nfunction extractPathForTransaction(\n req,\n options = {},\n) {\n const method = req.method && req.method.toUpperCase();\n\n let path = '';\n let source = 'url';\n\n // Check to see if there's a parameterized route we can use (as there is in Express)\n if (options.customRoute || req.route) {\n path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`;\n source = 'route';\n }\n\n // Otherwise, just take the original URL\n else if (req.originalUrl || req.url) {\n path = utils.stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let name = '';\n if (options.method && method) {\n name += method;\n }\n if (options.method && options.path) {\n name += ' ';\n }\n if (options.path && path) {\n name += path;\n }\n\n return [name, source];\n}\n\n/** JSDoc */\nfunction extractTransaction(req, type) {\n switch (type) {\n case 'path': {\n return extractPathForTransaction(req, { path: true })[0];\n }\n case 'handler': {\n return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '';\n }\n case 'methodPath':\n default: {\n return extractPathForTransaction(req, { path: true, method: true })[0];\n }\n }\n}\n\n/** JSDoc */\nfunction extractUserData(\n user\n\n,\n keys,\n) {\n const extractedUser = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/**\n * Normalize data from the request object\n *\n * @param req The request object from which to extract data\n * @param options.include An optional array of keys to include in the normalized data. Defaults to\n * DEFAULT_REQUEST_INCLUDES if not provided.\n * @param options.deps Injected, platform-specific dependencies\n *\n * @returns An object containing normalized request data\n */\nfunction extractRequestData(\n req,\n options\n\n,\n) {\n const { include = DEFAULT_REQUEST_INCLUDES } = options || {};\n const requestData = {};\n\n // headers:\n // node, express, koa, nextjs: req.headers\n const headers = (req.headers || {})\n\n;\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n const host = req.hostname || req.host || headers.host || '';\n // protocol:\n // node, nextjs: \n // express, koa: req.protocol\n const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = req.originalUrl || req.url || '';\n // absolute url\n const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`;\n include.forEach(key => {\n switch (key) {\n case 'headers': {\n requestData.headers = headers;\n\n // Remove the Cookie header in case cookie data should not be included in the event\n if (!include.includes('cookies')) {\n delete (requestData.headers ).cookie;\n }\n\n break;\n }\n case 'method': {\n requestData.method = method;\n break;\n }\n case 'url': {\n requestData.url = absoluteUrl;\n break;\n }\n case 'cookies': {\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.cookies =\n // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can\n // come off in v8\n req.cookies || (headers.cookie && cookie.parse(headers.cookie)) || {};\n break;\n }\n case 'query_string': {\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = extractQueryParams(req);\n break;\n }\n case 'data': {\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = utils.isString(req.body) ? req.body : JSON.stringify(utils.normalize(req.body));\n }\n break;\n }\n default: {\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req )[key];\n }\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Add data from the given request to the given event\n *\n * @param event The event to which the request data will be added\n * @param req Request object\n * @param options.include Flags to control what data is included\n *\n * @returns The mutated `Event` object\n */\nfunction addRequestDataToEvent(\n event,\n req,\n options,\n) {\n const include = {\n ...DEFAULT_INCLUDES,\n ..._optionalChain([options, 'optionalAccess', _ => _.include]),\n };\n\n if (include.request) {\n const extractedRequestData = Array.isArray(include.request)\n ? extractRequestData(req, { include: include.request })\n : extractRequestData(req);\n\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (include.user) {\n const extractedUser = req.user && utils.isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};\n\n if (Object.keys(extractedUser).length) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.socket.remoteAddress\n // express, koa: req.ip\n if (include.ip) {\n const ip = req.ip || (req.socket && req.socket.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (include.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, include.transaction);\n }\n\n return event;\n}\n\nfunction extractQueryParams(req) {\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n let originalUrl = req.originalUrl || req.url || '';\n\n if (!originalUrl) {\n return;\n }\n\n // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use.\n if (originalUrl.startsWith('/')) {\n originalUrl = `http://dogs.are.great${originalUrl}`;\n }\n\n return (\n req.query ||\n (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) ||\n // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node\n url.parse(originalUrl).query ||\n undefined\n );\n}\n\nexports.DEFAULT_USER_INCLUDES = DEFAULT_USER_INCLUDES;\nexports.addRequestDataToEvent = addRequestDataToEvent;\nexports.extractPathForTransaction = extractPathForTransaction;\nexports.extractRequestData = extractRequestData;\n//# sourceMappingURL=requestdata.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst domain = require('domain');\nconst client = require('./client.js');\nconst console = require('./integrations/console.js');\nconst http = require('./integrations/http.js');\nconst onuncaughtexception = require('./integrations/onuncaughtexception.js');\nconst onunhandledrejection = require('./integrations/onunhandledrejection.js');\nconst linkederrors = require('./integrations/linkederrors.js');\nconst modules = require('./integrations/modules.js');\nconst contextlines = require('./integrations/contextlines.js');\nconst context = require('./integrations/context.js');\nconst requestdata = require('./integrations/requestdata.js');\nconst localvariables = require('./integrations/localvariables.js');\nconst module$1 = require('./module.js');\nconst http$1 = require('./transports/http.js');\n\n/* eslint-disable max-lines */\n\nconst defaultIntegrations = [\n // Common\n new core.Integrations.InboundFilters(),\n new core.Integrations.FunctionToString(),\n // Native Wrappers\n new console.Console(),\n new http.Http(),\n // Global Handlers\n new onuncaughtexception.OnUncaughtException(),\n new onunhandledrejection.OnUnhandledRejection(),\n // Event Info\n new contextlines.ContextLines(),\n new localvariables.LocalVariables(),\n new context.Context(),\n new modules.Modules(),\n new requestdata.RequestData(),\n // Misc\n new linkederrors.LinkedErrors(),\n];\n\n/**\n * The Sentry Node SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible in the\n * main entry module. To set context information or send manual events, use the\n * provided methods.\n *\n * @example\n * ```\n *\n * const { init } = require('@sentry/node');\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { configureScope } = require('@sentry/node');\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { addBreadcrumb } = require('@sentry/node');\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const Sentry = require('@sentry/node');\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link NodeOptions} for documentation on configuration options.\n */\nfunction init(options = {}) {\n const carrier = core.getMainCarrier();\n const autoloadedIntegrations = _optionalChain([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || [];\n\n options.defaultIntegrations =\n options.defaultIntegrations === false\n ? []\n : [\n ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations),\n ...autoloadedIntegrations,\n ];\n\n if (options.dsn === undefined && process.env.SENTRY_DSN) {\n options.dsn = process.env.SENTRY_DSN;\n }\n\n if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) {\n const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE);\n if (isFinite(tracesSampleRate)) {\n options.tracesSampleRate = tracesSampleRate;\n }\n }\n\n if (options.release === undefined) {\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n options.release = detectedRelease;\n } else {\n // If release is not provided, then we should disable autoSessionTracking\n options.autoSessionTracking = false;\n }\n }\n\n if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) {\n options.environment = process.env.SENTRY_ENVIRONMENT;\n }\n\n if (options.autoSessionTracking === undefined && options.dsn !== undefined) {\n options.autoSessionTracking = true;\n }\n\n if (options.instrumenter === undefined) {\n options.instrumenter = 'sentry';\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if ((domain ).active) {\n core.setHubOnCarrier(carrier, core.getCurrentHub());\n }\n\n // TODO(v7): Refactor this to reduce the logic above\n const clientOptions = {\n ...options,\n stackParser: utils.stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: core.getIntegrationsToSetup(options),\n transport: options.transport || http$1.makeNodeTransport,\n };\n\n core.initAndBind(client.NodeClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nfunction lastEventId() {\n return core.getCurrentHub().lastEventId();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function flush(timeout) {\n const client = core.getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function close(timeout) {\n const client = core.getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client\n */\nfunction isAutoSessionTrackingEnabled(client) {\n if (client === undefined) {\n return false;\n }\n const clientOptions = client && client.getOptions();\n if (clientOptions && clientOptions.autoSessionTracking !== undefined) {\n return clientOptions.autoSessionTracking;\n }\n return false;\n}\n\n/**\n * Returns a release dynamically from environment variables.\n */\nfunction getSentryRelease(fallback) {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (utils.GLOBAL_OBJ.SENTRY_RELEASE && utils.GLOBAL_OBJ.SENTRY_RELEASE.id) {\n return utils.GLOBAL_OBJ.SENTRY_RELEASE.id;\n }\n\n return (\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env.GITHUB_SHA ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env.COMMIT_REF ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.VERCEL_GITHUB_COMMIT_SHA ||\n process.env.VERCEL_GITLAB_COMMIT_SHA ||\n process.env.VERCEL_BITBUCKET_COMMIT_SHA ||\n // Zeit (now known as Vercel)\n process.env.ZEIT_GITHUB_COMMIT_SHA ||\n process.env.ZEIT_GITLAB_COMMIT_SHA ||\n process.env.ZEIT_BITBUCKET_COMMIT_SHA ||\n fallback\n );\n}\n\n/** Node.js stack parser */\nconst defaultStackParser = utils.createStackParser(utils.nodeStackLineParser(module$1.getModule));\n\n/**\n * Enable automatic Session Tracking for the node process.\n */\nfunction startSessionTracking() {\n const hub = core.getCurrentHub();\n hub.startSession();\n // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because\n // The 'beforeExit' event is not emitted for conditions causing explicit termination,\n // such as calling process.exit() or uncaught exceptions.\n // Ref: https://nodejs.org/api/process.html#process_event_beforeexit\n process.on('beforeExit', () => {\n const session = _optionalChain([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]);\n const terminalStates = ['exited', 'crashed'];\n // Only call endSession, if the Session exists on Scope and SessionStatus is not a\n // Terminal Status i.e. Exited or Crashed because\n // \"When a session is moved away from ok it must not be updated anymore.\"\n // Ref: https://develop.sentry.dev/sdk/sessions/\n if (session && !terminalStates.includes(session.status)) hub.endSession();\n });\n}\n\nexports.close = close;\nexports.defaultIntegrations = defaultIntegrations;\nexports.defaultStackParser = defaultStackParser;\nexports.flush = flush;\nexports.getSentryRelease = getSentryRelease;\nexports.init = init;\nexports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled;\nexports.lastEventId = lastEventId;\n//# sourceMappingURL=sdk.js.map\n","var {\n _nullishCoalesce\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst http = require('http');\nconst https = require('https');\nconst stream = require('stream');\nconst url = require('url');\nconst zlib = require('zlib');\n\n// Estimated maximum size for reasonable standalone event\nconst GZIP_THRESHOLD = 1024 * 32;\n\n/**\n * Gets a stream from a Uint8Array or string\n * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0\n */\nfunction streamFromBody(body) {\n return new stream.Readable({\n read() {\n this.push(body);\n this.push(null);\n },\n });\n}\n\n/**\n * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry.\n */\nfunction makeNodeTransport(options) {\n let urlSegments;\n\n try {\n urlSegments = new url.URL(options.url);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n '[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.',\n );\n return core.createTransport(options, () => Promise.resolve({}));\n }\n\n const isHttps = urlSegments.protocol === 'https:';\n\n // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`\n // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`\n const proxy = applyNoProxyOption(\n urlSegments,\n options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy,\n );\n\n const nativeHttpModule = isHttps ? https : http;\n const keepAlive = options.keepAlive === undefined ? false : options.keepAlive;\n\n // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node\n // versions(>= 8) as they had memory leaks when using it: #2555\n const agent = proxy\n ? // eslint-disable-next-line @typescript-eslint/no-var-requires\n (new (require('https-proxy-agent'))(proxy) )\n : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 });\n\n const requestExecutor = createRequestExecutor(options, _nullishCoalesce(options.httpModule, () => ( nativeHttpModule)), agent);\n return core.createTransport(options, requestExecutor);\n}\n\n/**\n * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion.\n *\n * @param transportUrl The URL the transport intends to send events to.\n * @param proxy The client configured proxy.\n * @returns A proxy the transport should use.\n */\nfunction applyNoProxyOption(transportUrlSegments, proxy) {\n const { no_proxy } = process.env;\n\n const urlIsExemptFromProxy =\n no_proxy &&\n no_proxy\n .split(',')\n .some(\n exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption),\n );\n\n if (urlIsExemptFromProxy) {\n return undefined;\n } else {\n return proxy;\n }\n}\n\n/**\n * Creates a RequestExecutor to be used with `createTransport`.\n */\nfunction createRequestExecutor(\n options,\n httpModule,\n agent,\n) {\n const { hostname, pathname, port, protocol, search } = new url.URL(options.url);\n return function makeRequest(request) {\n return new Promise((resolve, reject) => {\n let body = streamFromBody(request.body);\n\n const headers = { ...options.headers };\n\n if (request.body.length > GZIP_THRESHOLD) {\n headers['content-encoding'] = 'gzip';\n body = body.pipe(zlib.createGzip());\n }\n\n const req = httpModule.request(\n {\n method: 'POST',\n agent,\n headers,\n hostname,\n path: `${pathname}${search}`,\n port,\n protocol,\n ca: options.caCerts,\n },\n res => {\n res.on('data', () => {\n // Drain socket\n });\n\n res.on('end', () => {\n // Drain socket\n });\n\n res.setEncoding('utf8');\n\n // \"Key-value pairs of header names and values. Header names are lower-cased.\"\n // https://nodejs.org/api/http.html#http_message_headers\n const retryAfterHeader = _nullishCoalesce(res.headers['retry-after'], () => ( null));\n const rateLimitsHeader = _nullishCoalesce(res.headers['x-sentry-rate-limits'], () => ( null));\n\n resolve({\n statusCode: res.statusCode,\n headers: {\n 'retry-after': retryAfterHeader,\n 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader,\n },\n });\n },\n );\n\n req.on('error', reject);\n body.pipe(req);\n });\n };\n}\n\nexports.makeNodeTransport = makeNodeTransport;\n//# sourceMappingURL=http.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst fs = require('fs');\nconst path = require('path');\n\n/**\n * Recursively read the contents of a directory.\n *\n * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this\n * directory.\n * @returns Array holding all relative paths\n */\nfunction deepReadDirSync(targetDir) {\n const targetDirAbsPath = path.resolve(targetDir);\n\n if (!fs.existsSync(targetDirAbsPath)) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);\n }\n\n if (!fs.statSync(targetDirAbsPath).isDirectory()) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);\n }\n\n // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it\n // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve\n // the difference between `targetDirAbsPath` and `currentDirAbsPath`.\n const deepReadCurrentDir = (currentDirAbsPath) => {\n return fs.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => {\n const itemAbsPath = path.join(currentDirAbsPath, itemName);\n\n if (fs.statSync(itemAbsPath).isDirectory()) {\n return [...absPaths, ...deepReadCurrentDir(itemAbsPath)];\n }\n\n return [...absPaths, itemAbsPath];\n }, []);\n };\n\n return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath));\n}\n\nexports.deepReadDirSync = deepReadDirSync;\n//# sourceMappingURL=utils.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils$1 = require('@sentry/utils');\nconst utils = require('../utils.js');\nconst types = require('./types.js');\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (types.WINDOW && types.WINDOW.document) {\n types.WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = utils.getActiveTransaction() ;\n if (types.WINDOW.document.hidden && activeTransaction) {\n const statusType = 'cancelled';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils$1.logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils$1.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexports.registerBackgroundTabDetection = registerBackgroundTabDetection;\n//# sourceMappingURL=backgroundtab.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst hubextensions = require('../hubextensions.js');\nconst idletransaction = require('../idletransaction.js');\nrequire('@sentry/core');\nconst backgroundtab = require('./backgroundtab.js');\nconst index = require('./metrics/index.js');\nconst request = require('./request.js');\nconst router = require('./router.js');\nconst types = require('./types.js');\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n idleTimeout: idletransaction.DEFAULT_IDLE_TIMEOUT,\n finalTimeout: idletransaction.DEFAULT_FINAL_TIMEOUT,\n heartbeatInterval: idletransaction.DEFAULT_HEARTBEAT_INTERVAL,\n markBackgroundTransactions: true,\n routingInstrumentation: router.instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...request.defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nclass BrowserTracing {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n\n /**\n * @inheritDoc\n */\n __init() {this.name = BROWSER_TRACING_INTEGRATION_ID;}\n\n constructor(_options) {BrowserTracing.prototype.__init.call(this);\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n index.startTrackingWebVitals();\n if (this.options.enableLongTask) {\n index.startTrackingLongTasks();\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n _experiments,\n } = this.options;\n\n instrumentRouting(\n (context) => this._createRouteTransaction(context),\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n backgroundtab.registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n request.instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n });\n }\n\n /** Create routing idle transaction. */\n _createRouteTransaction(context) {\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;\n const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;\n\n const traceParentData = sentryTraceMetaTagValue ? utils.extractTraceparentData(sentryTraceMetaTagValue) : undefined;\n const dynamicSamplingContext = baggageMetaTagValue\n ? utils.baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)\n : undefined;\n\n const expandedContext = {\n ...context,\n ...traceParentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = types.WINDOW;\n\n const idleTransaction = hubextensions.startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n idleTransaction.registerBeforeFinishCallback(transaction => {\n index.addPerformanceEntries(transaction);\n });\n\n return idleTransaction ;\n }\n\n /** Start listener for interaction transactions */\n _registerInteractionListener() {\n let inflightInteractionTransaction;\n const registerInteractionTransaction = () => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const op = 'ui.action.click';\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = types.WINDOW;\n\n const context = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = hubextensions.startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = utils.getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : null;\n}\n\nexports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID;\nexports.BrowserTracing = BrowserTracing;\nexports.getMetaContent = getMetaContent;\n//# sourceMappingURL=browsertracing.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst utils$1 = require('../../utils.js');\nconst types = require('../types.js');\nconst getCLS = require('../web-vitals/getCLS.js');\nconst getFID = require('../web-vitals/getFID.js');\nconst getLCP = require('../web-vitals/getLCP.js');\nconst getVisibilityWatcher = require('../web-vitals/lib/getVisibilityWatcher.js');\nconst observe = require('../web-vitals/lib/observe.js');\nconst utils$2 = require('./utils.js');\n\nfunction getBrowserPerformanceAPI() {\n return types.WINDOW && types.WINDOW.addEventListener && types.WINDOW.performance;\n}\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals\n */\nfunction startTrackingWebVitals() {\n const performance = getBrowserPerformanceAPI();\n if (performance && utils.browserPerformanceTimeOrigin) {\n if (performance.mark) {\n types.WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackCLS();\n _trackLCP();\n _trackFID();\n }\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = utils$1.getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n const startTime = utils$1.msToSec((utils.browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = utils$1.msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe.observe('longtask', entryHandler);\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS() {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n getCLS.onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry ;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n getLCP.onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n getFID.onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = utils$1.msToSec(utils.browserPerformanceTimeOrigin );\n const startTime = utils$1.msToSec(entry.startTime);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(transaction) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !types.WINDOW.performance.getEntries || !utils.browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = utils$1.msToSec(utils.browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp;\n let requestStartTimestamp;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry) => {\n const startTime = utils$1.msToSec(entry.startTime);\n const duration = utils$1.msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + utils$1.msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + utils$1.msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher.getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name ).replace(types.WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + utils$1.msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n utils$2._startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + utils$1.msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nfunction _addMeasureSpans(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n utils$2._startChild(transaction, {\n description: entry.name ,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType ,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction, entry, timeOrigin) {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n event,\n timeOrigin,\n description,\n eventEnd,\n) {\n const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] );\n const start = entry[`${event}Start`] ;\n if (!start || !end) {\n return;\n }\n utils$2._startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + utils$1.msToSec(start),\n endTimestamp: timeOrigin + utils$1.msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction, entry, timeOrigin) {\n utils$2._startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + utils$1.msToSec(entry.requestStart ),\n endTimestamp: timeOrigin + utils$1.msToSec(entry.responseEnd ),\n });\n\n utils$2._startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + utils$1.msToSec(entry.responseStart ),\n endTimestamp: timeOrigin + utils$1.msToSec(entry.responseEnd ),\n });\n}\n\n/** Create resource-related spans */\nfunction _addResourceSpans(\n transaction,\n entry,\n resourceName,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n utils$2._startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction) {\n const navigator = types.WINDOW.navigator ;\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (utils$2.isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (utils$2.isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (utils$2.isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction) {\n if (_lcpEntry) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', utils.htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, utils.htmlTreeAsString(source.node)),\n );\n }\n}\n\nexports._addMeasureSpans = _addMeasureSpans;\nexports._addResourceSpans = _addResourceSpans;\nexports.addPerformanceEntries = addPerformanceEntries;\nexports.startTrackingLongTasks = startTrackingLongTasks;\nexports.startTrackingWebVitals = startTrackingWebVitals;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nfunction _startChild(transaction, { startTimestamp, ...ctx }) {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\nexports._startChild = _startChild;\nexports.isMeasurementValue = isMeasurementValue;\n//# sourceMappingURL=utils.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst utils$1 = require('../utils.js');\n\n/* eslint-disable max-lines */\n\nconst DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(_options) {\n // eslint-disable-next-line deprecation/deprecation\n const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url) =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans = {};\n\n if (traceFetch) {\n utils.addInstrumentationHandler('fetch', (handlerData) => {\n fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n\n if (traceXHR) {\n utils.addInstrumentationHandler('xhr', (handlerData) => {\n xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nfunction shouldAttachHeaders(url, tracePropagationTargets) {\n return utils.stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n */\nfunction fetchCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (!utils$1.hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = core.getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = handlerData.args[1];\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n options.headers = addTracingHeadersToFetchRequest(\n request,\n activeTransaction.getDynamicSamplingContext(),\n span,\n options,\n );\n\n activeTransaction.metadata.propagations++;\n }\n }\n}\n\nfunction addTracingHeadersToFetchRequest(\n request,\n dynamicSamplingContext,\n span,\n options\n\n,\n) {\n const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n const sentryTraceHeader = span.toTraceparent();\n\n const headers =\n typeof Request !== 'undefined' && utils.isInstanceOf(request, Request) ? (request ).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && utils.isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers );\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended miultiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders ;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (\n !utils$1.hasTracingEnabled() ||\n (handlerData.xhr && handlerData.xhr.__sentry_own_request__) ||\n !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))\n ) {\n return;\n }\n\n const xhr = handlerData.xhr.__sentry_xhr__;\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp) {\n const spanId = handlerData.xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = core.getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...xhr.data,\n type: 'xhr',\n method: xhr.method,\n url: xhr.url,\n },\n description: `${xhr.method} ${xhr.url}`,\n op: 'http.client',\n });\n\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader && shouldAttachHeaders(handlerData.xhr.__sentry_xhr__.url)) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n\n const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext();\n const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n handlerData.xhr.setRequestHeader(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n activeTransaction.metadata.propagations++;\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n\nexports.DEFAULT_TRACE_PROPAGATION_TARGETS = DEFAULT_TRACE_PROPAGATION_TARGETS;\nexports.defaultRequestInstrumentationOptions = defaultRequestInstrumentationOptions;\nexports.fetchCallback = fetchCallback;\nexports.instrumentOutgoingRequests = instrumentOutgoingRequests;\nexports.shouldAttachHeaders = shouldAttachHeaders;\nexports.xhrCallback = xhrCallback;\n//# sourceMappingURL=request.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst types = require('./types.js');\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nfunction instrumentRoutingWithDefaults(\n customStartTransaction,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n if (!types.WINDOW || !types.WINDOW.location) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl = types.WINDOW.location.href;\n\n let activeTransaction;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: types.WINDOW.location.pathname,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n utils.addInstrumentationHandler('history', ({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: types.WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n\nexports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults;\n//# sourceMappingURL=router.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\nconst WINDOW = utils.GLOBAL_OBJ ;\n\nexports.WINDOW = WINDOW;\n//# sourceMappingURL=types.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst bindReporter = require('./lib/bindReporter.js');\nconst initMetric = require('./lib/initMetric.js');\nconst observe = require('./lib/observe.js');\nconst onHidden = require('./lib/onHidden.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport) => {\n const metric = initMetric.initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe.observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter.bindReporter(onReport, metric);\n\n onHidden.onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n }\n};\n\nexports.onCLS = onCLS;\n//# sourceMappingURL=getCLS.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst bindReporter = require('./lib/bindReporter.js');\nconst getVisibilityWatcher = require('./lib/getVisibilityWatcher.js');\nconst initMetric = require('./lib/initMetric.js');\nconst observe = require('./lib/observe.js');\nconst onHidden = require('./lib/onHidden.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher();\n const metric = initMetric.initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe.observe('first-input', handleEntries);\n report = bindReporter.bindReporter(onReport, metric);\n\n if (po) {\n onHidden.onHidden(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }, true);\n }\n};\n\nexports.onFID = onFID;\n//# sourceMappingURL=getFID.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst bindReporter = require('./lib/bindReporter.js');\nconst getActivationStart = require('./lib/getActivationStart.js');\nconst getVisibilityWatcher = require('./lib/getVisibilityWatcher.js');\nconst initMetric = require('./lib/initMetric.js');\nconst observe = require('./lib/observe.js');\nconst onHidden = require('./lib/onHidden.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nconst onLCP = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher();\n const metric = initMetric.initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n const lastEntry = entries[entries.length - 1] ;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart.getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe.observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter.bindReporter(onReport, metric);\n\n const stopListening = () => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden.onHidden(stopListening, true);\n }\n};\n\nexports.onLCP = onLCP;\n//# sourceMappingURL=getLCP.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst bindReporter = (\n callback,\n metric,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n\nexports.bindReporter = bindReporter;\n//# sourceMappingURL=bindReporter.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexports.generateUniqueID = generateUniqueID;\n//# sourceMappingURL=generateUniqueID.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst getNavigationEntry = require('./getNavigationEntry.js');\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry.getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexports.getActivationStart = getActivationStart;\n//# sourceMappingURL=getActivationStart.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst types = require('../../types.js');\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getNavigationEntryFromPerformanceTiming = () => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = types.WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = types.WINDOW.performance.navigation.type;\n\n const navigationEntry = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0);\n }\n }\n return navigationEntry ;\n};\n\nconst getNavigationEntry = () => {\n if (types.WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n types.WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return types.WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n\nexports.getNavigationEntry = getNavigationEntry;\n//# sourceMappingURL=getNavigationEntry.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst types = require('../../types.js');\nconst onHidden = require('./onHidden.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return types.WINDOW.document.visibilityState === 'hidden' && !types.WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = () => {\n // Update the time if/when the document becomes hidden.\n onHidden.onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nconst getVisibilityWatcher = (\n\n) => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexports.getVisibilityWatcher = getVisibilityWatcher;\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst types = require('../../types.js');\nconst generateUniqueID = require('./generateUniqueID.js');\nconst getActivationStart = require('./getActivationStart.js');\nconst getNavigationEntry = require('./getNavigationEntry.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry.getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (types.WINDOW.document.prerendering || getActivationStart.getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID.generateUniqueID(),\n navigationType,\n };\n};\n\nexports.initMetric = initMetric;\n//# sourceMappingURL=initMetric.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts,\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() );\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexports.observe = observe;\n//# sourceMappingURL=observe.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst types = require('../../types.js');\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst onHidden = (cb, once) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || types.WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n\nexports.onHidden = onHidden;\n//# sourceMappingURL=onHidden.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst utils$1 = require('./utils.js');\n\n/**\n * Configures global error listeners\n */\nfunction registerErrorInstrumentation() {\n utils.addInstrumentationHandler('error', errorCallback);\n utils.addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback() {\n const activeTransaction = utils$1.getActiveTransaction();\n if (activeTransaction) {\n const status = 'internal_error';\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\nexports.registerErrorInstrumentation = registerErrorInstrumentation;\n//# sourceMappingURL=errors.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst errors = require('./errors.js');\nconst idletransaction = require('./idletransaction.js');\nconst transaction = require('./transaction.js');\nconst utils$1 = require('./utils.js');\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders() {\n const scope = this.getScope();\n if (scope) {\n const span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(\n transaction,\n options,\n samplingContext,\n) {\n // nothing to do if tracing is not enabled\n if (!utils$1.hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate );\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (utils.isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n\n transactionContext,\n customSamplingContext,\n) {\n const client = this.getClient();\n const options = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction$1 = new transaction.Transaction(transactionContext, this);\n transaction$1 = sample(transaction$1, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction$1.sampled) {\n transaction$1.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n return transaction$1;\n}\n\n/**\n * Create new idle transaction.\n */\nfunction startIdleTransaction(\n hub,\n transactionContext,\n idleTimeout,\n finalTimeout,\n onScope,\n customSamplingContext,\n heartbeatInterval,\n) {\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {};\n\n let transaction = new idletransaction.IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n return transaction;\n}\n\n/**\n * @private\n */\nfunction _addTracingExtensions() {\n const carrier = core.getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations() {\n const carrier = core.getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping = {\n mongodb() {\n const integration = utils.dynamicRequire(module, './integrations/node/mongo')\n\n;\n return new integration.Mongo();\n },\n mongoose() {\n const integration = utils.dynamicRequire(module, './integrations/node/mongo')\n\n;\n return new integration.Mongo({ mongoose: true });\n },\n mysql() {\n const integration = utils.dynamicRequire(module, './integrations/node/mysql')\n\n;\n return new integration.Mysql();\n },\n pg() {\n const integration = utils.dynamicRequire(module, './integrations/node/postgres')\n\n;\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!utils.loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) ;\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nfunction addExtensionMethods() {\n _addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (utils.isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n\n // If an error happens globally, we should make sure transaction status is set to error.\n errors.registerErrorInstrumentation();\n}\n\nexports._addTracingExtensions = _addTracingExtensions;\nexports.addExtensionMethods = addExtensionMethods;\nexports.startIdleTransaction = startIdleTransaction;\n//# sourceMappingURL=hubextensions.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst span = require('./span.js');\nconst transaction = require('./transaction.js');\n\nconst DEFAULT_IDLE_TIMEOUT = 1000;\nconst DEFAULT_FINAL_TIMEOUT = 30000;\nconst DEFAULT_HEARTBEAT_INTERVAL = 5000;\n\n/**\n * @inheritDoc\n */\nclass IdleTransactionSpanRecorder extends span.SpanRecorder {\n constructor(\n _pushActivity,\n _popActivity,\n transactionSpanId,\n maxlen,\n ) {\n super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }\n\n /**\n * @inheritDoc\n */\n add(span) {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils.timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nclass IdleTransaction extends transaction.Transaction {\n // Activities store a list of active spans\n __init() {this.activities = {};}\n\n // Track state of activities in previous heartbeat\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n __init2() {this._heartbeatCounter = 0;}\n\n // We should not use heartbeat if we finished a transaction\n __init3() {this._finished = false;}\n\n __init4() {this._beforeFinishCallbacks = [];}\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n\n constructor(\n transactionContext,\n _idleHub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n _idleTimeout = DEFAULT_IDLE_TIMEOUT,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n _finalTimeout = DEFAULT_FINAL_TIMEOUT,\n _heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n _onScope = false,\n ) {\n super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;IdleTransaction.prototype.__init.call(this);IdleTransaction.prototype.__init2.call(this);IdleTransaction.prototype.__init3.call(this);IdleTransaction.prototype.__init4.call(this);\n if (_onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._startIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n finish(endTimestamp = utils.timestampWithMs()) {\n this._finished = true;\n this.activities = {};\n\n if (this.spanRecorder) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] flushing IdleTransaction');\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n registerBeforeFinishCallback(callback) {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n initSpanRecorder(maxlen) {\n if (!this.spanRecorder) {\n const pushActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idletimeout, if there is one\n */\n _cancelIdleTimeout() {\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n }\n }\n\n /**\n * Creates an idletimeout\n */\n _startIdleTimeout(endTimestamp) {\n this._cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n _pushActivity(spanId) {\n this._cancelIdleTimeout();\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n _popActivity(spanId) {\n if (this.activities[spanId]) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n const endTimestamp = utils.timestampWithMs() + this._idleTimeout / 1000;\n this._startIdleTimeout(endTimestamp);\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n _beat() {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n _pingHeartbeat() {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n\n/**\n * Reset transaction on scope to `undefined`\n */\nfunction clearActiveTransaction(hub) {\n const scope = hub.getScope();\n if (scope) {\n const transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n}\n\nexports.DEFAULT_FINAL_TIMEOUT = DEFAULT_FINAL_TIMEOUT;\nexports.DEFAULT_HEARTBEAT_INTERVAL = DEFAULT_HEARTBEAT_INTERVAL;\nexports.DEFAULT_IDLE_TIMEOUT = DEFAULT_IDLE_TIMEOUT;\nexports.IdleTransaction = IdleTransaction;\nexports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder;\n//# sourceMappingURL=idletransaction.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst hubextensions = require('./hubextensions.js');\nconst index = require('./integrations/index.js');\nconst browsertracing = require('./browser/browsertracing.js');\nconst request = require('./browser/request.js');\nconst span = require('./span.js');\nconst spanstatus = require('./spanstatus.js');\nconst transaction = require('./transaction.js');\nconst idletransaction = require('./idletransaction.js');\nconst utils$1 = require('./utils.js');\nconst utils = require('@sentry/utils');\n\n// Treeshakable guard to remove all code related to tracing\n\n// Guard for tree\nif (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {\n // We are patching the global object with our hub extension methods\n hubextensions.addExtensionMethods();\n}\n\nexports.addExtensionMethods = hubextensions.addExtensionMethods;\nexports.startIdleTransaction = hubextensions.startIdleTransaction;\nexports.Integrations = index;\nexports.BROWSER_TRACING_INTEGRATION_ID = browsertracing.BROWSER_TRACING_INTEGRATION_ID;\nexports.BrowserTracing = browsertracing.BrowserTracing;\nexports.defaultRequestInstrumentationOptions = request.defaultRequestInstrumentationOptions;\nexports.instrumentOutgoingRequests = request.instrumentOutgoingRequests;\nexports.Span = span.Span;\nexports.spanStatusfromHttpCode = span.spanStatusfromHttpCode;\nObject.defineProperty(exports, 'SpanStatus', {\n enumerable: true,\n get: () => spanstatus.SpanStatus\n});\nexports.Transaction = transaction.Transaction;\nexports.IdleTransaction = idletransaction.IdleTransaction;\nexports.getActiveTransaction = utils$1.getActiveTransaction;\nexports.hasTracingEnabled = utils$1.hasTracingEnabled;\nexports.TRACEPARENT_REGEXP = utils.TRACEPARENT_REGEXP;\nexports.extractTraceparentData = utils.extractTraceparentData;\nexports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst express = require('./node/express.js');\nconst postgres = require('./node/postgres.js');\nconst mysql = require('./node/mysql.js');\nconst mongo = require('./node/mongo.js');\nconst prisma = require('./node/prisma.js');\nconst graphql = require('./node/graphql.js');\nconst apollo = require('./node/apollo.js');\nconst browsertracing = require('../browser/browsertracing.js');\nrequire('@sentry/core');\nrequire('@sentry/utils');\n\n\n\nexports.Express = express.Express;\nexports.Postgres = postgres.Postgres;\nexports.Mysql = mysql.Mysql;\nexports.Mongo = mongo.Mongo;\nexports.Prisma = prisma.Prisma;\nexports.GraphQL = graphql.GraphQL;\nexports.Apollo = apollo.Apollo;\nexports.BrowserTracing = browsertracing.BrowserTracing;\n//# sourceMappingURL=index.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n/** Tracing integration for Apollo */\nclass Apollo {constructor() { Apollo.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Apollo';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Apollo.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Apollo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = utils.loadModule\n\n('apollo-server-core');\n\n if (!pkg) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Apollo Integration was unable to require apollo-server-core package.');\n return;\n }\n\n /**\n * Iterate over resolvers of the ApolloServer instance before schemas are constructed.\n */\n utils.fill(pkg.ApolloServerBase.prototype, 'constructSchema', function (orig) {\n return function () {\n if (!this.config.resolvers) {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n if (this.config.schema) {\n utils.logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.',\n );\n } else if (this.config.modules) {\n utils.logger.warn(\n 'Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property.',\n );\n }\n\n utils.logger.error('Skipping tracing as no resolvers found on the `ApolloServer` instance.');\n }\n\n return orig.call(this);\n }\n\n const resolvers = utils.arrayify(this.config.resolvers);\n\n this.config.resolvers = resolvers.map(model => {\n Object.keys(model).forEach(resolverGroupName => {\n Object.keys(model[resolverGroupName]).forEach(resolverName => {\n if (typeof model[resolverGroupName][resolverName] !== 'function') {\n return;\n }\n\n wrapResolver(model, resolverGroupName, resolverName, getCurrentHub);\n });\n });\n\n return model;\n });\n\n return orig.call(this);\n };\n });\n }\n}Apollo.__initStatic();\n\n/**\n * Wrap a single resolver which can be a parent of other resolvers and/or db operations.\n */\nfunction wrapResolver(\n model,\n resolverGroupName,\n resolverName,\n getCurrentHub,\n) {\n utils.fill(model[resolverGroupName], resolverName, function (orig) {\n return function ( ...args) {\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]);\n const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({\n description: `${resolverGroupName}.${resolverName}`,\n op: 'graphql.resolve',\n })]);\n\n const rv = orig.call(this, ...args);\n\n if (utils.isThenable(rv)) {\n return rv.then((res) => {\n _optionalChain([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]);\n return res;\n });\n }\n\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n\n return rv;\n };\n });\n}\n\nexports.Apollo = Apollo;\n//# sourceMappingURL=apollo.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\nclass Express {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Express';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Express.id;}\n\n /**\n * Express App instance\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {Express.prototype.__init.call(this);\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (!this._router) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Express Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n instrumentMiddlewares(this._router, this._methods);\n instrumentRouter(this._router );\n }\n}Express.__initStatic();\n\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\nfunction wrap(fn, method) {\n const arity = fn.length;\n\n switch (arity) {\n case 2: {\n return function ( req, res) {\n const transaction = res.__sentry_transaction;\n if (transaction) {\n const span = transaction.startChild({\n description: fn.name,\n op: `middleware.express.${method}`,\n });\n res.once('finish', () => {\n span.finish();\n });\n }\n return fn.call(this, req, res);\n };\n }\n case 3: {\n return function (\n\n req,\n res,\n next,\n ) {\n const transaction = res.__sentry_transaction;\n const span = _optionalChain([transaction, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({\n description: fn.name,\n op: `middleware.express.${method}`,\n })]);\n fn.call(this, req, res, function ( ...args) {\n _optionalChain([span, 'optionalAccess', _4 => _4.finish, 'call', _5 => _5()]);\n next.call(this, ...args);\n });\n };\n }\n case 4: {\n return function (\n\n err,\n req,\n res,\n next,\n ) {\n const transaction = res.__sentry_transaction;\n const span = _optionalChain([transaction, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({\n description: fn.name,\n op: `middleware.express.${method}`,\n })]);\n fn.call(this, err, req, res, function ( ...args) {\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n next.call(this, ...args);\n });\n };\n }\n default: {\n throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);\n }\n }\n}\n\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([], )\n * app.use([], , ...)\n * app.use([], ...[])\n */\nfunction wrapMiddlewareArgs(args, method) {\n return args.map((arg) => {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map((a) => {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n return a;\n });\n }\n\n return arg;\n });\n}\n\n/**\n * Patches original router to utilize our tracing functionality\n */\nfunction patchMiddleware(router, method) {\n const originalCallback = router[method];\n\n router[method] = function (...args) {\n return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));\n };\n\n return router;\n}\n\n/**\n * Patches original router methods\n */\nfunction instrumentMiddlewares(router, methods = []) {\n methods.forEach((method) => patchMiddleware(router, method));\n}\n\n/**\n * Patches the prototype of Express.Router to accumulate the resolved route\n * if a layer instance's `match` function was called and it returned a successful match.\n *\n * @see https://github.com/expressjs/express/blob/master/lib/router/index.js\n *\n * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router.\n */\nfunction instrumentRouter(appOrRouter) {\n // This is how we can distinguish between app and routers\n const isApp = 'settings' in appOrRouter;\n\n // In case the app's top-level router hasn't been initialized yet, we have to do it now\n if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) {\n appOrRouter.lazyrouter();\n }\n\n const router = isApp ? appOrRouter._router : appOrRouter;\n\n if (!router) {\n /*\n If we end up here, this means likely that this integration is used with Express 3 or Express 5.\n For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5,\n we'd need to make more changes to the routing instrumentation because the router is no longer part of\n the Express core package but maintained in its own package. The new router has different function\n signatures and works slightly differently, demanding more changes than just taking the router from\n `app.router` instead of `app._router`.\n @see https://github.com/pillarjs/router\n\n TODO: Proper Express 5 support\n */\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).');\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.debug('Routing instrumentation is currently only supported in Express 4.');\n return;\n }\n\n const routerProto = Object.getPrototypeOf(router) ;\n\n const originalProcessParams = routerProto.process_params;\n routerProto.process_params = function process_params(\n layer,\n called,\n req,\n res,\n done,\n ) {\n // Base case: We're in the first part of the URL (thus we start with the root '/')\n if (!req._reconstructedRoute) {\n req._reconstructedRoute = '';\n }\n\n // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route.\n const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer);\n\n if (layerRoutePath || isRegex || isArray) {\n req._hasParameters = true;\n }\n\n // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path\n const partialRoute = layerRoutePath || layer.path || '';\n\n // Normalize the partial route so that it doesn't contain leading or trailing slashes\n // and exclude empty or '*' wildcard routes.\n // The exclusion of '*' routes is our best effort to not \"pollute\" the transaction name\n // with interim handlers (e.g. ones that check authentication or do other middleware stuff).\n // We want to end up with the parameterized URL of the incoming request without any extraneous path segments.\n const finalPartialRoute = partialRoute\n .split('/')\n .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*')))\n .join('/');\n\n // If we found a valid partial URL, we append it to the reconstructed route\n if (finalPartialRoute && finalPartialRoute.length > 0) {\n // If the partial route is from a regex route, we append a '/' to close the regex\n req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`;\n }\n\n // Now we check if we are in the \"last\" part of the route. We determine this by comparing the\n // number of URL segments from the original URL to that of our reconstructed parameterized URL.\n // If we've reached our final destination, we update the transaction name.\n const urlLength = utils.getNumberOfUrlSegments(req.originalUrl || '') + numExtraSegments;\n const routeLength = utils.getNumberOfUrlSegments(req._reconstructedRoute);\n\n if (urlLength === routeLength) {\n if (!req._hasParameters) {\n if (req._reconstructedRoute !== req.originalUrl) {\n req._reconstructedRoute = req.originalUrl;\n }\n }\n\n const transaction = res.__sentry_transaction;\n if (transaction && transaction.metadata.source !== 'custom') {\n // If the request URL is '/' or empty, the reconstructed route will be empty.\n // Therefore, we fall back to setting the final route to '/' in this case.\n const finalRoute = req._reconstructedRoute || '/';\n\n transaction.setName(...utils.extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute }));\n }\n }\n\n return originalProcessParams.call(this, layer, called, req, res, done);\n };\n}\n\n/**\n * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`),\n * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\\/path[2-5]/, /path/:id]`). Additionally\n * returns extra information about the route, such as if the route is defined as regex or as an array.\n *\n * @param layer the layer to extract the stringified route from\n *\n * @returns an object containing the stringified route, a flag determining if the route was a regex\n * and the number of extra segments to the matched path that are additionally in the route,\n * if the route was an array (defaults to 0).\n */\nfunction getLayerRoutePathInfo(layer) {\n const lrp = _optionalChain([layer, 'access', _10 => _10.route, 'optionalAccess', _11 => _11.path]);\n\n const isRegex = utils.isRegExp(lrp);\n const isArray = Array.isArray(lrp);\n\n if (!lrp) {\n return { isRegex, isArray, numExtraSegments: 0 };\n }\n\n const numExtraSegments = isArray\n ? Math.max(getNumberOfArrayUrlSegments(lrp ) - utils.getNumberOfUrlSegments(layer.path || ''), 0)\n : 0;\n\n const layerRoutePath = getLayerRoutePathString(isArray, lrp);\n\n return { layerRoutePath, isRegex, isArray, numExtraSegments };\n}\n\n/**\n * Returns the number of URL segments in an array of routes\n *\n * Example: ['/api/test', /\\/api\\/post[0-9]/, '/users/:id/details`] -> 7\n */\nfunction getNumberOfArrayUrlSegments(routesArray) {\n return routesArray.reduce((accNumSegments, currentRoute) => {\n // array members can be a RegEx -> convert them toString\n return accNumSegments + utils.getNumberOfUrlSegments(currentRoute.toString());\n }, 0);\n}\n\n/**\n * Extracts and returns the stringified version of the layers route path\n * Handles route arrays (by joining the paths together) as well as RegExp and normal\n * string values (in the latter case the toString conversion is technically unnecessary but\n * it doesn't hurt us either).\n */\nfunction getLayerRoutePathString(isArray, lrp) {\n if (isArray) {\n return (lrp ).map(r => r.toString()).join(',');\n }\n return lrp && lrp.toString();\n}\n\nexports.Express = Express;\n//# sourceMappingURL=express.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n/** Tracing integration for graphql package */\nclass GraphQL {constructor() { GraphQL.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'GraphQL';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = GraphQL.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('GraphQL Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = utils.loadModule\n\n('graphql/execution/execute.js');\n\n if (!pkg) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('GraphQL Integration was unable to require graphql/execution package.');\n return;\n }\n\n utils.fill(pkg, 'execute', function (orig) {\n return function ( ...args) {\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]);\n\n const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({\n description: 'execute',\n op: 'graphql.execute',\n })]);\n\n _optionalChain([scope, 'optionalAccess', _6 => _6.setSpan, 'call', _7 => _7(span)]);\n\n const rv = orig.call(this, ...args);\n\n if (utils.isThenable(rv)) {\n return rv.then((res) => {\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n _optionalChain([scope, 'optionalAccess', _10 => _10.setSpan, 'call', _11 => _11(parentSpan)]);\n\n return res;\n });\n }\n\n _optionalChain([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]);\n _optionalChain([scope, 'optionalAccess', _14 => _14.setSpan, 'call', _15 => _15(parentSpan)]);\n return rv;\n };\n });\n }\n}GraphQL.__initStatic();\n\nexports.GraphQL = GraphQL;\n//# sourceMappingURL=graphql.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n// This allows us to use the same array for both defaults options and the type itself.\n// (note `as const` at the end to make it a union of string literal types (i.e. \"a\" | \"b\" | ... )\n// and not just a string[])\n\nconst OPERATIONS = [\n 'aggregate', // aggregate(pipeline, options, callback)\n 'bulkWrite', // bulkWrite(operations, options, callback)\n 'countDocuments', // countDocuments(query, options, callback)\n 'createIndex', // createIndex(fieldOrSpec, options, callback)\n 'createIndexes', // createIndexes(indexSpecs, options, callback)\n 'deleteMany', // deleteMany(filter, options, callback)\n 'deleteOne', // deleteOne(filter, options, callback)\n 'distinct', // distinct(key, query, options, callback)\n 'drop', // drop(options, callback)\n 'dropIndex', // dropIndex(indexName, options, callback)\n 'dropIndexes', // dropIndexes(options, callback)\n 'estimatedDocumentCount', // estimatedDocumentCount(options, callback)\n 'find', // find(query, options, callback)\n 'findOne', // findOne(query, options, callback)\n 'findOneAndDelete', // findOneAndDelete(filter, options, callback)\n 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)\n 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)\n 'indexes', // indexes(options, callback)\n 'indexExists', // indexExists(indexes, options, callback)\n 'indexInformation', // indexInformation(options, callback)\n 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)\n 'insertMany', // insertMany(docs, options, callback)\n 'insertOne', // insertOne(doc, options, callback)\n 'isCapped', // isCapped(options, callback)\n 'mapReduce', // mapReduce(map, reduce, options, callback)\n 'options', // options(options, callback)\n 'parallelCollectionScan', // parallelCollectionScan(options, callback)\n 'rename', // rename(newName, options, callback)\n 'replaceOne', // replaceOne(filter, doc, options, callback)\n 'stats', // stats(options, callback)\n 'updateMany', // updateMany(filter, update, options, callback)\n 'updateOne', // updateOne(filter, update, options, callback)\n] ;\n\n// All of the operations above take `options` and `callback` as their final parameters, but some of them\n// take additional parameters as well. For those operations, this is a map of\n// { : [] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\nconst OPERATION_SIGNATURES\n\n = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update'],\n};\n\nfunction isCursor(maybeCursor) {\n return maybeCursor && typeof maybeCursor === 'object' && maybeCursor.once && typeof maybeCursor.once === 'function';\n}\n\n/** Tracing integration for mongo package */\nclass Mongo {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Mongo';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Mongo.id;}\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {Mongo.prototype.__init.call(this);\n this._operations = Array.isArray(options.operations) ? options.operations : (OPERATIONS );\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Mongo Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n const pkg = utils.loadModule(moduleName);\n\n if (!pkg) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(`Mongo Integration was unable to require \\`${moduleName}\\` package.`);\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n }\n\n /**\n * Patches original collection methods\n */\n _instrumentOperations(collection, operations, getCurrentHub) {\n operations.forEach((operation) => this._patchOperation(collection, operation, getCurrentHub));\n }\n\n /**\n * Patches original collection to utilize our tracing functionality\n */\n _patchOperation(collection, operation, getCurrentHub) {\n if (!(operation in collection.prototype)) return;\n\n const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n utils.fill(collection.prototype, operation, function (orig) {\n return function ( ...args) {\n const lastArg = args[args.length - 1];\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]);\n\n // Check if the operation was passed a callback. (mapReduce requires a different check, as\n // its (non-callback) arguments can also be functions.)\n if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {\n const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5(getSpanContext(this, operation, args))]);\n const maybePromiseOrCursor = orig.call(this, ...args);\n\n if (utils.isThenable(maybePromiseOrCursor)) {\n return maybePromiseOrCursor.then((res) => {\n _optionalChain([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]);\n return res;\n });\n }\n // If the operation returns a Cursor\n // we need to attach a listener to it to finish the span when the cursor is closed.\n else if (isCursor(maybePromiseOrCursor)) {\n const cursor = maybePromiseOrCursor ;\n\n try {\n cursor.once('close', () => {\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n });\n } catch (e) {\n // If the cursor is already closed, `once` will throw an error. In that case, we can\n // finish the span immediately.\n _optionalChain([span, 'optionalAccess', _10 => _10.finish, 'call', _11 => _11()]);\n }\n\n return cursor;\n } else {\n _optionalChain([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]);\n return maybePromiseOrCursor;\n }\n }\n\n const span = _optionalChain([parentSpan, 'optionalAccess', _14 => _14.startChild, 'call', _15 => _15(getSpanContext(this, operation, args.slice(0, -1)))]);\n\n return orig.call(this, ...args.slice(0, -1), function (err, result) {\n _optionalChain([span, 'optionalAccess', _16 => _16.finish, 'call', _17 => _17()]);\n lastArg(err, result);\n });\n };\n });\n }\n\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n _getSpanContextFromOperationArguments(\n collection,\n operation,\n args,\n ) {\n const data = {\n collectionName: collection.collectionName,\n dbName: collection.dbName,\n namespace: collection.namespace,\n };\n const spanContext = {\n op: 'db',\n description: operation,\n data,\n };\n\n // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n const signature = OPERATION_SIGNATURES[operation];\n const shouldDescribe = Array.isArray(this._describeOperations)\n ? this._describeOperations.includes(operation)\n : this._describeOperations;\n\n if (!signature || !shouldDescribe) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n const [map, reduce] = args ;\n data[signature[0]] = typeof map === 'string' ? map : map.name || '';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '';\n } else {\n for (let i = 0; i < signature.length; i++) {\n data[signature[i]] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {\n // no-empty\n }\n\n return spanContext;\n }\n}Mongo.__initStatic();\n\nexports.Mongo = Mongo;\n//# sourceMappingURL=mongo.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n/** Tracing integration for node-mysql package */\nclass Mysql {constructor() { Mysql.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Mysql';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Mysql.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Mysql Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = utils.loadModule('mysql/lib/Connection.js');\n\n if (!pkg) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n }\n\n // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n utils.fill(pkg, 'createQuery', function (orig) {\n return function ( options, values, callback) {\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]);\n const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({\n description: typeof options === 'string' ? options : (options ).sql,\n op: 'db',\n })]);\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function (err, result, fields) {\n _optionalChain([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]);\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function (err, result, fields) {\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n values(err, result, fields);\n });\n }\n\n return orig.call(this, options, values, callback);\n };\n });\n }\n}Mysql.__initStatic();\n\nexports.Mysql = Mysql;\n//# sourceMappingURL=mysql.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\n/** Tracing integration for node-postgres package */\nclass Postgres {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Postgres';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Postgres.id;}\n\n constructor(options = {}) {Postgres.prototype.__init.call(this);\n this._usePgNative = !!options.usePgNative;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Postgres Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n const pkg = utils.loadModule('pg');\n\n if (!pkg) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n if (this._usePgNative && !_optionalChain([pkg, 'access', _2 => _2.native, 'optionalAccess', _3 => _3.Client])) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(\"Postgres Integration was unable to access 'pg-native' bindings.\");\n return;\n }\n\n const { Client } = this._usePgNative ? pkg.native : pkg;\n\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n utils.fill(Client.prototype, 'query', function (orig) {\n return function ( config, values, callback) {\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _4 => _4.getSpan, 'call', _5 => _5()]);\n const span = _optionalChain([parentSpan, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({\n description: typeof config === 'string' ? config : (config ).text,\n op: 'db',\n })]);\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function (err, result) {\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function (err, result) {\n _optionalChain([span, 'optionalAccess', _10 => _10.finish, 'call', _11 => _11()]);\n values(err, result);\n });\n }\n\n const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (utils.isThenable(rv)) {\n return rv.then((res) => {\n _optionalChain([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]);\n return res;\n });\n }\n\n _optionalChain([span, 'optionalAccess', _14 => _14.finish, 'call', _15 => _15()]);\n return rv;\n };\n });\n }\n}Postgres.__initStatic();\n\nexports.Postgres = Postgres;\n//# sourceMappingURL=postgres.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\nconst nodeUtils = require('./utils/node-utils.js');\n\nfunction isValidPrismaClient(possibleClient) {\n return possibleClient && !!(possibleClient )['$use'];\n}\n\n/** Tracing integration for @prisma/client package */\nclass Prisma {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Prisma';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Prisma.id;}\n\n /**\n * Prisma ORM Client Instance\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {Prisma.prototype.__init.call(this);\n if (isValidPrismaClient(options.client)) {\n this._client = options.client;\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.warn(\n `Unsupported Prisma client provided to PrismaIntegration. Provided client: ${JSON.stringify(options.client)}`,\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n if (!this._client) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('PrismaIntegration is missing a Prisma Client Instance');\n return;\n }\n\n if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('Prisma Integration is skipped because of instrumenter configuration.');\n return;\n }\n\n this._client.$use((params, next) => {\n const scope = getCurrentHub().getScope();\n const parentSpan = _optionalChain([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]);\n\n const action = params.action;\n const model = params.model;\n\n const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({\n description: model ? `${model} ${action}` : action,\n op: 'db.sql.prisma',\n })]);\n\n const rv = next(params);\n\n if (utils.isThenable(rv)) {\n return rv.then((res) => {\n _optionalChain([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]);\n return res;\n });\n }\n\n _optionalChain([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]);\n return rv;\n });\n }\n}Prisma.__initStatic();\n\nexports.Prisma = Prisma;\n//# sourceMappingURL=prisma.js.map\n","var {\n _optionalChain\n} = require('@sentry/utils/cjs/buildPolyfills');\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Check if Sentry auto-instrumentation should be disabled.\n *\n * @param getCurrentHub A method to fetch the current hub\n * @returns boolean\n */\nfunction shouldDisableAutoInstrumentation(getCurrentHub) {\n const clientOptions = _optionalChain([getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]);\n const instrumenter = _optionalChain([clientOptions, 'optionalAccess', _6 => _6.instrumenter]) || 'sentry';\n\n return instrumenter !== 'sentry';\n}\n\nexports.shouldDisableAutoInstrumentation = shouldDisableAutoInstrumentation;\n//# sourceMappingURL=node-utils.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst utils = require('@sentry/utils');\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nclass SpanRecorder {\n __init() {this.spans = [];}\n\n constructor(maxlen = 1000) {SpanRecorder.prototype.__init.call(this);\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n add(span) {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nclass Span {\n /**\n * @inheritDoc\n */\n __init2() {this.traceId = utils.uuid4();}\n\n /**\n * @inheritDoc\n */\n __init3() {this.spanId = utils.uuid4().substring(16);}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Internal keeper of the status\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * Timestamp in seconds when the span was created.\n */\n __init4() {this.startTimestamp = utils.timestampWithMs();}\n\n /**\n * Timestamp in seconds when the span ended.\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n __init5() {this.tags = {};}\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n __init6() {this.data = {};}\n\n /**\n * List of spans that were finalized\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * The instrumenter that created this span.\n */\n __init7() {this.instrumenter = 'sentry';}\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext) {Span.prototype.__init2.call(this);Span.prototype.__init3.call(this);Span.prototype.__init4.call(this);Span.prototype.__init5.call(this);Span.prototype.__init6.call(this);Span.prototype.__init7.call(this);\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n if (spanContext.instrumenter) {\n this.instrumenter = spanContext.instrumenter;\n }\n }\n\n /**\n * @inheritDoc\n */\n startChild(\n spanContext,\n ) {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n utils.logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n setData(key, value) {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setHttpStatus(httpStatus) {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n isSuccess() {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n if (\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n utils.logger.log((logMessage ).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils.timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n toTraceparent() {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n return utils.dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(spanContext) {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getTraceContext() {\n return utils.dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n toJSON()\n\n {\n return utils.dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nfunction spanStatusfromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\nexports.Span = Span;\nexports.SpanRecorder = SpanRecorder;\nexports.spanStatusfromHttpCode = spanStatusfromHttpCode;\n//# sourceMappingURL=span.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/** The status of an Span.\n *\n * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type\n */\n// eslint-disable-next-line import/export\nexports.SpanStatus = void 0; (function (SpanStatus) {\n /** The operation completed successfully. */\n const Ok = 'ok'; SpanStatus[\"Ok\"] = Ok;\n /** Deadline expired before operation could complete. */\n const DeadlineExceeded = 'deadline_exceeded'; SpanStatus[\"DeadlineExceeded\"] = DeadlineExceeded;\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n const Unauthenticated = 'unauthenticated'; SpanStatus[\"Unauthenticated\"] = Unauthenticated;\n /** 403 Forbidden */\n const PermissionDenied = 'permission_denied'; SpanStatus[\"PermissionDenied\"] = PermissionDenied;\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n const NotFound = 'not_found'; SpanStatus[\"NotFound\"] = NotFound;\n /** 429 Too Many Requests */\n const ResourceExhausted = 'resource_exhausted'; SpanStatus[\"ResourceExhausted\"] = ResourceExhausted;\n /** Client specified an invalid argument. 4xx. */\n const InvalidArgument = 'invalid_argument'; SpanStatus[\"InvalidArgument\"] = InvalidArgument;\n /** 501 Not Implemented */\n const Unimplemented = 'unimplemented'; SpanStatus[\"Unimplemented\"] = Unimplemented;\n /** 503 Service Unavailable */\n const Unavailable = 'unavailable'; SpanStatus[\"Unavailable\"] = Unavailable;\n /** Other/generic 5xx. */\n const InternalError = 'internal_error'; SpanStatus[\"InternalError\"] = InternalError;\n /** Unknown. Any non-standard HTTP status code. */\n const UnknownError = 'unknown_error'; SpanStatus[\"UnknownError\"] = UnknownError;\n /** The operation was cancelled (typically by the user). */\n const Cancelled = 'cancelled'; SpanStatus[\"Cancelled\"] = Cancelled;\n /** Already exists (409) */\n const AlreadyExists = 'already_exists'; SpanStatus[\"AlreadyExists\"] = AlreadyExists;\n /** Operation was rejected because the system is not in a state required for the operation's */\n const FailedPrecondition = 'failed_precondition'; SpanStatus[\"FailedPrecondition\"] = FailedPrecondition;\n /** The operation was aborted, typically due to a concurrency issue. */\n const Aborted = 'aborted'; SpanStatus[\"Aborted\"] = Aborted;\n /** Operation was attempted past the valid range. */\n const OutOfRange = 'out_of_range'; SpanStatus[\"OutOfRange\"] = OutOfRange;\n /** Unrecoverable data loss or corruption */\n const DataLoss = 'data_loss'; SpanStatus[\"DataLoss\"] = DataLoss;\n})(exports.SpanStatus || (exports.SpanStatus = {}));\n//# sourceMappingURL=spanstatus.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\nconst span = require('./span.js');\n\n/** JSDoc */\nclass Transaction extends span.Span {\n\n /**\n * The reference to the current hub.\n */\n\n __init() {this._measurements = {};}\n\n __init2() {this._contexts = {};}\n\n __init3() {this._frozenDynamicSamplingContext = undefined;}\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(transactionContext, hub) {\n super(transactionContext);Transaction.prototype.__init.call(this);Transaction.prototype.__init2.call(this);Transaction.prototype.__init3.call(this);\n this._hub = hub || core.getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n changes: [],\n propagations: 0,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n get name() {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n set name(newName) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n setName(name, source = 'custom') {\n // `source` could change without the name changing if we discover that an unparameterized route is actually\n // parameterized by virtue of having no parameters in its path\n if (name !== this.name || source !== this.metadata.source) {\n this.metadata.changes.push({\n // log previous source\n source: this.metadata.source,\n timestamp: utils.timestampInSeconds(),\n propagations: this.metadata.propagations,\n });\n }\n\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n initSpanRecorder(maxlen = 1000) {\n if (!this.spanRecorder) {\n this.spanRecorder = new span.SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n setMeasurement(name, value, unit = '') {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n setMetadata(newMetadata) {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n const client = this._hub.getClient();\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev, current) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n changes: metadata.changes,\n propagations: metadata.propagations,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n utils.logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n const spanContext = super.toContext();\n\n return utils.dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(transactionContext) {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n getDynamicSamplingContext() {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub = this._hub || core.getCurrentHub();\n const client = hub && hub.getClient();\n\n if (!client) return {};\n\n const { environment, release } = client.getOptions() || {};\n const { publicKey: public_key } = client.getDsn() || {};\n\n const maybeSampleRate = this.metadata.sampleRate;\n const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;\n\n const scope = hub.getScope();\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const source = this.metadata.source;\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const transaction = source && source !== 'url' ? this.name : undefined;\n\n const dsc = utils.dropUndefinedKeys({\n environment,\n release,\n transaction,\n user_segment,\n public_key,\n trace_id: this.traceId,\n sample_rate,\n });\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n return dsc;\n }\n}\n\nexports.Transaction = Transaction;\n//# sourceMappingURL=transaction.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst core = require('@sentry/core');\nconst utils = require('@sentry/utils');\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n const client = core.getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && ('tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\n/** Grabs active transaction off scope, if any */\nfunction getActiveTransaction(maybeHub) {\n const hub = maybeHub || core.getCurrentHub();\n const scope = hub.getScope();\n return scope && (scope.getTransaction() );\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\nexports.TRACEPARENT_REGEXP = utils.TRACEPARENT_REGEXP;\nexports.extractTraceparentData = utils.extractTraceparentData;\nexports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment;\nexports.getActiveTransaction = getActiveTransaction;\nexports.hasTracingEnabled = hasTracingEnabled;\nexports.msToSec = msToSec;\n//# sourceMappingURL=utils.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\nconst logger = require('./logger.js');\n\nconst BAGGAGE_HEADER_NAME = 'baggage';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n if (!is.isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexports.BAGGAGE_HEADER_NAME = BAGGAGE_HEADER_NAME;\nexports.MAX_BAGGAGE_STRING_LENGTH = MAX_BAGGAGE_STRING_LENGTH;\nexports.SENTRY_BAGGAGE_KEY_PREFIX = SENTRY_BAGGAGE_KEY_PREFIX;\nexports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = SENTRY_BAGGAGE_KEY_PREFIX_REGEX;\nexports.baggageHeaderToDynamicSamplingContext = baggageHeaderToDynamicSamplingContext;\nexports.dynamicSamplingContextToSentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader;\n//# sourceMappingURL=baggage.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\nconst worldwide = require('./worldwide.js');\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = worldwide.getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && is.isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\nexports.getDomElement = getDomElement;\nexports.getLocationHref = getLocationHref;\nexports.htmlTreeAsString = htmlTreeAsString;\n//# sourceMappingURL=browser.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst _nullishCoalesce = require('./_nullishCoalesce.js');\n\n// adapted from Sucrase (https://github.com/alangpierce/sucrase)\n\n/**\n * Polyfill for the nullish coalescing operator (`??`), when used in situations where at least one of the values is the\n * result of an async operation.\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nasync function _asyncNullishCoalesce(lhs, rhsFn) {\n return _nullishCoalesce._nullishCoalesce(lhs, rhsFn);\n}\n\n// Sucrase version:\n// async function _asyncNullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return await rhsFn();\n// }\n// }\n\nexports._asyncNullishCoalesce = _asyncNullishCoalesce;\n//# sourceMappingURL=_asyncNullishCoalesce.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, for situations in which at least one part of the expression is async.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nasync function _asyncOptionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = await fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = await fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version:\n// async function _asyncOptionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = await fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = await fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n\nexports._asyncOptionalChain = _asyncOptionalChain;\n//# sourceMappingURL=_asyncOptionalChain.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst _asyncOptionalChain = require('./_asyncOptionalChain.js');\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, in cases where the value of the expression is to be deleted.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable\n * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which\n * case `false`.\n */\nasync function _asyncOptionalChainDelete(ops) {\n const result = (await _asyncOptionalChain._asyncOptionalChain(ops)) ;\n // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case,\n // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in\n // which case we return whatever the `delete` returned, which will be a boolean.\n return result == null ? true : (result );\n}\n\n// Sucrase version:\n// async function asyncOptionalChainDelete(ops) {\n// const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);\n// return result == null ? true : result;\n// }\n\nexports._asyncOptionalChainDelete = _asyncOptionalChainDelete;\n//# sourceMappingURL=_asyncOptionalChainDelete.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Copy a property from the given object into `exports`, under the given name.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param obj The object containing the property to copy.\n * @param localName The name under which to export the property\n * @param importedName The name under which the property lives in `obj`\n */\nfunction _createNamedExportFrom(obj, localName, importedName) {\n exports[localName] = obj[importedName];\n}\n\n// Sucrase version:\n// function _createNamedExportFrom(obj, localName, importedName) {\n// Object.defineProperty(exports, localName, {enumerable: true, get: () => obj[importedName]});\n// }\n\nexports._createNamedExportFrom = _createNamedExportFrom;\n//# sourceMappingURL=_createNamedExportFrom.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Copy properties from an object into `exports`.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param obj The object containing the properties to copy.\n */\nfunction _createStarExport(obj) {\n Object.keys(obj)\n .filter(key => key !== 'default' && key !== '__esModule' && !(key in exports))\n .forEach(key => (exports[key] = obj[key]));\n}\n\n// Sucrase version:\n// function _createStarExport(obj) {\n// Object.keys(obj)\n// .filter(key => key !== 'default' && key !== '__esModule')\n// .forEach(key => {\n// if (exports.hasOwnProperty(key)) {\n// return;\n// }\n// Object.defineProperty(exports, key, { enumerable: true, get: () => obj[key] });\n// });\n// }\n\nexports._createStarExport = _createStarExport;\n//# sourceMappingURL=_createStarExport.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Unwraps a module if it has been wrapped in an object under the key `default`.\n *\n * Adapted from Rollup (https://github.com/rollup/rollup)\n *\n * @param requireResult The result of calling `require` on a module\n * @returns The full module, unwrapped if necessary.\n */\nfunction _interopDefault$1(requireResult) {\n return requireResult.__esModule ? (requireResult.default ) : requireResult;\n}\n\n// Rollup version:\n// function _interopDefault(e) {\n// return e && e.__esModule ? e['default'] : e;\n// }\n\nexports._interopDefault = _interopDefault$1;\n//# sourceMappingURL=_interopDefault.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Adds a self-referential `default` property to CJS modules which aren't the result of transpilation from ESM modules.\n *\n * Adapted from Rollup (https://github.com/rollup/rollup)\n *\n * @param requireResult The result of calling `require` on a module\n * @returns Either `requireResult` or a copy of `requireResult` with an added self-referential `default` property\n */\nfunction _interopNamespace$1(requireResult) {\n return requireResult.__esModule ? requireResult : { ...requireResult, default: requireResult };\n}\n\n// Rollup version (with `output.externalLiveBindings` and `output.freeze` both set to false)\n// function _interopNamespace(e) {\n// if (e && e.__esModule) return e;\n// var n = Object.create(null);\n// if (e) {\n// for (var k in e) {\n// n[k] = e[k];\n// }\n// }\n// n[\"default\"] = e;\n// return n;\n// }\n\nexports._interopNamespace = _interopNamespace$1;\n//# sourceMappingURL=_interopNamespace.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Wrap a module in an object, as the value under the key `default`.\n *\n * Adapted from Rollup (https://github.com/rollup/rollup)\n *\n * @param requireResult The result of calling `require` on a module\n * @returns An object containing the key-value pair (`default`, `requireResult`)\n */\nfunction _interopNamespaceDefaultOnly$1(requireResult) {\n return {\n __proto__: null,\n default: requireResult,\n };\n}\n\n// Rollup version\n// function _interopNamespaceDefaultOnly(e) {\n// return {\n// __proto__: null,\n// 'default': e\n// };\n// }\n\nexports._interopNamespaceDefaultOnly = _interopNamespaceDefaultOnly$1;\n//# sourceMappingURL=_interopNamespaceDefaultOnly.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Wraps modules which aren't the result of transpiling an ESM module in an object under the key `default`\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param requireResult The result of calling `require` on a module\n * @returns `requireResult` or `requireResult` wrapped in an object, keyed as `default`\n */\nfunction _interopRequireDefault(requireResult) {\n return requireResult.__esModule ? requireResult : { default: requireResult };\n}\n\n// Sucrase version\n// function _interopRequireDefault(obj) {\n// return obj && obj.__esModule ? obj : { default: obj };\n// }\n\nexports._interopRequireDefault = _interopRequireDefault;\n//# sourceMappingURL=_interopRequireDefault.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Adds a `default` property to CJS modules which aren't the result of transpilation from ESM modules.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param requireResult The result of calling `require` on a module\n * @returns Either `requireResult` or a copy of `requireResult` with an added self-referential `default` property\n */\nfunction _interopRequireWildcard(requireResult) {\n return requireResult.__esModule ? requireResult : { ...requireResult, default: requireResult };\n}\n\n// Sucrase version\n// function _interopRequireWildcard(obj) {\n// if (obj && obj.__esModule) {\n// return obj;\n// } else {\n// var newObj = {};\n// if (obj != null) {\n// for (var key in obj) {\n// if (Object.prototype.hasOwnProperty.call(obj, key)) {\n// newObj[key] = obj[key];\n// }\n// }\n// }\n// newObj.default = obj;\n// return newObj;\n// }\n// }\n\nexports._interopRequireWildcard = _interopRequireWildcard;\n//# sourceMappingURL=_interopRequireWildcard.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Polyfill for the nullish coalescing operator (`??`).\n *\n * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the\n * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n *\n * @param lhs The value of the expression to the left of the `??`\n * @param rhsFn A function returning the value of the expression to the right of the `??`\n * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value\n */\nfunction _nullishCoalesce(lhs, rhsFn) {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}\n\n// Sucrase version:\n// function _nullishCoalesce(lhs, rhsFn) {\n// if (lhs != null) {\n// return lhs;\n// } else {\n// return rhsFn();\n// }\n// }\n\nexports._nullishCoalesce = _nullishCoalesce;\n//# sourceMappingURL=_nullishCoalesce.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nfunction _optionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n\nexports._optionalChain = _optionalChain;\n//# sourceMappingURL=_optionalChain.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst _optionalChain = require('./_optionalChain.js');\n\n/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions, in cases where the value of the expression is to be deleted.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See\n * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable\n * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which\n * case `false`.\n */\nfunction _optionalChainDelete(ops) {\n const result = _optionalChain._optionalChain(ops) ;\n // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case,\n // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in\n // which case we return whatever the `delete` returned, which will be a boolean.\n return result == null ? true : result;\n}\n\n// Sucrase version:\n// function _optionalChainDelete(ops) {\n// const result = _optionalChain(ops);\n// // by checking for loose equality to `null`, we catch both `null` and `undefined`\n// return result == null ? true : result;\n// }\n\nexports._optionalChainDelete = _optionalChainDelete;\n//# sourceMappingURL=_optionalChainDelete.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst _asyncNullishCoalesce = require('./_asyncNullishCoalesce.js');\nconst _asyncOptionalChain = require('./_asyncOptionalChain.js');\nconst _asyncOptionalChainDelete = require('./_asyncOptionalChainDelete.js');\nconst _createNamedExportFrom = require('./_createNamedExportFrom.js');\nconst _createStarExport = require('./_createStarExport.js');\nconst _interopDefault$1 = require('./_interopDefault.js');\nconst _interopNamespace$1 = require('./_interopNamespace.js');\nconst _interopNamespaceDefaultOnly$1 = require('./_interopNamespaceDefaultOnly.js');\nconst _interopRequireDefault = require('./_interopRequireDefault.js');\nconst _interopRequireWildcard = require('./_interopRequireWildcard.js');\nconst _nullishCoalesce = require('./_nullishCoalesce.js');\nconst _optionalChain = require('./_optionalChain.js');\nconst _optionalChainDelete = require('./_optionalChainDelete.js');\n\n\n\nexports._asyncNullishCoalesce = _asyncNullishCoalesce._asyncNullishCoalesce;\nexports._asyncOptionalChain = _asyncOptionalChain._asyncOptionalChain;\nexports._asyncOptionalChainDelete = _asyncOptionalChainDelete._asyncOptionalChainDelete;\nexports._createNamedExportFrom = _createNamedExportFrom._createNamedExportFrom;\nexports._createStarExport = _createStarExport._createStarExport;\nexports._interopDefault = _interopDefault$1._interopDefault;\nexports._interopNamespace = _interopNamespace$1._interopNamespace;\nexports._interopNamespaceDefaultOnly = _interopNamespaceDefaultOnly$1._interopNamespaceDefaultOnly;\nexports._interopRequireDefault = _interopRequireDefault._interopRequireDefault;\nexports._interopRequireWildcard = _interopRequireWildcard._interopRequireWildcard;\nexports._nullishCoalesce = _nullishCoalesce._nullishCoalesce;\nexports._optionalChain = _optionalChain._optionalChain;\nexports._optionalChainDelete = _optionalChainDelete._optionalChainDelete;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst envelope = require('./envelope.js');\nconst time = require('./time.js');\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || time.dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return envelope.createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexports.createClientReportEnvelope = createClientReportEnvelope;\n//# sourceMappingURL=clientreport.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst error = require('./error.js');\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new error.SentryError(`Invalid Sentry Dsn: ${str}`);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n return;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n requiredComponents.forEach(component => {\n if (!dsn[component]) {\n throw new error.SentryError(`Invalid Sentry Dsn: ${component} missing`);\n }\n });\n\n if (!projectId.match(/^\\d+$/)) {\n throw new error.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n }\n\n if (!isValidProtocol(protocol)) {\n throw new error.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n throw new error.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`);\n }\n\n return true;\n}\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n validateDsn(components);\n return components;\n}\n\nexports.dsnFromString = dsnFromString;\nexports.dsnToString = dsnToString;\nexports.makeDsn = makeDsn;\n//# sourceMappingURL=dsn.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // @ts-ignore \"npm\" is injected by rollup during build process\n return \"npm\";\n}\n\nexports.getSDKSource = getSDKSource;\nexports.isBrowserBundle = isBrowserBundle;\n//# sourceMappingURL=env.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst dsn = require('./dsn.js');\nconst normalize = require('./normalize.js');\nconst object = require('./object.js');\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n envelopeItems.forEach((envelopeItem) => {\n const envelopeItemType = envelopeItem[0].type;\n callback(envelopeItem, envelopeItemType);\n });\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input, textEncoder) {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope, textEncoder) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize.normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(\n env,\n textEncoder,\n textDecoder,\n) {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(\n attachment,\n textEncoder,\n) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n object.dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn$1,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsn.dsnToString(dsn$1) }),\n ...(event.type === 'transaction' &&\n dynamicSamplingContext && {\n trace: object.dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexports.addItemToEnvelope = addItemToEnvelope;\nexports.createAttachmentEnvelopeItem = createAttachmentEnvelopeItem;\nexports.createEnvelope = createEnvelope;\nexports.createEventEnvelopeHeaders = createEventEnvelopeHeaders;\nexports.envelopeItemTypeToDataCategory = envelopeItemTypeToDataCategory;\nexports.forEachEnvelopeItem = forEachEnvelopeItem;\nexports.getSdkMetadataForEnvelopeHeader = getSdkMetadataForEnvelopeHeader;\nexports.parseEnvelope = parseEnvelope;\nexports.serializeEnvelope = serializeEnvelope;\n//# sourceMappingURL=envelope.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor( message, logLevel = 'warn') {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexports.SentryError = SentryError;\n//# sourceMappingURL=error.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst browser = require('./browser.js');\nconst dsn = require('./dsn.js');\nconst error = require('./error.js');\nconst worldwide = require('./worldwide.js');\nconst instrument = require('./instrument.js');\nconst is = require('./is.js');\nconst logger = require('./logger.js');\nconst memo = require('./memo.js');\nconst misc = require('./misc.js');\nconst node = require('./node.js');\nconst normalize = require('./normalize.js');\nconst object = require('./object.js');\nconst path = require('./path.js');\nconst promisebuffer = require('./promisebuffer.js');\nconst requestdata = require('./requestdata.js');\nconst severity = require('./severity.js');\nconst stacktrace = require('./stacktrace.js');\nconst string = require('./string.js');\nconst supports = require('./supports.js');\nconst syncpromise = require('./syncpromise.js');\nconst time = require('./time.js');\nconst tracing = require('./tracing.js');\nconst env = require('./env.js');\nconst envelope = require('./envelope.js');\nconst clientreport = require('./clientreport.js');\nconst ratelimit = require('./ratelimit.js');\nconst baggage = require('./baggage.js');\nconst url = require('./url.js');\n\n\n\nexports.getDomElement = browser.getDomElement;\nexports.getLocationHref = browser.getLocationHref;\nexports.htmlTreeAsString = browser.htmlTreeAsString;\nexports.dsnFromString = dsn.dsnFromString;\nexports.dsnToString = dsn.dsnToString;\nexports.makeDsn = dsn.makeDsn;\nexports.SentryError = error.SentryError;\nexports.GLOBAL_OBJ = worldwide.GLOBAL_OBJ;\nexports.getGlobalObject = worldwide.getGlobalObject;\nexports.getGlobalSingleton = worldwide.getGlobalSingleton;\nexports.addInstrumentationHandler = instrument.addInstrumentationHandler;\nexports.isDOMError = is.isDOMError;\nexports.isDOMException = is.isDOMException;\nexports.isElement = is.isElement;\nexports.isError = is.isError;\nexports.isErrorEvent = is.isErrorEvent;\nexports.isEvent = is.isEvent;\nexports.isInstanceOf = is.isInstanceOf;\nexports.isNaN = is.isNaN;\nexports.isPlainObject = is.isPlainObject;\nexports.isPrimitive = is.isPrimitive;\nexports.isRegExp = is.isRegExp;\nexports.isString = is.isString;\nexports.isSyntheticEvent = is.isSyntheticEvent;\nexports.isThenable = is.isThenable;\nexports.CONSOLE_LEVELS = logger.CONSOLE_LEVELS;\nexports.consoleSandbox = logger.consoleSandbox;\nObject.defineProperty(exports, 'logger', {\n\tenumerable: true,\n\tget: () => logger.logger\n});\nexports.memoBuilder = memo.memoBuilder;\nexports.addContextToFrame = misc.addContextToFrame;\nexports.addExceptionMechanism = misc.addExceptionMechanism;\nexports.addExceptionTypeValue = misc.addExceptionTypeValue;\nexports.arrayify = misc.arrayify;\nexports.checkOrSetAlreadyCaught = misc.checkOrSetAlreadyCaught;\nexports.getEventDescription = misc.getEventDescription;\nexports.parseSemver = misc.parseSemver;\nexports.uuid4 = misc.uuid4;\nexports.dynamicRequire = node.dynamicRequire;\nexports.isNodeEnv = node.isNodeEnv;\nexports.loadModule = node.loadModule;\nexports.normalize = normalize.normalize;\nexports.normalizeToSize = normalize.normalizeToSize;\nexports.walk = normalize.walk;\nexports.addNonEnumerableProperty = object.addNonEnumerableProperty;\nexports.convertToPlainObject = object.convertToPlainObject;\nexports.dropUndefinedKeys = object.dropUndefinedKeys;\nexports.extractExceptionKeysForMessage = object.extractExceptionKeysForMessage;\nexports.fill = object.fill;\nexports.getOriginalFunction = object.getOriginalFunction;\nexports.markFunctionWrapped = object.markFunctionWrapped;\nexports.objectify = object.objectify;\nexports.urlEncode = object.urlEncode;\nexports.basename = path.basename;\nexports.dirname = path.dirname;\nexports.isAbsolute = path.isAbsolute;\nexports.join = path.join;\nexports.normalizePath = path.normalizePath;\nexports.relative = path.relative;\nexports.resolve = path.resolve;\nexports.makePromiseBuffer = promisebuffer.makePromiseBuffer;\nexports.addRequestDataToEvent = requestdata.addRequestDataToEvent;\nexports.addRequestDataToTransaction = requestdata.addRequestDataToTransaction;\nexports.extractPathForTransaction = requestdata.extractPathForTransaction;\nexports.extractRequestData = requestdata.extractRequestData;\nexports.severityFromString = severity.severityFromString;\nexports.severityLevelFromString = severity.severityLevelFromString;\nexports.validSeverityLevels = severity.validSeverityLevels;\nexports.createStackParser = stacktrace.createStackParser;\nexports.getFunctionName = stacktrace.getFunctionName;\nexports.nodeStackLineParser = stacktrace.nodeStackLineParser;\nexports.stackParserFromStackParserOptions = stacktrace.stackParserFromStackParserOptions;\nexports.stripSentryFramesAndReverse = stacktrace.stripSentryFramesAndReverse;\nexports.escapeStringForRegex = string.escapeStringForRegex;\nexports.isMatchingPattern = string.isMatchingPattern;\nexports.safeJoin = string.safeJoin;\nexports.snipLine = string.snipLine;\nexports.stringMatchesSomePattern = string.stringMatchesSomePattern;\nexports.truncate = string.truncate;\nexports.isNativeFetch = supports.isNativeFetch;\nexports.supportsDOMError = supports.supportsDOMError;\nexports.supportsDOMException = supports.supportsDOMException;\nexports.supportsErrorEvent = supports.supportsErrorEvent;\nexports.supportsFetch = supports.supportsFetch;\nexports.supportsHistory = supports.supportsHistory;\nexports.supportsNativeFetch = supports.supportsNativeFetch;\nexports.supportsReferrerPolicy = supports.supportsReferrerPolicy;\nexports.supportsReportingObserver = supports.supportsReportingObserver;\nexports.SyncPromise = syncpromise.SyncPromise;\nexports.rejectedSyncPromise = syncpromise.rejectedSyncPromise;\nexports.resolvedSyncPromise = syncpromise.resolvedSyncPromise;\nObject.defineProperty(exports, '_browserPerformanceTimeOriginMode', {\n\tenumerable: true,\n\tget: () => time._browserPerformanceTimeOriginMode\n});\nexports.browserPerformanceTimeOrigin = time.browserPerformanceTimeOrigin;\nexports.dateTimestampInSeconds = time.dateTimestampInSeconds;\nexports.timestampInSeconds = time.timestampInSeconds;\nexports.timestampWithMs = time.timestampWithMs;\nexports.usingPerformanceAPI = time.usingPerformanceAPI;\nexports.TRACEPARENT_REGEXP = tracing.TRACEPARENT_REGEXP;\nexports.extractTraceparentData = tracing.extractTraceparentData;\nexports.getSDKSource = env.getSDKSource;\nexports.isBrowserBundle = env.isBrowserBundle;\nexports.addItemToEnvelope = envelope.addItemToEnvelope;\nexports.createAttachmentEnvelopeItem = envelope.createAttachmentEnvelopeItem;\nexports.createEnvelope = envelope.createEnvelope;\nexports.createEventEnvelopeHeaders = envelope.createEventEnvelopeHeaders;\nexports.envelopeItemTypeToDataCategory = envelope.envelopeItemTypeToDataCategory;\nexports.forEachEnvelopeItem = envelope.forEachEnvelopeItem;\nexports.getSdkMetadataForEnvelopeHeader = envelope.getSdkMetadataForEnvelopeHeader;\nexports.parseEnvelope = envelope.parseEnvelope;\nexports.serializeEnvelope = envelope.serializeEnvelope;\nexports.createClientReportEnvelope = clientreport.createClientReportEnvelope;\nexports.DEFAULT_RETRY_AFTER = ratelimit.DEFAULT_RETRY_AFTER;\nexports.disabledUntil = ratelimit.disabledUntil;\nexports.isRateLimited = ratelimit.isRateLimited;\nexports.parseRetryAfterHeader = ratelimit.parseRetryAfterHeader;\nexports.updateRateLimits = ratelimit.updateRateLimits;\nexports.BAGGAGE_HEADER_NAME = baggage.BAGGAGE_HEADER_NAME;\nexports.MAX_BAGGAGE_STRING_LENGTH = baggage.MAX_BAGGAGE_STRING_LENGTH;\nexports.SENTRY_BAGGAGE_KEY_PREFIX = baggage.SENTRY_BAGGAGE_KEY_PREFIX;\nexports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = baggage.SENTRY_BAGGAGE_KEY_PREFIX_REGEX;\nexports.baggageHeaderToDynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext;\nexports.dynamicSamplingContextToSentryBaggageHeader = baggage.dynamicSamplingContextToSentryBaggageHeader;\nexports.getNumberOfUrlSegments = url.getNumberOfUrlSegments;\nexports.parseUrl = url.parseUrl;\nexports.stripUrlQueryAndFragment = url.stripUrlQueryAndFragment;\n//# sourceMappingURL=index.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\nconst logger = require('./logger.js');\nconst object = require('./object.js');\nconst stacktrace = require('./stacktrace.js');\nconst supports = require('./supports.js');\nconst worldwide = require('./worldwide.js');\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = worldwide.getGlobalObject();\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers = {};\nconst instrumented = {};\n\n/** Instruments given API */\nfunction instrument(type) {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addInstrumentationHandler(type, callback) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type, data) {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${stacktrace.getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole() {\n if (!('console' in WINDOW)) {\n return;\n }\n\n logger.CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n object.fill(WINDOW.console, level, function (originalConsoleMethod) {\n return function (...args) {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch() {\n if (!supports.supportsNativeFetch()) {\n return;\n }\n\n object.fill(WINDOW, 'fetch', function (originalFetch) {\n return function (...args) {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs = []) {\n if ('Request' in WINDOW && is.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs = []) {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in WINDOW && is.isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR() {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n object.fill(xhrproto, 'open', function (originalOpen) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n const xhrInfo = (xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: is.isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (is.isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function () {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhr.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n object.fill(xhr, 'onreadystatechange', function (original) {\n return function (...readyStateArgs) {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n object.fill(xhrproto, 'send', function (originalSend) {\n return function ( ...args) {\n if (this.__sentry_xhr__ && args[0] !== undefined) {\n this.__sentry_xhr__.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref;\n\n/** JSDoc */\nfunction instrumentHistory() {\n if (!supports.supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n object.fill(WINDOW.history, 'pushState', historyReplacementFunction);\n object.fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID;\nlet lastCapturedEvent;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous, current) {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event) {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target ;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler, globalListener = false) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\n/** JSDoc */\nfunction instrumentDOM() {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW )[target] && (WINDOW )[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n object.fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n object.fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler = null;\n/** JSDoc */\nfunction instrumentError() {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg, url, line, column, error) {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e) {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n\nexports.addInstrumentationHandler = addInstrumentationHandler;\n//# sourceMappingURL=instrument.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isNaN(wat) {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\nexports.isDOMError = isDOMError;\nexports.isDOMException = isDOMException;\nexports.isElement = isElement;\nexports.isError = isError;\nexports.isErrorEvent = isErrorEvent;\nexports.isEvent = isEvent;\nexports.isInstanceOf = isInstanceOf;\nexports.isNaN = isNaN;\nexports.isPlainObject = isPlainObject;\nexports.isPrimitive = isPrimitive;\nexports.isRegExp = isRegExp;\nexports.isString = isString;\nexports.isSyntheticEvent = isSyntheticEvent;\nexports.isThenable = isThenable;\n//# sourceMappingURL=is.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst worldwide = require('./worldwide.js');\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ;\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in worldwide.GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = worldwide.GLOBAL_OBJ.console ;\n const wrappedLevels = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] ).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] ;\n originalConsole[level] = originalWrappedFunc ;\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level ];\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n worldwide.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nexports.logger = void 0;\nif ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n exports.logger = worldwide.getGlobalSingleton('logger', makeLogger);\n} else {\n exports.logger = makeLogger();\n}\n\nexports.CONSOLE_LEVELS = CONSOLE_LEVELS;\nexports.consoleSandbox = consoleSandbox;\n//# sourceMappingURL=logger.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexports.memoBuilder = memoBuilder;\n//# sourceMappingURL=memo.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst object = require('./object.js');\nconst string = require('./string.js');\nconst worldwide = require('./worldwide.js');\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = worldwide.GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => string.snipLine(line, 0));\n\n frame.context_line = string.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => string.snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception ).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n object.addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexports.addContextToFrame = addContextToFrame;\nexports.addExceptionMechanism = addExceptionMechanism;\nexports.addExceptionTypeValue = addExceptionTypeValue;\nexports.arrayify = arrayify;\nexports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught;\nexports.getEventDescription = getEventDescription;\nexports.parseSemver = parseSemver;\nexports.uuid4 = uuid4;\n//# sourceMappingURL=misc.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst env = require('./env.js');\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !env.isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nfunction loadModule(moduleName) {\n let mod;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n\nexports.dynamicRequire = dynamicRequire;\nexports.isNodeEnv = isNodeEnv;\nexports.loadModule = loadModule;\n//# sourceMappingURL=node.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\nconst memo = require('./memo.js');\nconst object = require('./object.js');\nconst stacktrace = require('./stacktrace.js');\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = +Infinity, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n memo$1 = memo.memoBuilder(),\n) {\n const [memoize, unmemoize] = memo$1;\n\n // Get the simple cases out of the way first\n if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !is.isNaN(value))) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // We're also done if we've reached the max depth\n if (depth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, depth - 1, maxProperties, memo$1);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = object.convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo$1);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (is.isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own)\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${stacktrace.getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n return `[object ${getConstructorName(value)}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\nexports.normalize = normalize;\nexports.normalizeToSize = normalizeToSize;\nexports.walk = visit;\n//# sourceMappingURL=normalize.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst browser = require('./browser.js');\nconst is = require('./is.js');\nconst string = require('./string.js');\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nfunction urlEncode(object) {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (is.isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (is.isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && is.isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return is.isElement(target) ? browser.htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return string.truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return string.truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n if (is.isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case is.isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexports.addNonEnumerableProperty = addNonEnumerableProperty;\nexports.convertToPlainObject = convertToPlainObject;\nexports.dropUndefinedKeys = dropUndefinedKeys;\nexports.extractExceptionKeysForMessage = extractExceptionKeysForMessage;\nexports.fill = fill;\nexports.getOriginalFunction = getOriginalFunction;\nexports.markFunctionWrapped = markFunctionWrapped;\nexports.objectify = objectify;\nexports.urlEncode = urlEncode;\n//# sourceMappingURL=object.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js\n\n/** JSDoc */\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^/]+?|)(\\.[^./]*|))(?:[/]*)$/;\n/** JSDoc */\nfunction splitPath(filename) {\n const parts = splitPathRe.exec(filename);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nfunction resolve(...args) {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr) {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nfunction relative(from, to) {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nfunction normalizePath(path) {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nfunction isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nfunction join(...args) {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nfunction dirname(path) {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nfunction basename(path, ext) {\n let f = splitPath(path)[2];\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n\nexports.basename = basename;\nexports.dirname = dirname;\nexports.isAbsolute = isAbsolute;\nexports.join = join;\nexports.normalizePath = normalizePath;\nexports.relative = relative;\nexports.resolve = resolve;\n//# sourceMappingURL=path.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst error = require('./error.js');\nconst syncpromise = require('./syncpromise.js');\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return syncpromise.rejectedSyncPromise(new error.SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new syncpromise.SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void syncpromise.resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexports.makePromiseBuffer = makePromiseBuffer;\n//# sourceMappingURL=promisebuffer.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, category) {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, category, now = Date.now()) {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexports.DEFAULT_RETRY_AFTER = DEFAULT_RETRY_AFTER;\nexports.disabledUntil = disabledUntil;\nexports.isRateLimited = isRateLimited;\nexports.parseRetryAfterHeader = parseRetryAfterHeader;\nexports.updateRateLimits = updateRateLimits;\n//# sourceMappingURL=ratelimit.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\nconst normalize = require('./normalize.js');\nconst url = require('./url.js');\n\nconst DEFAULT_INCLUDES = {\n ip: false,\n request: true,\n transaction: true,\n user: true,\n};\nconst DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\nconst DEFAULT_USER_INCLUDES = ['id', 'username', 'email'];\n\n/**\n * Sets parameterized route as transaction name e.g.: `GET /users/:id`\n * Also adds more context data on the transaction from the request\n */\nfunction addRequestDataToTransaction(\n transaction,\n req,\n deps,\n) {\n if (!transaction) return;\n if (!transaction.metadata.source || transaction.metadata.source === 'url') {\n // Attempt to grab a parameterized route off of the request\n transaction.setName(...extractPathForTransaction(req, { path: true, method: true }));\n }\n transaction.setData('url', req.originalUrl || req.url);\n if (req.baseUrl) {\n transaction.setData('baseUrl', req.baseUrl);\n }\n transaction.setData('query', extractQueryParams(req, deps));\n}\n\n/**\n * Extracts a complete and parameterized path from the request object and uses it to construct transaction name.\n * If the parameterized transaction name cannot be extracted, we fall back to the raw URL.\n *\n * Additionally, this function determines and returns the transaction name source\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req A request object\n * @param options What to include in the transaction name (method, path, or a custom route name to be\n * used instead of the request's route)\n *\n * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')\n */\nfunction extractPathForTransaction(\n req,\n options = {},\n) {\n const method = req.method && req.method.toUpperCase();\n\n let path = '';\n let source = 'url';\n\n // Check to see if there's a parameterized route we can use (as there is in Express)\n if (options.customRoute || req.route) {\n path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`;\n source = 'route';\n }\n\n // Otherwise, just take the original URL\n else if (req.originalUrl || req.url) {\n path = url.stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let name = '';\n if (options.method && method) {\n name += method;\n }\n if (options.method && options.path) {\n name += ' ';\n }\n if (options.path && path) {\n name += path;\n }\n\n return [name, source];\n}\n\n/** JSDoc */\nfunction extractTransaction(req, type) {\n switch (type) {\n case 'path': {\n return extractPathForTransaction(req, { path: true })[0];\n }\n case 'handler': {\n return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '';\n }\n case 'methodPath':\n default: {\n return extractPathForTransaction(req, { path: true, method: true })[0];\n }\n }\n}\n\n/** JSDoc */\nfunction extractUserData(\n user\n\n,\n keys,\n) {\n const extractedUser = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/**\n * Normalize data from the request object, accounting for framework differences.\n *\n * @param req The request object from which to extract data\n * @param options.include An optional array of keys to include in the normalized data. Defaults to\n * DEFAULT_REQUEST_INCLUDES if not provided.\n * @param options.deps Injected, platform-specific dependencies\n * @returns An object containing normalized request data\n */\nfunction extractRequestData(\n req,\n options\n\n,\n) {\n const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {};\n const requestData = {};\n\n // headers:\n // node, express, koa, nextjs: req.headers\n const headers = (req.headers || {})\n\n;\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n const host = req.hostname || req.host || headers.host || '';\n // protocol:\n // node, nextjs: \n // express, koa: req.protocol\n const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = req.originalUrl || req.url || '';\n // absolute url\n const absoluteUrl = `${protocol}://${host}${originalUrl}`;\n include.forEach(key => {\n switch (key) {\n case 'headers': {\n requestData.headers = headers;\n break;\n }\n case 'method': {\n requestData.method = method;\n break;\n }\n case 'url': {\n requestData.url = absoluteUrl;\n break;\n }\n case 'cookies': {\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.cookies =\n // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can\n // come off in v8\n req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {};\n break;\n }\n case 'query_string': {\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = extractQueryParams(req, deps);\n break;\n }\n case 'data': {\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = is.isString(req.body) ? req.body : JSON.stringify(normalize.normalize(req.body));\n }\n break;\n }\n default: {\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req )[key];\n }\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n */\n\n/**\n * Add data from the given request to the given event\n *\n * @param event The event to which the request data will be added\n * @param req Request object\n * @param options.include Flags to control what data is included\n * @param options.deps Injected platform-specific dependencies\n * @hidden\n */\nfunction addRequestDataToEvent(\n event,\n req,\n options,\n) {\n const include = {\n ...DEFAULT_INCLUDES,\n ...(options && options.include),\n };\n\n if (include.request) {\n const extractedRequestData = Array.isArray(include.request)\n ? extractRequestData(req, { include: include.request, deps: options && options.deps })\n : extractRequestData(req, { deps: options && options.deps });\n\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (include.user) {\n const extractedUser = req.user && is.isPlainObject(req.user) ? extractUserData(req.user, include.user) : {};\n\n if (Object.keys(extractedUser).length) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.socket.remoteAddress\n // express, koa: req.ip\n if (include.ip) {\n const ip = req.ip || (req.socket && req.socket.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (include.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, include.transaction);\n }\n\n return event;\n}\n\nfunction extractQueryParams(\n req,\n deps,\n) {\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n let originalUrl = req.originalUrl || req.url || '';\n\n if (!originalUrl) {\n return;\n }\n\n // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use.\n if (originalUrl.startsWith('/')) {\n originalUrl = `http://dogs.are.great${originalUrl}`;\n }\n\n return (\n req.query ||\n (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) ||\n // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node\n (deps && deps.url && deps.url.parse(originalUrl).query) ||\n undefined\n );\n}\n\nexports.addRequestDataToEvent = addRequestDataToEvent;\nexports.addRequestDataToTransaction = addRequestDataToTransaction;\nexports.extractPathForTransaction = extractPathForTransaction;\nexports.extractRequestData = extractRequestData;\n//# sourceMappingURL=requestdata.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nfunction severityFromString(level) {\n return severityLevelFromString(level) ;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ;\n}\n\nexports.severityFromString = severityFromString;\nexports.severityLevelFromString = severityLevelFromString;\nexports.validSeverityLevels = validSeverityLevels;\n//# sourceMappingURL=severity.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst worldwide = require('./worldwide.js');\n\nconst STACKTRACE_LIMIT = 50;\n\nconst debugIdParserCache = new Map();\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirst = 0) => {\n const frames = [];\n\n for (const parser of sortedParsers) {\n let debugIdCache = debugIdParserCache.get(parser);\n if (!debugIdCache) {\n debugIdCache = new Map();\n debugIdParserCache.set(parser, debugIdCache);\n }\n\n const debugIdMap = worldwide.GLOBAL_OBJ._sentryDebugIds;\n\n if (debugIdMap) {\n Object.keys(debugIdMap).forEach(debugIdStackTrace => {\n debugIdStackTrace.split('\\n').forEach(line => {\n const frame = parser(line);\n if (frame && frame.filename) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n debugIdCache.set(frame.filename, debugIdMap[debugIdStackTrace]);\n }\n });\n });\n }\n }\n\n for (const line of stack.split('\\n').slice(skipFirst)) {\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = line.replace(/\\(error: (.*)\\)/, '$1');\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n const debugIdCache = debugIdParserCache.get(parser);\n if (debugIdCache && frame.filename) {\n const cachedDebugId = debugIdCache.get(frame.filename);\n if (cachedDebugId) {\n frame.debug_id = cachedDebugId;\n }\n }\n\n frames.push(frame);\n break;\n }\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n let localStack = stack;\n\n const firstFrameFunction = localStack[0].function || '';\n const lastFrameFunction = localStack[localStack.length - 1].function || '';\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {\n localStack = localStack.slice(0, -1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack\n .slice(0, STACKTRACE_LIMIT)\n .map(frame => ({\n ...frame,\n filename: frame.filename || localStack[0].filename,\n function: frame.function || '?',\n }))\n .reverse();\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n// eslint-disable-next-line complexity\nfunction node(getModule) {\n const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n\n // eslint-disable-next-line complexity\n return (line) => {\n if (line.match(FILENAME_MATCH)) {\n return {\n filename: line,\n };\n }\n\n const lineMatch = line.match(FULL_MATCH);\n if (!lineMatch) {\n return undefined;\n }\n\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n methodStart--;\n }\n\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = undefined;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '') {\n methodName = undefined;\n functionName = undefined;\n }\n\n if (functionName === undefined) {\n methodName = methodName || '';\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n\n const filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = lineMatch[5] === 'native';\n const isInternal =\n isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\\\') !== 1);\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/');\n\n return {\n filename,\n module: getModule ? getModule(filename) : undefined,\n function: functionName,\n lineno: parseInt(lineMatch[3], 10) || undefined,\n colno: parseInt(lineMatch[4], 10) || undefined,\n in_app,\n };\n };\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nfunction nodeStackLineParser(getModule) {\n return [90, node(getModule)];\n}\n\nexports.createStackParser = createStackParser;\nexports.getFunctionName = getFunctionName;\nexports.nodeStackLineParser = nodeStackLineParser;\nexports.stackParserFromStackParserOptions = stackParserFromStackParserOptions;\nexports.stripSentryFramesAndReverse = stripSentryFramesAndReverse;\n//# sourceMappingURL=stacktrace.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!is.isString(value)) {\n return false;\n }\n\n if (is.isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (is.isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nfunction escapeStringForRegex(regexString) {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n\nexports.escapeStringForRegex = escapeStringForRegex;\nexports.isMatchingPattern = isMatchingPattern;\nexports.safeJoin = safeJoin;\nexports.snipLine = snipLine;\nexports.stringMatchesSomePattern = stringMatchesSomePattern;\nexports.truncate = truncate;\n//# sourceMappingURL=string.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst logger = require('./logger.js');\nconst worldwide = require('./worldwide.js');\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = worldwide.getGlobalObject();\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFetch(func) {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW ).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexports.isNativeFetch = isNativeFetch;\nexports.supportsDOMError = supportsDOMError;\nexports.supportsDOMException = supportsDOMException;\nexports.supportsErrorEvent = supportsErrorEvent;\nexports.supportsFetch = supportsFetch;\nexports.supportsHistory = supportsHistory;\nexports.supportsNativeFetch = supportsNativeFetch;\nexports.supportsReferrerPolicy = supportsReferrerPolicy;\nexports.supportsReportingObserver = supportsReportingObserver;\n//# sourceMappingURL=supports.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst is = require('./is.js');\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n __init() {this._state = States.PENDING;}\n __init2() {this._handlers = [];}\n\n constructor(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this);\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** JSDoc */\n __init3() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init4() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init5() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (is.isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init6() {this._executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };}\n}\n\nexports.SyncPromise = SyncPromise;\nexports.rejectedSyncPromise = rejectedSyncPromise;\nexports.resolvedSyncPromise = resolvedSyncPromise;\n//# sourceMappingURL=syncpromise.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst node = require('./node.js');\nconst worldwide = require('./worldwide.js');\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = worldwide.getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance() {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance() {\n try {\n const perfHooks = node.dynamicRequire(module, 'perf_hooks') ;\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance = node.isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nconst dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nconst timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nconst usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexports._browserPerformanceTimeOriginMode = void 0;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nconst browserPerformanceTimeOrigin = (() => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n exports._browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n exports._browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n exports._browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n exports._browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexports.browserPerformanceTimeOrigin = browserPerformanceTimeOrigin;\nexports.dateTimestampInSeconds = dateTimestampInSeconds;\nexports.timestampInSeconds = timestampInSeconds;\nexports.timestampWithMs = timestampWithMs;\nexports.usingPerformanceAPI = usingPerformanceAPI;\n//# sourceMappingURL=time.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\nconst TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n\n if (!traceparent || !matches) {\n // empty string or no matches is invalid traceparent data\n return undefined;\n }\n\n let parentSampled;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\nexports.TRACEPARENT_REGEXP = TRACEPARENT_REGEXP;\nexports.extractTraceparentData = extractTraceparentData;\n//# sourceMappingURL=tracing.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url)\n\n {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\nexports.getNumberOfUrlSegments = getNumberOfUrlSegments;\nexports.parseUrl = parseUrl;\nexports.stripUrlQueryAndFragment = stripUrlQueryAndFragment;\n//# sourceMappingURL=url.js.map\n","Object.defineProperty(exports, '__esModule', { value: true });\n\n/** Internal global with common properties and Sentry extensions */\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj) {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function () {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nfunction getGlobalObject() {\n return GLOBAL_OBJ ;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n\nexports.GLOBAL_OBJ = GLOBAL_OBJ;\nexports.getGlobalObject = getGlobalObject;\nexports.getGlobalSingleton = getGlobalSingleton;\n//# sourceMappingURL=worldwide.js.map\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nconst events_1 = require(\"events\");\nconst debug_1 = __importDefault(require(\"debug\"));\nconst promisify_1 = __importDefault(require(\"./promisify\"));\nconst debug = debug_1.default('agent-base');\nfunction isAgent(v) {\n return Boolean(v) && typeof v.addRequest === 'function';\n}\nfunction isSecureEndpoint() {\n const { stack } = new Error();\n if (typeof stack !== 'string')\n return false;\n return stack.split('\\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);\n}\nfunction createAgent(callback, opts) {\n return new createAgent.Agent(callback, opts);\n}\n(function (createAgent) {\n /**\n * Base `http.Agent` implementation.\n * No pooling/keep-alive is implemented by default.\n *\n * @param {Function} callback\n * @api public\n */\n class Agent extends events_1.EventEmitter {\n constructor(callback, _opts) {\n super();\n let opts = _opts;\n if (typeof callback === 'function') {\n this.callback = callback;\n }\n else if (callback) {\n opts = callback;\n }\n // Timeout for the socket to be returned from the callback\n this.timeout = null;\n if (opts && typeof opts.timeout === 'number') {\n this.timeout = opts.timeout;\n }\n // These aren't actually used by `agent-base`, but are required\n // for the TypeScript definition files in `@types/node` :/\n this.maxFreeSockets = 1;\n this.maxSockets = 1;\n this.maxTotalSockets = Infinity;\n this.sockets = {};\n this.freeSockets = {};\n this.requests = {};\n this.options = {};\n }\n get defaultPort() {\n if (typeof this.explicitDefaultPort === 'number') {\n return this.explicitDefaultPort;\n }\n return isSecureEndpoint() ? 443 : 80;\n }\n set defaultPort(v) {\n this.explicitDefaultPort = v;\n }\n get protocol() {\n if (typeof this.explicitProtocol === 'string') {\n return this.explicitProtocol;\n }\n return isSecureEndpoint() ? 'https:' : 'http:';\n }\n set protocol(v) {\n this.explicitProtocol = v;\n }\n callback(req, opts, fn) {\n throw new Error('\"agent-base\" has no default implementation, you must subclass and override `callback()`');\n }\n /**\n * Called by node-core's \"_http_client.js\" module when creating\n * a new HTTP request with this Agent instance.\n *\n * @api public\n */\n addRequest(req, _opts) {\n const opts = Object.assign({}, _opts);\n if (typeof opts.secureEndpoint !== 'boolean') {\n opts.secureEndpoint = isSecureEndpoint();\n }\n if (opts.host == null) {\n opts.host = 'localhost';\n }\n if (opts.port == null) {\n opts.port = opts.secureEndpoint ? 443 : 80;\n }\n if (opts.protocol == null) {\n opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';\n }\n if (opts.host && opts.path) {\n // If both a `host` and `path` are specified then it's most\n // likely the result of a `url.parse()` call... we need to\n // remove the `path` portion so that `net.connect()` doesn't\n // attempt to open that as a unix socket file.\n delete opts.path;\n }\n delete opts.agent;\n delete opts.hostname;\n delete opts._defaultAgent;\n delete opts.defaultPort;\n delete opts.createConnection;\n // Hint to use \"Connection: close\"\n // XXX: non-documented `http` module API :(\n req._last = true;\n req.shouldKeepAlive = false;\n let timedOut = false;\n let timeoutId = null;\n const timeoutMs = opts.timeout || this.timeout;\n const onerror = (err) => {\n if (req._hadError)\n return;\n req.emit('error', err);\n // For Safety. Some additional errors might fire later on\n // and we need to make sure we don't double-fire the error event.\n req._hadError = true;\n };\n const ontimeout = () => {\n timeoutId = null;\n timedOut = true;\n const err = new Error(`A \"socket\" was not created for HTTP request before ${timeoutMs}ms`);\n err.code = 'ETIMEOUT';\n onerror(err);\n };\n const callbackError = (err) => {\n if (timedOut)\n return;\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n onerror(err);\n };\n const onsocket = (socket) => {\n if (timedOut)\n return;\n if (timeoutId != null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n if (isAgent(socket)) {\n // `socket` is actually an `http.Agent` instance, so\n // relinquish responsibility for this `req` to the Agent\n // from here on\n debug('Callback returned another Agent instance %o', socket.constructor.name);\n socket.addRequest(req, opts);\n return;\n }\n if (socket) {\n socket.once('free', () => {\n this.freeSocket(socket, opts);\n });\n req.onSocket(socket);\n return;\n }\n const err = new Error(`no Duplex stream was returned to agent-base for \\`${req.method} ${req.path}\\``);\n onerror(err);\n };\n if (typeof this.callback !== 'function') {\n onerror(new Error('`callback` is not defined'));\n return;\n }\n if (!this.promisifiedCallback) {\n if (this.callback.length >= 3) {\n debug('Converting legacy callback function to promise');\n this.promisifiedCallback = promisify_1.default(this.callback);\n }\n else {\n this.promisifiedCallback = this.callback;\n }\n }\n if (typeof timeoutMs === 'number' && timeoutMs > 0) {\n timeoutId = setTimeout(ontimeout, timeoutMs);\n }\n if ('port' in opts && typeof opts.port !== 'number') {\n opts.port = Number(opts.port);\n }\n try {\n debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);\n Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);\n }\n catch (err) {\n Promise.reject(err).catch(callbackError);\n }\n }\n freeSocket(socket, opts) {\n debug('Freeing socket %o %o', socket.constructor.name, opts);\n socket.destroy();\n }\n destroy() {\n debug('Destroying agent %o', this.constructor.name);\n }\n }\n createAgent.Agent = Agent;\n // So that `instanceof` works correctly\n createAgent.prototype = createAgent.Agent.prototype;\n})(createAgent || (createAgent = {}));\nmodule.exports = createAgent;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction promisify(fn) {\n return function (req, opts) {\n return new Promise((resolve, reject) => {\n fn.call(this, req, opts, (err, rtn) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(rtn);\n }\n });\n });\n };\n}\nexports.default = promisify;\n//# sourceMappingURL=promisify.js.map","/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar decode = decodeURIComponent;\nvar encode = encodeURIComponent;\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var pairs = str.split(';')\n var dec = opt.decode || decode;\n\n for (var i = 0; i < pairs.length; i++) {\n var pair = pairs[i];\n var index = pair.indexOf('=')\n\n // skip things that don't look like key=value\n if (index < 0) {\n continue;\n }\n\n var key = pair.substring(0, index).trim()\n\n // only assign once\n if (undefined == obj[key]) {\n var val = pair.substring(index + 1, pair.length).trim()\n\n // quoted values\n if (val[0] === '\"') {\n val = val.slice(1, -1)\n }\n\n obj[key] = tryDecode(val, dec);\n }\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n if (typeof opt.expires.toUTCString !== 'function') {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst net_1 = __importDefault(require(\"net\"));\nconst tls_1 = __importDefault(require(\"tls\"));\nconst url_1 = __importDefault(require(\"url\"));\nconst assert_1 = __importDefault(require(\"assert\"));\nconst debug_1 = __importDefault(require(\"debug\"));\nconst agent_base_1 = require(\"agent-base\");\nconst parse_proxy_response_1 = __importDefault(require(\"./parse-proxy-response\"));\nconst debug = debug_1.default('https-proxy-agent:agent');\n/**\n * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to\n * the specified \"HTTP(s) proxy server\" in order to proxy HTTPS requests.\n *\n * Outgoing HTTP requests are first tunneled through the proxy server using the\n * `CONNECT` HTTP request method to establish a connection to the proxy server,\n * and then the proxy server connects to the destination target and issues the\n * HTTP request from the proxy server.\n *\n * `https:` requests have their socket connection upgraded to TLS once\n * the connection to the proxy server has been established.\n *\n * @api public\n */\nclass HttpsProxyAgent extends agent_base_1.Agent {\n constructor(_opts) {\n let opts;\n if (typeof _opts === 'string') {\n opts = url_1.default.parse(_opts);\n }\n else {\n opts = _opts;\n }\n if (!opts) {\n throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');\n }\n debug('creating new HttpsProxyAgent instance: %o', opts);\n super(opts);\n const proxy = Object.assign({}, opts);\n // If `true`, then connect to the proxy server over TLS.\n // Defaults to `false`.\n this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);\n // Prefer `hostname` over `host`, and set the `port` if needed.\n proxy.host = proxy.hostname || proxy.host;\n if (typeof proxy.port === 'string') {\n proxy.port = parseInt(proxy.port, 10);\n }\n if (!proxy.port && proxy.host) {\n proxy.port = this.secureProxy ? 443 : 80;\n }\n // ALPN is supported by Node.js >= v5.\n // attempt to negotiate http/1.1 for proxy servers that support http/2\n if (this.secureProxy && !('ALPNProtocols' in proxy)) {\n proxy.ALPNProtocols = ['http 1.1'];\n }\n if (proxy.host && proxy.path) {\n // If both a `host` and `path` are specified then it's most likely\n // the result of a `url.parse()` call... we need to remove the\n // `path` portion so that `net.connect()` doesn't attempt to open\n // that as a Unix socket file.\n delete proxy.path;\n delete proxy.pathname;\n }\n this.proxy = proxy;\n }\n /**\n * Called when the node-core HTTP client library is creating a\n * new HTTP request.\n *\n * @api protected\n */\n callback(req, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n const { proxy, secureProxy } = this;\n // Create a socket connection to the proxy server.\n let socket;\n if (secureProxy) {\n debug('Creating `tls.Socket`: %o', proxy);\n socket = tls_1.default.connect(proxy);\n }\n else {\n debug('Creating `net.Socket`: %o', proxy);\n socket = net_1.default.connect(proxy);\n }\n const headers = Object.assign({}, proxy.headers);\n const hostname = `${opts.host}:${opts.port}`;\n let payload = `CONNECT ${hostname} HTTP/1.1\\r\\n`;\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.auth) {\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;\n }\n // The `Host` header should only include the port\n // number when it is not the default port.\n let { host, port, secureEndpoint } = opts;\n if (!isDefaultPort(port, secureEndpoint)) {\n host += `:${port}`;\n }\n headers.Host = host;\n headers.Connection = 'close';\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n const proxyResponsePromise = parse_proxy_response_1.default(socket);\n socket.write(`${payload}\\r\\n`);\n const { statusCode, buffered } = yield proxyResponsePromise;\n if (statusCode === 200) {\n req.once('socket', resume);\n if (opts.secureEndpoint) {\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n const servername = opts.servername || opts.host;\n return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,\n servername }));\n }\n return socket;\n }\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n const fakeSocket = new net_1.default.Socket({ writable: false });\n fakeSocket.readable = true;\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s) => {\n debug('replaying proxy buffer for failed request');\n assert_1.default(s.listenerCount('data') > 0);\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n return fakeSocket;\n });\n }\n}\nexports.default = HttpsProxyAgent;\nfunction resume(socket) {\n socket.resume();\n}\nfunction isDefaultPort(port, secure) {\n return Boolean((!secure && port === 80) || (secure && port === 443));\n}\nfunction isHTTPS(protocol) {\n return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;\n}\nfunction omit(obj, ...keys) {\n const ret = {};\n let key;\n for (key in obj) {\n if (!keys.includes(key)) {\n ret[key] = obj[key];\n }\n }\n return ret;\n}\n//# sourceMappingURL=agent.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nconst agent_1 = __importDefault(require(\"./agent\"));\nfunction createHttpsProxyAgent(opts) {\n return new agent_1.default(opts);\n}\n(function (createHttpsProxyAgent) {\n createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;\n createHttpsProxyAgent.prototype = agent_1.default.prototype;\n})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));\nmodule.exports = createHttpsProxyAgent;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst debug_1 = __importDefault(require(\"debug\"));\nconst debug = debug_1.default('https-proxy-agent:parse-proxy-response');\nfunction parseProxyResponse(socket) {\n return new Promise((resolve, reject) => {\n // we need to buffer any HTTP traffic that happens with the proxy before we get\n // the CONNECT response, so that if the response is anything other than an \"200\"\n // response code, then we can re-play the \"data\" events on the socket once the\n // HTTP parser is hooked up...\n let buffersLength = 0;\n const buffers = [];\n function read() {\n const b = socket.read();\n if (b)\n ondata(b);\n else\n socket.once('readable', read);\n }\n function cleanup() {\n socket.removeListener('end', onend);\n socket.removeListener('error', onerror);\n socket.removeListener('close', onclose);\n socket.removeListener('readable', read);\n }\n function onclose(err) {\n debug('onclose had error %o', err);\n }\n function onend() {\n debug('onend');\n }\n function onerror(err) {\n cleanup();\n debug('onerror %o', err);\n reject(err);\n }\n function ondata(b) {\n buffers.push(b);\n buffersLength += b.length;\n const buffered = Buffer.concat(buffers, buffersLength);\n const endOfHeaders = buffered.indexOf('\\r\\n\\r\\n');\n if (endOfHeaders === -1) {\n // keep buffering\n debug('have not received end of HTTP headers yet...');\n read();\n return;\n }\n const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\\r\\n'));\n const statusCode = +firstLine.split(' ')[1];\n debug('got proxy server response: %o', firstLine);\n resolve({\n statusCode,\n buffered\n });\n }\n socket.on('error', onerror);\n socket.on('close', onclose);\n socket.on('end', onend);\n read();\n });\n}\nexports.default = parseProxyResponse;\n//# sourceMappingURL=parse-proxy-response.js.map","/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n","/**\n * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most\n * recently used items while discarding least recently used items when its limit\n * is reached.\n *\n * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson \n * See README.md for details.\n *\n * Illustration of the design:\n *\n * entry entry entry entry\n * ______ ______ ______ ______\n * | head |.newer => | |.newer => | |.newer => | tail |\n * | A | | B | | C | | D |\n * |______| <= older.|______| <= older.|______| <= older.|______|\n *\n * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added\n */\n(function(g,f){\n const e = typeof exports == 'object' ? exports : typeof g == 'object' ? g : {};\n f(e);\n if (typeof define == 'function' && define.amd) { define('lru', e); }\n})(this, function(exports) {\n\nconst NEWER = Symbol('newer');\nconst OLDER = Symbol('older');\n\nfunction LRUMap(limit, entries) {\n if (typeof limit !== 'number') {\n // called as (entries)\n entries = limit;\n limit = 0;\n }\n\n this.size = 0;\n this.limit = limit;\n this.oldest = this.newest = undefined;\n this._keymap = new Map();\n\n if (entries) {\n this.assign(entries);\n if (limit < 1) {\n this.limit = this.size;\n }\n }\n}\n\nexports.LRUMap = LRUMap;\n\nfunction Entry(key, value) {\n this.key = key;\n this.value = value;\n this[NEWER] = undefined;\n this[OLDER] = undefined;\n}\n\n\nLRUMap.prototype._markEntryAsUsed = function(entry) {\n if (entry === this.newest) {\n // Already the most recenlty used entry, so no need to update the list\n return;\n }\n // HEAD--------------TAIL\n // <.older .newer>\n // <--- add direction --\n // A B C E\n if (entry[NEWER]) {\n if (entry === this.oldest) {\n this.oldest = entry[NEWER];\n }\n entry[NEWER][OLDER] = entry[OLDER]; // C <-- E.\n }\n if (entry[OLDER]) {\n entry[OLDER][NEWER] = entry[NEWER]; // C. --> E\n }\n entry[NEWER] = undefined; // D --x\n entry[OLDER] = this.newest; // D. --> E\n if (this.newest) {\n this.newest[NEWER] = entry; // E. <-- D\n }\n this.newest = entry;\n};\n\nLRUMap.prototype.assign = function(entries) {\n let entry, limit = this.limit || Number.MAX_VALUE;\n this._keymap.clear();\n let it = entries[Symbol.iterator]();\n for (let itv = it.next(); !itv.done; itv = it.next()) {\n let e = new Entry(itv.value[0], itv.value[1]);\n this._keymap.set(e.key, e);\n if (!entry) {\n this.oldest = e;\n } else {\n entry[NEWER] = e;\n e[OLDER] = entry;\n }\n entry = e;\n if (limit-- == 0) {\n throw new Error('overflow');\n }\n }\n this.newest = entry;\n this.size = this._keymap.size;\n};\n\nLRUMap.prototype.get = function(key) {\n // First, find our cache entry\n var entry = this._keymap.get(key);\n if (!entry) return; // Not cached. Sorry.\n // As was found in the cache, register it as being requested recently\n this._markEntryAsUsed(entry);\n return entry.value;\n};\n\nLRUMap.prototype.set = function(key, value) {\n var entry = this._keymap.get(key);\n\n if (entry) {\n // update existing\n entry.value = value;\n this._markEntryAsUsed(entry);\n return this;\n }\n\n // new entry\n this._keymap.set(key, (entry = new Entry(key, value)));\n\n if (this.newest) {\n // link previous tail to the new tail (entry)\n this.newest[NEWER] = entry;\n entry[OLDER] = this.newest;\n } else {\n // we're first in -- yay\n this.oldest = entry;\n }\n\n // add new entry to the end of the linked list -- it's now the freshest entry.\n this.newest = entry;\n ++this.size;\n if (this.size > this.limit) {\n // we hit the limit -- remove the head\n this.shift();\n }\n\n return this;\n};\n\nLRUMap.prototype.shift = function() {\n // todo: handle special case when limit == 1\n var entry = this.oldest;\n if (entry) {\n if (this.oldest[NEWER]) {\n // advance the list\n this.oldest = this.oldest[NEWER];\n this.oldest[OLDER] = undefined;\n } else {\n // the cache is exhausted\n this.oldest = undefined;\n this.newest = undefined;\n }\n // Remove last strong reference to and remove links from the purged\n // entry being returned:\n entry[NEWER] = entry[OLDER] = undefined;\n this._keymap.delete(entry.key);\n --this.size;\n return [entry.key, entry.value];\n }\n};\n\n// ----------------------------------------------------------------------------\n// Following code is optional and can be removed without breaking the core\n// functionality.\n\nLRUMap.prototype.find = function(key) {\n let e = this._keymap.get(key);\n return e ? e.value : undefined;\n};\n\nLRUMap.prototype.has = function(key) {\n return this._keymap.has(key);\n};\n\nLRUMap.prototype['delete'] = function(key) {\n var entry = this._keymap.get(key);\n if (!entry) return;\n this._keymap.delete(entry.key);\n if (entry[NEWER] && entry[OLDER]) {\n // relink the older entry with the newer entry\n entry[OLDER][NEWER] = entry[NEWER];\n entry[NEWER][OLDER] = entry[OLDER];\n } else if (entry[NEWER]) {\n // remove the link to us\n entry[NEWER][OLDER] = undefined;\n // link the newer entry to head\n this.oldest = entry[NEWER];\n } else if (entry[OLDER]) {\n // remove the link to us\n entry[OLDER][NEWER] = undefined;\n // link the newer entry to head\n this.newest = entry[OLDER];\n } else {// if(entry[OLDER] === undefined && entry.newer === undefined) {\n this.oldest = this.newest = undefined;\n }\n\n this.size--;\n return entry.value;\n};\n\nLRUMap.prototype.clear = function() {\n // Not clearing links should be safe, as we don't expose live links to user\n this.oldest = this.newest = undefined;\n this.size = 0;\n this._keymap.clear();\n};\n\n\nfunction EntryIterator(oldestEntry) { this.entry = oldestEntry; }\nEntryIterator.prototype[Symbol.iterator] = function() { return this; }\nEntryIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: [ent.key, ent.value] };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nfunction KeyIterator(oldestEntry) { this.entry = oldestEntry; }\nKeyIterator.prototype[Symbol.iterator] = function() { return this; }\nKeyIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.key };\n } else {\n return { done: true, value: undefined };\n }\n};\n\nfunction ValueIterator(oldestEntry) { this.entry = oldestEntry; }\nValueIterator.prototype[Symbol.iterator] = function() { return this; }\nValueIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.value };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nLRUMap.prototype.keys = function() {\n return new KeyIterator(this.oldest);\n};\n\nLRUMap.prototype.values = function() {\n return new ValueIterator(this.oldest);\n};\n\nLRUMap.prototype.entries = function() {\n return this;\n};\n\nLRUMap.prototype[Symbol.iterator] = function() {\n return new EntryIterator(this.oldest);\n};\n\nLRUMap.prototype.forEach = function(fun, thisObj) {\n if (typeof thisObj !== 'object') {\n thisObj = this;\n }\n let entry = this.oldest;\n while (entry) {\n fun.call(thisObj, entry.value, entry.key, this);\n entry = entry[NEWER];\n }\n};\n\n/** Returns a JSON (array) representation */\nLRUMap.prototype.toJSON = function() {\n var s = new Array(this.size), i = 0, entry = this.oldest;\n while (entry) {\n s[i++] = { key: entry.key, value: entry.value };\n entry = entry[NEWER];\n }\n return s;\n};\n\n/** Returns a String representation */\nLRUMap.prototype.toString = function() {\n var s = '', entry = this.oldest;\n while (entry) {\n s += String(entry.key)+':'+entry.value;\n entry = entry[NEWER];\n if (entry) {\n s += ' < ';\n }\n }\n return s;\n};\n\n});\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","module.exports = require('./dist/shared/lib/constants')\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n"],"names":[],"mappings":"","debug_id":"2297b93d-928d-421e-8910-127c786382da"} \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.min.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.min.js new file mode 100644 index 0000000000..f1ba2ac246 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/1.min.js @@ -0,0 +1,5 @@ + +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2297b93d-928d-421e-8910-127c786382da")}catch(e){}}(); + + +//# debugId=2297b93d-928d-421e-8910-127c786382da diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/flight-server-css-manifest.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/flight-server-css-manifest.js new file mode 100644 index 0000000000..165bc8bda9 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/chunks/flight-server-css-manifest.js @@ -0,0 +1,3 @@ +self.__RSC_CSS_MANIFEST={"__entry_css_mods__":{"/workspaces/sentry-nextjs-vercel-testproject/app/client/page":[],"/workspaces/sentry-nextjs-vercel-testproject/app/error/page":[],"/workspaces/sentry-nextjs-vercel-testproject/app/page":[]}} +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d9ce7004-bf22-5042-ab0b-dcfd9ebc3979")}catch(e){}}(); +//# debugId=d9ce7004-bf22-5042-ab0b-dcfd9ebc3979 diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.js.map new file mode 100644 index 0000000000..03b7045b71 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edge-runtime-webpack.js","mappings":";;;;UAAA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA,GAAG;UACH;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;UAEA;UACA;;;;;WClCA;WACA;WACA;WACA;WACA,+BAA+B,wCAAwC;WACvE;WACA;WACA;WACA;WACA,iBAAiB,qBAAqB;WACtC;WACA;WACA,kBAAkB,qBAAqB;WACvC;WACA;WACA,KAAK;WACL;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;;;;WC3BA;WACA;WACA;WACA;WACA;WACA,iCAAiC,WAAW;WAC5C;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,GAAG;WACH;WACA;WACA,CAAC;;;;;WCPD;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,EAAE;WACF;WACA;;;;;WCVA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;WCNA;;WAEA;WACA;WACA;WACA;WACA;WACA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA,MAAM,qBAAqB;WAC3B;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;WAEA;WACA;WACA","sources":["webpack://_N_E/webpack/bootstrap","webpack://_N_E/webpack/runtime/chunk loaded","webpack://_N_E/webpack/runtime/compat get default export","webpack://_N_E/webpack/runtime/define property getters","webpack://_N_E/webpack/runtime/global","webpack://_N_E/webpack/runtime/harmony module decorator","webpack://_N_E/webpack/runtime/hasOwnProperty shorthand","webpack://_N_E/webpack/runtime/make namespace object","webpack://_N_E/webpack/runtime/jsonp chunk loading","webpack://_N_E/webpack/before-startup","webpack://_N_E/webpack/startup","webpack://_N_E/webpack/after-startup"],"sourcesContent":["// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\tvar threw = true;\n\ttry {\n\t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\t\tthrew = false;\n\t} finally {\n\t\tif(threw) delete __webpack_module_cache__[moduleId];\n\t}\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.hmd = (module) => {\n\tmodule = Object.create(module);\n\tif (!module.children) module.children = [];\n\tObject.defineProperty(module, 'exports', {\n\t\tenumerable: true,\n\t\tset: () => {\n\t\t\tthrow new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);\n\t\t}\n\t});\n\treturn module;\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t993: 0\n};\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunk_N_E\"] = self[\"webpackChunk_N_E\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","","",""],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.min.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.min.js new file mode 100644 index 0000000000..e34564d2dc --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/edge-runtime-webpack.min.js @@ -0,0 +1 @@ +//# debugId=2297b93d-928d-421e-8910-127c786382dd \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/flight-manifest.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/flight-manifest.js new file mode 100644 index 0000000000..816b1f082a --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/flight-manifest.js @@ -0,0 +1,3 @@ +self.__RSC_MANIFEST={"__ssr_module_mapping__":{"2092":{"":{"id":"1295","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"1295","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"1295","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"3330":{"":{"id":"6542","name":"","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false},"*":{"id":"6542","name":"*","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false},"default":{"id":"6542","name":"default","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false}},"7043":{"":{"id":"5657","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"5657","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"5657","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"7954":{"":{"id":"3957","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"3957","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"3957","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"9875":{"":{"id":"4606","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"4606","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"4606","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}}},"__edge_ssr_module_mapping__":{},"__entry_css_files__":{},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/client/components/app-router.js":{"":{"id":"7954","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"7954","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"7954","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/esm/client/components/app-router.js":{"":{"id":"7954","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"7954","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"7954","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/client/components/error-boundary.js":{"":{"id":"7043","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"7043","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"7043","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/esm/client/components/error-boundary.js":{"":{"id":"7043","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"7043","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"7043","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/client/components/layout-router.js":{"":{"id":"9875","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"9875","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"9875","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/esm/client/components/layout-router.js":{"":{"id":"9875","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"9875","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"9875","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/client/components/render-from-template-context.js":{"":{"id":"2092","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"2092","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"2092","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/node_modules/next/dist/esm/client/components/render-from-template-context.js":{"":{"id":"2092","name":"","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"*":{"id":"2092","name":"*","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false},"default":{"id":"2092","name":"default","chunks":["272:webpack-92781b978857bf95","575:575-bb7d7e0e6de8d623","744:main-app-ad4a762f03983bd7"],"async":false}},"/workspaces/sentry-nextjs-vercel-testproject/app/client/page.tsx":{"":{"id":"3330","name":"","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false},"*":{"id":"3330","name":"*","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false},"default":{"id":"3330","name":"default","chunks":["394:app/client/page-d5742c254d9533f8"],"async":false}}} +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ded681e3-c344-549e-8a5d-1b40543f2331")}catch(e){}}(); +//# debugId=ded681e3-c344-549e-8a5d-1b40543f2331 diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.js.map new file mode 100644 index 0000000000..935bd65668 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.js.map @@ -0,0 +1 @@ +{"version":3,"file":"../pages/_document.js","sources":["webpack://sentry-nextjs-vercel-testproject/external commonjs \"@sentry/nextjs\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/compiled/react\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/server/get-page-files.js\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/server/htmlescape.js\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/server/utils.js\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/shared/lib/constants.js\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/shared/lib/html-context.js\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/shared/lib/is-plain-object.js\""],"sourceRoot":"","sourcesContent":["module.exports = require(\"@sentry/nextjs\");","module.exports = require(\"next/dist/compiled/react\");","module.exports = require(\"next/dist/server/get-page-files.js\");","module.exports = require(\"next/dist/server/htmlescape.js\");","module.exports = require(\"next/dist/server/utils.js\");","module.exports = require(\"next/dist/shared/lib/constants.js\");","module.exports = require(\"next/dist/shared/lib/html-context.js\");","module.exports = require(\"next/dist/shared/lib/is-plain-object.js\");"],"names":[],"mappings":"","debug_id":"38790a18-b17b-5a7a-9f30-27ef38dbe4ae"} \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.min.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.min.js new file mode 100644 index 0000000000..063822073a --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/_document.min.js @@ -0,0 +1,4 @@ + +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="38790a18-b17b-5a7a-9f30-27ef38dbe4ae")}catch(e){}}(); + +//# debugId=38790a18-b17b-5a7a-9f30-27ef38dbe4ae diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/api/hello.min.js b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/api/hello.min.js new file mode 100644 index 0000000000..30155b8392 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/api/hello.min.js @@ -0,0 +1,3 @@ + +!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="adc83b19-e793-591b-9c6e-a0fd8b46cd9f")}catch(e){}}(); +//# debugId=adc83b19-e793-591b-9c6e-a0fd8b46cd9f diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/asdf.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/asdf.js.map new file mode 100644 index 0000000000..6cc52ded9c --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/server/pages/asdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"../pages/asdf.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAe,SAASA,IAAO;AAE/B;;;;;;;ACEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,cAAc,GAAG,UAAU,EAAE;AACnC;AACK,MAAC,aAAa,GAAG,cAAc,CAAC,QAAQ;AAC7C;AACA,MAAM,mBAAmB,GAAG,aAAa,CAAC,eAAe,CAAC;AAC1D,MAAM,kBAAkB,GAAG,cAAc,CAAC,cAAc,CAAC;AACzD,MAAM,sBAAsB,GAAG,cAAc,CAAC,kBAAkB,CAAC;AACjE;AACA,MAAM,uBAAuB,GAAG;AAChC,EAAE,OAAO,EAAE,4EAAuC;AAClD,EAAE,YAAY,EAAE,iFAA4C;AAC5D,EAAE,SAAS,EAAE,8EAAyC;AACtD,CAAC,CAAC;AACF;AACA,MAAM,sBAAsB,GAAG,uBAAuB,CAAC,OAAO,CAAC,IAAI,yEAAoC,CAAC;AACxG;AACA,IAAI,OAAO,mBAAmB,KAAK,UAAU,EAAE;AAC/C,EAAE,aAAa,CAAC,eAAe,GAAG,sBAAsB,CAAC,mBAAmB,CAAC,EAAE;AAC/E,CAAC;AACD;AACK,MAAC,cAAc;AACpB,EAAE,OAAO,kBAAkB,KAAK,UAAU;AAC1C,MAAM,wEAAmC,CAAC,kBAAkB,EAAE,OAAO,CAAC;AACtE,MAAM,UAAU;AACX,MAAC,kBAAkB;AACxB,EAAE,OAAO,sBAAsB,KAAK,UAAU;AAC9C,MAAM,4EAAuC,CAAC,sBAAsB,EAAE,OAAO,CAAC;AAC9E,MAAM;;;;;;;;;;ACvCN;;;;;;;ACAA","sources":["webpack://sentry-nextjs-vercel-testproject/pages/asdf.jsx","webpack://sentry-nextjs-vercel-testproject/sentry-wrapper-module","webpack://sentry-nextjs-vercel-testproject/external commonjs \"@sentry/nextjs\"","webpack://sentry-nextjs-vercel-testproject/external commonjs \"next/dist/compiled/react/jsx-runtime\""],"sourcesContent":["export default function asdf() {\n

hello world!!!!!!!!

;\n}\n","import * as origModule from '__SENTRY_WRAPPING_TARGET_FILE__.cjs';\nexport * from '__SENTRY_WRAPPING_TARGET_FILE__.cjs';\nimport * as Sentry from '@sentry/nextjs';\n\n/*\n * This file is a template for the code which will be substituted when our webpack loader handles non-API files in the\n * `pages/` directory.\n *\n * We use `__SENTRY_WRAPPING_TARGET_FILE__.cjs` as a placeholder for the path to the file being wrapped. Because it's not a real package,\n * this causes both TS and ESLint to complain, hence the pragma comments below.\n */\n\nconst userPageModule = origModule ;\n\nconst pageComponent = userPageModule.default;\n\nconst origGetInitialProps = pageComponent.getInitialProps;\nconst origGetStaticProps = userPageModule.getStaticProps;\nconst origGetServerSideProps = userPageModule.getServerSideProps;\n\nconst getInitialPropsWrappers = {\n '/_app': Sentry.wrapAppGetInitialPropsWithSentry,\n '/_document': Sentry.wrapDocumentGetInitialPropsWithSentry,\n '/_error': Sentry.wrapErrorGetInitialPropsWithSentry,\n};\n\nconst getInitialPropsWrapper = getInitialPropsWrappers['/asdf'] || Sentry.wrapGetInitialPropsWithSentry;\n\nif (typeof origGetInitialProps === 'function') {\n pageComponent.getInitialProps = getInitialPropsWrapper(origGetInitialProps) ;\n}\n\nconst getStaticProps =\n typeof origGetStaticProps === 'function'\n ? Sentry.wrapGetStaticPropsWithSentry(origGetStaticProps, '/asdf')\n : undefined;\nconst getServerSideProps =\n typeof origGetServerSideProps === 'function'\n ? Sentry.wrapGetServerSidePropsWithSentry(origGetServerSideProps, '/asdf')\n : undefined;\n\nexport { pageComponent as default, getServerSideProps, getStaticProps };\n","module.exports = require(\"@sentry/nextjs\");","module.exports = require(\"next/dist/compiled/react/jsx-runtime\");"],"names":["asdf"],"sourceRoot":""} \ No newline at end of file diff --git a/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/575-bb7d7e0e6de8d623.js.map b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/575-bb7d7e0e6de8d623.js.map new file mode 100644 index 0000000000..1fc0d71736 --- /dev/null +++ b/tests/integration/_expected_outputs/sourcemaps/sourcemaps-inject-nomappings/static/chunks/575-bb7d7e0e6de8d623.js.map @@ -0,0 +1 @@ +{"version":3,"file":"static/chunks/575-bb7d7e0e6de8d623.js","sources":["webpack://_N_E/./node_modules/@sentry/core/build/esm/hub.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/scope.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/session.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/buildPolyfills/_optionalChain.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/path.js","webpack://_N_E/./node_modules/@sentry/integrations/build/npm/esm/rewriteframes.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/version.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/integrations/inboundfilters.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/integrations/functiontostring.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/integration.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/sdk.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/error.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/dsn.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/memo.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/normalize.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/envelope.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/api.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/envelope.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/utils/prepareEvent.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/baseclient.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/clientreport.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/eventbuilder.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/exports.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/helpers.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/severity.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/url.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/client.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/trycatch.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/dedupe.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/stack-parsers.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/promisebuffer.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/ratelimit.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/transports/base.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/transports/utils.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/transports/fetch.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/transports/xhr.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/sdk.js","webpack://_N_E/./node_modules/@sentry/react/build/esm/sdk.js","webpack://_N_E/./node_modules/@sentry/core/build/esm/integrations/index.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/integrations/index.js","webpack://_N_E/./node_modules/@sentry/browser/build/npm/esm/index.js","webpack://_N_E/./node_modules/@sentry/react/build/esm/index.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/tracing.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/baggage.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/types.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/backgroundtab.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/bindReporter.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/generateUniqueID.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/getNavigationEntry.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/getActivationStart.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/initMetric.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/observe.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/onHidden.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/getCLS.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/lib/getVisibilityWatcher.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/getFID.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/web-vitals/getLCP.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/metrics/utils.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/metrics/index.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/request.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/router.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/browser/browsertracing.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/index.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/common/metadata.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/common/userIntegrations.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/client/performance.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/client/tunnelRoute.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/common/_error.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/client/index.js","webpack://_N_E/./node_modules/@sentry/nextjs/build/esm/index.client.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/errors.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/hubextensions.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/idletransaction.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/span.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/transaction.js","webpack://_N_E/./node_modules/@sentry/tracing/build/npm/esm/utils.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/browser.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/env.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/instrument.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/is.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/logger.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/misc.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/node.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/object.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/stacktrace.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/string.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/supports.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/syncpromise.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/time.js","webpack://_N_E/./node_modules/@sentry/utils/build/esm/worldwide.js","webpack://_N_E/./node_modules/@swc/helpers/lib/_async_to_generator.js","webpack://_N_E/./node_modules/@swc/helpers/lib/_extends.js","webpack://_N_E/./node_modules/@swc/helpers/lib/_interop_require_default.js","webpack://_N_E/./node_modules/@swc/helpers/lib/_interop_require_wildcard.js","webpack://_N_E/./node_modules/@swc/helpers/lib/_object_without_properties_loose.js","webpack://_N_E/./node_modules/next/dist/build/polyfills/polyfill-module.js","webpack://_N_E/./node_modules/next/dist/build/polyfills/process.js","webpack://_N_E/./node_modules/next/dist/client/add-base-path.js","webpack://_N_E/./node_modules/next/dist/client/add-locale.js","webpack://_N_E/./node_modules/next/dist/client/app-bootstrap.js","webpack://_N_E/./node_modules/next/dist/client/app-index.js","webpack://_N_E/./node_modules/next/dist/client/app-next.js","webpack://_N_E/./node_modules/next/dist/client/components/app-router-headers.js","webpack://_N_E/./node_modules/next/dist/client/components/app-router.js","webpack://_N_E/./node_modules/next/dist/client/components/bailout-to-client-rendering.js","webpack://_N_E/./node_modules/next/dist/client/components/client-hook-in-server-component-error.js","webpack://_N_E/./node_modules/next/dist/client/components/error-boundary.js","webpack://_N_E/./node_modules/next/dist/client/components/infinite-promise.js","webpack://_N_E/./node_modules/next/dist/client/components/layout-router.js","webpack://_N_E/./node_modules/next/dist/client/components/match-segments.js","webpack://_N_E/./node_modules/next/dist/client/components/navigation.js","webpack://_N_E/./node_modules/next/dist/client/components/not-found.js","webpack://_N_E/./node_modules/next/dist/client/components/redirect.js","webpack://_N_E/./node_modules/next/dist/client/components/reducer.js","webpack://_N_E/./node_modules/next/dist/client/components/render-from-template-context.js","webpack://_N_E/./node_modules/next/dist/client/components/use-reducer-with-devtools.js","webpack://_N_E/./node_modules/next/dist/client/detect-domain-locale.js","webpack://_N_E/./node_modules/next/dist/client/has-base-path.js","webpack://_N_E/./node_modules/next/dist/client/head-manager.js","webpack://_N_E/./node_modules/next/dist/client/normalize-trailing-slash.js","webpack://_N_E/./node_modules/next/dist/client/on-recoverable-error.js","webpack://_N_E/./node_modules/next/dist/client/remove-base-path.js","webpack://_N_E/./node_modules/next/dist/client/remove-locale.js","webpack://_N_E/./node_modules/next/dist/client/request-idle-callback.js","webpack://_N_E/./node_modules/next/dist/client/route-loader.js","webpack://_N_E/./node_modules/next/dist/client/router.js","webpack://_N_E/./node_modules/next/dist/client/script.js","webpack://_N_E/./node_modules/next/dist/client/trusted-types.js","webpack://_N_E/./node_modules/next/dist/client/with-router.js","webpack://_N_E/./node_modules/next/dist/shared/lib/app-router-context.js","webpack://_N_E/./node_modules/next/dist/shared/lib/dynamic-no-ssr.js","webpack://_N_E/./node_modules/next/dist/shared/lib/escape-regexp.js","webpack://_N_E/./node_modules/next/dist/shared/lib/head-manager-context.js","webpack://_N_E/./node_modules/next/dist/shared/lib/hooks-client-context.js","webpack://_N_E/./node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js","webpack://_N_E/./node_modules/next/dist/shared/lib/is-plain-object.js","webpack://_N_E/./node_modules/next/dist/shared/lib/mitt.js","webpack://_N_E/./node_modules/next/dist/shared/lib/no-ssr-error.js","webpack://_N_E/./node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","webpack://_N_E/./node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router-context.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/router.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/add-locale.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/compare-states.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/format-url.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/index.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/is-bot.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/parse-path.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/parse-url.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/path-match.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/prepare-destination.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/querystring.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/route-matcher.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/route-regex.js","webpack://_N_E/./node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","webpack://_N_E/./node_modules/next/dist/shared/lib/server-inserted-html.js","webpack://_N_E/./node_modules/next/dist/shared/lib/utils.js","webpack://_N_E/./node_modules/next/dist/compiled/path-to-regexp/index.js","webpack://_N_E/./node_modules/next/dist/compiled/process/browser.js","webpack://_N_E/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.production.min.js","webpack://_N_E/./node_modules/next/dist/compiled/react-dom/client.js","webpack://_N_E/./node_modules/next/dist/compiled/react-dom/index.js","webpack://_N_E/./node_modules/next/dist/compiled/react-server-dom-webpack/client.js","webpack://_N_E/./node_modules/next/dist/compiled/react/cjs/react.production.min.js","webpack://_N_E/./node_modules/next/dist/compiled/react/index.js","webpack://_N_E/./node_modules/next/dist/compiled/scheduler/index.js","webpack://_N_E/./node_modules/next/dist/lib/is-api-route.js","webpack://_N_E/./node_modules/next/dist/lib/is-error.js","webpack://_N_E/./node_modules/next/router.js","webpack://_N_E/./node_modules/next/dist/client/components/async-local-storage.js","webpack://_N_E/./node_modules/next/dist/client/components/static-generation-async-storage.js","webpack://_N_E/"],"sourceRoot":"","sourcesContent":["import { uuid4, dateTimestampInSeconds, consoleSandbox, logger, GLOBAL_OBJ, isNodeEnv, getGlobalSingleton } from '@sentry/utils';\nimport { Scope } from './scope.js';\nimport { closeSession, makeSession, updateSession } from './session.js';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nconst API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * A layer in the process stack.\n * @hidden\n */\n\n/**\n * @inheritDoc\n */\nclass Hub {\n /** Is a {@link Layer}[] containing the client and scope */\n __init() {this._stack = [{}];}\n\n /** Contains the last event id of a captured event. */\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n constructor(client, scope = new Scope(), _version = API_VERSION) {this._version = _version;Hub.prototype.__init.call(this);\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n isOlderThan(version) {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n bindClient(client) {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n pushScope() {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n popScope() {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n withScope(callback) {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /** Returns the scope of the top stack. */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n getStack() {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n getStackTop() {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n ) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, hint) {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) )\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setContext(name, context) {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n configureScope(callback) {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n run(callback) {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n startTransaction(context, customSamplingContext) {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n traceHeaders() {\n return this._callExtensionMethod('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n captureSession(endSession = false) {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n endSession() {\n const layer = this.getStackTop();\n const scope = layer && layer.scope;\n const session = scope && scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n if (scope) {\n scope.setSession();\n }\n }\n\n /**\n * @inheritDoc\n */\n startSession(context) {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n shouldSendDefaultPii() {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n _sendSessionUpdate() {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n _withClient(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _callExtensionMethod(method, ...args) {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nfunction makeMain(hub) {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nfunction getCurrentHub() {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry) {\n try {\n const sentry = getMainCarrier().__SENTRY__;\n const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier) {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nfunction getHubFromCarrier(carrier) {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nfunction setHubOnCarrier(carrier, hub) {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n\nexport { API_VERSION, Hub, getCurrentHub, getHubFromCarrier, getMainCarrier, makeMain, setHubOnCarrier };\n//# sourceMappingURL=hub.js.map\n","import { isPlainObject, dateTimestampInSeconds, SyncPromise, logger, isThenable, arrayify, getGlobalSingleton } from '@sentry/utils';\nimport { updateSession } from './session.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nclass Scope {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called after {@link applyToEvent}. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n\n /** Transaction Name */\n\n /** Span */\n\n /** Session */\n\n /** Request Mode Session Status */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n static clone(scope) {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level,\n ) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setSpan(span) {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSpan() {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n getTransaction() {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext )(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext ;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getAttachments() {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n applyToEvent(event, hint = {}) {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction && this._span.transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n _notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n ) {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n _applyFingerprint(event) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors() {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nfunction addGlobalEventProcessor(callback) {\n getGlobalEventProcessors().push(callback);\n}\n\nexport { Scope, addGlobalEventProcessor };\n//# sourceMappingURL=scope.js.map\n","import { timestampInSeconds, uuid4, dropUndefinedKeys } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","/**\n * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values,\n * descriptors, and functions.\n *\n * Adapted from Sucrase (https://github.com/alangpierce/sucrase)\n * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15\n *\n * @param ops Array result of expression conversion\n * @returns The value of the expression\n */\nfunction _optionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}\n\n// Sucrase version\n// function _optionalChain(ops) {\n// let lastAccessLHS = undefined;\n// let value = ops[0];\n// let i = 1;\n// while (i < ops.length) {\n// const op = ops[i];\n// const fn = ops[i + 1];\n// i += 2;\n// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n// return undefined;\n// }\n// if (op === 'access' || op === 'optionalAccess') {\n// lastAccessLHS = value;\n// value = fn(value);\n// } else if (op === 'call' || op === 'optionalCall') {\n// value = fn((...args) => value.call(lastAccessLHS, ...args));\n// lastAccessLHS = undefined;\n// }\n// }\n// return value;\n// }\n\nexport { _optionalChain };\n//# sourceMappingURL=_optionalChain.js.map\n","// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js\n\n/** JSDoc */\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^/]+?|)(\\.[^./]*|))(?:[/]*)$/;\n/** JSDoc */\nfunction splitPath(filename) {\n const parts = splitPathRe.exec(filename);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nfunction resolve(...args) {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr) {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nfunction relative(from, to) {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nfunction normalizePath(path) {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nfunction isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nfunction join(...args) {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nfunction dirname(path) {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nfunction basename(path, ext) {\n let f = splitPath(path)[2];\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n\nexport { basename, dirname, isAbsolute, join, normalizePath, relative, resolve };\n//# sourceMappingURL=path.js.map\n","import { relative, basename } from '@sentry/utils';\n\n/** Rewrite event frames paths */\nclass RewriteFrames {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'RewriteFrames';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = RewriteFrames.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n __init2() {this._prefix = 'app:///';}\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {RewriteFrames.prototype.__init.call(this);RewriteFrames.prototype.__init2.call(this);RewriteFrames.prototype.__init3.call(this);\n if (options.root) {\n this._root = options.root;\n }\n if (options.prefix) {\n this._prefix = options.prefix;\n }\n if (options.iteratee) {\n this._iteratee = options.iteratee;\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(RewriteFrames);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /** JSDoc */\n process(originalEvent) {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = this._processExceptionsEvent(processedEvent);\n }\n\n return processedEvent;\n }\n\n /**\n * @inheritDoc\n */\n __init3() {this._iteratee = (frame) => {\n if (!frame.filename) {\n return frame;\n }\n // Check if the frame filename begins with `/` or a Windows-style prefix such as `C:\\`\n const isWindowsFrame = /^[A-Z]:\\\\/.test(frame.filename);\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = this._root ? relative(this._root, filename) : basename(filename);\n frame.filename = `${this._prefix}${base}`;\n }\n return frame;\n };}\n\n /** JSDoc */\n _processExceptionsEvent(event) {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception.values.map(value => ({\n ...value,\n ...(value.stacktrace && { stacktrace: this._processStacktrace(value.stacktrace) }),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n _processStacktrace(stacktrace) {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => this._iteratee(f)),\n };\n }\n} RewriteFrames.__initStatic();\n\nexport { RewriteFrames };\n//# sourceMappingURL=rewriteframes.js.map\n","const SDK_VERSION = '7.37.0';\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { logger, getEventDescription, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** Options for the InboundFilters integration */\n\n/** Inbound filters configurable by the user */\nclass InboundFilters {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'InboundFilters';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = InboundFilters.id;}\n\n constructor( _options = {}) {this._options = _options;InboundFilters.prototype.__init.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcess = (event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n} InboundFilters.__initStatic();\n\n/** JSDoc */\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n if (!ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nexport { InboundFilters, _mergeOptions, _shouldDropEvent };\n//# sourceMappingURL=inboundfilters.js.map\n","import { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString;\n\n/** Patch toString calls to return proper name for wrapped functions */\nclass FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'FunctionToString';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = FunctionToString.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function ( ...args) {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n} FunctionToString.__initStatic();\n\nexport { FunctionToString };\n//# sourceMappingURL=functiontostring.js.map\n","import { arrayify, logger } from '@sentry/utils';\nimport { getCurrentHub } from './hub.js';\nimport { addGlobalEventProcessor } from './scope.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(integrations) {\n const integrationIndex = {};\n\n integrations.forEach(integration => {\n setupIntegration(integration, integrationIndex);\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(integration, integrationIndex) {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\nexport { getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { logger } from '@sentry/utils';\nimport { getCurrentHub } from './hub.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n if (scope) {\n scope.update(options.initialScope);\n }\n\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n\nexport { initAndBind };\n//# sourceMappingURL=sdk.js.map\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor( message, logLevel = 'warn') {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","import { SentryError } from './error.js';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(`Invalid Sentry Dsn: ${str}`);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n return;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n requiredComponents.forEach(component => {\n if (!dsn[component]) {\n throw new SentryError(`Invalid Sentry Dsn: ${component} missing`);\n }\n });\n\n if (!projectId.match(/^\\d+$/)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n }\n\n if (!isValidProtocol(protocol)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid port ${port}`);\n }\n\n return true;\n}\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n validateDsn(components);\n return components;\n}\n\nexport { dsnFromString, dsnToString, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexport { memoBuilder };\n//# sourceMappingURL=memo.js.map\n","import { isNaN, isSyntheticEvent } from './is.js';\nimport { memoBuilder } from './memo.js';\nimport { convertToPlainObject } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = +Infinity, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n memo = memoBuilder(),\n) {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // We're also done if we've reached the max depth\n if (depth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, depth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own)\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n return `[object ${getConstructorName(value)}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\nexport { normalize, normalizeToSize, visit as walk };\n//# sourceMappingURL=normalize.js.map\n","import { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n envelopeItems.forEach((envelopeItem) => {\n const envelopeItemType = envelopeItem[0].type;\n callback(envelopeItem, envelopeItemType);\n });\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input, textEncoder) {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope, textEncoder) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(\n env,\n textEncoder,\n textDecoder,\n) {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(\n attachment,\n textEncoder,\n) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(event.type === 'transaction' &&\n dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { makeDsn, dsnToString, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(\n dsn,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions = {} ,\n) {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\n const dsn = makeDsn(dsnLike);\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getSdkMetadataForEnvelopeHeader, dsnToString, createEnvelope, createEventEnvelopeHeaders } from '@sentry/utils';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjut a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\nexport { createEventEnvelope, createSessionEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { uuid4, dateTimestampInSeconds, resolvedSyncPromise, truncate, normalize } from '@sentry/utils';\nimport { Scope } from '../scope.js';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n\nexport { prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { makeDsn, logger, checkOrSetAlreadyCaught, isPrimitive, resolvedSyncPromise, addItemToEnvelope, createAttachmentEnvelopeItem, SyncPromise, rejectedSyncPromise, SentryError, isThenable, isPlainObject } from '@sentry/utils';\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegrations, setupIntegration } from './integration.js';\nimport { updateSession } from './session.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n __init() {this._integrations = {};}\n\n /** Indicates whether this client's integrations have been set up. */\n __init2() {this._integrationsInitialized = false;}\n\n /** Number of calls being processed */\n __init3() {this._numProcessing = 0;}\n\n /** Holds flushable */\n __init4() {this._outcomes = {};}\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this);\n this._options = options;\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('No DSN provided, client will not do anything.');\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint, scope) {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n scope,\n ) {\n let eventId = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session) {\n if (!this._isEnabled()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n setupIntegrations() {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n try {\n return (this._integrations[integration.id] ) || null;\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration) {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint = {}) {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n sendSession(session) {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, _event) {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(event, hint, scope) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(event, hint, scope) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n changes: [\n ...transactionInfo.changes,\n {\n source,\n // use the same timestamp as the processed event.\n timestamp: processedEvent.timestamp ,\n propagations: transactionInfo.propagations,\n },\n ],\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason ,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n _sendEnvelope(envelope) {\n if (this._transport && this._dsn) {\n this._transport.send(envelope).then(null, reason => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Error while sending event:', reason);\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient };\n//# sourceMappingURL=baseclient.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, extractExceptionKeysForMessage, normalizeToSize } from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception ).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nfunction eventFromError(stackParser, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex) {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex) {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.error );\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception ) || isDOMException(exception )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception ;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nfunction eventFromString(\n stackParser,\n input,\n syntheticException,\n attachStacktrace,\n) {\n const event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n\nexport { eventFromError, eventFromException, eventFromMessage, eventFromPlainObject, eventFromString, eventFromUnknownInput, exceptionFromError, parseStackFrames };\n//# sourceMappingURL=eventbuilder.js.map\n","import { getCurrentHub } from './hub.js';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction captureException(exception, captureContext) {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nfunction captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n captureContext,\n) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nfunction captureEvent(event, hint) {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nfunction configureScope(callback) {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nfunction addBreadcrumb(breadcrumb) {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setContext(name, context) {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nfunction withScope(callback) {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nfunction startTransaction(\n context,\n customSamplingContext,\n) {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\nexport { addBreadcrumb, captureEvent, captureException, captureMessage, configureScope, setContext, setExtra, setExtras, setTag, setTags, setUser, startTransaction, withScope };\n//# sourceMappingURL=exports.js.map\n","import { withScope, captureException } from '@sentry/core';\nimport { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, addExceptionTypeValue, addExceptionMechanism } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n before,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function () {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope) => {\n scope.addEventProcessor((event) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') ;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get() {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\n\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\n","// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nfunction severityFromString(level) {\n return severityLevelFromString(level) ;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ;\n}\n\nexport { severityFromString, severityLevelFromString, validSeverityLevels };\n//# sourceMappingURL=severity.js.map\n","/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not
href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url)\n\n {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\nexport { getNumberOfUrlSegments, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, getEventDescription, severityLevelFromString, safeJoin, parseUrl, logger, htmlTreeAsString } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nclass Breadcrumbs {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = BREADCRUMB_INTEGRATION_ID;}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Breadcrumbs.id;}\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n\n /**\n * @inheritDoc\n */\n constructor(options) {Breadcrumbs.prototype.__init.call(this);\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n setupOnce() {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n addSentryBreadcrumb(event) {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n} Breadcrumbs.__initStatic();\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _domBreadcrumb(dom) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _innerDomBreadcrumb(handlerData) {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = handlerData.event.target\n ? htmlTreeAsString(handlerData.event.target , { keyAttrs, maxStringLength })\n : htmlTreeAsString(handlerData.event , { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _consoleBreadcrumb(handlerData) {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _xhrBreadcrumb(handlerData) {\n if (handlerData.endTimestamp) {\n // We only capture complete, non-sentry requests\n if (handlerData.xhr.__sentry_own_request__) {\n return;\n }\n\n const { method, url, status_code, body } = handlerData.xhr.__sentry_xhr__ || {};\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data: {\n method,\n url,\n status_code,\n },\n type: 'http',\n },\n {\n xhr: handlerData.xhr,\n input: body,\n },\n );\n\n return;\n }\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _fetchBreadcrumb(handlerData) {\n // We only capture complete fetch requests\n if (!handlerData.endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: handlerData.fetchData,\n level: 'error',\n type: 'http',\n },\n {\n data: handlerData.error,\n input: handlerData.args,\n },\n );\n } else {\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data: {\n ...handlerData.fetchData,\n status_code: handlerData.response.status,\n },\n type: 'http',\n },\n {\n input: handlerData.args,\n response: handlerData.response,\n },\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _historyBreadcrumb(handlerData) {\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nexport { BREADCRUMB_INTEGRATION_ID, Breadcrumbs };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { BaseClient, SDK_VERSION, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';\nimport { getSDKSource, logger, createClientReportEnvelope, dsnToString, serializeEnvelope } from '@sentry/utils';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint) {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) ;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Sending outcomes:', outcomes);\n\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, this._options);\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n try {\n const isRealNavigator = Object.prototype.toString.call(WINDOW && WINDOW.navigator) === '[object Navigator]';\n const hasSendBeacon = isRealNavigator && typeof WINDOW.navigator.sendBeacon === 'function';\n // Make sure beacon is not used if user configures custom transport options\n if (hasSendBeacon && !this._options.transportOptions) {\n // Prevent illegal invocations - https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n const sendBeacon = WINDOW.navigator.sendBeacon.bind(WINDOW.navigator);\n sendBeacon(url, serializeEnvelope(envelope));\n } else {\n // If beacon is not supported or if they are using the tunnel option\n // use our regular transport to send client reports to Sentry.\n this._sendEnvelope(envelope);\n }\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(e);\n }\n }\n}\n\nexport { BrowserClient };\n//# sourceMappingURL=client.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, isString, isPrimitive, isErrorEvent, getLocationHref, logger, addExceptionMechanism } from '@sentry/utils';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** Global handlers */\nclass GlobalHandlers {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'GlobalHandlers';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = GlobalHandlers.id;}\n\n /** JSDoc */\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n __init2() {this._installFunc = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };}\n\n /** JSDoc */\n constructor(options) {GlobalHandlers.prototype.__init.call(this);GlobalHandlers.prototype.__init2.call(this);\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n setupOnce() {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key ];\n if (installFunc && options[key ]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key ] = undefined;\n }\n }\n }\n} GlobalHandlers.__initStatic();\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler() {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler() {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg, url, line, column) {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event, url, line, column) {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub, error, event, type) {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions() {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n\nexport { GlobalHandlers };\n//# sourceMappingURL=globalhandlers.js.map\n","import { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\nimport { WINDOW, wrap } from '../helpers.js';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nclass TryCatch {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'TryCatch';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = TryCatch.id;}\n\n /** JSDoc */\n\n /**\n * @inheritDoc\n */\n constructor(options) {TryCatch.prototype.__init.call(this);\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n setupOnce() {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n} TryCatch.__initStatic();\n\n/** JSDoc */\nfunction _wrapTimeFunction(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( callback) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW ;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn , {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn ;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n\nexport { TryCatch };\n//# sourceMappingURL=trycatch.js.map\n","import { getCurrentHub, addGlobalEventProcessor } from '@sentry/core';\nimport { isInstanceOf } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nclass LinkedErrors {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'LinkedErrors';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = LinkedErrors.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {LinkedErrors.prototype.__init.call(this);\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event, hint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n} LinkedErrors.__initStatic();\n\n/**\n * @inheritDoc\n */\nfunction _handler(\n parser,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException , key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nfunction _walkErrorTree(\n parser,\n limit,\n error,\n key,\n stack = [],\n) {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n\nexport { LinkedErrors, _handler, _walkErrorTree };\n//# sourceMappingURL=linkederrors.js.map\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/** HttpContext integration collects information about HTTP request headers */\nclass HttpContext {constructor() { HttpContext.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'HttpContext';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = HttpContext.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n addGlobalEventProcessor((event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n} HttpContext.__initStatic();\n\nexport { HttpContext };\n//# sourceMappingURL=httpcontext.js.map\n","import { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nclass Dedupe {constructor() { Dedupe.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Dedupe';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Dedupe.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcessor = currentEvent => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n} Dedupe.__initStatic();\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { Dedupe };\n//# sourceMappingURL=dedupe.js.map\n","import { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\n filename,\n function: func,\n // All browser frames are considered in_app\n in_app: true,\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.*\\).*?|.*?) ?\\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex =\n /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nconst defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","import { SentryError } from './error.js';\nimport { rejectedSyncPromise, SyncPromise, resolvedSyncPromise } from './syncpromise.js';\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexport { makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, category) {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, category, now = Date.now()) {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { makePromiseBuffer, forEachEnvelopeItem, envelopeItemTypeToDataCategory, isRateLimited, resolvedSyncPromise, createEnvelope, SentryError, logger, serializeEnvelope, updateRateLimits } from '@sentry/utils';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","import { isNativeFetch, logger } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\nlet cachedFetchImpl = undefined;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nfunction getNativeFetchImplementation() {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nfunction clearCachedFetchImplementation() {\n cachedFetchImpl = undefined;\n}\n\nexport { clearCachedFetchImplementation, getNativeFetchImplementation };\n//# sourceMappingURL=utils.js.map\n","import { createTransport } from '@sentry/core';\nimport { rejectedSyncPromise } from '@sentry/utils';\nimport { getNativeFetchImplementation, clearCachedFetchImplementation } from './utils.js';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeFetchImplementation(),\n) {\n function makeRequest(request) {\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch), a request with `keepalive: true`\n // and a content length of > 64 kibibytes returns a network error. We will therefore only activate the flag when\n // we're below that limit.\n keepalive: request.body.length <= 65536,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => ({\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n }));\n } catch (e) {\n clearCachedFetchImplementation();\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","import { createTransport } from '@sentry/core';\nimport { SyncPromise } from '@sentry/utils';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nfunction makeXHRTransport(options) {\n function makeRequest(request) {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeXHRTransport };\n//# sourceMappingURL=xhr.js.map\n","import { Integrations, getIntegrationsToSetup, initAndBind, getReportDialogEndpoint, getCurrentHub } from '@sentry/core';\nimport { stackParserFromStackParserOptions, supportsFetch, logger, resolvedSyncPromise, addInstrumentationHandler } from '@sentry/utils';\nimport { BrowserClient } from './client.js';\nimport { WINDOW, wrap as wrap$1 } from './helpers.js';\nimport { GlobalHandlers } from './integrations/globalhandlers.js';\nimport { TryCatch } from './integrations/trycatch.js';\nimport { Breadcrumbs } from './integrations/breadcrumbs.js';\nimport { LinkedErrors } from './integrations/linkederrors.js';\nimport { HttpContext } from './integrations/httpcontext.js';\nimport { Dedupe } from './integrations/dedupe.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\nimport { makeXHRTransport } from './transports/xhr.js';\n\nconst defaultIntegrations = [\n new Integrations.InboundFilters(),\n new Integrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nfunction init(options = {}) {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nfunction showReportDialog(options = {}, hub = getCurrentHub()) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nfunction lastEventId() {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nfunction flush(timeout) {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nfunction close(timeout) {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrap(fn) {\n return wrap$1(fn)();\n}\n\nfunction startSessionOnHub(hub) {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking() {\n if (typeof WINDOW.document === 'undefined') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\nexport { close, defaultIntegrations, flush, forceLoad, init, lastEventId, onLoad, showReportDialog, wrap };\n//# sourceMappingURL=sdk.js.map\n","import { SDK_VERSION, init as init$1 } from '@sentry/browser';\n\n/**\n * Inits the React SDK\n */\nfunction init(options) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.react',\n packages: [\n {\n name: 'npm:@sentry/react',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n init$1(options);\n}\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","export { FunctionToString } from './functiontostring.js';\nexport { InboundFilters } from './inboundfilters.js';\n//# sourceMappingURL=index.js.map\n","export { GlobalHandlers } from './globalhandlers.js';\nexport { TryCatch } from './trycatch.js';\nexport { Breadcrumbs } from './breadcrumbs.js';\nexport { LinkedErrors } from './linkederrors.js';\nexport { HttpContext } from './httpcontext.js';\nexport { Dedupe } from './dedupe.js';\n//# sourceMappingURL=index.js.map\n","import { Integrations } from '@sentry/core';\nexport { FunctionToString, Hub, InboundFilters, SDK_VERSION, Scope, addBreadcrumb, addGlobalEventProcessor, captureEvent, captureException, captureMessage, configureScope, createTransport, getCurrentHub, getHubFromCarrier, makeMain, setContext, setExtra, setExtras, setTag, setTags, setUser, startTransaction, withScope } from '@sentry/core';\nimport { WINDOW } from './helpers.js';\nexport { WINDOW } from './helpers.js';\nexport { BrowserClient } from './client.js';\nexport { makeFetchTransport } from './transports/fetch.js';\nexport { makeXHRTransport } from './transports/xhr.js';\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser } from './stack-parsers.js';\nexport { eventFromException, eventFromMessage } from './eventbuilder.js';\nexport { close, defaultIntegrations, flush, forceLoad, init, lastEventId, onLoad, showReportDialog, wrap } from './sdk.js';\nimport * as index from './integrations/index.js';\nexport { Replay } from '@sentry/replay';\nexport { makeBrowserOfflineTransport } from './transports/offline.js';\nexport { GlobalHandlers } from './integrations/globalhandlers.js';\nexport { TryCatch } from './integrations/trycatch.js';\nexport { Breadcrumbs } from './integrations/breadcrumbs.js';\nexport { LinkedErrors } from './integrations/linkederrors.js';\nexport { HttpContext } from './integrations/httpcontext.js';\nexport { Dedupe } from './integrations/dedupe.js';\n\nlet windowIntegrations = {};\n\n// This block is needed to add compatibility with the integrations packages when used with a CDN\nif (WINDOW.Sentry && WINDOW.Sentry.Integrations) {\n windowIntegrations = WINDOW.Sentry.Integrations;\n}\n\nconst INTEGRATIONS = {\n ...windowIntegrations,\n ...Integrations,\n ...index,\n};\n// __ROLLUP_EXCLUDE_OFFLINE_FROM_BUNDLES_END__\n\nexport { INTEGRATIONS as Integrations };\n//# sourceMappingURL=index.js.map\n","export * from '@sentry/browser';\nexport { init } from './sdk.js';\nexport { Profiler, useProfiler, withProfiler } from './profiler.js';\nexport { ErrorBoundary, withErrorBoundary } from './errorboundary.js';\nexport { createReduxEnhancer } from './redux.js';\nexport { reactRouterV3Instrumentation } from './reactrouterv3.js';\nexport { reactRouterV4Instrumentation, reactRouterV5Instrumentation, withSentryRouting } from './reactrouter.js';\nexport { reactRouterV6Instrumentation, withSentryReactRouterV6Routing, wrapCreateBrowserRouter, wrapUseRoutes } from './reactrouterv6.js';\n//# sourceMappingURL=index.js.map\n","const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n\n if (!traceparent || !matches) {\n // empty string or no matches is invalid traceparent data\n return undefined;\n }\n\n let parentSampled;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData };\n//# sourceMappingURL=tracing.js.map\n","import { isString } from './is.js';\nimport { logger } from './logger.js';\n\nconst BAGGAGE_HEADER_NAME = 'baggage';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","import { logger } from '@sentry/utils';\nimport { getActiveTransaction } from '../utils.js';\nimport { WINDOW } from './types.js';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() ;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType = 'cancelled';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n//# sourceMappingURL=backgroundtab.js.map\n","const bindReporter = (\n callback,\n metric,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getNavigationEntryFromPerformanceTiming = () => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0);\n }\n }\n return navigationEntry ;\n};\n\nconst getNavigationEntry = () => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\n","/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts,\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() );\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst onHidden = (cb, once) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n\nexport { onHidden };\n//# sourceMappingURL=onHidden.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport) => {\n const metric = initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n }\n};\n\nexport { onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { WINDOW } from '../../types.js';\nimport { onHidden } from './onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = () => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nconst getVisibilityWatcher = (\n\n) => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }, true);\n }\n};\n\nexport { onFID };\n//# sourceMappingURL=getFID.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nconst onLCP = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n const lastEntry = entries[entries.length - 1] ;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n }\n};\n\nexport { onLCP };\n//# sourceMappingURL=getLCP.js.map\n","/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nfunction _startChild(transaction, { startTimestamp, ...ctx }) {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\nexport { _startChild, isMeasurementValue };\n//# sourceMappingURL=utils.js.map\n","import { browserPerformanceTimeOrigin, logger, htmlTreeAsString } from '@sentry/utils';\nimport { msToSec, getActiveTransaction } from '../../utils.js';\nimport { WINDOW } from '../types.js';\nimport { onCLS } from '../web-vitals/getCLS.js';\nimport { onFID } from '../web-vitals/getFID.js';\nimport { onLCP } from '../web-vitals/getLCP.js';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher.js';\nimport { observe } from '../web-vitals/lib/observe.js';\nimport { _startChild, isMeasurementValue } from './utils.js';\n\nfunction getBrowserPerformanceAPI() {\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals\n */\nfunction startTrackingWebVitals() {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackCLS();\n _trackLCP();\n _trackFID();\n }\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS() {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry ;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin );\n const startTime = msToSec(entry.startTime);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(transaction) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp;\n let requestStartTimestamp;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name ).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nfunction _addMeasureSpans(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name ,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType ,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction, entry, timeOrigin) {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n event,\n timeOrigin,\n description,\n eventEnd,\n) {\n const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] );\n const start = entry[`${event}Start`] ;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction, entry, timeOrigin) {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n}\n\n/** Create resource-related spans */\nfunction _addResourceSpans(\n transaction,\n entry,\n resourceName,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction) {\n const navigator = WINDOW.navigator ;\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction) {\n if (_lcpEntry) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingLongTasks, startTrackingWebVitals };\n//# sourceMappingURL=index.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, dynamicSamplingContextToSentryBaggageHeader, isInstanceOf, BAGGAGE_HEADER_NAME, stringMatchesSomePattern } from '@sentry/utils';\nimport { hasTracingEnabled } from '../utils.js';\n\n/* eslint-disable max-lines */\n\nconst DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(_options) {\n // eslint-disable-next-line deprecation/deprecation\n const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url) =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData) => {\n fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData) => {\n xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nfunction shouldAttachHeaders(url, tracePropagationTargets) {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n */\nfunction fetchCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = handlerData.args[1];\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n options.headers = addTracingHeadersToFetchRequest(\n request,\n activeTransaction.getDynamicSamplingContext(),\n span,\n options,\n );\n\n activeTransaction.metadata.propagations++;\n }\n }\n}\n\nfunction addTracingHeadersToFetchRequest(\n request,\n dynamicSamplingContext,\n span,\n options\n\n,\n) {\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n const sentryTraceHeader = span.toTraceparent();\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request ).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers );\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended miultiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders ;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (\n !hasTracingEnabled() ||\n (handlerData.xhr && handlerData.xhr.__sentry_own_request__) ||\n !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))\n ) {\n return;\n }\n\n const xhr = handlerData.xhr.__sentry_xhr__;\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp) {\n const spanId = handlerData.xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...xhr.data,\n type: 'xhr',\n method: xhr.method,\n url: xhr.url,\n },\n description: `${xhr.method} ${xhr.url}`,\n op: 'http.client',\n });\n\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader && shouldAttachHeaders(handlerData.xhr.__sentry_xhr__.url)) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n\n const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n handlerData.xhr.setRequestHeader(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n activeTransaction.metadata.propagations++;\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n\nexport { DEFAULT_TRACE_PROPAGATION_TARGETS, defaultRequestInstrumentationOptions, fetchCallback, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n//# sourceMappingURL=request.js.map\n","import { logger, addInstrumentationHandler } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nfunction instrumentRoutingWithDefaults(\n customStartTransaction,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n if (!WINDOW || !WINDOW.location) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl = WINDOW.location.href;\n\n let activeTransaction;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n\nexport { instrumentRoutingWithDefaults };\n//# sourceMappingURL=router.js.map\n","import { logger, extractTraceparentData, baggageHeaderToDynamicSamplingContext, getDomElement } from '@sentry/utils';\nimport { startIdleTransaction } from '../hubextensions.js';\nimport { DEFAULT_IDLE_TIMEOUT, DEFAULT_FINAL_TIMEOUT, DEFAULT_HEARTBEAT_INTERVAL } from '../idletransaction.js';\nimport '@sentry/core';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { startTrackingWebVitals, startTrackingLongTasks, addPerformanceEntries } from './metrics/index.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\nimport { instrumentRoutingWithDefaults } from './router.js';\nimport { WINDOW } from './types.js';\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n idleTimeout: DEFAULT_IDLE_TIMEOUT,\n finalTimeout: DEFAULT_FINAL_TIMEOUT,\n heartbeatInterval: DEFAULT_HEARTBEAT_INTERVAL,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nclass BrowserTracing {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n\n /**\n * @inheritDoc\n */\n __init() {this.name = BROWSER_TRACING_INTEGRATION_ID;}\n\n constructor(_options) {BrowserTracing.prototype.__init.call(this);\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n _experiments,\n } = this.options;\n\n instrumentRouting(\n (context) => this._createRouteTransaction(context),\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n });\n }\n\n /** Create routing idle transaction. */\n _createRouteTransaction(context) {\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;\n const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;\n\n const traceParentData = sentryTraceMetaTagValue ? extractTraceparentData(sentryTraceMetaTagValue) : undefined;\n const dynamicSamplingContext = baggageMetaTagValue\n ? baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)\n : undefined;\n\n const expandedContext = {\n ...context,\n ...traceParentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n idleTransaction.registerBeforeFinishCallback(transaction => {\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction ;\n }\n\n /** Start listener for interaction transactions */\n _registerInteractionListener() {\n let inflightInteractionTransaction;\n const registerInteractionTransaction = () => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const op = 'ui.action.click';\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : null;\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing, getMetaContent };\n//# sourceMappingURL=browsertracing.js.map\n","import { addExtensionMethods } from './hubextensions.js';\nexport { addExtensionMethods, startIdleTransaction } from './hubextensions.js';\nimport * as index from './integrations/index.js';\nexport { index as Integrations };\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing } from './browser/browsertracing.js';\nexport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './browser/request.js';\nexport { Span, spanStatusfromHttpCode } from './span.js';\nexport { SpanStatus } from './spanstatus.js';\nexport { Transaction } from './transaction.js';\nexport { IdleTransaction } from './idletransaction.js';\nexport { getActiveTransaction, hasTracingEnabled } from './utils.js';\nexport { TRACEPARENT_REGEXP, extractTraceparentData, stripUrlQueryAndFragment } from '@sentry/utils';\n\n// Treeshakable guard to remove all code related to tracing\n\n// Guard for tree\nif (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {\n // We are patching the global object with our hub extension methods\n addExtensionMethods();\n}\n//# sourceMappingURL=index.js.map\n","import { SDK_VERSION } from '@sentry/core';\n\nconst PACKAGE_NAME_PREFIX = 'npm:@sentry/';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n * @param options sdk options object that gets mutated\n * @param names list of package names\n */\nfunction buildMetadata(options, names) {\n options._metadata = options._metadata || {};\n options._metadata.sdk =\n options._metadata.sdk ||\n ({\n name: 'sentry.javascript.nextjs',\n packages: names.map(name => ({\n name: `${PACKAGE_NAME_PREFIX}${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n } );\n}\n\nexport { buildMetadata };\n//# sourceMappingURL=metadata.js.map\n","/**\n * Recursively traverses an object to update an existing nested key.\n * Note: The provided key path must include existing properties,\n * the function will not create objects while traversing.\n *\n * @param obj An object to update\n * @param value The value to update the nested key with\n * @param keyPath The path to the key to update ex. fizz.buzz.foo\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setNestedKey(obj, keyPath, value) {\n // Ex. foo.bar.zoop will extract foo and bar.zoop\n const match = keyPath.match(/([a-z_]+)\\.(.*)/i);\n // The match will be null when there's no more recursing to do, i.e., when we've reached the right level of the object\n if (match === null) {\n obj[keyPath] = value;\n } else {\n // `match[1]` is the initial segment of the path, and `match[2]` is the remainder of the path\n const innerObj = obj[match[1]];\n setNestedKey(innerObj, match[2], value);\n }\n}\n\n/**\n * Enforces inclusion of a given integration with specified options in an integration array originally determined by the\n * user, by either including the given default instance or by patching an existing user instance with the given options.\n *\n * Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging\n * options from a default integration instance with those from a user-provided instance of the same integration, only\n * for allowing the user to override a default instance entirely. (TODO: Fix that.)\n *\n * @param defaultIntegrationInstance An instance of the integration with the correct options already set\n * @param userIntegrations Integrations defined by the user.\n * @param forcedOptions Options with which to patch an existing user-derived instance on the integration.\n * @returns A final integrations array.\n */\nfunction addOrUpdateIntegration(\n defaultIntegrationInstance,\n userIntegrations,\n forcedOptions = {},\n) {\n return (\n Array.isArray(userIntegrations)\n ? addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions)\n : addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance,\n // Somehow TS can't figure out that not being an array makes this necessarily a function\n userIntegrations ,\n forcedOptions,\n )\n ) ;\n}\n\nfunction addOrUpdateIntegrationInArray(\n defaultIntegrationInstance,\n userIntegrations,\n forcedOptions,\n) {\n const userInstance = userIntegrations.find(integration => integration.name === defaultIntegrationInstance.name);\n\n if (userInstance) {\n for (const [keyPath, value] of Object.entries(forcedOptions)) {\n setNestedKey(userInstance, keyPath, value);\n }\n\n return userIntegrations;\n }\n\n return [...userIntegrations, defaultIntegrationInstance];\n}\n\nfunction addOrUpdateIntegrationInFunction(\n defaultIntegrationInstance,\n userIntegrationsFunc,\n forcedOptions,\n) {\n const wrapper = defaultIntegrations => {\n const userFinalIntegrations = userIntegrationsFunc(defaultIntegrations);\n\n // There are instances where we want the user to be able to prevent an integration from appearing at all, which they\n // would do by providing a function which filters out the integration in question. If that's happened in one of\n // those cases, don't add our default back in.\n if (defaultIntegrationInstance.allowExclusionByUser) {\n const userFinalInstance = userFinalIntegrations.find(\n integration => integration.name === defaultIntegrationInstance.name,\n );\n if (!userFinalInstance) {\n return userFinalIntegrations;\n }\n }\n\n return addOrUpdateIntegrationInArray(defaultIntegrationInstance, userFinalIntegrations, forcedOptions);\n };\n\n return wrapper;\n}\n\nexport { addOrUpdateIntegration };\n//# sourceMappingURL=userIntegrations.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { WINDOW } from '@sentry/react';\nimport { baggageHeaderToDynamicSamplingContext, stripUrlQueryAndFragment, logger, extractTraceparentData } from '@sentry/utils';\nimport Router from 'next/router';\n\nconst globalObject = WINDOW\n\n;\n\n/**\n * Every Next.js page (static and dynamic ones) comes with a script tag with the id \"__NEXT_DATA__\". This script tag\n * contains a JSON object with data that was either generated at build time for static pages (`getStaticProps`), or at\n * runtime with data fetchers like `getServerSideProps.`.\n *\n * We can use this information to:\n * - Always get the parameterized route we're in when loading a page.\n * - Send trace information (trace-id, baggage) from the server to the client.\n *\n * This function extracts this information.\n */\nfunction extractNextDataTagInformation() {\n let nextData;\n // Let's be on the safe side and actually check first if there is really a __NEXT_DATA__ script tag on the page.\n // Theoretically this should always be the case though.\n const nextDataTag = globalObject.document.getElementById('__NEXT_DATA__');\n if (nextDataTag && nextDataTag.innerHTML) {\n try {\n nextData = JSON.parse(nextDataTag.innerHTML);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Could not extract __NEXT_DATA__');\n }\n }\n\n if (!nextData) {\n return {};\n }\n\n const nextDataTagInfo = {};\n\n const { page, query, props } = nextData;\n\n // `nextData.page` always contains the parameterized route - except for when an error occurs in a data fetching\n // function, then it is \"/_error\", but that isn't a problem since users know which route threw by looking at the\n // parent transaction\n // TODO: Actually this is a problem (even though it is not that big), because the DSC and the transaction payload will contain\n // a different transaction name. Maybe we can fix this. Idea: Also send transaction name via pageProps when available.\n nextDataTagInfo.route = page;\n nextDataTagInfo.params = query;\n\n if (props && props.pageProps) {\n if (props.pageProps._sentryBaggage) {\n nextDataTagInfo.baggage = props.pageProps._sentryBaggage;\n }\n\n if (props.pageProps._sentryTraceData) {\n nextDataTagInfo.traceParentData = extractTraceparentData(props.pageProps._sentryTraceData);\n }\n }\n\n return nextDataTagInfo;\n}\n\nconst DEFAULT_TAGS = {\n 'routing.instrumentation': 'next-router',\n} ;\n\n// We keep track of the active transaction so we can finish it when we start a navigation transaction.\nlet activeTransaction = undefined;\n\n// We keep track of the previous location name so we can set the `from` field on navigation transactions.\n// This is either a route or a pathname.\nlet prevLocationName = undefined;\n\nconst client = getCurrentHub().getClient();\n\n/**\n * Creates routing instrumention for Next Router. Only supported for\n * client side routing. Works for Next >= 10.\n *\n * Leverages the SingletonRouter from the `next/router` to\n * generate pageload/navigation transactions and parameterize\n * transaction names.\n */\nfunction nextRouterInstrumentation(\n startTransactionCb,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n const { route, traceParentData, baggage, params } = extractNextDataTagInformation();\n prevLocationName = route || globalObject.location.pathname;\n\n if (startTransactionOnPageLoad) {\n const source = route ? 'route' : 'url';\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n activeTransaction = startTransactionCb({\n name: prevLocationName,\n op: 'pageload',\n tags: DEFAULT_TAGS,\n ...(params && client && client.getOptions().sendDefaultPii && { data: params }),\n ...traceParentData,\n metadata: {\n source,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n });\n }\n\n if (startTransactionOnLocationChange) {\n Router.events.on('routeChangeStart', (navigationTarget) => {\n const matchedRoute = getNextRouteFromPathname(stripUrlQueryAndFragment(navigationTarget));\n\n let transactionName;\n let transactionSource;\n\n if (matchedRoute) {\n transactionName = matchedRoute;\n transactionSource = 'route';\n } else {\n transactionName = navigationTarget;\n transactionSource = 'url';\n }\n\n const tags = {\n ...DEFAULT_TAGS,\n from: prevLocationName,\n };\n\n prevLocationName = transactionName;\n\n if (activeTransaction) {\n activeTransaction.finish();\n }\n\n const navigationTransaction = startTransactionCb({\n name: transactionName,\n op: 'navigation',\n tags,\n metadata: { source: transactionSource },\n });\n\n if (navigationTransaction) {\n // In addition to the navigation transaction we're also starting a span to mark Next.js's `routeChangeStart`\n // and `routeChangeComplete` events.\n // We don't want to finish the navigation transaction on `routeChangeComplete`, since users might want to attach\n // spans to that transaction even after `routeChangeComplete` is fired (eg. HTTP requests in some useEffect\n // hooks). Instead, we'll simply let the navigation transaction finish itself (it's an `IdleTransaction`).\n const nextRouteChangeSpan = navigationTransaction.startChild({\n op: 'ui.nextjs.route-change',\n description: 'Next.js Route Change',\n });\n\n const finishRouteChangeSpan = () => {\n nextRouteChangeSpan.finish();\n Router.events.off('routeChangeComplete', finishRouteChangeSpan);\n };\n\n Router.events.on('routeChangeComplete', finishRouteChangeSpan);\n }\n });\n }\n}\n\nfunction getNextRouteFromPathname(pathname) {\n const pageRoutes = (globalObject.__BUILD_MANIFEST || {}).sortedPages;\n\n // Page route should in 99.999% of the cases be defined by now but just to be sure we make a check here\n if (!pageRoutes) {\n return;\n }\n\n return pageRoutes.find(route => {\n const routeRegExp = convertNextRouteToRegExp(route);\n return pathname.match(routeRegExp);\n });\n}\n\n/**\n * Converts a Next.js style route to a regular expression that matches on pathnames (no query params or URL fragments).\n *\n * In general this involves replacing any instances of square brackets in a route with a wildcard:\n * e.g. \"/users/[id]/info\" becomes /\\/users\\/([^/]+?)\\/info/\n *\n * Some additional edgecases need to be considered:\n * - All routes have an optional slash at the end, meaning users can navigate to \"/users/[id]/info\" or\n * \"/users/[id]/info/\" - both will be resolved to \"/users/[id]/info\".\n * - Non-optional \"catchall\"s at the end of a route must be considered when matching (e.g. \"/users/[...params]\").\n * - Optional \"catchall\"s at the end of a route must be considered when matching (e.g. \"/users/[[...params]]\").\n *\n * @param route A Next.js style route as it is found in `global.__BUILD_MANIFEST.sortedPages`\n */\nfunction convertNextRouteToRegExp(route) {\n // We can assume a route is at least \"/\".\n const routeParts = route.split('/');\n\n let optionalCatchallWildcardRegex = '';\n if (routeParts[routeParts.length - 1].match(/^\\[\\[\\.\\.\\..+\\]\\]$/)) {\n // If last route part has pattern \"[[...xyz]]\" we pop the latest route part to get rid of the required trailing\n // slash that would come before it if we didn't pop it.\n routeParts.pop();\n optionalCatchallWildcardRegex = '(?:/(.+?))?';\n }\n\n const rejoinedRouteParts = routeParts\n .map(\n routePart =>\n routePart\n .replace(/^\\[\\.\\.\\..+\\]$/, '(.+?)') // Replace catch all wildcard with regex wildcard\n .replace(/^\\[.*\\]$/, '([^/]+?)'), // Replace route wildcards with lazy regex wildcards\n )\n .join('/');\n\n return new RegExp(\n `^${rejoinedRouteParts}${optionalCatchallWildcardRegex}(?:/)?$`, // optional slash at the end\n );\n}\n\nexport { nextRouterInstrumentation };\n//# sourceMappingURL=performance.js.map\n","import { dsnFromString, logger } from '@sentry/utils';\n\nconst globalWithInjectedValues = global\n\n;\n\n/**\n * Applies the `tunnel` option to the Next.js SDK options based on `withSentryConfig`'s `tunnelRoute` option.\n */\nfunction applyTunnelRouteOption(options) {\n const tunnelRouteOption = globalWithInjectedValues.__sentryRewritesTunnelPath__;\n if (tunnelRouteOption && options.dsn) {\n const dsnComponents = dsnFromString(options.dsn);\n const sentrySaasDsnMatch = dsnComponents.host.match(/^o(\\d+)\\.ingest\\.sentry\\.io$/);\n if (sentrySaasDsnMatch) {\n const orgId = sentrySaasDsnMatch[1];\n const tunnelPath = `${tunnelRouteOption}?o=${orgId}&p=${dsnComponents.projectId}`;\n options.tunnel = tunnelPath;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.info(`Tunneling events to \"${tunnelPath}\"`);\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Provided DSN is not a Sentry SaaS DSN. Will not tunnel events.');\n }\n }\n}\n\nexport { applyTunnelRouteOption };\n//# sourceMappingURL=tunnelRoute.js.map\n","import { withScope, captureException, getCurrentHub } from '@sentry/core';\nimport { addExceptionMechanism } from '@sentry/utils';\n\n/** Platform-agnostic version of `flush` */\nfunction flush(timeout) {\n const client = getCurrentHub().getClient();\n return client ? client.flush(timeout) : Promise.resolve(false);\n}\n\n/**\n * Capture the exception passed by nextjs to the `_error` page, adding context data as appropriate.\n *\n * @param contextOrProps The data passed to either `getInitialProps` or `render` by nextjs\n */\nasync function captureUnderscoreErrorException(contextOrProps) {\n const { req, res, err } = contextOrProps;\n\n // 404s (and other 400-y friends) can trigger `_error`, but we don't want to send them to Sentry\n const statusCode = (res && res.statusCode) || contextOrProps.statusCode;\n if (statusCode && statusCode < 500) {\n return Promise.resolve();\n }\n\n // In previous versions of the suggested `_error.js` page in which this function is meant to be used, there was a\n // workaround for https://github.com/vercel/next.js/issues/8592 which involved an extra call to this function, in the\n // custom error component's `render` method, just in case it hadn't been called by `getInitialProps`. Now that that\n // issue has been fixed, the second call is unnecessary, but since it lives in user code rather than our code, users\n // have to be the ones to get rid of it, and guaraneteedly, not all of them will. So, rather than capture the error\n // twice, we just bail if we sense we're in that now-extraneous second call. (We can tell which function we're in\n // because Nextjs passes `pathname` to `getInitialProps` but not to `render`.)\n if (!contextOrProps.pathname) {\n return Promise.resolve();\n }\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n addExceptionMechanism(event, {\n type: 'instrument',\n handled: true,\n data: {\n function: '_error.getInitialProps',\n },\n });\n return event;\n });\n\n if (req) {\n scope.setSDKProcessingMetadata({ request: req });\n }\n\n // If third-party libraries (or users themselves) throw something falsy, we want to capture it as a message (which\n // is what passing a string to `captureException` will wind up doing)\n captureException(err || `_error.js called with falsy error (${err})`);\n });\n\n // In case this is being run as part of a serverless function (as is the case with the server half of nextjs apps\n // deployed to vercel), make sure the error gets sent to Sentry before the lambda exits.\n await flush(2000);\n}\n\nexport { captureUnderscoreErrorException };\n//# sourceMappingURL=_error.js.map\n","import { _optionalChain } from '@sentry/utils/esm/buildPolyfills';\nimport { RewriteFrames } from '@sentry/integrations';\nimport { init as init$1, configureScope } from '@sentry/react';\nexport * from '@sentry/react';\nexport { Integrations } from '@sentry/react';\nimport { hasTracingEnabled, BrowserTracing, defaultRequestInstrumentationOptions } from '@sentry/tracing';\nexport { BrowserTracing } from '@sentry/tracing';\nimport { buildMetadata } from '../common/metadata.js';\nimport { addOrUpdateIntegration } from '../common/userIntegrations.js';\nimport { nextRouterInstrumentation } from './performance.js';\nexport { nextRouterInstrumentation } from './performance.js';\nimport { applyTunnelRouteOption } from './tunnelRoute.js';\nexport { captureUnderscoreErrorException } from '../common/_error.js';\nexport { withSentryServerSideGetInitialProps, wrapGetInitialPropsWithSentry } from './wrapGetInitialPropsWithSentry.js';\nexport { withSentryServerSideAppGetInitialProps, wrapAppGetInitialPropsWithSentry } from './wrapAppGetInitialPropsWithSentry.js';\nexport { withSentryServerSideDocumentGetInitialProps, wrapDocumentGetInitialPropsWithSentry } from './wrapDocumentGetInitialPropsWithSentry.js';\nexport { withSentryServerSideErrorGetInitialProps, wrapErrorGetInitialPropsWithSentry } from './wrapErrorGetInitialPropsWithSentry.js';\nexport { wrapAppDirComponentWithSentry } from './wrapAppDirComponentWithSentry.js';\n\n// Treeshakable guard to remove all code related to tracing\n\nconst globalWithInjectedValues = global\n\n;\n\n/** Inits the Sentry NextJS SDK on the browser with the React SDK. */\nfunction init(options) {\n applyTunnelRouteOption(options);\n buildMetadata(options, ['nextjs', 'react']);\n options.environment = options.environment || process.env.NODE_ENV;\n addClientIntegrations(options);\n\n init$1(options);\n\n configureScope(scope => {\n scope.setTag('runtime', 'browser');\n const filterTransactions = event =>\n event.type === 'transaction' && event.transaction === '/404' ? null : event;\n filterTransactions.id = 'NextClient404Filter';\n scope.addEventProcessor(filterTransactions);\n });\n}\n\nfunction addClientIntegrations(options) {\n let integrations = options.integrations || [];\n\n // This value is injected at build time, based on the output directory specified in the build config. Though a default\n // is set there, we set it here as well, just in case something has gone wrong with the injection.\n const assetPrefixPath = globalWithInjectedValues.__rewriteFramesAssetPrefixPath__ || '';\n\n const defaultRewriteFramesIntegration = new RewriteFrames({\n // Turn `//_next/static/...` into `app:///_next/static/...`\n iteratee: frame => {\n try {\n const { origin } = new URL(frame.filename );\n frame.filename = _optionalChain([frame, 'access', _ => _.filename, 'optionalAccess', _2 => _2.replace, 'call', _3 => _3(origin, 'app://'), 'access', _4 => _4.replace, 'call', _5 => _5(assetPrefixPath, '')]);\n } catch (err) {\n // Filename wasn't a properly formed URL, so there's nothing we can do\n }\n\n if (frame.filename && frame.filename.startsWith('app:///_next')) {\n // We need to URI-decode the filename because Next.js has wildcard routes like \"/users/[id].js\" which show up as \"/users/%5id%5.js\" in Error stacktraces.\n // The corresponding sources that Next.js generates have proper brackets so we also need proper brackets in the frame so that source map resolving works.\n frame.filename = decodeURI(frame.filename);\n }\n\n if (\n frame.filename &&\n frame.filename.match(\n /^app:\\/\\/\\/_next\\/static\\/chunks\\/(main-|main-app-|polyfills-|webpack-|framework-|framework\\.)[0-9a-f]+\\.js$/,\n )\n ) {\n // We don't care about these frames. It's Next.js internal code.\n frame.in_app = false;\n }\n\n return frame;\n },\n });\n integrations = addOrUpdateIntegration(defaultRewriteFramesIntegration, integrations);\n\n // This evaluates to true unless __SENTRY_TRACING__ is text-replaced with \"false\", in which case everything inside\n // will get treeshaken away\n if (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {\n if (hasTracingEnabled(options)) {\n const defaultBrowserTracingIntegration = new BrowserTracing({\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins: [...defaultRequestInstrumentationOptions.tracingOrigins, /^(api\\/)/],\n routingInstrumentation: nextRouterInstrumentation,\n });\n\n integrations = addOrUpdateIntegration(defaultBrowserTracingIntegration, integrations, {\n 'options.routingInstrumentation': nextRouterInstrumentation,\n });\n }\n }\n\n options.integrations = integrations;\n}\n\nexport { init };\n//# sourceMappingURL=index.js.map\n","export * from \"./client\";","import { addInstrumentationHandler, logger } from '@sentry/utils';\nimport { getActiveTransaction } from './utils.js';\n\n/**\n * Configures global error listeners\n */\nfunction registerErrorInstrumentation() {\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback() {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status = 'internal_error';\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\nexport { registerErrorInstrumentation };\n//# sourceMappingURL=errors.js.map\n","import { getMainCarrier } from '@sentry/core';\nimport { isNodeEnv, logger, isNaN, loadModule, dynamicRequire } from '@sentry/utils';\nimport { registerErrorInstrumentation } from './errors.js';\nimport { IdleTransaction } from './idletransaction.js';\nimport { Transaction } from './transaction.js';\nimport { hasTracingEnabled } from './utils.js';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders() {\n const scope = this.getScope();\n if (scope) {\n const span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(\n transaction,\n options,\n samplingContext,\n) {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate );\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n\n transactionContext,\n customSamplingContext,\n) {\n const client = this.getClient();\n const options = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nfunction startIdleTransaction(\n hub,\n transactionContext,\n idleTimeout,\n finalTimeout,\n onScope,\n customSamplingContext,\n heartbeatInterval,\n) {\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n return transaction;\n}\n\n/**\n * @private\n */\nfunction _addTracingExtensions() {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations() {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping = {\n mongodb() {\n const integration = dynamicRequire(module, './integrations/node/mongo')\n\n;\n return new integration.Mongo();\n },\n mongoose() {\n const integration = dynamicRequire(module, './integrations/node/mongo')\n\n;\n return new integration.Mongo({ mongoose: true });\n },\n mysql() {\n const integration = dynamicRequire(module, './integrations/node/mysql')\n\n;\n return new integration.Mysql();\n },\n pg() {\n const integration = dynamicRequire(module, './integrations/node/postgres')\n\n;\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) ;\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nfunction addExtensionMethods() {\n _addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n\n // If an error happens globally, we should make sure transaction status is set to error.\n registerErrorInstrumentation();\n}\n\nexport { _addTracingExtensions, addExtensionMethods, startIdleTransaction };\n//# sourceMappingURL=hubextensions.js.map\n","import { logger, timestampWithMs } from '@sentry/utils';\nimport { SpanRecorder } from './span.js';\nimport { Transaction } from './transaction.js';\n\nconst DEFAULT_IDLE_TIMEOUT = 1000;\nconst DEFAULT_FINAL_TIMEOUT = 30000;\nconst DEFAULT_HEARTBEAT_INTERVAL = 5000;\n\n/**\n * @inheritDoc\n */\nclass IdleTransactionSpanRecorder extends SpanRecorder {\n constructor(\n _pushActivity,\n _popActivity,\n transactionSpanId,\n maxlen,\n ) {\n super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }\n\n /**\n * @inheritDoc\n */\n add(span) {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nclass IdleTransaction extends Transaction {\n // Activities store a list of active spans\n __init() {this.activities = {};}\n\n // Track state of activities in previous heartbeat\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n __init2() {this._heartbeatCounter = 0;}\n\n // We should not use heartbeat if we finished a transaction\n __init3() {this._finished = false;}\n\n __init4() {this._beforeFinishCallbacks = [];}\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n\n constructor(\n transactionContext,\n _idleHub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n _idleTimeout = DEFAULT_IDLE_TIMEOUT,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n _finalTimeout = DEFAULT_FINAL_TIMEOUT,\n _heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n _onScope = false,\n ) {\n super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;IdleTransaction.prototype.__init.call(this);IdleTransaction.prototype.__init2.call(this);IdleTransaction.prototype.__init3.call(this);IdleTransaction.prototype.__init4.call(this);\n if (_onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._startIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n finish(endTimestamp = timestampWithMs()) {\n this._finished = true;\n this.activities = {};\n\n if (this.spanRecorder) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n registerBeforeFinishCallback(callback) {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n initSpanRecorder(maxlen) {\n if (!this.spanRecorder) {\n const pushActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idletimeout, if there is one\n */\n _cancelIdleTimeout() {\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n }\n }\n\n /**\n * Creates an idletimeout\n */\n _startIdleTimeout(endTimestamp) {\n this._cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n _pushActivity(spanId) {\n this._cancelIdleTimeout();\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n _popActivity(spanId) {\n if (this.activities[spanId]) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n const endTimestamp = timestampWithMs() + this._idleTimeout / 1000;\n this._startIdleTimeout(endTimestamp);\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n _beat() {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n _pingHeartbeat() {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n\n/**\n * Reset transaction on scope to `undefined`\n */\nfunction clearActiveTransaction(hub) {\n const scope = hub.getScope();\n if (scope) {\n const transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n}\n\nexport { DEFAULT_FINAL_TIMEOUT, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_IDLE_TIMEOUT, IdleTransaction, IdleTransactionSpanRecorder };\n//# sourceMappingURL=idletransaction.js.map\n","import { uuid4, timestampWithMs, logger, dropUndefinedKeys } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nclass SpanRecorder {\n __init() {this.spans = [];}\n\n constructor(maxlen = 1000) {SpanRecorder.prototype.__init.call(this);\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n add(span) {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nclass Span {\n /**\n * @inheritDoc\n */\n __init2() {this.traceId = uuid4();}\n\n /**\n * @inheritDoc\n */\n __init3() {this.spanId = uuid4().substring(16);}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Internal keeper of the status\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * Timestamp in seconds when the span was created.\n */\n __init4() {this.startTimestamp = timestampWithMs();}\n\n /**\n * Timestamp in seconds when the span ended.\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n __init5() {this.tags = {};}\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n __init6() {this.data = {};}\n\n /**\n * List of spans that were finalized\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * The instrumenter that created this span.\n */\n __init7() {this.instrumenter = 'sentry';}\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext) {Span.prototype.__init2.call(this);Span.prototype.__init3.call(this);Span.prototype.__init4.call(this);Span.prototype.__init5.call(this);Span.prototype.__init6.call(this);Span.prototype.__init7.call(this);\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n if (spanContext.instrumenter) {\n this.instrumenter = spanContext.instrumenter;\n }\n }\n\n /**\n * @inheritDoc\n */\n startChild(\n spanContext,\n ) {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n setData(key, value) {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setHttpStatus(httpStatus) {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n isSuccess() {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n if (\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage ).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n toTraceparent() {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(spanContext) {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getTraceContext() {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n toJSON()\n\n {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nfunction spanStatusfromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\nexport { Span, SpanRecorder, spanStatusfromHttpCode };\n//# sourceMappingURL=span.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { timestampInSeconds, logger, dropUndefinedKeys } from '@sentry/utils';\nimport { Span, SpanRecorder } from './span.js';\n\n/** JSDoc */\nclass Transaction extends Span {\n\n /**\n * The reference to the current hub.\n */\n\n __init() {this._measurements = {};}\n\n __init2() {this._contexts = {};}\n\n __init3() {this._frozenDynamicSamplingContext = undefined;}\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(transactionContext, hub) {\n super(transactionContext);Transaction.prototype.__init.call(this);Transaction.prototype.__init2.call(this);Transaction.prototype.__init3.call(this);\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n changes: [],\n propagations: 0,\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n get name() {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n set name(newName) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n setName(name, source = 'custom') {\n // `source` could change without the name changing if we discover that an unparameterized route is actually\n // parameterized by virtue of having no parameters in its path\n if (name !== this.name || source !== this.metadata.source) {\n this.metadata.changes.push({\n // log previous source\n source: this.metadata.source,\n timestamp: timestampInSeconds(),\n propagations: this.metadata.propagations,\n });\n }\n\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n initSpanRecorder(maxlen = 1000) {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n setMeasurement(name, value, unit = '') {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n setMetadata(newMetadata) {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n const client = this._hub.getClient();\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev, current) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n changes: metadata.changes,\n propagations: metadata.propagations,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(transactionContext) {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n getDynamicSamplingContext() {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub = this._hub || getCurrentHub();\n const client = hub && hub.getClient();\n\n if (!client) return {};\n\n const { environment, release } = client.getOptions() || {};\n const { publicKey: public_key } = client.getDsn() || {};\n\n const maybeSampleRate = this.metadata.sampleRate;\n const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;\n\n const scope = hub.getScope();\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const source = this.metadata.source;\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const transaction = source && source !== 'url' ? this.name : undefined;\n\n const dsc = dropUndefinedKeys({\n environment,\n release,\n transaction,\n user_segment,\n public_key,\n trace_id: this.traceId,\n sample_rate,\n });\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n return dsc;\n }\n}\n\nexport { Transaction };\n//# sourceMappingURL=transaction.js.map\n","import { getCurrentHub } from '@sentry/core';\nexport { TRACEPARENT_REGEXP, extractTraceparentData, stripUrlQueryAndFragment } from '@sentry/utils';\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && ('tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\n/** Grabs active transaction off scope, if any */\nfunction getActiveTransaction(maybeHub) {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope && (scope.getTransaction() );\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\nexport { getActiveTransaction, hasTracingEnabled, msToSec };\n//# sourceMappingURL=utils.js.map\n","import { isString } from './is.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\nexport { getDomElement, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // @ts-ignore \"npm\" is injected by rollup during build process\n return \"npm\";\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isInstanceOf, isString } from './is.js';\nimport { logger, CONSOLE_LEVELS } from './logger.js';\nimport { fill } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\nimport { supportsNativeFetch, supportsHistory } from './supports.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers = {};\nconst instrumented = {};\n\n/** Instruments given API */\nfunction instrument(type) {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addInstrumentationHandler(type, callback) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type, data) {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole() {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod) {\n return function (...args) {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch() {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch) {\n return function (...args) {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs = []) {\n if ('Request' in WINDOW && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs = []) {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in WINDOW && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR() {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n const xhrInfo = (xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function () {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhr.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function (original) {\n return function (...readyStateArgs) {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend) {\n return function ( ...args) {\n if (this.__sentry_xhr__ && args[0] !== undefined) {\n this.__sentry_xhr__.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref;\n\n/** JSDoc */\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID;\nlet lastCapturedEvent;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous, current) {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event) {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target ;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler, globalListener = false) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\n/** JSDoc */\nfunction instrumentDOM() {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW )[target] && (WINDOW )[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler = null;\n/** JSDoc */\nfunction instrumentError() {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg, url, line, column, error) {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e) {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n\nexport { addInstrumentationHandler };\n//# sourceMappingURL=instrument.js.map\n","// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isNaN(wat) {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isNaN, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable };\n//# sourceMappingURL=is.js.map\n","import { getGlobalSingleton, GLOBAL_OBJ } from './worldwide.js';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ;\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console ;\n const wrappedLevels = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] ).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] ;\n originalConsole[level] = originalWrappedFunc ;\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level ];\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger;\nif ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger };\n//# sourceMappingURL=logger.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception ).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nfunction loadModule(moduleName) {\n let mod;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n\nexport { dynamicRequire, isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { htmlTreeAsString } from './browser.js';\nimport { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';\nimport { truncate } from './string.js';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nfunction urlEncode(object) {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode };\n//# sourceMappingURL=object.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nconst STACKTRACE_LIMIT = 50;\n\nconst debugIdParserCache = new Map();\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirst = 0) => {\n const frames = [];\n\n for (const parser of sortedParsers) {\n let debugIdCache = debugIdParserCache.get(parser);\n if (!debugIdCache) {\n debugIdCache = new Map();\n debugIdParserCache.set(parser, debugIdCache);\n }\n\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (debugIdMap) {\n Object.keys(debugIdMap).forEach(debugIdStackTrace => {\n debugIdStackTrace.split('\\n').forEach(line => {\n const frame = parser(line);\n if (frame && frame.filename) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n debugIdCache.set(frame.filename, debugIdMap[debugIdStackTrace]);\n }\n });\n });\n }\n }\n\n for (const line of stack.split('\\n').slice(skipFirst)) {\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = line.replace(/\\(error: (.*)\\)/, '$1');\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n const debugIdCache = debugIdParserCache.get(parser);\n if (debugIdCache && frame.filename) {\n const cachedDebugId = debugIdCache.get(frame.filename);\n if (cachedDebugId) {\n frame.debug_id = cachedDebugId;\n }\n }\n\n frames.push(frame);\n break;\n }\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n let localStack = stack;\n\n const firstFrameFunction = localStack[0].function || '';\n const lastFrameFunction = localStack[localStack.length - 1].function || '';\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {\n localStack = localStack.slice(0, -1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack\n .slice(0, STACKTRACE_LIMIT)\n .map(frame => ({\n ...frame,\n filename: frame.filename || localStack[0].filename,\n function: frame.function || '?',\n }))\n .reverse();\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n// eslint-disable-next-line complexity\nfunction node(getModule) {\n const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n\n // eslint-disable-next-line complexity\n return (line) => {\n if (line.match(FILENAME_MATCH)) {\n return {\n filename: line,\n };\n }\n\n const lineMatch = line.match(FULL_MATCH);\n if (!lineMatch) {\n return undefined;\n }\n\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n methodStart--;\n }\n\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = undefined;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '') {\n methodName = undefined;\n functionName = undefined;\n }\n\n if (functionName === undefined) {\n methodName = methodName || '';\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n\n const filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = lineMatch[5] === 'native';\n const isInternal =\n isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\\\') !== 1);\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/');\n\n return {\n filename,\n module: getModule ? getModule(filename) : undefined,\n function: functionName,\n lineno: parseInt(lineMatch[3], 10) || undefined,\n colno: parseInt(lineMatch[4], 10) || undefined,\n in_app,\n };\n };\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nfunction nodeStackLineParser(getModule) {\n return [90, node(getModule)];\n}\n\nexport { createStackParser, getFunctionName, nodeStackLineParser, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { isString, isRegExp } from './is.js';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nfunction escapeStringForRegex(regexString) {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n\nexport { escapeStringForRegex, isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { logger } from './logger.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFetch(func) {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW ).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexport { isNativeFetch, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsHistory, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n __init() {this._state = States.PENDING;}\n __init2() {this._handlers = [];}\n\n constructor(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this);\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** JSDoc */\n __init3() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init4() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init5() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init6() {this._executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };}\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import { isNodeEnv, dynamicRequire } from './node.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance() {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance() {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') ;\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nconst dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nconst timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nconst usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nlet _browserPerformanceTimeOriginMode;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nconst browserPerformanceTimeOrigin = (() => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds, timestampWithMs, usingPerformanceAPI };\n//# sourceMappingURL=time.js.map\n","/** Internal global with common properties and Sentry extensions */\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj) {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function () {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nfunction getGlobalObject() {\n return GLOBAL_OBJ ;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n\nexport { GLOBAL_OBJ, getGlobalObject, getGlobalSingleton };\n//# sourceMappingURL=worldwide.js.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function() {\n return _asyncToGenerator;\n }\n});\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nfunction _asyncToGenerator(fn) {\n return function() {\n var self = this, args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function() {\n return _extends;\n }\n});\nfunction extends_() {\n extends_ = Object.assign || function(target) {\n for(var i = 1; i < arguments.length; i++){\n var source = arguments[i];\n for(var key in source){\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return extends_.apply(this, arguments);\n}\nfunction _extends() {\n return extends_.apply(this, arguments);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function() {\n return _interopRequireDefault;\n }\n});\nfunction _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n default: obj\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function() {\n return _interopRequireWildcard;\n }\n});\nfunction _getRequireWildcardCache(nodeInterop) {\n if (typeof WeakMap !== \"function\") return null;\n var cacheBabelInterop = new WeakMap();\n var cacheNodeInterop = new WeakMap();\n return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {\n return nodeInterop ? cacheNodeInterop : cacheBabelInterop;\n })(nodeInterop);\n}\nfunction _interopRequireWildcard(obj, nodeInterop) {\n if (!nodeInterop && obj && obj.__esModule) {\n return obj;\n }\n if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") {\n return {\n default: obj\n };\n }\n var cache = _getRequireWildcardCache(nodeInterop);\n if (cache && cache.has(obj)) {\n return cache.get(obj);\n }\n var newObj = {};\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n for(var key in obj){\n if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n if (desc && (desc.get || desc.set)) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n newObj.default = obj;\n if (cache) {\n cache.set(obj, newObj);\n }\n return newObj;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function() {\n return _objectWithoutPropertiesLoose;\n }\n});\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for(i = 0; i < sourceKeys.length; i++){\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\n","\"trimStart\"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),\"trimEnd\"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),\"description\"in Symbol.prototype||Object.defineProperty(Symbol.prototype,\"description\",{configurable:!0,get:function(){var t=/\\((.*)\\)/.exec(this.toString());return t?t[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(t,r){return r=this.concat.apply([],this),t>1&&r.some(Array.isArray)?r.flat(t-1):r},Array.prototype.flatMap=function(t,r){return this.map(t,r).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(t){if(\"function\"!=typeof t)return this.then(t,t);var r=this.constructor||Promise;return this.then(function(o){return r.resolve(t()).then(function(){return o})},function(o){return r.resolve(t()).then(function(){throw o})})}),Object.fromEntries||(Object.fromEntries=function(t){return Array.from(t).reduce(function(t,r){return t[r[0]]=r[1],t},{})});\n","\"use strict\";\nvar ref, ref1;\nmodule.exports = ((ref = global.process) == null ? void 0 : ref.env) && typeof ((ref1 = global.process) == null ? void 0 : ref1.env) === \"object\" ? global.process : require(\"../../compiled/process\");\n\n//# sourceMappingURL=process.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.addBasePath = addBasePath;\nvar _addPathPrefix = require(\"../shared/lib/router/utils/add-path-prefix\");\nvar _normalizeTrailingSlash = require(\"./normalize-trailing-slash\");\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nfunction addBasePath(path, required) {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!required) {\n return path;\n }\n }\n return (0, _normalizeTrailingSlash).normalizePathTrailingSlash((0, _addPathPrefix).addPathPrefix(path, basePath));\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=add-base-path.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.addLocale = void 0;\nvar _normalizeTrailingSlash = require(\"./normalize-trailing-slash\");\nconst addLocale = (path, ...args)=>{\n if (process.env.__NEXT_I18N_SUPPORT) {\n return (0, _normalizeTrailingSlash).normalizePathTrailingSlash(require('../shared/lib/router/utils/add-locale').addLocale(path, ...args));\n }\n return path;\n};\nexports.addLocale = addLocale;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=add-locale.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.appBootstrap = appBootstrap;\n/**\n * Before starting the Next.js runtime and requiring any module, we need to make\n * sure the following scripts are executed in the correct order:\n * - Polyfills\n * - next/script with `beforeInteractive` strategy\n */ const version = \"13.1.2\";\nwindow.next = {\n version,\n appDir: true\n};\nfunction loadScriptsInSequence(scripts, hydrate) {\n if (!scripts || !scripts.length) {\n return hydrate();\n }\n return scripts.reduce((promise, [src, props])=>{\n return promise.then(()=>{\n return new Promise((resolve, reject)=>{\n const el = document.createElement('script');\n if (props) {\n for(const key in props){\n if (key !== 'children') {\n el.setAttribute(key, props[key]);\n }\n }\n }\n if (src) {\n el.src = src;\n el.onload = ()=>resolve();\n el.onerror = reject;\n } else if (props) {\n el.innerHTML = props.children;\n setTimeout(resolve);\n }\n document.head.appendChild(el);\n });\n });\n }, Promise.resolve()).then(()=>{\n hydrate();\n }).catch((err)=>{\n console.error(err);\n // Still try to hydrate even if there's an error.\n hydrate();\n });\n}\nfunction appBootstrap(callback) {\n loadScriptsInSequence(self.__next_s, ()=>{\n callback();\n });\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=app-bootstrap.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.hydrate = hydrate;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _interop_require_wildcard = require(\"@swc/helpers/lib/_interop_require_wildcard.js\").default;\nrequire(\"../build/polyfills/polyfill-module\");\nvar _client = _interop_require_default(require(\"react-dom/client\"));\nvar _react = _interop_require_wildcard(require(\"react\"));\nvar _client1 = require(\"next/dist/compiled/react-server-dom-webpack/client\");\nvar _headManagerContext = require(\"../shared/lib/head-manager-context\");\nvar _appRouterContext = require(\"../shared/lib/app-router-context\");\nvar _onRecoverableError = _interop_require_default(require(\"./on-recoverable-error\"));\n// eslint-disable-next-line no-undef\nconst getChunkScriptFilename = __webpack_require__.u;\nconst chunkFilenameMap = {};\n// eslint-disable-next-line no-undef\n__webpack_require__.u = (chunkId)=>{\n return chunkFilenameMap[chunkId] || getChunkScriptFilename(chunkId);\n};\n// Ignore the module ID transform in client.\n// eslint-disable-next-line no-undef\n// @ts-expect-error TODO: fix type\nself.__next_require__ = process.env.NODE_ENV !== 'production' ? (id)=>{\n const mod = __webpack_require__(id);\n if (typeof mod === 'object') {\n // Return a proxy to flight client to make sure it's always getting\n // the latest module, instead of being cached.\n return new Proxy(mod, {\n get (_target, prop) {\n return __webpack_require__(id)[prop];\n }\n });\n }\n return mod;\n} : __webpack_require__;\nself.__next_chunk_load__ = (chunk)=>{\n if (!chunk) return Promise.resolve();\n const [chunkId, chunkFileName] = chunk.split(':');\n chunkFilenameMap[chunkId] = `static/chunks/${chunkFileName}.js`;\n // @ts-ignore\n // eslint-disable-next-line no-undef\n return __webpack_chunk_load__(chunkId);\n};\nconst appElement = document;\nconst getCacheKey = ()=>{\n const { pathname , search } = location;\n return pathname + search;\n};\nconst encoder = new TextEncoder();\nlet initialServerDataBuffer = undefined;\nlet initialServerDataWriter = undefined;\nlet initialServerDataLoaded = false;\nlet initialServerDataFlushed = false;\nfunction nextServerDataCallback(seg) {\n if (seg[0] === 0) {\n initialServerDataBuffer = [];\n } else {\n if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.');\n if (initialServerDataWriter) {\n initialServerDataWriter.enqueue(encoder.encode(seg[1]));\n } else {\n initialServerDataBuffer.push(seg[1]);\n }\n }\n}\n// There might be race conditions between `nextServerDataRegisterWriter` and\n// `DOMContentLoaded`. The former will be called when React starts to hydrate\n// the root, the latter will be called when the DOM is fully loaded.\n// For streaming, the former is called first due to partial hydration.\n// For non-streaming, the latter can be called first.\n// Hence, we use two variables `initialServerDataLoaded` and\n// `initialServerDataFlushed` to make sure the writer will be closed and\n// `initialServerDataBuffer` will be cleared in the right time.\nfunction nextServerDataRegisterWriter(ctr) {\n if (initialServerDataBuffer) {\n initialServerDataBuffer.forEach((val)=>{\n ctr.enqueue(encoder.encode(val));\n });\n if (initialServerDataLoaded && !initialServerDataFlushed) {\n ctr.close();\n initialServerDataFlushed = true;\n initialServerDataBuffer = undefined;\n }\n }\n initialServerDataWriter = ctr;\n}\n// When `DOMContentLoaded`, we can close all pending writers to finish hydration.\nconst DOMContentLoaded = function() {\n if (initialServerDataWriter && !initialServerDataFlushed) {\n initialServerDataWriter.close();\n initialServerDataFlushed = true;\n initialServerDataBuffer = undefined;\n }\n initialServerDataLoaded = true;\n};\n// It's possible that the DOM is already loaded.\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);\n} else {\n DOMContentLoaded();\n}\nconst nextServerDataLoadingGlobal = self.__next_f = self.__next_f || [];\nnextServerDataLoadingGlobal.forEach(nextServerDataCallback);\nnextServerDataLoadingGlobal.push = nextServerDataCallback;\nfunction createResponseCache() {\n return new Map();\n}\nconst rscCache = createResponseCache();\nfunction useInitialServerResponse(cacheKey) {\n const response = rscCache.get(cacheKey);\n if (response) return response;\n const readable = new ReadableStream({\n start (controller) {\n nextServerDataRegisterWriter(controller);\n }\n });\n const newResponse = (0, _client1).createFromReadableStream(readable);\n rscCache.set(cacheKey, newResponse);\n return newResponse;\n}\nfunction ServerRoot({ cacheKey }) {\n _react.default.useEffect(()=>{\n rscCache.delete(cacheKey);\n });\n const response = useInitialServerResponse(cacheKey);\n const root = (0, _react).use(response);\n return root;\n}\nconst StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP ? _react.default.StrictMode : _react.default.Fragment;\nfunction Root({ children }) {\n _react.default.useEffect(()=>{\n if (process.env.__NEXT_ANALYTICS_ID) {\n require('./performance-relayer-app')();\n }\n }, []);\n if (process.env.__NEXT_TEST_MODE) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n _react.default.useEffect(()=>{\n window.__NEXT_HYDRATED = true;\n if (window.__NEXT_HYDRATED_CB) {\n window.__NEXT_HYDRATED_CB();\n }\n }, []);\n }\n return children;\n}\nfunction RSCComponent(props) {\n const cacheKey = getCacheKey();\n return /*#__PURE__*/ _react.default.createElement(ServerRoot, Object.assign({}, props, {\n cacheKey: cacheKey\n }));\n}\nfunction hydrate() {\n if (process.env.NODE_ENV !== 'production') {\n const rootLayoutMissingTagsError = self.__next_root_layout_missing_tags_error;\n const HotReload = require('./components/react-dev-overlay/hot-reloader-client').default;\n // Don't try to hydrate if root layout is missing required tags, render error instead\n if (rootLayoutMissingTagsError) {\n const reactRootElement = document.createElement('div');\n document.body.appendChild(reactRootElement);\n const reactRoot = _client.default.createRoot(reactRootElement, {\n onRecoverableError: _onRecoverableError.default\n });\n reactRoot.render(/*#__PURE__*/ _react.default.createElement(_appRouterContext.GlobalLayoutRouterContext.Provider, {\n value: {\n tree: rootLayoutMissingTagsError.tree,\n changeByServerResponse: ()=>{},\n focusAndScrollRef: {\n apply: false\n }\n }\n }, /*#__PURE__*/ _react.default.createElement(HotReload, {\n assetPrefix: rootLayoutMissingTagsError.assetPrefix\n })));\n return;\n }\n }\n const reactEl = /*#__PURE__*/ _react.default.createElement(StrictModeIfEnabled, null, /*#__PURE__*/ _react.default.createElement(_headManagerContext.HeadManagerContext.Provider, {\n value: {\n appDir: true\n }\n }, /*#__PURE__*/ _react.default.createElement(Root, null, /*#__PURE__*/ _react.default.createElement(RSCComponent, null))));\n const options = {\n onRecoverableError: _onRecoverableError.default\n };\n const isError = document.documentElement.id === '__next_error__';\n const reactRoot = isError ? _client.default.createRoot(appElement, options) : _react.default.startTransition(()=>_client.default.hydrateRoot(appElement, reactEl, options));\n if (isError) {\n reactRoot.render(reactEl);\n }\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=app-index.js.map","\"use strict\";\nvar _appBootstrap = require(\"./app-bootstrap\");\n(0, _appBootstrap).appBootstrap(()=>{\n // Include app-router and layout-router in the main chunk\n require('next/dist/client/components/app-router');\n require('next/dist/client/components/layout-router');\n const { hydrate } = require('./app-index');\n hydrate();\n});\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=app-next.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.FLIGHT_PARAMETERS = exports.RSC_VARY_HEADER = exports.FETCH_CACHE_HEADER = exports.NEXT_ROUTER_PREFETCH = exports.NEXT_ROUTER_STATE_TREE = exports.RSC = void 0;\nconst RSC = 'RSC';\nexports.RSC = RSC;\nconst NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree';\nexports.NEXT_ROUTER_STATE_TREE = NEXT_ROUTER_STATE_TREE;\nconst NEXT_ROUTER_PREFETCH = 'Next-Router-Prefetch';\nexports.NEXT_ROUTER_PREFETCH = NEXT_ROUTER_PREFETCH;\nconst FETCH_CACHE_HEADER = 'x-vercel-sc-headers';\nexports.FETCH_CACHE_HEADER = FETCH_CACHE_HEADER;\nconst RSC_VARY_HEADER = `${RSC}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH}`;\nexports.RSC_VARY_HEADER = RSC_VARY_HEADER;\nconst FLIGHT_PARAMETERS = [\n [\n RSC\n ],\n [\n NEXT_ROUTER_STATE_TREE\n ],\n [\n NEXT_ROUTER_PREFETCH\n ], \n];\nexports.FLIGHT_PARAMETERS = FLIGHT_PARAMETERS;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=app-router-headers.js.map","\"use client\";\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = AppRouter;\nexports.fetchServerResponse = fetchServerResponse;\nvar _async_to_generator = require(\"@swc/helpers/lib/_async_to_generator.js\").default;\nvar _interop_require_wildcard = require(\"@swc/helpers/lib/_interop_require_wildcard.js\").default;\nvar _object_without_properties_loose = require(\"@swc/helpers/lib/_object_without_properties_loose.js\").default;\nvar _react = _interop_require_wildcard(require(\"react\"));\nvar _client = require(\"next/dist/compiled/react-server-dom-webpack/client\");\nvar _appRouterContext = require(\"../../shared/lib/app-router-context\");\nvar _reducer = require(\"./reducer\");\nvar _hooksClientContext = require(\"../../shared/lib/hooks-client-context\");\nvar _useReducerWithDevtools = require(\"./use-reducer-with-devtools\");\nvar _errorBoundary = require(\"./error-boundary\");\nvar _appRouterHeaders = require(\"./app-router-headers\");\nfunction AppRouter(props) {\n const { globalErrorComponent } = props, rest = _object_without_properties_loose(props, [\n \"globalErrorComponent\"\n ]);\n return /*#__PURE__*/ _react.default.createElement(_errorBoundary.ErrorBoundary, {\n errorComponent: globalErrorComponent\n }, /*#__PURE__*/ _react.default.createElement(Router, Object.assign({}, rest)));\n}\n\nfunction urlToUrlWithoutFlightMarker(url) {\n const urlWithoutFlightParameters = new URL(url, location.origin);\n // TODO-APP: handle .rsc for static export case\n return urlWithoutFlightParameters;\n}\nconst HotReloader = process.env.NODE_ENV === 'production' ? null : require('./react-dev-overlay/hot-reloader-client').default;\nfunction fetchServerResponse(url, flightRouterState, prefetch) {\n return _fetchServerResponse.apply(this, arguments);\n}\nfunction _fetchServerResponse() {\n _fetchServerResponse = _async_to_generator(function*(url, flightRouterState, prefetch) {\n const headers = {\n // Enable flight response\n [_appRouterHeaders.RSC]: '1',\n // Provide the current router state\n [_appRouterHeaders.NEXT_ROUTER_STATE_TREE]: JSON.stringify(flightRouterState)\n };\n if (prefetch) {\n // Enable prefetch response\n headers[_appRouterHeaders.NEXT_ROUTER_PREFETCH] = '1';\n }\n const res = yield fetch(url.toString(), {\n headers\n });\n const canonicalUrl = res.redirected ? urlToUrlWithoutFlightMarker(res.url) : undefined;\n const isFlightResponse = res.headers.get('content-type') === 'application/octet-stream';\n // If fetch returns something different than flight response handle it like a mpa navigation\n if (!isFlightResponse) {\n return [\n res.url,\n undefined\n ];\n }\n // Handle the `fetch` readable stream that can be unwrapped by `React.use`.\n const flightData = yield (0, _client).createFromFetch(Promise.resolve(res));\n return [\n flightData,\n canonicalUrl\n ];\n });\n return _fetchServerResponse.apply(this, arguments);\n}\n// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.\nlet initialParallelRoutes = typeof window === 'undefined' ? null : new Map();\nconst prefetched = new Set();\nfunction findHeadInCache(cache, parallelRoutes) {\n const isLastItem = Object.keys(parallelRoutes).length === 0;\n if (isLastItem) {\n return cache.head;\n }\n for(const key in parallelRoutes){\n const [segment, childParallelRoutes] = parallelRoutes[key];\n const childSegmentMap = cache.parallelRoutes.get(key);\n if (!childSegmentMap) {\n continue;\n }\n const cacheKey = Array.isArray(segment) ? segment[1] : segment;\n const cacheNode = childSegmentMap.get(cacheKey);\n if (!cacheNode) {\n continue;\n }\n const item = findHeadInCache(cacheNode, childParallelRoutes);\n if (item) {\n return item;\n }\n }\n return undefined;\n}\n/**\n * The global router that wraps the application components.\n */ function Router({ initialHead , initialTree , initialCanonicalUrl , children , assetPrefix }) {\n const initialState = (0, _react).useMemo(()=>{\n return {\n tree: initialTree,\n cache: {\n status: _appRouterContext.CacheStates.READY,\n data: null,\n subTreeData: children,\n parallelRoutes: typeof window === 'undefined' ? new Map() : initialParallelRoutes\n },\n prefetchCache: new Map(),\n pushRef: {\n pendingPush: false,\n mpaNavigation: false\n },\n focusAndScrollRef: {\n apply: false\n },\n canonicalUrl: // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n typeof window !== 'undefined' ? (0, _reducer).createHrefFromUrl(window.location) : initialCanonicalUrl\n };\n }, [\n children,\n initialCanonicalUrl,\n initialTree\n ]);\n const [{ tree , cache , prefetchCache , pushRef , focusAndScrollRef , canonicalUrl }, dispatch, sync, ] = (0, _useReducerWithDevtools).useReducerWithReduxDevtools(_reducer.reducer, initialState);\n const head = (0, _react).useMemo(()=>{\n return findHeadInCache(cache, tree[1]);\n }, [\n cache,\n tree\n ]);\n (0, _react).useEffect(()=>{\n // Ensure initialParallelRoutes is cleaned up from memory once it's used.\n initialParallelRoutes = null;\n }, []);\n // Add memoized pathname/query for useSearchParams and usePathname.\n const { searchParams , pathname } = (0, _react).useMemo(()=>{\n const url = new URL(canonicalUrl, typeof window === 'undefined' ? 'http://n' : window.location.href);\n return {\n // This is turned into a readonly class in `useSearchParams`\n searchParams: url.searchParams,\n pathname: url.pathname\n };\n }, [\n canonicalUrl\n ]);\n /**\n * Server response that only patches the cache and tree.\n */ const changeByServerResponse = (0, _react).useCallback((previousTree, flightData, overrideCanonicalUrl)=>{\n dispatch({\n type: _reducer.ACTION_SERVER_PATCH,\n flightData,\n previousTree,\n overrideCanonicalUrl,\n cache: {\n status: _appRouterContext.CacheStates.LAZY_INITIALIZED,\n data: null,\n subTreeData: null,\n parallelRoutes: new Map()\n },\n mutable: {}\n });\n }, [\n dispatch\n ]);\n /**\n * The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.\n */ const appRouter = (0, _react).useMemo(()=>{\n const navigate = (href, navigateType, forceOptimisticNavigation)=>{\n return dispatch({\n type: _reducer.ACTION_NAVIGATE,\n url: new URL(href, location.origin),\n forceOptimisticNavigation,\n navigateType,\n cache: {\n status: _appRouterContext.CacheStates.LAZY_INITIALIZED,\n data: null,\n subTreeData: null,\n parallelRoutes: new Map()\n },\n mutable: {}\n });\n };\n const routerInstance = {\n back: ()=>window.history.back(),\n forward: ()=>window.history.forward(),\n prefetch: _async_to_generator(function*(href) {\n // If prefetch has already been triggered, don't trigger it again.\n if (prefetched.has(href)) {\n return;\n }\n prefetched.add(href);\n const url = new URL(href, location.origin);\n try {\n var ref;\n const routerTree = ((ref = window.history.state) == null ? void 0 : ref.tree) || initialTree;\n const serverResponse = yield fetchServerResponse(url, // initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.\n routerTree, true);\n // @ts-ignore startTransition exists\n _react.default.startTransition(()=>{\n dispatch({\n type: _reducer.ACTION_PREFETCH,\n url,\n tree: routerTree,\n serverResponse\n });\n });\n } catch (err) {\n console.error('PREFETCH ERROR', err);\n }\n }),\n replace: (href, options = {})=>{\n // @ts-ignore startTransition exists\n _react.default.startTransition(()=>{\n navigate(href, 'replace', Boolean(options.forceOptimisticNavigation));\n });\n },\n push: (href, options = {})=>{\n // @ts-ignore startTransition exists\n _react.default.startTransition(()=>{\n navigate(href, 'push', Boolean(options.forceOptimisticNavigation));\n });\n },\n refresh: ()=>{\n // @ts-ignore startTransition exists\n _react.default.startTransition(()=>{\n dispatch({\n type: _reducer.ACTION_REFRESH,\n cache: {\n status: _appRouterContext.CacheStates.LAZY_INITIALIZED,\n data: null,\n subTreeData: null,\n parallelRoutes: new Map()\n },\n mutable: {}\n });\n });\n }\n };\n return routerInstance;\n }, [\n dispatch,\n initialTree\n ]);\n (0, _react).useEffect(()=>{\n // When mpaNavigation flag is set do a hard navigation to the new url.\n if (pushRef.mpaNavigation) {\n window.location.href = canonicalUrl;\n return;\n }\n // Identifier is shortened intentionally.\n // __NA is used to identify if the history entry can be handled by the app-router.\n // __N is used to identify if the history entry can be handled by the old router.\n const historyState = {\n __NA: true,\n tree\n };\n if (pushRef.pendingPush && (0, _reducer).createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl) {\n // This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.\n pushRef.pendingPush = false;\n window.history.pushState(historyState, '', canonicalUrl);\n } else {\n window.history.replaceState(historyState, '', canonicalUrl);\n }\n sync();\n }, [\n tree,\n pushRef,\n canonicalUrl,\n sync\n ]);\n // Add `window.nd` for debugging purposes.\n // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.\n if (typeof window !== 'undefined') {\n // @ts-ignore this is for debugging\n window.nd = {\n router: appRouter,\n cache,\n prefetchCache,\n tree\n };\n }\n /**\n * Handle popstate event, this is used to handle back/forward in the browser.\n * By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */ const onPopState = (0, _react).useCallback(({ state })=>{\n if (!state) {\n // TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.\n return;\n }\n // This case happens when the history entry was pushed by the `pages` router.\n if (!state.__NA) {\n window.location.reload();\n return;\n }\n // @ts-ignore useTransition exists\n // TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously\n // Without startTransition works if the cache is there for this path\n _react.default.startTransition(()=>{\n dispatch({\n type: _reducer.ACTION_RESTORE,\n url: new URL(window.location.href),\n tree: state.tree\n });\n });\n }, [\n dispatch\n ]);\n // Register popstate event to call onPopstate.\n (0, _react).useEffect(()=>{\n window.addEventListener('popstate', onPopState);\n return ()=>{\n window.removeEventListener('popstate', onPopState);\n };\n }, [\n onPopState\n ]);\n const content = /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, head || initialHead, cache.subTreeData);\n return /*#__PURE__*/ _react.default.createElement(_hooksClientContext.PathnameContext.Provider, {\n value: pathname\n }, /*#__PURE__*/ _react.default.createElement(_hooksClientContext.SearchParamsContext.Provider, {\n value: searchParams\n }, /*#__PURE__*/ _react.default.createElement(_appRouterContext.GlobalLayoutRouterContext.Provider, {\n value: {\n changeByServerResponse,\n tree,\n focusAndScrollRef\n }\n }, /*#__PURE__*/ _react.default.createElement(_appRouterContext.AppRouterContext.Provider, {\n value: appRouter\n }, /*#__PURE__*/ _react.default.createElement(_appRouterContext.LayoutRouterContext.Provider, {\n value: {\n childNodes: cache.parallelRoutes,\n tree: tree,\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl\n }\n }, HotReloader ? /*#__PURE__*/ _react.default.createElement(HotReloader, {\n assetPrefix: assetPrefix\n }, content) : content)))));\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=app-router.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.bailoutToClientRendering = bailoutToClientRendering;\nvar _dynamicNoSsr = require(\"../../shared/lib/dynamic-no-ssr\");\nvar _staticGenerationAsyncStorage = require(\"./static-generation-async-storage\");\nfunction bailoutToClientRendering() {\n const staticGenerationStore = _staticGenerationAsyncStorage.staticGenerationAsyncStorage.getStore();\n if (staticGenerationStore == null ? void 0 : staticGenerationStore.forceStatic) {\n return true;\n }\n if (staticGenerationStore == null ? void 0 : staticGenerationStore.isStaticGeneration) {\n (0, _dynamicNoSsr).suspense();\n }\n return false;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=bailout-to-client-rendering.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.clientHookInServerComponentError = clientHookInServerComponentError;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _react = _interop_require_default(require(\"react\"));\nfunction clientHookInServerComponentError(hookName) {\n if (process.env.NODE_ENV !== 'production') {\n // If useState is undefined we're in a server component\n if (!_react.default.useState) {\n throw new Error(`${hookName} only works in Client Components. Add the \"use client\" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`);\n }\n }\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=client-hook-in-server-component-error.js.map","\"use client\";\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = GlobalError;\nexports.ErrorBoundary = ErrorBoundary;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _react = _interop_require_default(require(\"react\"));\nfunction GlobalError({ error }) {\n return /*#__PURE__*/ _react.default.createElement(\"html\", null, /*#__PURE__*/ _react.default.createElement(\"head\", null), /*#__PURE__*/ _react.default.createElement(\"body\", null, /*#__PURE__*/ _react.default.createElement(\"div\", {\n style: styles.error\n }, /*#__PURE__*/ _react.default.createElement(\"div\", {\n style: styles.desc\n }, /*#__PURE__*/ _react.default.createElement(\"h2\", {\n style: styles.text\n }, \"Application error: a client-side exception has occurred (see the browser console for more information).\"), (error == null ? void 0 : error.digest) && /*#__PURE__*/ _react.default.createElement(\"p\", {\n style: styles.text\n }, `Digest: ${error.digest}`)))));\n}\n\nconst styles = {\n error: {\n fontFamily: '-apple-system, BlinkMacSystemFont, Roboto, \"Segoe UI\", \"Fira Sans\", Avenir, \"Helvetica Neue\", \"Lucida Grande\", sans-serif',\n height: '100vh',\n textAlign: 'center',\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n justifyContent: 'center'\n },\n desc: {\n display: 'inline-block',\n textAlign: 'left',\n lineHeight: '49px',\n height: '49px',\n verticalAlign: 'middle'\n },\n text: {\n fontSize: '14px',\n fontWeight: 'normal',\n lineHeight: '49px',\n margin: 0,\n padding: 0\n }\n};\nclass ErrorBoundaryHandler extends _react.default.Component {\n static getDerivedStateFromError(error) {\n return {\n error\n };\n }\n render() {\n if (this.state.error) {\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, this.props.errorStyles, /*#__PURE__*/ _react.default.createElement(this.props.errorComponent, {\n error: this.state.error,\n reset: this.reset\n }));\n }\n return this.props.children;\n }\n constructor(props){\n super(props);\n this.reset = ()=>{\n this.setState({\n error: null\n });\n };\n this.state = {\n error: null\n };\n }\n}\nexports.ErrorBoundaryHandler = ErrorBoundaryHandler;\nfunction ErrorBoundary({ errorComponent , errorStyles , children }) {\n if (errorComponent) {\n return /*#__PURE__*/ _react.default.createElement(ErrorBoundaryHandler, {\n errorComponent: errorComponent,\n errorStyles: errorStyles\n }, children);\n }\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children);\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=error-boundary.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createInfinitePromise = createInfinitePromise;\n/**\n * Used to cache in createInfinitePromise\n */ let infinitePromise;\nfunction createInfinitePromise() {\n if (!infinitePromise) {\n // Only create the Promise once\n infinitePromise = new Promise(()=>{\n // This is used to debug when the rendering is never updated.\n // setTimeout(() => {\n // infinitePromise = new Error('Infinite promise')\n // resolve()\n // }, 5000)\n });\n }\n return infinitePromise;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=infinite-promise.js.map","\"use client\";\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = OuterLayoutRouter;\nexports.InnerLayoutRouter = InnerLayoutRouter;\nvar _extends = require(\"@swc/helpers/lib/_extends.js\").default;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _interop_require_wildcard = require(\"@swc/helpers/lib/_interop_require_wildcard.js\").default;\nvar _react = _interop_require_wildcard(require(\"react\"));\nvar _reactDom = _interop_require_default(require(\"react-dom\"));\nvar _appRouterContext = require(\"../../shared/lib/app-router-context\");\nvar _appRouter = require(\"./app-router\");\nvar _infinitePromise = require(\"./infinite-promise\");\nvar _errorBoundary = require(\"./error-boundary\");\nvar _matchSegments = require(\"./match-segments\");\nvar _navigation = require(\"./navigation\");\nfunction OuterLayoutRouter({ parallelRouterKey , segmentPath , childProp , error , errorStyles , templateStyles , loading , loadingStyles , hasLoading , template , notFound , notFoundStyles }) {\n const context = (0, _react).useContext(_appRouterContext.LayoutRouterContext);\n if (!context) {\n throw new Error('invariant expected layout router to be mounted');\n }\n const { childNodes , tree , url } = context;\n // Get the current parallelRouter cache node\n let childNodesForParallelRouter = childNodes.get(parallelRouterKey);\n // If the parallel router cache node does not exist yet, create it.\n // This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode.\n if (!childNodesForParallelRouter) {\n childNodes.set(parallelRouterKey, new Map());\n childNodesForParallelRouter = childNodes.get(parallelRouterKey);\n }\n // Get the active segment in the tree\n // The reason arrays are used in the data format is that these are transferred from the server to the browser so it's optimized to save bytes.\n const treeSegment = tree[1][parallelRouterKey][0];\n const childPropSegment = Array.isArray(childProp.segment) ? childProp.segment[1] : childProp.segment;\n // If segment is an array it's a dynamic route and we want to read the dynamic route value as the segment to get from the cache.\n const currentChildSegment = Array.isArray(treeSegment) ? treeSegment[1] : treeSegment;\n /**\n * Decides which segments to keep rendering, all segments that are not active will be wrapped in ``.\n */ // TODO-APP: Add handling of `` when it's available.\n const preservedSegments = [\n currentChildSegment\n ];\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, preservedSegments.map((preservedSegment)=>{\n return(/*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */ /*#__PURE__*/ _react.default.createElement(_appRouterContext.TemplateContext.Provider, {\n key: preservedSegment,\n value: /*#__PURE__*/ _react.default.createElement(_errorBoundary.ErrorBoundary, {\n errorComponent: error,\n errorStyles: errorStyles\n }, /*#__PURE__*/ _react.default.createElement(LoadingBoundary, {\n hasLoading: hasLoading,\n loading: loading,\n loadingStyles: loadingStyles\n }, /*#__PURE__*/ _react.default.createElement(NotFoundBoundary, {\n notFound: notFound,\n notFoundStyles: notFoundStyles\n }, /*#__PURE__*/ _react.default.createElement(RedirectBoundary, null, /*#__PURE__*/ _react.default.createElement(InnerLayoutRouter, {\n parallelRouterKey: parallelRouterKey,\n url: url,\n tree: tree,\n childNodes: childNodesForParallelRouter,\n childProp: childPropSegment === preservedSegment ? childProp : null,\n segmentPath: segmentPath,\n path: preservedSegment,\n isActive: currentChildSegment === preservedSegment\n })))))\n }, /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, templateStyles, template)));\n }));\n}\n\n/**\n * Add refetch marker to router state at the point of the current layout segment.\n * This ensures the response returned is not further down than the current layout segment.\n */ function walkAddRefetch(segmentPathToWalk, treeToRecreate) {\n if (segmentPathToWalk) {\n const [segment, parallelRouteKey] = segmentPathToWalk;\n const isLast = segmentPathToWalk.length === 2;\n if ((0, _matchSegments).matchSegment(treeToRecreate[0], segment)) {\n if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) {\n if (isLast) {\n const subTree = walkAddRefetch(undefined, treeToRecreate[1][parallelRouteKey]);\n return [\n treeToRecreate[0],\n _extends({}, treeToRecreate[1], {\n [parallelRouteKey]: [\n subTree[0],\n subTree[1],\n subTree[2],\n 'refetch', \n ]\n }), \n ];\n }\n return [\n treeToRecreate[0],\n _extends({}, treeToRecreate[1], {\n [parallelRouteKey]: walkAddRefetch(segmentPathToWalk.slice(2), treeToRecreate[1][parallelRouteKey])\n }), \n ];\n }\n }\n }\n return treeToRecreate;\n}\n// TODO-APP: Replace with new React API for finding dom nodes without a `ref` when available\n/**\n * Wraps ReactDOM.findDOMNode with additional logic to hide React Strict Mode warning\n */ function findDOMNode(instance) {\n // Tree-shake for server bundle\n if (typeof window === undefined) return null;\n // Only apply strict mode warning when not in production\n if (process.env.NODE_ENV !== 'production') {\n const originalConsoleError = console.error;\n try {\n console.error = (...messages)=>{\n // Ignore strict mode warning for the findDomNode call below\n if (!messages[0].includes('Warning: %s is deprecated in StrictMode.')) {\n originalConsoleError(...messages);\n }\n };\n return _reactDom.default.findDOMNode(instance);\n } finally{\n console.error = originalConsoleError;\n }\n }\n return _reactDom.default.findDOMNode(instance);\n}\n/**\n * Check if the top of the HTMLElement is in the viewport.\n */ function topOfElementInViewport(element) {\n const rect = element.getBoundingClientRect();\n return rect.top >= 0;\n}\nclass ScrollAndFocusHandler extends _react.default.Component {\n componentDidMount() {\n // Handle scroll and focus, it's only applied once in the first useEffect that triggers that changed.\n const { focusAndScrollRef } = this.props;\n const domNode = findDOMNode(this);\n if (focusAndScrollRef.apply && domNode instanceof HTMLElement) {\n // State is mutated to ensure that the focus and scroll is applied only once.\n focusAndScrollRef.apply = false;\n // Set focus on the element\n domNode.focus();\n // Only scroll into viewport when the layout is not visible currently.\n if (!topOfElementInViewport(domNode)) {\n const htmlElement = document.documentElement;\n const existing = htmlElement.style.scrollBehavior;\n htmlElement.style.scrollBehavior = 'auto';\n // In Chrome-based browsers we need to force reflow before calling `scrollTo`.\n // Otherwise it will not pickup the change in scrollBehavior\n // More info here: https://github.com/vercel/next.js/issues/40719#issuecomment-1336248042\n htmlElement.getClientRects();\n domNode.scrollIntoView();\n htmlElement.style.scrollBehavior = existing;\n }\n }\n }\n render() {\n return this.props.children;\n }\n}\nfunction InnerLayoutRouter({ parallelRouterKey , url , childNodes , childProp , segmentPath , tree , // TODO-APP: implement `` when available.\n// isActive,\npath }) {\n const context = (0, _react).useContext(_appRouterContext.GlobalLayoutRouterContext);\n if (!context) {\n throw new Error('invariant global layout router not mounted');\n }\n const { changeByServerResponse , tree: fullTree , focusAndScrollRef } = context;\n // Read segment path from the parallel router cache node.\n let childNode = childNodes.get(path);\n // If childProp is available this means it's the Flight / SSR case.\n if (childProp && // TODO-APP: verify if this can be null based on user code\n childProp.current !== null) {\n if (childNode && childNode.status === _appRouterContext.CacheStates.LAZY_INITIALIZED) {\n // @ts-expect-error TODO-APP: handle changing of the type\n childNode.status = _appRouterContext.CacheStates.READY;\n // @ts-expect-error TODO-APP: handle changing of the type\n childNode.subTreeData = childProp.current;\n // Mutates the prop in order to clean up the memory associated with the subTreeData as it is now part of the cache.\n childProp.current = null;\n } else {\n // Add the segment's subTreeData to the cache.\n // This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode.\n childNodes.set(path, {\n status: _appRouterContext.CacheStates.READY,\n data: null,\n subTreeData: childProp.current,\n parallelRoutes: new Map()\n });\n // Mutates the prop in order to clean up the memory associated with the subTreeData as it is now part of the cache.\n childProp.current = null;\n // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again.\n childNode = childNodes.get(path);\n }\n }\n // When childNode is not available during rendering client-side we need to fetch it from the server.\n if (!childNode || childNode.status === _appRouterContext.CacheStates.LAZY_INITIALIZED) {\n /**\n * Router state with refetch marker added\n */ // TODO-APP: remove ''\n const refetchTree = walkAddRefetch([\n '',\n ...segmentPath\n ], fullTree);\n /**\n * Flight data fetch kicked off during render and put into the cache.\n */ childNodes.set(path, {\n status: _appRouterContext.CacheStates.DATA_FETCH,\n data: (0, _appRouter).fetchServerResponse(new URL(url, location.origin), refetchTree),\n subTreeData: null,\n head: childNode && childNode.status === _appRouterContext.CacheStates.LAZY_INITIALIZED ? childNode.head : undefined,\n parallelRoutes: childNode && childNode.status === _appRouterContext.CacheStates.LAZY_INITIALIZED ? childNode.parallelRoutes : new Map()\n });\n // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again.\n childNode = childNodes.get(path);\n }\n // This case should never happen so it throws an error. It indicates there's a bug in the Next.js.\n if (!childNode) {\n throw new Error('Child node should always exist');\n }\n // This case should never happen so it throws an error. It indicates there's a bug in the Next.js.\n if (childNode.subTreeData && childNode.data) {\n throw new Error('Child node should not have both subTreeData and data');\n }\n // If cache node has a data request we have to unwrap response by `use` and update the cache.\n if (childNode.data) {\n /**\n * Flight response data\n */ // When the data has not resolved yet `use` will suspend here.\n const [flightData, overrideCanonicalUrl] = (0, _react).use(childNode.data);\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n window.location.href = url;\n return null;\n }\n // segmentPath from the server does not match the layout's segmentPath\n childNode.data = null;\n // setTimeout is used to start a new transition during render, this is an intentional hack around React.\n setTimeout(()=>{\n // @ts-ignore startTransition exists\n _react.default.startTransition(()=>{\n changeByServerResponse(fullTree, flightData, overrideCanonicalUrl);\n });\n });\n // Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered.\n (0, _react).use((0, _infinitePromise).createInfinitePromise());\n }\n // If cache node has no subTreeData and no data request we have to infinitely suspend as the data will likely flow in from another place.\n // TODO-APP: double check users can't return null in a component that will kick in here.\n if (!childNode.subTreeData) {\n (0, _react).use((0, _infinitePromise).createInfinitePromise());\n }\n const subtree = // The layout router context narrows down tree and childNodes at each level.\n /*#__PURE__*/ _react.default.createElement(_appRouterContext.LayoutRouterContext.Provider, {\n value: {\n tree: tree[1][parallelRouterKey],\n childNodes: childNode.parallelRoutes,\n // TODO-APP: overriding of url for parallel routes\n url: url\n }\n }, childNode.subTreeData);\n // Ensure root layout is not wrapped in a div as the root layout renders ``\n return /*#__PURE__*/ _react.default.createElement(ScrollAndFocusHandler, {\n focusAndScrollRef: focusAndScrollRef\n }, subtree);\n}\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */ function LoadingBoundary({ children , loading , loadingStyles , hasLoading }) {\n if (hasLoading) {\n return /*#__PURE__*/ _react.default.createElement(_react.default.Suspense, {\n fallback: /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, loadingStyles, loading)\n }, children);\n }\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children);\n}\nfunction HandleRedirect({ redirect }) {\n const router = (0, _navigation).useRouter();\n (0, _react).useEffect(()=>{\n router.replace(redirect, {});\n }, [\n redirect,\n router\n ]);\n return null;\n}\nclass RedirectErrorBoundary extends _react.default.Component {\n static getDerivedStateFromError(error) {\n var ref;\n if (error == null ? void 0 : (ref = error.digest) == null ? void 0 : ref.startsWith('NEXT_REDIRECT')) {\n const url = error.digest.split(';')[1];\n return {\n redirect: url\n };\n }\n // Re-throw if error is not for redirect\n throw error;\n }\n render() {\n const redirect = this.state.redirect;\n if (redirect !== null) {\n return /*#__PURE__*/ _react.default.createElement(HandleRedirect, {\n redirect: redirect\n });\n }\n return this.props.children;\n }\n constructor(props){\n super(props);\n this.state = {\n redirect: null\n };\n }\n}\nfunction RedirectBoundary({ children }) {\n const router = (0, _navigation).useRouter();\n return /*#__PURE__*/ _react.default.createElement(RedirectErrorBoundary, {\n router: router\n }, children);\n}\nclass NotFoundErrorBoundary extends _react.default.Component {\n static getDerivedStateFromError(error) {\n if ((error == null ? void 0 : error.digest) === 'NEXT_NOT_FOUND') {\n return {\n notFoundTriggered: true\n };\n }\n // Re-throw if error is not for 404\n throw error;\n }\n render() {\n if (this.state.notFoundTriggered) {\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(\"meta\", {\n name: \"robots\",\n content: \"noindex\"\n }), this.props.notFoundStyles, this.props.notFound);\n }\n return this.props.children;\n }\n constructor(props){\n super(props);\n this.state = {\n notFoundTriggered: false\n };\n }\n}\nfunction NotFoundBoundary({ notFound , notFoundStyles , children }) {\n return notFound ? /*#__PURE__*/ _react.default.createElement(NotFoundErrorBoundary, {\n notFound: notFound,\n notFoundStyles: notFoundStyles\n }, children) : /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children);\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=layout-router.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.matchSegment = void 0;\nconst matchSegment = (existingSegment, segment)=>{\n // Common case: segment is just a string\n if (typeof existingSegment === 'string' && typeof segment === 'string') {\n return existingSegment === segment;\n }\n // Dynamic parameter case: segment is an array with param/value. Both param and value are compared.\n if (Array.isArray(existingSegment) && Array.isArray(segment)) {\n return existingSegment[0] === segment[0] && existingSegment[1] === segment[1];\n }\n return false;\n};\nexports.matchSegment = matchSegment;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=match-segments.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.useSearchParams = useSearchParams;\nexports.usePathname = usePathname;\nObject.defineProperty(exports, \"ServerInsertedHTMLContext\", {\n enumerable: true,\n get: function() {\n return _serverInsertedHtml.ServerInsertedHTMLContext;\n }\n});\nObject.defineProperty(exports, \"useServerInsertedHTML\", {\n enumerable: true,\n get: function() {\n return _serverInsertedHtml.useServerInsertedHTML;\n }\n});\nexports.useRouter = useRouter;\nexports.useSelectedLayoutSegments = useSelectedLayoutSegments;\nexports.useSelectedLayoutSegment = useSelectedLayoutSegment;\nObject.defineProperty(exports, \"redirect\", {\n enumerable: true,\n get: function() {\n return _redirect.redirect;\n }\n});\nObject.defineProperty(exports, \"notFound\", {\n enumerable: true,\n get: function() {\n return _notFound.notFound;\n }\n});\nvar _react = require(\"react\");\nvar _appRouterContext = require(\"../../shared/lib/app-router-context\");\nvar _hooksClientContext = require(\"../../shared/lib/hooks-client-context\");\nvar _bailoutToClientRendering = require(\"./bailout-to-client-rendering\");\nvar _clientHookInServerComponentError = require(\"./client-hook-in-server-component-error\");\nvar _serverInsertedHtml = require(\"../../shared/lib/server-inserted-html\");\nvar _redirect = require(\"./redirect\");\nvar _notFound = require(\"./not-found\");\nconst INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol('internal for urlsearchparams readonly');\nfunction readonlyURLSearchParamsError() {\n return new Error('ReadonlyURLSearchParams cannot be modified');\n}\nclass ReadonlyURLSearchParams {\n [Symbol.iterator]() {\n return this[INTERNAL_URLSEARCHPARAMS_INSTANCE][Symbol.iterator]();\n }\n append() {\n throw readonlyURLSearchParamsError();\n }\n delete() {\n throw readonlyURLSearchParamsError();\n }\n set() {\n throw readonlyURLSearchParamsError();\n }\n sort() {\n throw readonlyURLSearchParamsError();\n }\n constructor(urlSearchParams){\n // Since `new Headers` uses `this.append()` to fill the headers object ReadonlyHeaders can't extend from Headers directly as it would throw.\n this[INTERNAL_URLSEARCHPARAMS_INSTANCE] = urlSearchParams;\n this.entries = urlSearchParams.entries.bind(urlSearchParams);\n this.forEach = urlSearchParams.forEach.bind(urlSearchParams);\n this.get = urlSearchParams.get.bind(urlSearchParams);\n this.getAll = urlSearchParams.getAll.bind(urlSearchParams);\n this.has = urlSearchParams.has.bind(urlSearchParams);\n this.keys = urlSearchParams.keys.bind(urlSearchParams);\n this.values = urlSearchParams.values.bind(urlSearchParams);\n this.toString = urlSearchParams.toString.bind(urlSearchParams);\n }\n}\nfunction useSearchParams() {\n (0, _clientHookInServerComponentError).clientHookInServerComponentError('useSearchParams');\n const searchParams = (0, _react).useContext(_hooksClientContext.SearchParamsContext);\n const readonlySearchParams = (0, _react).useMemo(()=>{\n return new ReadonlyURLSearchParams(searchParams || new URLSearchParams());\n }, [\n searchParams\n ]);\n if ((0, _bailoutToClientRendering).bailoutToClientRendering()) {\n // TODO-APP: handle dynamic = 'force-static' here and on the client\n return readonlySearchParams;\n }\n if (!searchParams) {\n throw new Error('invariant expected search params to be mounted');\n }\n return readonlySearchParams;\n}\nfunction usePathname() {\n (0, _clientHookInServerComponentError).clientHookInServerComponentError('usePathname');\n return (0, _react).useContext(_hooksClientContext.PathnameContext);\n}\nfunction useRouter() {\n (0, _clientHookInServerComponentError).clientHookInServerComponentError('useRouter');\n const router = (0, _react).useContext(_appRouterContext.AppRouterContext);\n if (router === null) {\n throw new Error('invariant expected app router to be mounted');\n }\n return router;\n}\n// TODO-APP: handle parallel routes\nfunction getSelectedLayoutSegmentPath(tree, parallelRouteKey, first = true, segmentPath = []) {\n let node;\n if (first) {\n // Use the provided parallel route key on the first parallel route\n node = tree[1][parallelRouteKey];\n } else {\n // After first parallel route prefer children, if there's no children pick the first parallel route.\n const parallelRoutes = tree[1];\n var _children;\n node = (_children = parallelRoutes.children) != null ? _children : Object.values(parallelRoutes)[0];\n }\n if (!node) return segmentPath;\n const segment = node[0];\n const segmentValue = Array.isArray(segment) ? segment[1] : segment;\n if (!segmentValue) return segmentPath;\n segmentPath.push(segmentValue);\n return getSelectedLayoutSegmentPath(node, parallelRouteKey, false, segmentPath);\n}\nfunction useSelectedLayoutSegments(parallelRouteKey = 'children') {\n (0, _clientHookInServerComponentError).clientHookInServerComponentError('useSelectedLayoutSegments');\n const { tree } = (0, _react).useContext(_appRouterContext.LayoutRouterContext);\n return getSelectedLayoutSegmentPath(tree, parallelRouteKey);\n}\nfunction useSelectedLayoutSegment(parallelRouteKey = 'children') {\n (0, _clientHookInServerComponentError).clientHookInServerComponentError('useSelectedLayoutSegment');\n const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey);\n if (selectedLayoutSegments.length === 0) {\n return null;\n }\n return selectedLayoutSegments[0];\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=navigation.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.notFound = notFound;\nexports.NOT_FOUND_ERROR_CODE = void 0;\nconst NOT_FOUND_ERROR_CODE = 'NEXT_NOT_FOUND';\nexports.NOT_FOUND_ERROR_CODE = NOT_FOUND_ERROR_CODE;\nfunction notFound() {\n // eslint-disable-next-line no-throw-literal\n const error = new Error(NOT_FOUND_ERROR_CODE);\n error.digest = NOT_FOUND_ERROR_CODE;\n throw error;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=not-found.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.redirect = redirect;\nexports.REDIRECT_ERROR_CODE = void 0;\nconst REDIRECT_ERROR_CODE = 'NEXT_REDIRECT';\nexports.REDIRECT_ERROR_CODE = REDIRECT_ERROR_CODE;\nfunction redirect(url) {\n // eslint-disable-next-line no-throw-literal\n const error = new Error(REDIRECT_ERROR_CODE);\n error.digest = REDIRECT_ERROR_CODE + ';' + url;\n throw error;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=redirect.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.createHrefFromUrl = createHrefFromUrl;\nexports.reducer = exports.ACTION_PREFETCH = exports.ACTION_SERVER_PATCH = exports.ACTION_RESTORE = exports.ACTION_NAVIGATE = exports.ACTION_REFRESH = void 0;\nvar _extends = require(\"@swc/helpers/lib/_extends.js\").default;\nvar _appRouterContext = require(\"../../shared/lib/app-router-context\");\nvar _matchSegments = require(\"./match-segments\");\nvar _appRouter = require(\"./app-router\");\n/**\n * Create data fetching record for Promise.\n */ // TODO-APP: change `any` to type inference.\nfunction createRecordFromThenable(thenable) {\n thenable.status = 'pending';\n thenable.then((value)=>{\n if (thenable.status === 'pending') {\n thenable.status = 'fulfilled';\n thenable.value = value;\n }\n }, (err)=>{\n if (thenable.status === 'pending') {\n thenable.status = 'rejected';\n thenable.value = err;\n }\n });\n return thenable;\n}\n/**\n * Read record value or throw Promise if it's not resolved yet.\n */ function readRecordValue(thenable) {\n // @ts-expect-error TODO: fix type\n if (thenable.status === 'fulfilled') {\n // @ts-expect-error TODO: fix type\n return thenable.value;\n } else {\n throw thenable;\n }\n}\nfunction createHrefFromUrl(url) {\n return url.pathname + url.search + url.hash;\n}\n/**\n * Invalidate cache one level down from the router state.\n */ function invalidateCacheByRouterState(newCache, existingCache, routerState) {\n // Remove segment that we got data for so that it is filled in during rendering of subTreeData.\n for(const key in routerState[1]){\n const segmentForParallelRoute = routerState[1][key][0];\n const cacheKey = Array.isArray(segmentForParallelRoute) ? segmentForParallelRoute[1] : segmentForParallelRoute;\n const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key);\n if (existingParallelRoutesCacheNode) {\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode);\n parallelRouteCacheNode.delete(cacheKey);\n newCache.parallelRoutes.set(key, parallelRouteCacheNode);\n }\n }\n}\nfunction fillLazyItemsTillLeafWithHead(newCache, existingCache, routerState, head) {\n const isLastSegment = Object.keys(routerState[1]).length === 0;\n if (isLastSegment) {\n newCache.head = head;\n return;\n }\n // Remove segment that we got data for so that it is filled in during rendering of subTreeData.\n for(const key in routerState[1]){\n const parallelRouteState = routerState[1][key];\n const segmentForParallelRoute = parallelRouteState[0];\n const cacheKey = Array.isArray(segmentForParallelRoute) ? segmentForParallelRoute[1] : segmentForParallelRoute;\n if (existingCache) {\n const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key);\n if (existingParallelRoutesCacheNode) {\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode);\n parallelRouteCacheNode.delete(cacheKey);\n const newCacheNode = {\n status: _appRouterContext.CacheStates.LAZY_INITIALIZED,\n data: null,\n subTreeData: null,\n parallelRoutes: new Map()\n };\n parallelRouteCacheNode.set(cacheKey, newCacheNode);\n fillLazyItemsTillLeafWithHead(newCacheNode, undefined, parallelRouteState, head);\n newCache.parallelRoutes.set(key, parallelRouteCacheNode);\n continue;\n }\n }\n const newCacheNode = {\n status: _appRouterContext.CacheStates.LAZY_INITIALIZED,\n data: null,\n subTreeData: null,\n parallelRoutes: new Map()\n };\n newCache.parallelRoutes.set(key, new Map([\n [\n cacheKey,\n newCacheNode\n ]\n ]));\n fillLazyItemsTillLeafWithHead(newCacheNode, undefined, parallelRouteState, head);\n }\n}\n/**\n * Fill cache with subTreeData based on flightDataPath\n */ function fillCacheWithNewSubTreeData(newCache, existingCache, flightDataPath) {\n const isLastEntry = flightDataPath.length <= 5;\n const [parallelRouteKey, segment] = flightDataPath;\n const segmentForCache = Array.isArray(segment) ? segment[1] : segment;\n const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return;\n }\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap);\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);\n }\n const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache);\n let childCacheNode = childSegmentMap.get(segmentForCache);\n if (isLastEntry) {\n if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n status: _appRouterContext.CacheStates.READY,\n data: null,\n subTreeData: flightDataPath[3],\n // Ensure segments other than the one we got data for are preserved.\n parallelRoutes: existingChildCacheNode ? new Map(existingChildCacheNode.parallelRoutes) : new Map()\n };\n if (existingChildCacheNode) {\n invalidateCacheByRouterState(childCacheNode, existingChildCacheNode, flightDataPath[2]);\n }\n fillLazyItemsTillLeafWithHead(childCacheNode, existingChildCacheNode, flightDataPath[2], flightDataPath[4]);\n childSegmentMap.set(segmentForCache, childCacheNode);\n }\n return;\n }\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return;\n }\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n status: childCacheNode.status,\n data: childCacheNode.data,\n subTreeData: childCacheNode.subTreeData,\n parallelRoutes: new Map(childCacheNode.parallelRoutes)\n };\n childSegmentMap.set(segmentForCache, childCacheNode);\n }\n fillCacheWithNewSubTreeData(childCacheNode, existingChildCacheNode, flightDataPath.slice(2));\n}\n/**\n * Fill cache up to the end of the flightSegmentPath, invalidating anything below it.\n */ function invalidateCacheBelowFlightSegmentPath(newCache, existingCache, flightSegmentPath) {\n const isLastEntry = flightSegmentPath.length <= 2;\n const [parallelRouteKey, segment] = flightSegmentPath;\n const segmentForCache = Array.isArray(segment) ? segment[1] : segment;\n const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return;\n }\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap);\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);\n }\n // In case of last entry don't copy further down.\n if (isLastEntry) {\n childSegmentMap.delete(segmentForCache);\n return;\n }\n const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache);\n let childCacheNode = childSegmentMap.get(segmentForCache);\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return;\n }\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n status: childCacheNode.status,\n data: childCacheNode.data,\n subTreeData: childCacheNode.subTreeData,\n parallelRoutes: new Map(childCacheNode.parallelRoutes)\n };\n childSegmentMap.set(segmentForCache, childCacheNode);\n }\n invalidateCacheBelowFlightSegmentPath(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2));\n}\n/**\n * Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch.\n */ function fillCacheWithDataProperty(newCache, existingCache, segments, fetchResponse) {\n const isLastEntry = segments.length === 1;\n const parallelRouteKey = 'children';\n const [segment] = segments;\n const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return {\n bailOptimistic: true\n };\n }\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap);\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);\n }\n const existingChildCacheNode = existingChildSegmentMap.get(segment);\n let childCacheNode = childSegmentMap.get(segment);\n // In case of last segment start off the fetch at this level and don't copy further down.\n if (isLastEntry) {\n if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) {\n childSegmentMap.set(segment, {\n status: _appRouterContext.CacheStates.DATA_FETCH,\n data: fetchResponse(),\n subTreeData: null,\n parallelRoutes: new Map()\n });\n }\n return;\n }\n if (!childCacheNode || !existingChildCacheNode) {\n // Start fetch in the place where the existing cache doesn't have the data yet.\n if (!childCacheNode) {\n childSegmentMap.set(segment, {\n status: _appRouterContext.CacheStates.DATA_FETCH,\n data: fetchResponse(),\n subTreeData: null,\n parallelRoutes: new Map()\n });\n }\n return;\n }\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n status: childCacheNode.status,\n data: childCacheNode.data,\n subTreeData: childCacheNode.subTreeData,\n parallelRoutes: new Map(childCacheNode.parallelRoutes)\n };\n childSegmentMap.set(segment, childCacheNode);\n }\n return fillCacheWithDataProperty(childCacheNode, existingChildCacheNode, segments.slice(1), fetchResponse);\n}\n/**\n * Create optimistic version of router state based on the existing router state and segments.\n * This is used to allow rendering layout-routers up till the point where data is missing.\n */ function createOptimisticTree(segments, flightRouterState, _isFirstSegment, parentRefetch, _href) {\n const [existingSegment, existingParallelRoutes] = flightRouterState || [\n null,\n {}, \n ];\n const segment = segments[0];\n const isLastSegment = segments.length === 1;\n const segmentMatches = existingSegment !== null && (0, _matchSegments).matchSegment(existingSegment, segment);\n const shouldRefetchThisLevel = !flightRouterState || !segmentMatches;\n let parallelRoutes = {};\n if (existingSegment !== null && segmentMatches) {\n parallelRoutes = existingParallelRoutes;\n }\n let childTree;\n if (!isLastSegment) {\n const childItem = createOptimisticTree(segments.slice(1), parallelRoutes ? parallelRoutes.children : null, false, parentRefetch || shouldRefetchThisLevel);\n childTree = childItem;\n }\n const result = [\n segment,\n _extends({}, parallelRoutes, childTree ? {\n children: childTree\n } : {}), \n ];\n if (!parentRefetch && shouldRefetchThisLevel) {\n result[3] = 'refetch';\n }\n return result;\n}\n/**\n * Apply the router state from the Flight response. Creates a new router state tree.\n */ function applyRouterStatePatchToTree(flightSegmentPath, flightRouterState, treePatch) {\n const [segment, parallelRoutes, , , isRootLayout] = flightRouterState;\n // Root refresh\n if (flightSegmentPath.length === 1) {\n const tree = [\n ...treePatch\n ];\n return tree;\n }\n const [currentSegment, parallelRouteKey] = flightSegmentPath;\n // Tree path returned from the server should always match up with the current tree in the browser\n if (!(0, _matchSegments).matchSegment(currentSegment, segment)) {\n return null;\n }\n const lastSegment = flightSegmentPath.length === 2;\n let parallelRoutePatch;\n if (lastSegment) {\n parallelRoutePatch = treePatch;\n } else {\n parallelRoutePatch = applyRouterStatePatchToTree(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch);\n if (parallelRoutePatch === null) {\n return null;\n }\n }\n const tree = [\n flightSegmentPath[0],\n _extends({}, parallelRoutes, {\n [parallelRouteKey]: parallelRoutePatch\n }), \n ];\n // Current segment is the root layout\n if (isRootLayout) {\n tree[4] = true;\n }\n return tree;\n}\nfunction shouldHardNavigate(flightSegmentPath, flightRouterState, treePatch) {\n const [segment, parallelRoutes] = flightRouterState;\n // TODO-APP: Check if `as` can be replaced.\n const [currentSegment, parallelRouteKey] = flightSegmentPath;\n // Check if current segment matches the existing segment.\n if (!(0, _matchSegments).matchSegment(currentSegment, segment)) {\n // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.\n if (Array.isArray(currentSegment)) {\n return true;\n }\n // If the existing segment did not match soft navigation is triggered.\n return false;\n }\n const lastSegment = flightSegmentPath.length <= 2;\n if (lastSegment) {\n return false;\n }\n return shouldHardNavigate(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch);\n}\nfunction isNavigatingToNewRootLayout(currentTree, nextTree) {\n // Compare segments\n const currentTreeSegment = currentTree[0];\n const nextTreeSegment = nextTree[0];\n // If any segment is different before we find the root layout, the root layout has changed.\n // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js\n // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.\n if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {\n // Compare dynamic param name and type but ignore the value, different values would not affect the current root layout\n // /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js\n if (currentTreeSegment[0] !== nextTreeSegment[0] || currentTreeSegment[2] !== nextTreeSegment[2]) {\n return true;\n }\n } else if (currentTreeSegment !== nextTreeSegment) {\n return true;\n }\n // Current tree root layout found\n if (currentTree[4]) {\n // If the next tree doesn't have the root layout flag, it must have changed.\n return !nextTree[4];\n }\n // Current tree didn't have its root layout here, must have changed.\n if (nextTree[4]) {\n return true;\n }\n // We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js`\n // But it's not possible to be more than one parallelRoutes before the root layout is found\n // TODO-APP: change to traverse all parallel routes\n const currentTreeChild = Object.values(currentTree[1])[0];\n const nextTreeChild = Object.values(nextTree[1])[0];\n if (!currentTreeChild || !nextTreeChild) return true;\n return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild);\n}\nconst ACTION_REFRESH = 'refresh';\nexports.ACTION_REFRESH = ACTION_REFRESH;\nconst ACTION_NAVIGATE = 'navigate';\nexports.ACTION_NAVIGATE = ACTION_NAVIGATE;\nconst ACTION_RESTORE = 'restore';\nexports.ACTION_RESTORE = ACTION_RESTORE;\nconst ACTION_SERVER_PATCH = 'server-patch';\nexports.ACTION_SERVER_PATCH = ACTION_SERVER_PATCH;\nconst ACTION_PREFETCH = 'prefetch';\nexports.ACTION_PREFETCH = ACTION_PREFETCH;\n/**\n * Reducer that handles the app-router state updates.\n */ function clientReducer(state, action) {\n switch(action.type){\n case ACTION_NAVIGATE:\n {\n const { url , navigateType , cache , mutable , forceOptimisticNavigation } = action;\n const { pathname , search } = url;\n const href = createHrefFromUrl(url);\n const pendingPush = navigateType === 'push';\n const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree);\n if (mutable.mpaNavigation && isForCurrentTree) {\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : href,\n pushRef: {\n pendingPush,\n mpaNavigation: mutable.mpaNavigation\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: false\n },\n // Apply cache.\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n // Apply patched router state.\n tree: state.tree\n };\n }\n // Handle concurrent rendering / strict mode case where the cache and tree were already populated.\n if (mutable.patchedTree && isForCurrentTree) {\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : href,\n pushRef: {\n pendingPush,\n mpaNavigation: false\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: true\n },\n // Apply cache.\n cache: mutable.useExistingCache ? state.cache : cache,\n prefetchCache: state.prefetchCache,\n // Apply patched router state.\n tree: mutable.patchedTree\n };\n }\n const prefetchValues = state.prefetchCache.get(href);\n if (prefetchValues) {\n // The one before last item is the router state tree patch\n const { flightData , tree: newTree , canonicalUrlOverride , } = prefetchValues;\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return {\n canonicalUrl: flightData,\n // Enable mpaNavigation\n pushRef: {\n pendingPush: true,\n mpaNavigation: true\n },\n // Don't apply scroll and focus management.\n focusAndScrollRef: {\n apply: false\n },\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n tree: state.tree\n };\n }\n if (newTree !== null) {\n mutable.previousTree = state.tree;\n mutable.patchedTree = newTree;\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree);\n if (newTree === null) {\n throw new Error('SEGMENT MISMATCH');\n }\n const canonicalUrlOverrideHrefVal = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : undefined;\n if (canonicalUrlOverrideHrefVal) {\n mutable.canonicalUrlOverride = canonicalUrlOverrideHrefVal;\n }\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree);\n // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.\n const flightDataPath = flightData[0];\n const flightSegmentPath = flightDataPath.slice(0, -3);\n // The one before last item is the router state tree patch\n const [treePatch, subTreeData, head] = flightDataPath.slice(-3);\n // Handles case where prefetch only returns the router tree patch without rendered components.\n if (subTreeData !== null) {\n if (flightDataPath.length === 3) {\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = subTreeData;\n fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head);\n } else {\n cache.status = _appRouterContext.CacheStates.READY;\n // Copy subTreeData for the root node of the cache.\n cache.subTreeData = state.cache.subTreeData;\n // Create a copy of the existing cache with the subTreeData applied.\n fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath);\n }\n }\n const hardNavigate = // TODO-APP: Revisit if this is correct.\n search !== location.search || shouldHardNavigate(// TODO-APP: remove ''\n [\n '',\n ...flightSegmentPath\n ], state.tree, newTree);\n if (hardNavigate) {\n cache.status = _appRouterContext.CacheStates.READY;\n // Copy subTreeData for the root node of the cache.\n cache.subTreeData = state.cache.subTreeData;\n invalidateCacheBelowFlightSegmentPath(cache, state.cache, flightSegmentPath);\n // Ensure the existing cache value is used when the cache was not invalidated.\n } else if (subTreeData === null) {\n mutable.useExistingCache = true;\n }\n const canonicalUrlOverrideHref = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : undefined;\n if (canonicalUrlOverrideHref) {\n mutable.canonicalUrlOverride = canonicalUrlOverrideHref;\n }\n return {\n // Set href.\n canonicalUrl: canonicalUrlOverrideHref ? canonicalUrlOverrideHref : href,\n // Set pendingPush.\n pushRef: {\n pendingPush,\n mpaNavigation: false\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: true\n },\n // Apply patched cache.\n cache: mutable.useExistingCache ? state.cache : cache,\n prefetchCache: state.prefetchCache,\n // Apply patched tree.\n tree: newTree\n };\n }\n }\n // When doing a hard push there can be two cases: with optimistic tree and without\n // The with optimistic tree case only happens when the layouts have a loading state (loading.js)\n // The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer\n // forceOptimisticNavigation is used for links that have `prefetch={false}`.\n if (forceOptimisticNavigation) {\n const segments = pathname.split('/');\n // TODO-APP: figure out something better for index pages\n segments.push('');\n // Optimistic tree case.\n // If the optimistic tree is deeper than the current state leave that deeper part out of the fetch\n const optimisticTree = createOptimisticTree(segments, state.tree, true, false, href);\n // Copy subTreeData for the root node of the cache.\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = state.cache.subTreeData;\n // Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch.\n // The `data` property is used to suspend in layout-router during render if it hasn't resolved yet by the time it renders.\n const res = fillCacheWithDataProperty(cache, state.cache, // TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.\n segments.slice(1), ()=>(0, _appRouter).fetchServerResponse(url, optimisticTree));\n // If optimistic fetch couldn't happen it falls back to the non-optimistic case.\n if (!(res == null ? void 0 : res.bailOptimistic)) {\n mutable.previousTree = state.tree;\n mutable.patchedTree = optimisticTree;\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, optimisticTree);\n return {\n // Set href.\n canonicalUrl: href,\n // Set pendingPush.\n pushRef: {\n pendingPush,\n mpaNavigation: false\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: true\n },\n // Apply patched cache.\n cache: cache,\n prefetchCache: state.prefetchCache,\n // Apply optimistic tree.\n tree: optimisticTree\n };\n }\n }\n // Below is the not-optimistic case. Data is fetched at the root and suspended there without a suspense boundary.\n // If no in-flight fetch at the top, start it.\n if (!cache.data) {\n cache.data = createRecordFromThenable((0, _appRouter).fetchServerResponse(url, state.tree));\n }\n // Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.\n const [flightData, canonicalUrlOverride] = readRecordValue(cache.data);\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return {\n canonicalUrl: flightData,\n // Enable mpaNavigation\n pushRef: {\n pendingPush: true,\n mpaNavigation: true\n },\n // Don't apply scroll and focus management.\n focusAndScrollRef: {\n apply: false\n },\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n tree: state.tree\n };\n }\n // Remove cache.data as it has been resolved at this point.\n cache.data = null;\n // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.\n const flightDataPath = flightData[0];\n // The one before last item is the router state tree patch\n const [treePatch, subTreeData, head] = flightDataPath.slice(-3);\n // Path without the last segment, router state, and the subTreeData\n const flightSegmentPath = flightDataPath.slice(0, -4);\n // Create new tree based on the flightSegmentPath and router state patch\n const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''\n [\n '',\n ...flightSegmentPath\n ], state.tree, treePatch);\n if (newTree === null) {\n throw new Error('SEGMENT MISMATCH');\n }\n const canonicalUrlOverrideHref = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : undefined;\n if (canonicalUrlOverrideHref) {\n mutable.canonicalUrlOverride = canonicalUrlOverrideHref;\n }\n mutable.previousTree = state.tree;\n mutable.patchedTree = newTree;\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree);\n if (flightDataPath.length === 3) {\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = subTreeData;\n fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head);\n } else {\n // Copy subTreeData for the root node of the cache.\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = state.cache.subTreeData;\n // Create a copy of the existing cache with the subTreeData applied.\n fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath);\n }\n return {\n // Set href.\n canonicalUrl: canonicalUrlOverrideHref ? canonicalUrlOverrideHref : href,\n // Set pendingPush.\n pushRef: {\n pendingPush,\n mpaNavigation: false\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: true\n },\n // Apply patched cache.\n cache: cache,\n prefetchCache: state.prefetchCache,\n // Apply patched tree.\n tree: newTree\n };\n }\n case ACTION_SERVER_PATCH:\n {\n const { flightData , previousTree , overrideCanonicalUrl , cache , mutable } = action;\n // When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs.\n // In that case opt-out of applying the patch given that the data could be stale.\n if (JSON.stringify(previousTree) !== JSON.stringify(state.tree)) {\n // TODO-APP: Handle tree mismatch\n console.log('TREE MISMATCH');\n // Keep everything as-is.\n return state;\n }\n if (mutable.mpaNavigation) {\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : state.canonicalUrl,\n // TODO-APP: verify mpaNavigation not being set is correct here.\n pushRef: {\n pendingPush: true,\n mpaNavigation: mutable.mpaNavigation\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: false\n },\n // Apply cache.\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n // Apply patched router state.\n tree: state.tree\n };\n }\n // Handle concurrent rendering / strict mode case where the cache and tree were already populated.\n if (mutable.patchedTree) {\n return {\n // Keep href as it was set during navigate / restore\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : state.canonicalUrl,\n // Keep pushRef as server-patch only causes cache/tree update.\n pushRef: state.pushRef,\n // Keep focusAndScrollRef as server-patch only causes cache/tree update.\n focusAndScrollRef: state.focusAndScrollRef,\n // Apply patched router state\n tree: mutable.patchedTree,\n prefetchCache: state.prefetchCache,\n // Apply patched cache\n cache: cache\n };\n }\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return {\n // Set href.\n canonicalUrl: flightData,\n // Enable mpaNavigation as this is a navigation that the app-router shouldn't handle.\n pushRef: {\n pendingPush: true,\n mpaNavigation: true\n },\n // Don't apply scroll and focus management.\n focusAndScrollRef: {\n apply: false\n },\n // Other state is kept as-is.\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n tree: state.tree\n };\n }\n // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.\n const flightDataPath = flightData[0];\n // Slices off the last segment (which is at -4) as it doesn't exist in the tree yet\n const flightSegmentPath = flightDataPath.slice(0, -4);\n const [treePatch, subTreeData, head] = flightDataPath.slice(-3);\n const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''\n [\n '',\n ...flightSegmentPath\n ], state.tree, treePatch);\n if (newTree === null) {\n throw new Error('SEGMENT MISMATCH');\n }\n const canonicalUrlOverrideHref = overrideCanonicalUrl ? createHrefFromUrl(overrideCanonicalUrl) : undefined;\n if (canonicalUrlOverrideHref) {\n mutable.canonicalUrlOverride = canonicalUrlOverrideHref;\n }\n mutable.patchedTree = newTree;\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree);\n // Root refresh\n if (flightDataPath.length === 3) {\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = subTreeData;\n fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head);\n } else {\n // Copy subTreeData for the root node of the cache.\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = state.cache.subTreeData;\n fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath);\n }\n return {\n // Keep href as it was set during navigate / restore\n canonicalUrl: canonicalUrlOverrideHref ? canonicalUrlOverrideHref : state.canonicalUrl,\n // Keep pushRef as server-patch only causes cache/tree update.\n pushRef: state.pushRef,\n // Keep focusAndScrollRef as server-patch only causes cache/tree update.\n focusAndScrollRef: state.focusAndScrollRef,\n // Apply patched router state\n tree: newTree,\n prefetchCache: state.prefetchCache,\n // Apply patched cache\n cache: cache\n };\n }\n case ACTION_RESTORE:\n {\n const { url , tree } = action;\n const href = createHrefFromUrl(url);\n return {\n // Set canonical url\n canonicalUrl: href,\n pushRef: state.pushRef,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n // Restore provided tree\n tree: tree\n };\n }\n // TODO-APP: Add test for not scrolling to nearest layout when calling refresh.\n // TODO-APP: Add test for startTransition(() => {router.push('/'); router.refresh();}), that case should scroll.\n case ACTION_REFRESH:\n {\n const { cache , mutable } = action;\n const href = state.canonicalUrl;\n const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree);\n if (mutable.mpaNavigation && isForCurrentTree) {\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : state.canonicalUrl,\n // TODO-APP: verify mpaNavigation not being set is correct here.\n pushRef: {\n pendingPush: true,\n mpaNavigation: mutable.mpaNavigation\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: false\n },\n // Apply cache.\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n // Apply patched router state.\n tree: state.tree\n };\n }\n // Handle concurrent rendering / strict mode case where the cache and tree were already populated.\n if (mutable.patchedTree && isForCurrentTree) {\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride : href,\n // set pendingPush (always false in this case).\n pushRef: state.pushRef,\n // Apply focus and scroll.\n // TODO-APP: might need to disable this for Fast Refresh.\n focusAndScrollRef: {\n apply: false\n },\n cache: cache,\n prefetchCache: state.prefetchCache,\n tree: mutable.patchedTree\n };\n }\n if (!cache.data) {\n // Fetch data from the root of the tree.\n cache.data = createRecordFromThenable((0, _appRouter).fetchServerResponse(new URL(href, location.origin), [\n state.tree[0],\n state.tree[1],\n state.tree[2],\n 'refetch', \n ]));\n }\n const [flightData, canonicalUrlOverride] = readRecordValue(cache.data);\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return {\n canonicalUrl: flightData,\n pushRef: {\n pendingPush: true,\n mpaNavigation: true\n },\n focusAndScrollRef: {\n apply: false\n },\n cache: state.cache,\n prefetchCache: state.prefetchCache,\n tree: state.tree\n };\n }\n // Remove cache.data as it has been resolved at this point.\n cache.data = null;\n // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.\n const flightDataPath = flightData[0];\n // FlightDataPath with more than two items means unexpected Flight data was returned\n if (flightDataPath.length !== 3) {\n // TODO-APP: handle this case better\n console.log('REFRESH FAILED');\n return state;\n }\n // Given the path can only have two items the items are only the router state and subTreeData for the root.\n const [treePatch, subTreeData, head] = flightDataPath;\n const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''\n [\n ''\n ], state.tree, treePatch);\n if (newTree === null) {\n throw new Error('SEGMENT MISMATCH');\n }\n const canonicalUrlOverrideHref = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : undefined;\n if (canonicalUrlOverride) {\n mutable.canonicalUrlOverride = canonicalUrlOverrideHref;\n }\n mutable.previousTree = state.tree;\n mutable.patchedTree = newTree;\n mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree);\n // Set subTreeData for the root node of the cache.\n cache.status = _appRouterContext.CacheStates.READY;\n cache.subTreeData = subTreeData;\n fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head);\n return {\n // Set href, this doesn't reuse the state.canonicalUrl as because of concurrent rendering the href might change between dispatching and applying.\n canonicalUrl: canonicalUrlOverrideHref ? canonicalUrlOverrideHref : href,\n // set pendingPush (always false in this case).\n pushRef: state.pushRef,\n // TODO-APP: might need to disable this for Fast Refresh.\n focusAndScrollRef: {\n apply: false\n },\n // Apply patched cache.\n cache: cache,\n prefetchCache: state.prefetchCache,\n // Apply patched router state.\n tree: newTree\n };\n }\n case ACTION_PREFETCH:\n {\n const { url , serverResponse } = action;\n const [flightData, canonicalUrlOverride] = serverResponse;\n if (typeof flightData === 'string') {\n return state;\n }\n const href = createHrefFromUrl(url);\n // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.\n const flightDataPath = flightData[0];\n // The one before last item is the router state tree patch\n const [treePatch] = flightDataPath.slice(-3);\n const flightSegmentPath = flightDataPath.slice(0, -3);\n const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''\n [\n '',\n ...flightSegmentPath\n ], state.tree, treePatch);\n // Patch did not apply correctly\n if (newTree === null) {\n return state;\n }\n // Create new tree based on the flightSegmentPath and router state patch\n state.prefetchCache.set(href, {\n flightData,\n // Create new tree based on the flightSegmentPath and router state patch\n tree: newTree,\n canonicalUrlOverride\n });\n return state;\n }\n // This case should never be hit as dispatch is strongly typed.\n default:\n throw new Error('Unknown action');\n }\n}\nfunction serverReducer(state, _action) {\n return state;\n}\nconst reducer = typeof window === 'undefined' ? serverReducer : clientReducer;\nexports.reducer = reducer;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=reducer.js.map","\"use client\";\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = RenderFromTemplateContext;\nvar _interop_require_wildcard = require(\"@swc/helpers/lib/_interop_require_wildcard.js\").default;\nvar _react = _interop_require_wildcard(require(\"react\"));\nvar _appRouterContext = require(\"../../shared/lib/app-router-context\");\nfunction RenderFromTemplateContext() {\n const children = (0, _react).useContext(_appRouterContext.TemplateContext);\n return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children);\n}\n\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=render-from-template-context.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.useReducerWithReduxDevtools = void 0;\nvar _react = require(\"react\");\nfunction normalizeRouterState(val) {\n if (val instanceof Map) {\n const obj = {};\n for (const [key, value] of val.entries()){\n if (typeof value === 'function') {\n obj[key] = 'fn()';\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n if (value.$$typeof) {\n obj[key] = value.$$typeof.toString();\n continue;\n }\n if (value._bundlerConfig) {\n obj[key] = 'FlightData';\n continue;\n }\n }\n obj[key] = normalizeRouterState(value);\n }\n return obj;\n }\n if (typeof val === 'object' && val !== null) {\n const obj = {};\n for(const key in val){\n const value = val[key];\n if (typeof value === 'function') {\n obj[key] = 'fn()';\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n if (value.$$typeof) {\n obj[key] = value.$$typeof.toString();\n continue;\n }\n if (value.hasOwnProperty('_bundlerConfig')) {\n obj[key] = 'FlightData';\n continue;\n }\n }\n obj[key] = normalizeRouterState(value);\n }\n return obj;\n }\n if (Array.isArray(val)) {\n return val.map(normalizeRouterState);\n }\n return val;\n}\nfunction devToolReducer(fn, ref) {\n return (state, action)=>{\n const res = fn(state, action);\n if (ref.current) {\n ref.current.send(action, normalizeRouterState(res));\n }\n return res;\n };\n}\nfunction useReducerWithReduxDevtoolsNoop(fn, initialState) {\n const [state, dispatch] = (0, _react).useReducer(fn, initialState);\n return [\n state,\n dispatch,\n ()=>{}\n ];\n}\nfunction useReducerWithReduxDevtoolsImpl(fn, initialState) {\n const devtoolsConnectionRef = (0, _react).useRef();\n const enabledRef = (0, _react).useRef();\n (0, _react).useEffect(()=>{\n if (devtoolsConnectionRef.current || enabledRef.current === false) {\n return;\n }\n if (enabledRef.current === undefined && typeof window.__REDUX_DEVTOOLS_EXTENSION__ === 'undefined') {\n enabledRef.current = false;\n return;\n }\n devtoolsConnectionRef.current = window.__REDUX_DEVTOOLS_EXTENSION__.connect({\n instanceId: 1,\n name: 'next-router'\n });\n if (devtoolsConnectionRef.current) {\n devtoolsConnectionRef.current.init(normalizeRouterState(initialState));\n }\n return ()=>{\n devtoolsConnectionRef.current = undefined;\n };\n }, [\n initialState\n ]);\n const [state, dispatch] = (0, _react).useReducer(devToolReducer(/* logReducer( */ fn /*)*/ , devtoolsConnectionRef), initialState);\n const sync = (0, _react).useCallback(()=>{\n if (devtoolsConnectionRef.current) {\n devtoolsConnectionRef.current.send({\n type: 'RENDER_SYNC'\n }, normalizeRouterState(state));\n }\n }, [\n state\n ]);\n return [\n state,\n dispatch,\n sync\n ];\n}\nconst useReducerWithReduxDevtools = typeof window !== 'undefined' ? useReducerWithReduxDevtoolsImpl : useReducerWithReduxDevtoolsNoop;\nexports.useReducerWithReduxDevtools = useReducerWithReduxDevtools;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=use-reducer-with-devtools.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.detectDomainLocale = void 0;\nconst detectDomainLocale = (...args)=>{\n if (process.env.__NEXT_I18N_SUPPORT) {\n return require('../shared/lib/i18n/detect-domain-locale').detectDomainLocale(...args);\n }\n};\nexports.detectDomainLocale = detectDomainLocale;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=detect-domain-locale.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.hasBasePath = hasBasePath;\nvar _pathHasPrefix = require(\"../shared/lib/router/utils/path-has-prefix\");\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nfunction hasBasePath(path) {\n return (0, _pathHasPrefix).pathHasPrefix(path, basePath);\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=has-base-path.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = initHeadManager;\nexports.isEqualNode = isEqualNode;\nexports.DOMAttributeNames = void 0;\nfunction initHeadManager() {\n return {\n mountedInstances: new Set(),\n updateHead: (head)=>{\n const tags = {};\n head.forEach((h)=>{\n if (// If the font tag is loaded only on client navigation\n // it won't be inlined. In this case revert to the original behavior\n h.type === 'link' && h.props['data-optimized-fonts']) {\n if (document.querySelector(`style[data-href=\"${h.props['data-href']}\"]`)) {\n return;\n } else {\n h.props.href = h.props['data-href'];\n h.props['data-href'] = undefined;\n }\n }\n const components = tags[h.type] || [];\n components.push(h);\n tags[h.type] = components;\n });\n const titleComponent = tags.title ? tags.title[0] : null;\n let title = '';\n if (titleComponent) {\n const { children } = titleComponent.props;\n title = typeof children === 'string' ? children : Array.isArray(children) ? children.join('') : '';\n }\n if (title !== document.title) document.title = title;\n [\n 'meta',\n 'base',\n 'link',\n 'style',\n 'script'\n ].forEach((type)=>{\n updateElements(type, tags[type] || []);\n });\n }\n };\n}\nconst DOMAttributeNames = {\n acceptCharset: 'accept-charset',\n className: 'class',\n htmlFor: 'for',\n httpEquiv: 'http-equiv',\n noModule: 'noModule'\n};\nexports.DOMAttributeNames = DOMAttributeNames;\nfunction reactElementToDOM({ type , props }) {\n const el = document.createElement(type);\n for(const p in props){\n if (!props.hasOwnProperty(p)) continue;\n if (p === 'children' || p === 'dangerouslySetInnerHTML') continue;\n // we don't render undefined props to the DOM\n if (props[p] === undefined) continue;\n const attr = DOMAttributeNames[p] || p.toLowerCase();\n if (type === 'script' && (attr === 'async' || attr === 'defer' || attr === 'noModule')) {\n el[attr] = !!props[p];\n } else {\n el.setAttribute(attr, props[p]);\n }\n }\n const { children , dangerouslySetInnerHTML } = props;\n if (dangerouslySetInnerHTML) {\n el.innerHTML = dangerouslySetInnerHTML.__html || '';\n } else if (children) {\n el.textContent = typeof children === 'string' ? children : Array.isArray(children) ? children.join('') : '';\n }\n return el;\n}\nfunction isEqualNode(oldTag, newTag) {\n if (oldTag instanceof HTMLElement && newTag instanceof HTMLElement) {\n const nonce = newTag.getAttribute('nonce');\n // Only strip the nonce if `oldTag` has had it stripped. An element's nonce attribute will not\n // be stripped if there is no content security policy response header that includes a nonce.\n if (nonce && !oldTag.getAttribute('nonce')) {\n const cloneTag = newTag.cloneNode(true);\n cloneTag.setAttribute('nonce', '');\n cloneTag.nonce = nonce;\n return nonce === oldTag.nonce && oldTag.isEqualNode(cloneTag);\n }\n }\n return oldTag.isEqualNode(newTag);\n}\nfunction updateElements(type, components) {\n const headEl = document.getElementsByTagName('head')[0];\n const headCountEl = headEl.querySelector('meta[name=next-head-count]');\n if (process.env.NODE_ENV !== 'production') {\n if (!headCountEl) {\n console.error('Warning: next-head-count is missing. https://nextjs.org/docs/messages/next-head-count-missing');\n return;\n }\n }\n const headCount = Number(headCountEl.content);\n const oldTags = [];\n for(let i = 0, j = headCountEl.previousElementSibling; i < headCount; i++, j = (j == null ? void 0 : j.previousElementSibling) || null){\n var ref;\n if ((j == null ? void 0 : (ref = j.tagName) == null ? void 0 : ref.toLowerCase()) === type) {\n oldTags.push(j);\n }\n }\n const newTags = components.map(reactElementToDOM).filter((newTag)=>{\n for(let k = 0, len = oldTags.length; k < len; k++){\n const oldTag = oldTags[k];\n if (isEqualNode(oldTag, newTag)) {\n oldTags.splice(k, 1);\n return false;\n }\n }\n return true;\n });\n oldTags.forEach((t)=>{\n var ref;\n return (ref = t.parentNode) == null ? void 0 : ref.removeChild(t);\n });\n newTags.forEach((t)=>headEl.insertBefore(t, headCountEl));\n headCountEl.content = (headCount - oldTags.length + newTags.length).toString();\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=head-manager.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.normalizePathTrailingSlash = void 0;\nvar _removeTrailingSlash = require(\"../shared/lib/router/utils/remove-trailing-slash\");\nvar _parsePath = require(\"../shared/lib/router/utils/parse-path\");\nconst normalizePathTrailingSlash = (path)=>{\n if (!path.startsWith('/') || process.env.__NEXT_MANUAL_TRAILING_SLASH) {\n return path;\n }\n const { pathname , query , hash } = (0, _parsePath).parsePath(path);\n if (process.env.__NEXT_TRAILING_SLASH) {\n if (/\\.[^/]+\\/?$/.test(pathname)) {\n return `${(0, _removeTrailingSlash).removeTrailingSlash(pathname)}${query}${hash}`;\n } else if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`;\n } else {\n return `${pathname}/${query}${hash}`;\n }\n }\n return `${(0, _removeTrailingSlash).removeTrailingSlash(pathname)}${query}${hash}`;\n};\nexports.normalizePathTrailingSlash = normalizePathTrailingSlash;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=normalize-trailing-slash.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = onRecoverableError;\nvar _noSsrError = require(\"../shared/lib/no-ssr-error\");\nfunction onRecoverableError(err, errorInfo) {\n const digest = err.digest || errorInfo.digest;\n // Using default react onRecoverableError\n // x-ref: https://github.com/facebook/react/blob/d4bc16a7d69eb2ea38a88c8ac0b461d5f72cdcab/packages/react-dom/src/client/ReactDOMRoot.js#L83\n const defaultOnRecoverableError = typeof reportError === 'function' ? // emulating an uncaught JavaScript error.\n reportError : (error)=>{\n window.console.error(error);\n };\n // Skip certain custom errors which are not expected to be reported on client\n if (digest === _noSsrError.NEXT_DYNAMIC_NO_SSR_CODE) return;\n defaultOnRecoverableError(err);\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=on-recoverable-error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.removeBasePath = removeBasePath;\nvar _hasBasePath = require(\"./has-base-path\");\nconst basePath = process.env.__NEXT_ROUTER_BASEPATH || '';\nfunction removeBasePath(path) {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!(0, _hasBasePath).hasBasePath(path)) {\n return path;\n }\n }\n path = path.slice(basePath.length);\n if (!path.startsWith('/')) path = `/${path}`;\n return path;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=remove-base-path.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.removeLocale = removeLocale;\nvar _parsePath = require(\"../shared/lib/router/utils/parse-path\");\nfunction removeLocale(path, locale) {\n if (process.env.__NEXT_I18N_SUPPORT) {\n const { pathname } = (0, _parsePath).parsePath(path);\n const pathLower = pathname.toLowerCase();\n const localeLower = locale == null ? void 0 : locale.toLowerCase();\n return locale && (pathLower.startsWith(`/${localeLower}/`) || pathLower === `/${localeLower}`) ? `${pathname.length === locale.length + 1 ? `/` : ``}${path.slice(locale.length + 1)}` : path;\n }\n return path;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=remove-locale.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.cancelIdleCallback = exports.requestIdleCallback = void 0;\nconst requestIdleCallback = typeof self !== 'undefined' && self.requestIdleCallback && self.requestIdleCallback.bind(window) || function(cb) {\n let start = Date.now();\n return self.setTimeout(function() {\n cb({\n didTimeout: false,\n timeRemaining: function() {\n return Math.max(0, 50 - (Date.now() - start));\n }\n });\n }, 1);\n};\nexports.requestIdleCallback = requestIdleCallback;\nconst cancelIdleCallback = typeof self !== 'undefined' && self.cancelIdleCallback && self.cancelIdleCallback.bind(window) || function(id) {\n return clearTimeout(id);\n};\nexports.cancelIdleCallback = cancelIdleCallback;\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=request-idle-callback.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.markAssetError = markAssetError;\nexports.isAssetError = isAssetError;\nexports.getClientBuildManifest = getClientBuildManifest;\nexports.createRouteLoader = createRouteLoader;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _getAssetPathFromRoute = _interop_require_default(require(\"../shared/lib/router/utils/get-asset-path-from-route\"));\nvar _trustedTypes = require(\"./trusted-types\");\nvar _requestIdleCallback = require(\"./request-idle-callback\");\n// 3.8s was arbitrarily chosen as it's what https://web.dev/interactive\n// considers as \"Good\" time-to-interactive. We must assume something went\n// wrong beyond this point, and then fall-back to a full page transition to\n// show the user something of value.\nconst MS_MAX_IDLE_DELAY = 3800;\nfunction withFuture(key, map, generator) {\n let entry = map.get(key);\n if (entry) {\n if ('future' in entry) {\n return entry.future;\n }\n return Promise.resolve(entry);\n }\n let resolver;\n const prom = new Promise((resolve)=>{\n resolver = resolve;\n });\n map.set(key, entry = {\n resolve: resolver,\n future: prom\n });\n return generator ? generator()// eslint-disable-next-line no-sequences\n .then((value)=>(resolver(value), value)).catch((err)=>{\n map.delete(key);\n throw err;\n }) : prom;\n}\nconst ASSET_LOAD_ERROR = Symbol('ASSET_LOAD_ERROR');\nfunction markAssetError(err) {\n return Object.defineProperty(err, ASSET_LOAD_ERROR, {});\n}\nfunction isAssetError(err) {\n return err && ASSET_LOAD_ERROR in err;\n}\nfunction hasPrefetch(link) {\n try {\n link = document.createElement('link');\n return(// detect IE11 since it supports prefetch but isn't detected\n // with relList.support\n (!!window.MSInputMethodContext && !!document.documentMode) || link.relList.supports('prefetch'));\n } catch (e) {\n return false;\n }\n}\nconst canPrefetch = hasPrefetch();\nfunction prefetchViaDom(href, as, link) {\n return new Promise((resolve, reject)=>{\n const selector = `\n link[rel=\"prefetch\"][href^=\"${href}\"],\n link[rel=\"preload\"][href^=\"${href}\"],\n script[src^=\"${href}\"]`;\n if (document.querySelector(selector)) {\n return resolve();\n }\n link = document.createElement('link');\n // The order of property assignment here is intentional:\n if (as) link.as = as;\n link.rel = `prefetch`;\n link.crossOrigin = process.env.__NEXT_CROSS_ORIGIN;\n link.onload = resolve;\n link.onerror = ()=>reject(markAssetError(new Error(`Failed to prefetch: ${href}`)));\n // `href` should always be last:\n link.href = href;\n document.head.appendChild(link);\n });\n}\nfunction appendScript(src, script) {\n return new Promise((resolve, reject)=>{\n script = document.createElement('script');\n // The order of property assignment here is intentional.\n // 1. Setup success/failure hooks in case the browser synchronously\n // executes when `src` is set.\n script.onload = resolve;\n script.onerror = ()=>reject(markAssetError(new Error(`Failed to load script: ${src}`)));\n // 2. Configure the cross-origin attribute before setting `src` in case the\n // browser begins to fetch.\n script.crossOrigin = process.env.__NEXT_CROSS_ORIGIN;\n // 3. Finally, set the source and inject into the DOM in case the child\n // must be appended for fetching to start.\n script.src = src;\n document.body.appendChild(script);\n });\n}\n// We wait for pages to be built in dev before we start the route transition\n// timeout to prevent an un-necessary hard navigation in development.\nlet devBuildPromise;\n// Resolve a promise that times out after given amount of milliseconds.\nfunction resolvePromiseWithTimeout(p, ms, err) {\n return new Promise((resolve, reject)=>{\n let cancelled = false;\n p.then((r)=>{\n // Resolved, cancel the timeout\n cancelled = true;\n resolve(r);\n }).catch(reject);\n // We wrap these checks separately for better dead-code elimination in\n // production bundles.\n if (process.env.NODE_ENV === 'development') {\n (devBuildPromise || Promise.resolve()).then(()=>{\n (0, _requestIdleCallback).requestIdleCallback(()=>setTimeout(()=>{\n if (!cancelled) {\n reject(err);\n }\n }, ms));\n });\n }\n if (process.env.NODE_ENV !== 'development') {\n (0, _requestIdleCallback).requestIdleCallback(()=>setTimeout(()=>{\n if (!cancelled) {\n reject(err);\n }\n }, ms));\n }\n });\n}\nfunction getClientBuildManifest() {\n if (self.__BUILD_MANIFEST) {\n return Promise.resolve(self.__BUILD_MANIFEST);\n }\n const onBuildManifest = new Promise((resolve)=>{\n // Mandatory because this is not concurrent safe:\n const cb = self.__BUILD_MANIFEST_CB;\n self.__BUILD_MANIFEST_CB = ()=>{\n resolve(self.__BUILD_MANIFEST);\n cb && cb();\n };\n });\n return resolvePromiseWithTimeout(onBuildManifest, MS_MAX_IDLE_DELAY, markAssetError(new Error('Failed to load client build manifest')));\n}\nfunction getFilesForRoute(assetPrefix, route) {\n if (process.env.NODE_ENV === 'development') {\n const scriptUrl = assetPrefix + '/_next/static/chunks/pages' + encodeURI((0, _getAssetPathFromRoute).default(route, '.js'));\n return Promise.resolve({\n scripts: [\n (0, _trustedTypes).__unsafeCreateTrustedScriptURL(scriptUrl)\n ],\n // Styles are handled by `style-loader` in development:\n css: []\n });\n }\n return getClientBuildManifest().then((manifest)=>{\n if (!(route in manifest)) {\n throw markAssetError(new Error(`Failed to lookup route: ${route}`));\n }\n const allFiles = manifest[route].map((entry)=>assetPrefix + '/_next/' + encodeURI(entry));\n return {\n scripts: allFiles.filter((v)=>v.endsWith('.js')).map((v)=>(0, _trustedTypes).__unsafeCreateTrustedScriptURL(v)),\n css: allFiles.filter((v)=>v.endsWith('.css'))\n };\n });\n}\nfunction createRouteLoader(assetPrefix) {\n const entrypoints = new Map();\n const loadedScripts = new Map();\n const styleSheets = new Map();\n const routes = new Map();\n function maybeExecuteScript(src) {\n // With HMR we might need to \"reload\" scripts when they are\n // disposed and readded. Executing scripts twice has no functional\n // differences\n if (process.env.NODE_ENV !== 'development') {\n let prom = loadedScripts.get(src.toString());\n if (prom) {\n return prom;\n }\n // Skip executing script if it's already in the DOM:\n if (document.querySelector(`script[src^=\"${src}\"]`)) {\n return Promise.resolve();\n }\n loadedScripts.set(src.toString(), prom = appendScript(src));\n return prom;\n } else {\n return appendScript(src);\n }\n }\n function fetchStyleSheet(href) {\n let prom = styleSheets.get(href);\n if (prom) {\n return prom;\n }\n styleSheets.set(href, prom = fetch(href).then((res)=>{\n if (!res.ok) {\n throw new Error(`Failed to load stylesheet: ${href}`);\n }\n return res.text().then((text)=>({\n href: href,\n content: text\n }));\n }).catch((err)=>{\n throw markAssetError(err);\n }));\n return prom;\n }\n return {\n whenEntrypoint (route) {\n return withFuture(route, entrypoints);\n },\n onEntrypoint (route, execute) {\n (execute ? Promise.resolve().then(()=>execute()).then((exports)=>({\n component: exports && exports.default || exports,\n exports: exports\n }), (err)=>({\n error: err\n })) : Promise.resolve(undefined)).then((input)=>{\n const old = entrypoints.get(route);\n if (old && 'resolve' in old) {\n if (input) {\n entrypoints.set(route, input);\n old.resolve(input);\n }\n } else {\n if (input) {\n entrypoints.set(route, input);\n } else {\n entrypoints.delete(route);\n }\n // when this entrypoint has been resolved before\n // the route is outdated and we want to invalidate\n // this cache entry\n routes.delete(route);\n }\n });\n },\n loadRoute (route, prefetch) {\n return withFuture(route, routes, ()=>{\n let devBuildPromiseResolve;\n if (process.env.NODE_ENV === 'development') {\n devBuildPromise = new Promise((resolve)=>{\n devBuildPromiseResolve = resolve;\n });\n }\n return resolvePromiseWithTimeout(getFilesForRoute(assetPrefix, route).then(({ scripts , css })=>{\n return Promise.all([\n entrypoints.has(route) ? [] : Promise.all(scripts.map(maybeExecuteScript)),\n Promise.all(css.map(fetchStyleSheet)), \n ]);\n }).then((res)=>{\n return this.whenEntrypoint(route).then((entrypoint)=>({\n entrypoint,\n styles: res[1]\n }));\n }), MS_MAX_IDLE_DELAY, markAssetError(new Error(`Route did not complete loading: ${route}`))).then(({ entrypoint , styles })=>{\n const res = Object.assign({\n styles: styles\n }, entrypoint);\n return 'error' in entrypoint ? entrypoint : res;\n }).catch((err)=>{\n if (prefetch) {\n // we don't want to cache errors during prefetch\n throw err;\n }\n return {\n error: err\n };\n }).finally(()=>{\n return devBuildPromiseResolve == null ? void 0 : devBuildPromiseResolve();\n });\n });\n },\n prefetch (route) {\n // https://github.com/GoogleChromeLabs/quicklink/blob/453a661fa1fa940e2d2e044452398e38c67a98fb/src/index.mjs#L115-L118\n // License: Apache 2.0\n let cn;\n if (cn = navigator.connection) {\n // Don't prefetch if using 2G or if Save-Data is enabled.\n if (cn.saveData || /2g/.test(cn.effectiveType)) return Promise.resolve();\n }\n return getFilesForRoute(assetPrefix, route).then((output)=>Promise.all(canPrefetch ? output.scripts.map((script)=>prefetchViaDom(script.toString(), 'script')) : [])).then(()=>{\n (0, _requestIdleCallback).requestIdleCallback(()=>this.loadRoute(route, true).catch(()=>{}));\n }).catch(// swallow prefetch errors\n ()=>{});\n }\n };\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=route-loader.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"Router\", {\n enumerable: true,\n get: function() {\n return _router.default;\n }\n});\nObject.defineProperty(exports, \"withRouter\", {\n enumerable: true,\n get: function() {\n return _withRouter.default;\n }\n});\nexports.useRouter = useRouter;\nexports.createRouter = createRouter;\nexports.makePublicRouterInstance = makePublicRouterInstance;\nexports.default = void 0;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _react = _interop_require_default(require(\"react\"));\nvar _router = _interop_require_default(require(\"../shared/lib/router/router\"));\nvar _routerContext = require(\"../shared/lib/router-context\");\nvar _isError = _interop_require_default(require(\"../lib/is-error\"));\nvar _withRouter = _interop_require_default(require(\"./with-router\"));\nconst singletonRouter = {\n router: null,\n readyCallbacks: [],\n ready (cb) {\n if (this.router) return cb();\n if (typeof window !== 'undefined') {\n this.readyCallbacks.push(cb);\n }\n }\n};\n// Create public properties and methods of the router in the singletonRouter\nconst urlPropertyFields = [\n 'pathname',\n 'route',\n 'query',\n 'asPath',\n 'components',\n 'isFallback',\n 'basePath',\n 'locale',\n 'locales',\n 'defaultLocale',\n 'isReady',\n 'isPreview',\n 'isLocaleDomain',\n 'domainLocales', \n];\nconst routerEvents = [\n 'routeChangeStart',\n 'beforeHistoryChange',\n 'routeChangeComplete',\n 'routeChangeError',\n 'hashChangeStart',\n 'hashChangeComplete', \n];\nconst coreMethodFields = [\n 'push',\n 'replace',\n 'reload',\n 'back',\n 'prefetch',\n 'beforePopState', \n];\n// Events is a static property on the router, the router doesn't have to be initialized to use it\nObject.defineProperty(singletonRouter, 'events', {\n get () {\n return _router.default.events;\n }\n});\nfunction getRouter() {\n if (!singletonRouter.router) {\n const message = 'No router instance found.\\n' + 'You should only use \"next/router\" on the client side of your app.\\n';\n throw new Error(message);\n }\n return singletonRouter.router;\n}\nurlPropertyFields.forEach((field)=>{\n // Here we need to use Object.defineProperty because we need to return\n // the property assigned to the actual router\n // The value might get changed as we change routes and this is the\n // proper way to access it\n Object.defineProperty(singletonRouter, field, {\n get () {\n const router = getRouter();\n return router[field];\n }\n });\n});\ncoreMethodFields.forEach((field)=>{\n singletonRouter[field] = (...args)=>{\n const router = getRouter();\n return router[field](...args);\n };\n});\nrouterEvents.forEach((event)=>{\n singletonRouter.ready(()=>{\n _router.default.events.on(event, (...args)=>{\n const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(1)}`;\n const _singletonRouter = singletonRouter;\n if (_singletonRouter[eventField]) {\n try {\n _singletonRouter[eventField](...args);\n } catch (err) {\n console.error(`Error when running the Router event: ${eventField}`);\n console.error((0, _isError).default(err) ? `${err.message}\\n${err.stack}` : err + '');\n }\n }\n });\n });\n});\nvar _default = singletonRouter;\nexports.default = _default;\nfunction useRouter() {\n const router = _react.default.useContext(_routerContext.RouterContext);\n if (!router) {\n throw new Error('Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted');\n }\n return router;\n}\nfunction createRouter(...args) {\n singletonRouter.router = new _router.default(...args);\n singletonRouter.readyCallbacks.forEach((cb)=>cb());\n singletonRouter.readyCallbacks = [];\n return singletonRouter.router;\n}\nfunction makePublicRouterInstance(router) {\n const scopedRouter = router;\n const instance = {};\n for (const property of urlPropertyFields){\n if (typeof scopedRouter[property] === 'object') {\n instance[property] = Object.assign(Array.isArray(scopedRouter[property]) ? [] : {}, scopedRouter[property]) // makes sure query is not stateful\n ;\n continue;\n }\n instance[property] = scopedRouter[property];\n }\n // Events is a static property on the router, the router doesn't have to be initialized to use it\n instance.events = _router.default.events;\n coreMethodFields.forEach((field)=>{\n instance[field] = (...args)=>{\n return scopedRouter[field](...args);\n };\n });\n return instance;\n}\n\nif ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {\n Object.defineProperty(exports.default, '__esModule', { value: true });\n Object.assign(exports.default, exports);\n module.exports = exports.default;\n}\n\n//# sourceMappingURL=router.js.map","\"use client\";\n\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.handleClientScriptLoad = handleClientScriptLoad;\nexports.initScriptLoader = initScriptLoader;\nexports.default = void 0;\nvar _extends = require(\"@swc/helpers/lib/_extends.js\").default;\nvar _interop_require_default = require(\"@swc/helpers/lib/_interop_require_default.js\").default;\nvar _interop_require_wildcard = require(\"@swc/helpers/lib/_interop_require_wildcard.js\").default;\nvar _object_without_properties_loose = require(\"@swc/helpers/lib/_object_without_properties_loose.js\").default;\nvar _reactDom = _interop_require_default(require(\"react-dom\"));\nvar _react = _interop_require_wildcard(require(\"react\"));\nvar _headManagerContext = require(\"../shared/lib/head-manager-context\");\nvar _headManager = require(\"./head-manager\");\nvar _requestIdleCallback = require(\"./request-idle-callback\");\n\nconst ScriptCache = new Map();\nconst LoadCache = new Set();\nconst ignoreProps = [\n 'onLoad',\n 'onReady',\n 'dangerouslySetInnerHTML',\n 'children',\n 'onError',\n 'strategy', \n];\nconst loadScript = (props)=>{\n const { src , id , onLoad =()=>{} , onReady =null , dangerouslySetInnerHTML , children ='' , strategy ='afterInteractive' , onError , } = props;\n const cacheKey = id || src;\n // Script has already loaded\n if (cacheKey && LoadCache.has(cacheKey)) {\n return;\n }\n // Contents of this script are already loading/loaded\n if (ScriptCache.has(src)) {\n LoadCache.add(cacheKey);\n // It is possible that multiple `next/script` components all have same \"src\", but has different \"onLoad\"\n // This is to make sure the same remote script will only load once, but \"onLoad\" are executed in order\n ScriptCache.get(src).then(onLoad, onError);\n return;\n }\n /** Execute after the script first loaded */ const afterLoad = ()=>{\n // Run onReady for the first time after load event\n if (onReady) {\n onReady();\n }\n // add cacheKey to LoadCache when load successfully\n LoadCache.add(cacheKey);\n };\n const el = document.createElement('script');\n const loadPromise = new Promise((resolve, reject)=>{\n el.addEventListener('load', function(e) {\n resolve();\n if (onLoad) {\n onLoad.call(this, e);\n }\n afterLoad();\n });\n el.addEventListener('error', function(e) {\n reject(e);\n });\n }).catch(function(e) {\n if (onError) {\n onError(e);\n }\n });\n if (dangerouslySetInnerHTML) {\n el.innerHTML = dangerouslySetInnerHTML.__html || '';\n afterLoad();\n } else if (children) {\n el.textContent = typeof children === 'string' ? children : Array.isArray(children) ? children.join('') : '';\n afterLoad();\n } else if (src) {\n el.src = src;\n // do not add cacheKey into LoadCache for remote script here\n // cacheKey will be added to LoadCache when it is actually loaded (see loadPromise above)\n ScriptCache.set(src, loadPromise);\n }\n for (const [k, value] of Object.entries(props)){\n if (value === undefined || ignoreProps.includes(k)) {\n continue;\n }\n const attr = _headManager.DOMAttributeNames[k] || k.toLowerCase();\n el.setAttribute(attr, value);\n }\n if (strategy === 'worker') {\n el.setAttribute('type', 'text/partytown');\n }\n el.setAttribute('data-nscript', strategy);\n document.body.appendChild(el);\n};\nfunction handleClientScriptLoad(props) {\n const { strategy ='afterInteractive' } = props;\n if (strategy === 'lazyOnload') {\n window.addEventListener('load', ()=>{\n (0, _requestIdleCallback).requestIdleCallback(()=>loadScript(props));\n });\n } else {\n loadScript(props);\n }\n}\nfunction loadLazyScript(props) {\n if (document.readyState === 'complete') {\n (0, _requestIdleCallback).requestIdleCallback(()=>loadScript(props));\n } else {\n window.addEventListener('load', ()=>{\n (0, _requestIdleCallback).requestIdleCallback(()=>loadScript(props));\n });\n }\n}\nfunction addBeforeInteractiveToCache() {\n const scripts = [\n ...document.querySelectorAll('[data-nscript=\"beforeInteractive\"]'),\n ...document.querySelectorAll('[data-nscript=\"beforePageRender\"]'), \n ];\n scripts.forEach((script)=>{\n const cacheKey = script.id || script.getAttribute('src');\n LoadCache.add(cacheKey);\n });\n}\nfunction initScriptLoader(scriptLoaderItems) {\n scriptLoaderItems.forEach(handleClientScriptLoad);\n addBeforeInteractiveToCache();\n}\nfunction Script(props) {\n const { id , src ='' , onLoad =()=>{} , onReady =null , strategy ='afterInteractive' , onError } = props, restProps = _object_without_properties_loose(props, [\n \"id\",\n \"src\",\n \"onLoad\",\n \"onReady\",\n \"strategy\",\n \"onError\"\n ]);\n // Context is available only during SSR\n const { updateScripts , scripts , getIsSsr , appDir , nonce } = (0, _react).useContext(_headManagerContext.HeadManagerContext);\n /**\n * - First mount:\n * 1. The useEffect for onReady executes\n * 2. hasOnReadyEffectCalled.current is false, but the script hasn't loaded yet (not in LoadCache)\n * onReady is skipped, set hasOnReadyEffectCalled.current to true\n * 3. The useEffect for loadScript executes\n * 4. hasLoadScriptEffectCalled.current is false, loadScript executes\n * Once the script is loaded, the onLoad and onReady will be called by then\n * [If strict mode is enabled / is wrapped in component]\n * 5. The useEffect for onReady executes again\n * 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped\n * 7. The useEffect for loadScript executes again\n * 8. hasLoadScriptEffectCalled.current is true, so entire effect is skipped\n *\n * - Second mount:\n * 1. The useEffect for onReady executes\n * 2. hasOnReadyEffectCalled.current is false, but the script has already loaded (found in LoadCache)\n * onReady is called, set hasOnReadyEffectCalled.current to true\n * 3. The useEffect for loadScript executes\n * 4. The script is already loaded, loadScript bails out\n * [If strict mode is enabled / is wrapped in component]\n * 5. The useEffect for onReady executes again\n * 6. hasOnReadyEffectCalled.current is true, so entire effect is skipped\n * 7. The useEffect for loadScript executes again\n * 8. hasLoadScriptEffectCalled.current is true, so entire effect is skipped\n */ const hasOnReadyEffectCalled = (0, _react).useRef(false);\n (0, _react).useEffect(()=>{\n const cacheKey = id || src;\n if (!hasOnReadyEffectCalled.current) {\n // Run onReady if script has loaded before but component is re-mounted\n if (onReady && cacheKey && LoadCache.has(cacheKey)) {\n onReady();\n }\n hasOnReadyEffectCalled.current = true;\n }\n }, [\n onReady,\n id,\n src\n ]);\n const hasLoadScriptEffectCalled = (0, _react).useRef(false);\n (0, _react).useEffect(()=>{\n if (!hasLoadScriptEffectCalled.current) {\n if (strategy === 'afterInteractive') {\n loadScript(props);\n } else if (strategy === 'lazyOnload') {\n loadLazyScript(props);\n }\n hasLoadScriptEffectCalled.current = true;\n }\n }, [\n props,\n strategy\n ]);\n if (strategy === 'beforeInteractive' || strategy === 'worker') {\n if (updateScripts) {\n scripts[strategy] = (scripts[strategy] || []).concat([\n _extends({\n id,\n src,\n onLoad,\n onReady,\n onError\n }, restProps), \n ]);\n updateScripts(scripts);\n } else if (getIsSsr && getIsSsr()) {\n // Script has already loaded during SSR\n LoadCache.add(id || src);\n } else if (getIsSsr && !getIsSsr()) {\n loadScript(props);\n }\n }\n // For the app directory, we need React Float to preload these scripts.\n if (appDir) {\n // Before interactive scripts need to be loaded by Next.js' runtime instead\n // of native