diff --git a/.craft.yml b/.craft.yml index 94e5b37d02a0..44efac4303c8 100644 --- a/.craft.yml +++ b/.craft.yml @@ -59,15 +59,23 @@ targets: id: '@sentry/integrations' includeNames: /^sentry-integrations-\d.*\.tgz$/ - ## 4. Node-based Packages + ## 4. WinterCG Packages + - name: npm + id: '@sentry/vercel-edge' + includeNames: /^sentry-vercel-edge-\d.*\.tgz$/ + + ## 5. Node-based Packages - name: npm id: '@sentry/serverless' includeNames: /^sentry-serverless-\d.*\.tgz$/ - name: npm id: '@sentry/opentelemetry-node' includeNames: /^sentry-opentelemetry-node-\d.*\.tgz$/ + - name: npm + id: '@sentry/bun' + includeNames: /^sentry-bun-\d.*\.tgz$/ - ## 5. Fullstack/Meta Frameworks (depending on Node and Browser or Framework SDKs) + ## 6. Fullstack/Meta Frameworks (depending on Node and Browser or Framework SDKs) - name: npm id: '@sentry/nextjs' includeNames: /^sentry-nextjs-\d.*\.tgz$/ @@ -81,20 +89,20 @@ targets: id: '@sentry/gatsby' includeNames: /^sentry-gatsby-\d.*\.tgz$/ - ## 6. Other Packages - ## 6.1 + ## 7. Other Packages + ## 7.1 - name: npm id: '@sentry-internal/typescript' includeNames: /^sentry-internal-typescript-\d.*\.tgz$/ - name: npm id: '@sentry-internal/eslint-plugin-sdk' includeNames: /^sentry-internal-eslint-plugin-sdk-\d.*\.tgz$/ - ## 6.2 + ## 7.2 - name: npm id: '@sentry-internal/eslint-config-sdk' includeNames: /^sentry-internal-eslint-config-sdk-\d.*\.tgz$/ - ## 7. Deprecated packages we still release (but no packages depend on them anymore) + ## 8. Deprecated packages we still release (but no packages depend on them anymore) - name: npm id: '@sentry/hub' includeNames: /^sentry-hub-\d.*\.tgz$/ @@ -102,7 +110,7 @@ targets: id: '@sentry/tracing' includeNames: /^sentry-tracing-\d.*\.tgz$/ - ## 8. Experimental packages + ## 9. Experimental packages - name: npm id: '@sentry/node-experimental' includeNames: /^sentry-node-experimental-\d.*\.tgz$/ diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 5495324f837d..50793411c277 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -33,6 +33,7 @@ body: - '@sentry/browser' - '@sentry/angular' - '@sentry/angular-ivy' + - '@sentry/bun' - '@sentry/ember' - '@sentry/gatsby' - '@sentry/nextjs' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6dc1f35ae8ba..56f61126a45a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -391,6 +391,34 @@ jobs: - name: Compute test coverage uses: codecov/codecov-action@v3 + job_bun_unit_tests: + name: Bun Unit Tests + needs: [job_get_metadata, job_build] + timeout-minutes: 10 + runs-on: ubuntu-20.04 + strategy: + fail-fast: false + steps: + - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + uses: actions/checkout@v3 + with: + ref: ${{ env.HEAD_COMMIT }} + - name: Set up Node + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + - name: Set up Bun + uses: oven-sh/setup-bun@v1 + - name: Restore caches + uses: ./.github/actions/restore-cache + env: + DEPENDENCY_CACHE_KEY: ${{ needs.job_build.outputs.dependency_cache_key }} + - name: Run tests + run: | + yarn test-ci-bun + - name: Compute test coverage + uses: codecov/codecov-action@v3 + job_node_unit_tests: name: Node (${{ matrix.node }}) Unit Tests needs: [job_get_metadata, job_build] @@ -787,6 +815,7 @@ jobs: 'create-react-app', 'create-next-app', 'create-remix-app', + 'create-remix-app-v2', 'nextjs-app-dir', 'react-create-hash-router', 'react-router-6-use-routes', @@ -864,6 +893,7 @@ jobs: job_build, job_browser_build_tests, job_browser_unit_tests, + job_bun_unit_tests, job_node_unit_tests, job_nextjs_integration_test, job_node_integration_tests, diff --git a/.github/workflows/issue-package-label.yml b/.github/workflows/issue-package-label.yml index cb7fddd1b50c..f50679e5f112 100644 --- a/.github/workflows/issue-package-label.yml +++ b/.github/workflows/issue-package-label.yml @@ -38,6 +38,9 @@ jobs: "@sentry.angular-ivy": { "label": "Package: Angular" }, + "@sentry.bun": { + "label": "Package: Bun" + }, "@sentry.ember": { "label": "Package: ember" }, diff --git a/CHANGELOG.md b/CHANGELOG.md index f08a6c49af17..819c17ef6f5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +## 7.70.0 + +### Important Changes + +- **feat: Add Bun SDK (#9029)** + +This release contains the beta version of `@sentry/bun`, our SDK for the [Bun JavaScript runtime](https://bun.sh/)! For details on how to use it, please see the [README](./packages/bun/README.md). Any feedback/bug reports are greatly appreciated, please [reach out on GitHub](https://github.com/getsentry/sentry-javascript/discussions/7979). + +Note that as of now the Bun runtime does not support global error handlers. This is being actively worked on, see [the tracking issue in Bun's GitHub repo](https://github.com/oven-sh/bun/issues/5091). + +- **feat(remix): Add Remix 2.x release support. (#8940)** + +The Sentry Remix SDK now officially supports Remix v2! See [our Remix docs for more details](https://docs.sentry.io/platforms/javascript/guides/remix/). + +### Other Changes + +- chore(node): Upgrade cookie to ^0.5.0 (#9013) +- feat(core): Introduce `processEvent` hook on `Integration` (#9017) +- feat(node): Improve non-error messages (#9026) +- feat(vercel-edge): Add Vercel Edge Runtime package (#9041) +- fix(remix): Use `React.ComponentType` instead of `React.FC` as `withSentry`'s generic type. (#9043) +- fix(replay): Ensure replay events go through `preprocessEvent` hook (#9034) +- fix(replay): Fix typo in Replay types (#9028) +- fix(sveltekit): Adjust `handleErrorWithSentry` type (#9054) +- fix(utils): Try-catch monkeypatching to handle frozen objects/functions (#9031) + +Work in this release contributed by @Dima-Dim, @krist7599555 and @lifeiscontent. Thank you for your contributions! + +Special thanks for @isaacharrisholt for helping us implement a Vercel Edge Runtime SDK which we use under the hood for our Next.js SDK. + ## 7.69.0 ### Important Changes diff --git a/package.json b/package.json index 849d79b3628a..6ae7e4f1d2cf 100644 --- a/package.json +++ b/package.json @@ -27,8 +27,9 @@ "postpublish": "lerna run --stream --concurrency 1 postpublish", "test": "lerna run --ignore \"@sentry-internal/{browser-integration-tests,e2e-tests,integration-shims,node-integration-tests,overhead-metrics}\" test", "test:unit": "lerna run --ignore \"@sentry-internal/{browser-integration-tests,e2e-tests,integration-shims,node-integration-tests,overhead-metrics}\" test:unit", - "test-ci-browser": "lerna run test --ignore \"@sentry/{node,node-experimental,opentelemetry-node,serverless,nextjs,remix,gatsby,sveltekit}\" --ignore \"@sentry-internal/{browser-integration-tests,e2e-tests,integration-shims,node-integration-tests,overhead-metrics}\"", + "test-ci-browser": "lerna run test --ignore \"@sentry/{bun,node,node-experimental,opentelemetry-node,serverless,nextjs,remix,gatsby,sveltekit,vercel-edge}\" --ignore \"@sentry-internal/{browser-integration-tests,e2e-tests,integration-shims,node-integration-tests,overhead-metrics}\"", "test-ci-node": "ts-node ./scripts/node-unit-tests.ts", + "test-ci-bun": "lerna run test --scope @sentry/bun", "test:update-snapshots": "lerna run test:update-snapshots", "yalc:publish": "lerna run yalc:publish" }, @@ -41,6 +42,7 @@ "packages/angular-ivy", "packages/browser", "packages/browser-integration-tests", + "packages/bun", "packages/core", "packages/e2e-tests", "packages/ember", @@ -68,6 +70,7 @@ "packages/types", "packages/typescript", "packages/utils", + "packages/vercel-edge", "packages/vue", "packages/wasm" ], diff --git a/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/subject.js b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/subject.js new file mode 100644 index 000000000000..cf5df02445bd --- /dev/null +++ b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/subject.js @@ -0,0 +1,5 @@ +function callback() { + throw new Error('setTimeout_error'); +} + +setTimeout(callback, 0); diff --git a/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/test.ts b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/test.ts new file mode 100644 index 000000000000..808e15285cb1 --- /dev/null +++ b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeout/test.ts @@ -0,0 +1,24 @@ +import { expect } from '@playwright/test'; +import type { Event } from '@sentry/types'; + +import { sentryTest } from '../../../../utils/fixtures'; +import { getFirstSentryEnvelopeRequest } from '../../../../utils/helpers'; + +sentryTest('Instrumentation should capture errors in setTimeout', async ({ getLocalTestPath, page }) => { + const url = await getLocalTestPath({ testDir: __dirname }); + + const eventData = await getFirstSentryEnvelopeRequest(page, url); + + expect(eventData.exception?.values).toHaveLength(1); + expect(eventData.exception?.values?.[0]).toMatchObject({ + type: 'Error', + value: 'setTimeout_error', + mechanism: { + type: 'instrument', + handled: false, + }, + stacktrace: { + frames: expect.any(Array), + }, + }); +}); diff --git a/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/init.js b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/init.js new file mode 100644 index 000000000000..573e4fdcb621 --- /dev/null +++ b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/init.js @@ -0,0 +1,8 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + debug: true, +}); diff --git a/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/subject.js b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/subject.js new file mode 100644 index 000000000000..29c9ca1f7594 --- /dev/null +++ b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/subject.js @@ -0,0 +1,5 @@ +function callback() { + throw new Error('setTimeout_error'); +} + +setTimeout(Object.freeze(callback), 0); diff --git a/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/test.ts b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/test.ts new file mode 100644 index 000000000000..91e82f8b1dcd --- /dev/null +++ b/packages/browser-integration-tests/suites/public-api/instrumentation/setTimeoutFrozen/test.ts @@ -0,0 +1,48 @@ +import { expect } from '@playwright/test'; +import type { Event } from '@sentry/types'; + +import { sentryTest } from '../../../../utils/fixtures'; +import { getFirstSentryEnvelopeRequest } from '../../../../utils/helpers'; + +sentryTest( + 'Instrumentation does not fail when using frozen callback for setTimeout', + async ({ getLocalTestPath, page }) => { + const bundleKey = process.env.PW_BUNDLE || ''; + const hasDebug = !bundleKey.includes('_min'); + + const url = await getLocalTestPath({ testDir: __dirname }); + + const logMessages: string[] = []; + + page.on('console', msg => { + logMessages.push(msg.text()); + }); + + const eventData = await getFirstSentryEnvelopeRequest(page, url); + + // It still captures the error + expect(eventData.exception?.values).toHaveLength(1); + expect(eventData.exception?.values?.[0]).toMatchObject({ + type: 'Error', + value: 'setTimeout_error', + mechanism: { + type: 'instrument', + handled: false, + }, + stacktrace: { + frames: expect.any(Array), + }, + }); + + // We only care about the message when debug is enabled + if (hasDebug) { + expect(logMessages).toEqual( + expect.arrayContaining([ + expect.stringContaining( + 'Sentry Logger [log]: Failed to add non-enumerable property "__sentry_wrapped__" to object function callback()', + ), + ]), + ); + } + }, +); diff --git a/packages/browser/test/unit/index.test.ts b/packages/browser/test/unit/index.test.ts index 95985a2a69d2..0b0df3c4300f 100644 --- a/packages/browser/test/unit/index.test.ts +++ b/packages/browser/test/unit/index.test.ts @@ -1,4 +1,5 @@ import { getReportDialogEndpoint, SDK_VERSION } from '@sentry/core'; +import type { WrappedFunction } from '@sentry/types'; import * as utils from '@sentry/utils'; import type { Event } from '../../src'; @@ -391,4 +392,14 @@ describe('wrap()', () => { expect(result2).toBe(42); }); + + it('should ignore frozen functions', () => { + const func = Object.freeze(() => 42); + + // eslint-disable-next-line deprecation/deprecation + wrap(func); + + expect(func()).toBe(42); + expect((func as WrappedFunction).__sentry_wrapped__).toBeUndefined(); + }); }); diff --git a/packages/bun/.eslintrc.js b/packages/bun/.eslintrc.js new file mode 100644 index 000000000000..bec6469d0e28 --- /dev/null +++ b/packages/bun/.eslintrc.js @@ -0,0 +1,12 @@ +module.exports = { + env: { + node: true, + }, + extends: ['../../.eslintrc.js'], + rules: { + '@sentry-internal/sdk/no-optional-chaining': 'off', + '@sentry-internal/sdk/no-nullish-coalescing': 'off', + '@sentry-internal/sdk/no-unsupported-es6-methods': 'off', + '@sentry-internal/sdk/no-class-field-initializers': 'off', + }, +}; diff --git a/packages/bun/LICENSE b/packages/bun/LICENSE new file mode 100644 index 000000000000..d11896ba1181 --- /dev/null +++ b/packages/bun/LICENSE @@ -0,0 +1,14 @@ +Copyright (c) 2023 Sentry (https://sentry.io) and individual contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/bun/README.md b/packages/bun/README.md new file mode 100644 index 000000000000..170059f193f5 --- /dev/null +++ b/packages/bun/README.md @@ -0,0 +1,78 @@ +

+ + Sentry + +

+ +# Official Sentry SDK for Bun (Beta) + +[![npm version](https://img.shields.io/npm/v/@sentry/bun.svg)](https://www.npmjs.com/package/@sentry/bun) +[![npm dm](https://img.shields.io/npm/dm/@sentry/bun.svg)](https://www.npmjs.com/package/@sentry/bun) +[![npm dt](https://img.shields.io/npm/dt/@sentry/bun.svg)](https://www.npmjs.com/package/@sentry/bun) + +## Links + +- [Official SDK Docs](https://docs.sentry.io/quickstart/) +- [TypeDoc](http://getsentry.github.io/sentry-javascript/) + +The Sentry Bun SDK is in beta. Please help us improve the SDK by [reporting any issues or giving us feedback](https://github.com/getsentry/sentry-javascript/issues). + +## Usage + +To use this SDK, call `init(options)` as early as possible in the main entry module. This will initialize the SDK and +hook into the environment. Note that you can turn off almost all side effects using the respective options. + +```javascript +// ES5 Syntax +const Sentry = require('@sentry/bun'); +// ES6 Syntax +import * as Sentry from '@sentry/bun'; + +Sentry.init({ + dsn: '__DSN__', + // ... +}); +``` + +To set context information or send manual events, use the exported functions of `@sentry/bun`. Note that these +functions will not perform any action before you have called `init()`: + +```javascript +// Set user information, as well as tags and further extras +Sentry.configureScope(scope => { + scope.setExtra('battery', 0.7); + scope.setTag('user_mode', 'admin'); + scope.setUser({ id: '4711' }); + // scope.clear(); +}); + +// Add a breadcrumb for future events +Sentry.addBreadcrumb({ + message: 'My Breadcrumb', + // ... +}); + +// Capture exceptions, messages or manual events +Sentry.captureMessage('Hello, world!'); +Sentry.captureException(new Error('Good bye')); +Sentry.captureEvent({ + message: 'Manual', + stacktrace: [ + // ... + ], +}); +``` + +It's not possible to capture unhandled exceptions, unhandled promise rejections now - Bun is working on adding support for it. +[Github Issue](https://github.com/oven-sh/bun/issues/5091) follow this issue. To report errors to Sentry, you have to manually try-catch and call `Sentry.captureException` in the catch block. + +```ts +import * as Sentry from '@sentry/bun'; + +try { + throw new Error('test'); +} catch (e) { + Sentry.captureException(e); +} +``` + diff --git a/packages/bun/jest.config.js b/packages/bun/jest.config.js new file mode 100644 index 000000000000..24f49ab59a4c --- /dev/null +++ b/packages/bun/jest.config.js @@ -0,0 +1 @@ +module.exports = require('../../jest/jest.config.js'); diff --git a/packages/bun/package.json b/packages/bun/package.json new file mode 100644 index 000000000000..00ef7f675c53 --- /dev/null +++ b/packages/bun/package.json @@ -0,0 +1,71 @@ +{ + "name": "@sentry/bun", + "version": "7.69.0", + "description": "Official Sentry SDK for bun", + "repository": "git://github.com/getsentry/sentry-javascript.git", + "homepage": "https://github.com/getsentry/sentry-javascript/tree/master/packages/bun", + "author": "Sentry", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "main": "build/esm/index.js", + "module": "build/esm/index.js", + "types": "build/types/index.d.ts", + "typesVersions": { + "<4.9": { + "build/npm/types/index.d.ts": [ + "build/npm/types-ts3.8/index.d.ts" + ] + } + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "@sentry/core": "7.69.0", + "@sentry/node": "7.69.0", + "@sentry/types": "7.69.0", + "@sentry/utils": "7.69.0" + }, + "devDependencies": { + "bun-types": "latest" + }, + "scripts": { + "build": "run-p build:transpile build:types", + "build:dev": "yarn build", + "build:transpile": "rollup -c rollup.npm.config.js", + "build:types": "run-s build:types:core build:types:downlevel", + "build:types:core": "tsc -p tsconfig.types.json", + "build:types:downlevel": "yarn downlevel-dts build/types build/types-ts3.8 --to ts3.8", + "build:watch": "run-p build:transpile:watch build:types:watch", + "build:dev:watch": "yarn build:watch", + "build:transpile:watch": "rollup -c rollup.npm.config.js --watch", + "build:types:watch": "tsc -p tsconfig.types.json --watch", + "build:tarball": "ts-node ../../scripts/prepack.ts && npm pack ./build", + "circularDepCheck": "madge --circular src/index.ts", + "clean": "rimraf build coverage sentry-node-*.tgz", + "fix": "run-s fix:eslint fix:prettier", + "fix:eslint": "eslint . --format stylish --fix", + "fix:prettier": "prettier --write \"{src,test,scripts}/**/**.ts\"", + "lint": "run-s lint:prettier lint:eslint", + "lint:eslint": "eslint . --format stylish", + "lint:prettier": "prettier --check \"{src,test,scripts}/**/**.ts\"", + "install:bun": "node ./scripts/install-bun.js", + "test": "run-s install:bun test:bun", + "test:bun": "bun test", + "test:watch": "bun test --watch", + "yalc:publish": "ts-node ../../scripts/prepack.ts && yalc publish build --push" + }, + "volta": { + "extends": "../../package.json" + }, + "sideEffects": false, + "madge":{ + "detectiveOptions": { + "ts": { + "skipTypeImports": true + } + } + } +} diff --git a/packages/bun/rollup.npm.config.js b/packages/bun/rollup.npm.config.js new file mode 100644 index 000000000000..ebbeb7063089 --- /dev/null +++ b/packages/bun/rollup.npm.config.js @@ -0,0 +1,6 @@ +import { makeBaseNPMConfig, makeNPMConfigVariants } from '../../rollup/index.js'; + +const config = makeNPMConfigVariants(makeBaseNPMConfig()); + +// remove cjs from config array config[0].output.format == cjs +export default [config[1]]; diff --git a/packages/bun/scripts/install-bun.js b/packages/bun/scripts/install-bun.js new file mode 100644 index 000000000000..33e798b0a6d6 --- /dev/null +++ b/packages/bun/scripts/install-bun.js @@ -0,0 +1,49 @@ +/* eslint-disable no-console */ +if (process.env.CI) { + // This script is not needed in CI we install bun via GH actions + return; +} +const { exec } = require('child_process'); +const https = require('https'); + +// Define the URL of the Bash script for bun installation +const installScriptUrl = 'https://bun.sh/install'; + +// Check if bun is installed +exec('bun -version', error => { + if (error) { + console.error('bun is not installed. Installing...'); + // Download and execute the installation script + https + .get(installScriptUrl, res => { + if (res.statusCode !== 200) { + console.error(`Failed to download the installation script (HTTP ${res.statusCode})`); + process.exit(1); + } + + res.setEncoding('utf8'); + let scriptData = ''; + + res.on('data', chunk => { + scriptData += chunk; + }); + + res.on('end', () => { + // Execute the downloaded script + exec(scriptData, installError => { + if (installError) { + console.error('Failed to install bun:', installError); + process.exit(1); + } + console.log('bun has been successfully installed.'); + }); + }); + }) + .on('error', e => { + console.error('Failed to download the installation script:', e); + process.exit(1); + }); + } else { + // Bun is installed + } +}); diff --git a/packages/bun/src/client.ts b/packages/bun/src/client.ts new file mode 100644 index 000000000000..b8cebbe7463e --- /dev/null +++ b/packages/bun/src/client.ts @@ -0,0 +1,40 @@ +import type { ServerRuntimeClientOptions } from '@sentry/core'; +import { SDK_VERSION, ServerRuntimeClient } from '@sentry/core'; +import * as os from 'os'; + +import type { BunClientOptions } from './types'; + +/** + * The Sentry Bun SDK Client. + * + * @see BunClientOptions for documentation on configuration options. + * @see SentryClient for usage documentation. + */ +export class BunClient extends ServerRuntimeClient { + /** + * Creates a new Bun SDK instance. + * @param options Configuration options for this SDK. + */ + public constructor(options: BunClientOptions) { + options._metadata = options._metadata || {}; + options._metadata.sdk = options._metadata.sdk || { + name: 'sentry.javascript.bun', + packages: [ + { + name: 'npm:@sentry/bun', + version: SDK_VERSION, + }, + ], + version: SDK_VERSION, + }; + + const clientOptions: ServerRuntimeClientOptions = { + ...options, + platform: 'bun', + runtime: { name: 'bun', version: Bun.version }, + serverName: options.serverName || global.process.env.SENTRY_NAME || os.hostname(), + }; + + super(clientOptions); + } +} diff --git a/packages/bun/src/index.ts b/packages/bun/src/index.ts new file mode 100644 index 000000000000..7be879568dec --- /dev/null +++ b/packages/bun/src/index.ts @@ -0,0 +1,77 @@ +export type { + Breadcrumb, + BreadcrumbHint, + PolymorphicRequest, + Request, + SdkInfo, + Event, + EventHint, + Exception, + Session, + // eslint-disable-next-line deprecation/deprecation + Severity, + SeverityLevel, + Span, + StackFrame, + Stacktrace, + Thread, + Transaction, + User, +} from '@sentry/types'; +export type { AddRequestDataToEventOptions } from '@sentry/utils'; + +export type { TransactionNamingScheme } from '@sentry/node'; +export type { BunOptions } from './types'; + +export { + addGlobalEventProcessor, + addBreadcrumb, + captureException, + captureEvent, + captureMessage, + close, + configureScope, + createTransport, + extractTraceparentData, + flush, + getActiveTransaction, + getHubFromCarrier, + getCurrentHub, + Hub, + lastEventId, + makeMain, + runWithAsyncContext, + Scope, + startTransaction, + SDK_VERSION, + setContext, + setExtra, + setExtras, + setTag, + setTags, + setUser, + spanStatusfromHttpCode, + trace, + withScope, + captureCheckIn, + setMeasurement, + getActiveSpan, + startSpan, + startInactiveSpan, + startSpanManual, +} from '@sentry/core'; +export type { SpanStatusType } from '@sentry/core'; +export { autoDiscoverNodePerformanceMonitoringIntegrations } from '@sentry/node'; + +export { BunClient } from './client'; +export { defaultIntegrations, init } from './sdk'; + +import { Integrations as CoreIntegrations } from '@sentry/core'; +import { Integrations as NodeIntegrations } from '@sentry/node'; + +const INTEGRATIONS = { + ...CoreIntegrations, + ...NodeIntegrations, +}; + +export { INTEGRATIONS as Integrations }; diff --git a/packages/bun/src/sdk.ts b/packages/bun/src/sdk.ts new file mode 100644 index 000000000000..11c7827b3faf --- /dev/null +++ b/packages/bun/src/sdk.ts @@ -0,0 +1,94 @@ +/* eslint-disable max-lines */ +import { Integrations as CoreIntegrations } from '@sentry/core'; +import { init as initNode, Integrations as NodeIntegrations } from '@sentry/node'; + +import { BunClient } from './client'; +import { makeFetchTransport } from './transports'; +import type { BunOptions } from './types'; + +export const defaultIntegrations = [ + // Common + new CoreIntegrations.InboundFilters(), + new CoreIntegrations.FunctionToString(), + // Native Wrappers + new NodeIntegrations.Console(), + new NodeIntegrations.Http(), + new NodeIntegrations.Undici(), + // Global Handlers # TODO (waiting for https://github.com/oven-sh/bun/issues/5091) + // new NodeIntegrations.OnUncaughtException(), + // new NodeIntegrations.OnUnhandledRejection(), + // Event Info + new NodeIntegrations.ContextLines(), + // new NodeIntegrations.LocalVariables(), # does't work with Bun + new NodeIntegrations.Context(), + new NodeIntegrations.Modules(), + new NodeIntegrations.RequestData(), + // Misc + new NodeIntegrations.LinkedErrors(), +]; + +/** + * The Sentry Bun SDK Client. + * + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. + * + * @example + * ``` + * + * const { init } = require('@sentry/bun'); + * + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` + * + * @example + * ``` + * + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` + * + * @see {@link BunOptions} for documentation on configuration options. + */ +export function init(options: BunOptions = {}): void { + options.clientClass = BunClient; + options.transport = options.transport || makeFetchTransport; + + options.defaultIntegrations = + options.defaultIntegrations === false + ? [] + : [...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations)]; + initNode(options); +} diff --git a/packages/bun/src/transports/index.ts b/packages/bun/src/transports/index.ts new file mode 100644 index 000000000000..96e3e99957fb --- /dev/null +++ b/packages/bun/src/transports/index.ts @@ -0,0 +1,38 @@ +import { createTransport } from '@sentry/core'; +import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types'; +import { rejectedSyncPromise } from '@sentry/utils'; + +export interface BunTransportOptions extends BaseTransportOptions { + /** Custom headers for the transport. Used by the XHRTransport and FetchTransport */ + headers?: { [key: string]: string }; +} + +/** + * Creates a Transport that uses the Fetch API to send events to Sentry. + */ +export function makeFetchTransport(options: BunTransportOptions): Transport { + function makeRequest(request: TransportRequest): PromiseLike { + const requestOptions: RequestInit = { + body: request.body, + method: 'POST', + referrerPolicy: 'origin', + headers: options.headers, + }; + + try { + return fetch(options.url, requestOptions).then(response => { + return { + statusCode: response.status, + headers: { + 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'), + 'retry-after': response.headers.get('Retry-After'), + }, + }; + }); + } catch (e) { + return rejectedSyncPromise(e); + } + } + + return createTransport(options, makeRequest); +} diff --git a/packages/bun/src/types.ts b/packages/bun/src/types.ts new file mode 100644 index 000000000000..c62e4fe320e3 --- /dev/null +++ b/packages/bun/src/types.ts @@ -0,0 +1,68 @@ +import type { ClientOptions, Options, TracePropagationTargets } from '@sentry/types'; + +import type { BunClient } from './client'; +import type { BunTransportOptions } from './transports'; + +export interface BaseBunOptions { + /** + * List of strings/regex controlling to which outgoing requests + * the SDK will attach tracing headers. + * + * By default the SDK will attach those headers to all outgoing + * requests. If this option is provided, the SDK will match the + * request URL of outgoing requests against the items in this + * array, and only attach tracing headers if a match was found. + * + * @example + * ```js + * Sentry.init({ + * tracePropagationTargets: ['api.site.com'], + * }); + * ``` + */ + tracePropagationTargets?: TracePropagationTargets; + + /** Sets an optional server name (device name) */ + serverName?: string; + + /** + * Specify a custom BunClient to be used. Must extend BunClient! + * This is not a public, supported API, but used internally only. + * + * @hidden + * */ + clientClass?: typeof BunClient; + + // TODO (v8): Remove this in v8 + /** + * @deprecated Moved to constructor options of the `Http` and `Undici` integration. + * @example + * ```js + * Sentry.init({ + * integrations: [ + * new Sentry.Integrations.Http({ + * tracing: { + * shouldCreateSpanForRequest: (url: string) => false, + * } + * }); + * ], + * }); + * ``` + */ + shouldCreateSpanForRequest?(this: void, url: string): boolean; + + /** Callback that is executed when a fatal global error occurs. */ + onFatalError?(this: void, error: Error): void; +} + +/** + * Configuration options for the Sentry Bun SDK + * @see @sentry/types Options for more information. + */ +export interface BunOptions extends Options, BaseBunOptions {} + +/** + * Configuration options for the Sentry Bun SDK Client class + * @see BunClient for more information. + */ +export interface BunClientOptions extends ClientOptions, BaseBunOptions {} diff --git a/packages/bun/test/sdk.test.ts b/packages/bun/test/sdk.test.ts new file mode 100644 index 000000000000..f92ff4c59b13 --- /dev/null +++ b/packages/bun/test/sdk.test.ts @@ -0,0 +1,11 @@ +// eslint-disable-next-line import/no-unresolved +import { expect, test } from 'bun:test'; + +import { init } from '../src/index'; + +test("calling init shouldn't fail", () => { + init({ + dsn: 'https://00000000000000000000000000000000@o000000.ingest.sentry.io/0000000', + }); + expect(true).toBe(true); +}); diff --git a/packages/bun/tsconfig.json b/packages/bun/tsconfig.json new file mode 100644 index 000000000000..70c4bde02040 --- /dev/null +++ b/packages/bun/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../tsconfig.json", + + "include": ["src/**/*"], + + "compilerOptions": { + "types": ["bun-types"], + "lib": ["esnext"], + "module": "esnext", + "target": "esnext", + + // if TS 4.x or earlier + "moduleResolution": "nodenext", + + "jsx": "react-jsx", // support JSX + "allowJs": true, // allow importing `.js` from `.ts` + "esModuleInterop": true, // allow default imports for CommonJS modules + + // best practices + "strict": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true + } +} diff --git a/packages/bun/tsconfig.test.json b/packages/bun/tsconfig.test.json new file mode 100644 index 000000000000..87f6afa06b86 --- /dev/null +++ b/packages/bun/tsconfig.test.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + + "include": ["test/**/*"], + + "compilerOptions": { + // should include all types from `./tsconfig.json` plus types for all test frameworks used + "types": ["node", "jest"] + + // other package-specific, test-specific options + } +} diff --git a/packages/bun/tsconfig.types.json b/packages/bun/tsconfig.types.json new file mode 100644 index 000000000000..65455f66bd75 --- /dev/null +++ b/packages/bun/tsconfig.types.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": true, + "outDir": "build/types" + } +} diff --git a/packages/core/src/baseclient.ts b/packages/core/src/baseclient.ts index 1d1ad6aaa377..1a15c4bc37bd 100644 --- a/packages/core/src/baseclient.ts +++ b/packages/core/src/baseclient.ts @@ -12,6 +12,7 @@ import type { Event, EventDropReason, EventHint, + EventProcessor, Integration, IntegrationClass, Outcome, @@ -107,6 +108,8 @@ export abstract class BaseClient implements Client { // eslint-disable-next-line @typescript-eslint/ban-types private _hooks: Record; + private _eventProcessors: EventProcessor[]; + /** * Initializes this client instance. * @@ -119,6 +122,7 @@ export abstract class BaseClient implements Client { this._numProcessing = 0; this._outcomes = {}; this._hooks = {}; + this._eventProcessors = []; if (options.dsn) { this._dsn = makeDsn(options.dsn); @@ -280,6 +284,16 @@ export abstract class BaseClient implements Client { }); } + /** Get all installed event processors. */ + public getEventProcessors(): EventProcessor[] { + return this._eventProcessors; + } + + /** @inheritDoc */ + public addEventProcessor(eventProcessor: EventProcessor): void { + this._eventProcessors.push(eventProcessor); + } + /** * Sets up the integrations */ @@ -545,7 +559,7 @@ export abstract class BaseClient implements Client { this.emit('preprocessEvent', event, hint); - return prepareEvent(options, event, hint, scope).then(evt => { + return prepareEvent(options, event, hint, scope, this).then(evt => { if (evt === null) { return evt; } diff --git a/packages/core/src/eventProcessors.ts b/packages/core/src/eventProcessors.ts new file mode 100644 index 000000000000..4596788b9dcb --- /dev/null +++ b/packages/core/src/eventProcessors.ts @@ -0,0 +1,51 @@ +import type { Event, EventHint, EventProcessor } from '@sentry/types'; +import { getGlobalSingleton, isThenable, logger, SyncPromise } from '@sentry/utils'; + +/** + * Returns the global event processors. + */ +export function getGlobalEventProcessors(): EventProcessor[] { + return getGlobalSingleton('globalEventProcessors', () => []); +} + +/** + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add + */ +export function addGlobalEventProcessor(callback: EventProcessor): void { + getGlobalEventProcessors().push(callback); +} + +/** + * Process an array of event processors, returning the processed event (or `null` if the event was dropped). + */ +export function notifyEventProcessors( + processors: EventProcessor[], + event: Event | null, + hint: EventHint, + index: number = 0, +): PromiseLike { + return new SyncPromise((resolve, reject) => { + const processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } else { + const result = processor({ ...event }, hint) as Event | null; + + __DEBUG_BUILD__ && + processor.id && + result === null && + logger.log(`Event processor "${processor.id}" dropped event`); + + if (isThenable(result)) { + void result + .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) + .then(null, reject); + } else { + void notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } + }); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 67c28a3e3c57..21f7cab37505 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -36,7 +36,8 @@ export { } from './hub'; export { makeSession, closeSession, updateSession } from './session'; export { SessionFlusher } from './sessionflusher'; -export { addGlobalEventProcessor, Scope } from './scope'; +export { Scope } from './scope'; +export { addGlobalEventProcessor } from './eventProcessors'; export { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint } from './api'; export { BaseClient } from './baseclient'; export { ServerRuntimeClient } from './server-runtime-client'; diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index b2c8e4547ab8..aa8968edc8dc 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -1,8 +1,8 @@ -import type { Client, Integration, Options } from '@sentry/types'; +import type { Client, Event, EventHint, Integration, Options } from '@sentry/types'; import { arrayify, logger } from '@sentry/utils'; +import { addGlobalEventProcessor } from './eventProcessors'; import { getCurrentHub } from './hub'; -import { addGlobalEventProcessor } from './scope'; declare module '@sentry/types' { interface Integration { @@ -107,10 +107,20 @@ export function setupIntegration(client: Client, integration: Integration, integ } if (client.on && typeof integration.preprocessEvent === 'function') { - const callback = integration.preprocessEvent.bind(integration); + const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent; client.on('preprocessEvent', (event, hint) => callback(event, hint, client)); } + if (client.addEventProcessor && typeof integration.processEvent === 'function') { + const callback = integration.processEvent.bind(integration) as typeof integration.processEvent; + + const processor = Object.assign((event: Event, hint: EventHint) => callback(event, hint, client), { + id: integration.name, + }); + + client.addEventProcessor(processor); + } + __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`); } diff --git a/packages/core/src/scope.ts b/packages/core/src/scope.ts index ef6832bc773d..ba4ccac23adb 100644 --- a/packages/core/src/scope.ts +++ b/packages/core/src/scope.ts @@ -22,17 +22,9 @@ import type { Transaction, User, } from '@sentry/types'; -import { - arrayify, - dateTimestampInSeconds, - getGlobalSingleton, - isPlainObject, - isThenable, - logger, - SyncPromise, - uuid4, -} from '@sentry/utils'; +import { arrayify, dateTimestampInSeconds, isPlainObject, uuid4 } from '@sentry/utils'; +import { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors'; import { updateSession } from './session'; /** @@ -525,7 +517,7 @@ export class Scope implements ScopeInterface { propagationContext: this._propagationContext, }; - return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); + return notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); } /** @@ -559,40 +551,6 @@ export class Scope implements ScopeInterface { return this._breadcrumbs; } - /** - * This will be called after {@link applyToEvent} is finished. - */ - protected _notifyEventProcessors( - processors: EventProcessor[], - event: Event | null, - hint: EventHint, - index: number = 0, - ): PromiseLike { - return new SyncPromise((resolve, reject) => { - const processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } else { - const result = processor({ ...event }, hint) as Event | null; - - __DEBUG_BUILD__ && - processor.id && - result === null && - logger.log(`Event processor "${processor.id}" dropped event`); - - if (isThenable(result)) { - void result - .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) - .then(null, reject); - } else { - void this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - } - /** * This will be called on every set call. */ @@ -629,21 +587,6 @@ export class Scope implements ScopeInterface { } } -/** - * Returns the global event processors. - */ -function getGlobalEventProcessors(): EventProcessor[] { - return getGlobalSingleton('globalEventProcessors', () => []); -} - -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -export function addGlobalEventProcessor(callback: EventProcessor): void { - getGlobalEventProcessors().push(callback); -} - function generatePropagationContext(): PropagationContext { return { traceId: uuid4(), diff --git a/packages/core/src/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index 7f3d5a6cf315..67d7055a1623 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -11,12 +11,13 @@ import type { SeverityLevel, TraceContext, } from '@sentry/types'; -import { eventFromMessage, eventFromUnknownInput, logger, uuid4 } from '@sentry/utils'; +import { eventFromMessage, eventFromUnknownInput, logger, resolvedSyncPromise, uuid4 } from '@sentry/utils'; import { BaseClient } from './baseclient'; import { createCheckInEnvelope } from './checkin'; import { getCurrentHub } from './hub'; import type { Scope } from './scope'; +import { SessionFlusher } from './sessionflusher'; import { addTracingExtensions, getDynamicSamplingContextFromClient } from './tracing'; export interface ServerRuntimeClientOptions extends ClientOptions { @@ -31,6 +32,8 @@ export interface ServerRuntimeClientOptions extends ClientOptions extends BaseClient { + protected _sessionFlusher: SessionFlusher | undefined; + /** * Creates a new Edge SDK instance. * @param options Configuration options for this SDK. @@ -46,7 +49,7 @@ export class ServerRuntimeClient< * @inheritDoc */ public eventFromException(exception: unknown, hint?: EventHint): PromiseLike { - return Promise.resolve(eventFromUnknownInput(getCurrentHub, this._options.stackParser, exception, hint)); + return resolvedSyncPromise(eventFromUnknownInput(getCurrentHub, this._options.stackParser, exception, hint)); } /** @@ -58,11 +61,83 @@ export class ServerRuntimeClient< level: Severity | SeverityLevel = 'info', hint?: EventHint, ): PromiseLike { - return Promise.resolve( + return resolvedSyncPromise( eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace), ); } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const requestSession = scope.getRequestSession(); + + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } + } + + return super.captureException(exception, hint, scope); + } + + /** + * @inheritDoc + */ + public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const eventType = event.type || 'exception'; + const isException = + eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; + + // If the event is of type Exception, then a request session should be captured + if (isException) { + const requestSession = scope.getRequestSession(); + + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } + } + } + + return super.captureEvent(event, hint, scope); + } + + /** + * + * @inheritdoc + */ + public close(timeout?: number): PromiseLike { + if (this._sessionFlusher) { + this._sessionFlusher.close(); + } + return super.close(timeout); + } + + /** Method that initialises an instance of SessionFlusher on Client */ + public initSessionFlusher(): void { + const { release, environment } = this._options; + if (!release) { + __DEBUG_BUILD__ && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } else { + this._sessionFlusher = new SessionFlusher(this, { + release, + environment, + }); + } + } + /** * Create a cron monitor check in and send it to Sentry. * @@ -121,6 +196,18 @@ export class ServerRuntimeClient< return id; } + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + protected _captureRequestSession(): void { + if (!this._sessionFlusher) { + __DEBUG_BUILD__ && logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } else { + this._sessionFlusher.incrementSessionStatusCount(); + } + } + /** * @inheritDoc */ diff --git a/packages/core/src/utils/prepareEvent.ts b/packages/core/src/utils/prepareEvent.ts index 84bfd404c56f..13a164dbaf76 100644 --- a/packages/core/src/utils/prepareEvent.ts +++ b/packages/core/src/utils/prepareEvent.ts @@ -1,7 +1,8 @@ -import type { ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types'; +import type { Client, ClientOptions, Event, EventHint, StackFrame, StackParser } from '@sentry/types'; import { dateTimestampInSeconds, GLOBAL_OBJ, normalize, resolvedSyncPromise, truncate, uuid4 } from '@sentry/utils'; import { DEFAULT_ENVIRONMENT } from '../constants'; +import { notifyEventProcessors } from '../eventProcessors'; import { Scope } from '../scope'; /** @@ -26,6 +27,7 @@ export function prepareEvent( event: Event, hint: EventHint, scope?: Scope, + client?: Client, ): PromiseLike { const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options; const prepared: Event = { @@ -74,20 +76,25 @@ export function prepareEvent( result = finalScope.applyToEvent(prepared, hint); } - return result.then(evt => { - if (evt) { - // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified - // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed. - // This should not cause any PII issues, since we're only moving data that is already on the event and not adding - // any new data - applyDebugMeta(evt); - } + return result + .then(evt => { + // Process client-scoped event processors + return client && client.getEventProcessors ? notifyEventProcessors(client.getEventProcessors(), evt, hint) : evt; + }) + .then(evt => { + if (evt) { + // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified + // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed. + // This should not cause any PII issues, since we're only moving data that is already on the event and not adding + // any new data + applyDebugMeta(evt); + } - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - return evt; - }); + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); + } + return evt; + }); } /** diff --git a/packages/core/test/lib/integration.test.ts b/packages/core/test/lib/integration.test.ts index 14b1697b9054..f431d30b2140 100644 --- a/packages/core/test/lib/integration.test.ts +++ b/packages/core/test/lib/integration.test.ts @@ -1,6 +1,15 @@ import type { Integration, Options } from '@sentry/types'; -import { getIntegrationsToSetup } from '../../src/integration'; +import { getIntegrationsToSetup, installedIntegrations, setupIntegration } from '../../src/integration'; +import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; + +function getTestClient(): TestClient { + return new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + }), + ); +} /** JSDoc */ class MockIntegration implements Integration { @@ -317,3 +326,236 @@ describe('getIntegrationsToSetup', () => { expect(integrations.map(i => i.name)).toEqual(['foo', 'Debug']); }); }); + +describe('setupIntegration', () => { + beforeEach(function () { + // Reset the (global!) list of installed integrations + installedIntegrations.splice(0, installedIntegrations.length); + }); + + it('works with a minimal integration', () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + } + + const client = getTestClient(); + const integrationIndex = {}; + const integration = new CustomIntegration(); + + setupIntegration(client, integration, integrationIndex); + + expect(integrationIndex).toEqual({ test: integration }); + expect(integration.setupOnce).toHaveBeenCalledTimes(1); + }); + + it('only calls setupOnce a single time', () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + } + + const client1 = getTestClient(); + const client2 = getTestClient(); + + const integrationIndex = {}; + const integration1 = new CustomIntegration(); + const integration2 = new CustomIntegration(); + const integration3 = new CustomIntegration(); + const integration4 = new CustomIntegration(); + + setupIntegration(client1, integration1, integrationIndex); + setupIntegration(client1, integration2, integrationIndex); + setupIntegration(client2, integration3, integrationIndex); + setupIntegration(client2, integration4, integrationIndex); + + expect(integrationIndex).toEqual({ test: integration4 }); + expect(integration1.setupOnce).toHaveBeenCalledTimes(1); + expect(integration2.setupOnce).not.toHaveBeenCalled(); + expect(integration3.setupOnce).not.toHaveBeenCalled(); + expect(integration4.setupOnce).not.toHaveBeenCalled(); + }); + + it('binds preprocessEvent for each client', () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + preprocessEvent = jest.fn(); + } + + const client1 = getTestClient(); + const client2 = getTestClient(); + + const integrationIndex = {}; + const integration1 = new CustomIntegration(); + const integration2 = new CustomIntegration(); + const integration3 = new CustomIntegration(); + const integration4 = new CustomIntegration(); + + setupIntegration(client1, integration1, integrationIndex); + setupIntegration(client1, integration2, integrationIndex); + setupIntegration(client2, integration3, integrationIndex); + setupIntegration(client2, integration4, integrationIndex); + + expect(integrationIndex).toEqual({ test: integration4 }); + expect(integration1.setupOnce).toHaveBeenCalledTimes(1); + expect(integration2.setupOnce).not.toHaveBeenCalled(); + expect(integration3.setupOnce).not.toHaveBeenCalled(); + expect(integration4.setupOnce).not.toHaveBeenCalled(); + + client1.captureEvent({ event_id: '1a' }); + client1.captureEvent({ event_id: '1b' }); + client2.captureEvent({ event_id: '2a' }); + client2.captureEvent({ event_id: '2b' }); + client2.captureEvent({ event_id: '2c' }); + + expect(integration1.preprocessEvent).toHaveBeenCalledTimes(2); + expect(integration2.preprocessEvent).toHaveBeenCalledTimes(2); + expect(integration3.preprocessEvent).toHaveBeenCalledTimes(3); + expect(integration4.preprocessEvent).toHaveBeenCalledTimes(3); + + expect(integration1.preprocessEvent).toHaveBeenLastCalledWith({ event_id: '1b' }, {}, client1); + expect(integration2.preprocessEvent).toHaveBeenLastCalledWith({ event_id: '1b' }, {}, client1); + expect(integration3.preprocessEvent).toHaveBeenLastCalledWith({ event_id: '2c' }, {}, client2); + expect(integration4.preprocessEvent).toHaveBeenLastCalledWith({ event_id: '2c' }, {}, client2); + }); + + it('allows to mutate events in preprocessEvent', async () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + preprocessEvent = jest.fn(event => { + event.event_id = 'mutated'; + }); + } + + const client = getTestClient(); + + const integrationIndex = {}; + const integration = new CustomIntegration(); + + setupIntegration(client, integration, integrationIndex); + + const sendEvent = jest.fn(); + client.sendEvent = sendEvent; + + client.captureEvent({ event_id: '1a' }); + await client.flush(); + + expect(sendEvent).toHaveBeenCalledTimes(1); + expect(sendEvent).toHaveBeenCalledWith(expect.objectContaining({ event_id: 'mutated' }), {}); + }); + + it('binds processEvent for each client', () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + processEvent = jest.fn(event => { + return event; + }); + } + + const client1 = getTestClient(); + const client2 = getTestClient(); + + const integrationIndex = {}; + const integration1 = new CustomIntegration(); + const integration2 = new CustomIntegration(); + const integration3 = new CustomIntegration(); + const integration4 = new CustomIntegration(); + + setupIntegration(client1, integration1, integrationIndex); + setupIntegration(client1, integration2, integrationIndex); + setupIntegration(client2, integration3, integrationIndex); + setupIntegration(client2, integration4, integrationIndex); + + expect(integrationIndex).toEqual({ test: integration4 }); + expect(integration1.setupOnce).toHaveBeenCalledTimes(1); + expect(integration2.setupOnce).not.toHaveBeenCalled(); + expect(integration3.setupOnce).not.toHaveBeenCalled(); + expect(integration4.setupOnce).not.toHaveBeenCalled(); + + client1.captureEvent({ event_id: '1a' }); + client1.captureEvent({ event_id: '1b' }); + client2.captureEvent({ event_id: '2a' }); + client2.captureEvent({ event_id: '2b' }); + client2.captureEvent({ event_id: '2c' }); + + expect(integration1.processEvent).toHaveBeenCalledTimes(2); + expect(integration2.processEvent).toHaveBeenCalledTimes(2); + expect(integration3.processEvent).toHaveBeenCalledTimes(3); + expect(integration4.processEvent).toHaveBeenCalledTimes(3); + + expect(integration1.processEvent).toHaveBeenLastCalledWith( + expect.objectContaining({ event_id: '1b' }), + {}, + client1, + ); + expect(integration2.processEvent).toHaveBeenLastCalledWith( + expect.objectContaining({ event_id: '1b' }), + {}, + client1, + ); + expect(integration3.processEvent).toHaveBeenLastCalledWith( + expect.objectContaining({ event_id: '2c' }), + {}, + client2, + ); + expect(integration4.processEvent).toHaveBeenLastCalledWith( + expect.objectContaining({ event_id: '2c' }), + {}, + client2, + ); + }); + + it('allows to mutate events in processEvent', async () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + processEvent = jest.fn(_event => { + return { event_id: 'mutated' }; + }); + } + + const client = getTestClient(); + + const integrationIndex = {}; + const integration = new CustomIntegration(); + + setupIntegration(client, integration, integrationIndex); + + const sendEvent = jest.fn(); + client.sendEvent = sendEvent; + + client.captureEvent({ event_id: '1a' }); + await client.flush(); + + expect(sendEvent).toHaveBeenCalledTimes(1); + expect(sendEvent).toHaveBeenCalledWith(expect.objectContaining({ event_id: 'mutated' }), {}); + }); + + it('allows to drop events in processEvent', async () => { + class CustomIntegration implements Integration { + name = 'test'; + setupOnce = jest.fn(); + processEvent = jest.fn(_event => { + return null; + }); + } + + const client = getTestClient(); + + const integrationIndex = {}; + const integration = new CustomIntegration(); + + setupIntegration(client, integration, integrationIndex); + + const sendEvent = jest.fn(); + client.sendEvent = sendEvent; + + client.captureEvent({ event_id: '1a' }); + await client.flush(); + + expect(sendEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/.eslintrc.js b/packages/e2e-tests/test-applications/create-remix-app-v2/.eslintrc.js new file mode 100644 index 000000000000..f2faf1470fd8 --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/.eslintrc.js @@ -0,0 +1,4 @@ +/** @type {import('eslint').Linter.Config} */ +module.exports = { + extends: ['@remix-run/eslint-config', '@remix-run/eslint-config/node'], +}; diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/.gitignore b/packages/e2e-tests/test-applications/create-remix-app-v2/.gitignore new file mode 100644 index 000000000000..3f7bf98da3e1 --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/.gitignore @@ -0,0 +1,6 @@ +node_modules + +/.cache +/build +/public/build +.env diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/.npmrc b/packages/e2e-tests/test-applications/create-remix-app-v2/.npmrc new file mode 100644 index 000000000000..c6b3ef9b3eaa --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/.npmrc @@ -0,0 +1,2 @@ +@sentry:registry=http://localhost:4873 +@sentry-internal:registry=http://localhost:4873 diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/README.md b/packages/e2e-tests/test-applications/create-remix-app-v2/README.md new file mode 100644 index 000000000000..54336d746713 --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/README.md @@ -0,0 +1,61 @@ +# Welcome to Remix! + +- [Remix Docs](https://remix.run/docs) + +## Development + +From your terminal: + +```sh +npm run dev +``` + +This starts your app in development mode, rebuilding assets on file changes. + +## Deployment + +First, build your app for production: + +```sh +npm run build +``` + +Then run the app in production mode: + +```sh +npm start +``` + +Now you'll need to pick a host to deploy it to. + +### DIY + +If you're familiar with deploying node applications, the built-in Remix app server is production-ready. + +Make sure to deploy the output of `remix build` + +- `build/` +- `public/build/` + +### Using a Template + +When you ran `npx create-remix@latest` there were a few choices for hosting. You can run that again to create a new +project, then copy over relevant code/assets from your current app to the new project that's pre-configured for your +target server. + +Most importantly, this means everything in the `app/` directory, but if you've further customized your current +application outside of there it may also include: + +- Any assets you've added/updated in `public/` +- Any updated versions of root files such as `.eslintrc.js`, etc. + +```sh +cd .. +# create a new project, and pick a pre-configured host +npx create-remix@latest +cd my-new-remix-app +# remove the new project's app (not the old one!) +rm -rf app +# copy your app over +cp -R ../my-old-remix-app/app app +``` diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.client.tsx b/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.client.tsx new file mode 100644 index 000000000000..605d8e792d23 --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.client.tsx @@ -0,0 +1,49 @@ +/** + * By default, Remix will handle hydrating your app on the client for you. + * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ + * For more information, see https://remix.run/file-conventions/entry.client + */ + +import { RemixBrowser, useLocation, useMatches } from '@remix-run/react'; +import { startTransition, StrictMode, useEffect } from 'react'; +import { hydrateRoot } from 'react-dom/client'; +import * as Sentry from '@sentry/remix'; + +Sentry.init({ + dsn: window.ENV.SENTRY_DSN, + integrations: [ + new Sentry.BrowserTracing({ + routingInstrumentation: Sentry.remixRouterInstrumentation(useEffect, useLocation, useMatches), + }), + new Sentry.Replay(), + ], + // Performance Monitoring + tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production! + // Session Replay + replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production. + replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur. +}); + +Sentry.addGlobalEventProcessor(event => { + if ( + event.type === 'transaction' && + (event.contexts?.trace?.op === 'pageload' || event.contexts?.trace?.op === 'navigation') + ) { + const eventId = event.event_id; + if (eventId) { + window.recordedTransactions = window.recordedTransactions || []; + window.recordedTransactions.push(eventId); + } + } + + return event; +}); + +startTransition(() => { + hydrateRoot( + document, + + + , + ); +}); diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.server.tsx b/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.server.tsx new file mode 100644 index 000000000000..bce3f38ae7f8 --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/app/entry.server.tsx @@ -0,0 +1,133 @@ +/** + * By default, Remix will handle generating the HTTP Response for you. + * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ + * For more information, see https://remix.run/file-conventions/entry.server + */ + +import { PassThrough } from 'node:stream'; + +import type { AppLoadContext, EntryContext, DataFunctionArgs } from '@remix-run/node'; +import { createReadableStreamFromReadable } from '@remix-run/node'; +import { RemixServer } from '@remix-run/react'; +import { renderToPipeableStream } from 'react-dom/server'; +import * as Sentry from '@sentry/remix'; +import { installGlobals } from '@remix-run/node'; +import isbot from 'isbot'; + +installGlobals(); + +const ABORT_DELAY = 5_000; + +Sentry.init({ + dsn: process.env.E2E_TEST_DSN, + // Performance Monitoring + tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production! +}); + +export function handleError(error: unknown, { request }: DataFunctionArgs): void { + Sentry.captureRemixServerException(error, 'remix.server', request); +} + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext, + loadContext: AppLoadContext, +) { + return isbot(request.headers.get('user-agent')) + ? handleBotRequest(request, responseStatusCode, responseHeaders, remixContext) + : handleBrowserRequest(request, responseStatusCode, responseHeaders, remixContext); +} + +function handleBotRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext, +) { + return new Promise((resolve, reject) => { + let shellRendered = false; + const { pipe, abort } = renderToPipeableStream( + , + { + onAllReady() { + shellRendered = true; + const body = new PassThrough(); + const stream = createReadableStreamFromReadable(body); + + responseHeaders.set('Content-Type', 'text/html'); + + resolve( + new Response(stream, { + headers: responseHeaders, + status: responseStatusCode, + }), + ); + + pipe(body); + }, + onShellError(error: unknown) { + reject(error); + }, + onError(error: unknown) { + responseStatusCode = 500; + // Log streaming rendering errors from inside the shell. Don't log + // errors encountered during initial shell rendering since they'll + // reject and get logged in handleDocumentRequest. + if (shellRendered) { + console.error(error); + } + }, + }, + ); + + setTimeout(abort, ABORT_DELAY); + }); +} + +function handleBrowserRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext, +) { + return new Promise((resolve, reject) => { + let shellRendered = false; + const { pipe, abort } = renderToPipeableStream( + , + { + onShellReady() { + shellRendered = true; + const body = new PassThrough(); + const stream = createReadableStreamFromReadable(body); + + responseHeaders.set('Content-Type', 'text/html'); + + resolve( + new Response(stream, { + headers: responseHeaders, + status: responseStatusCode, + }), + ); + + pipe(body); + }, + onShellError(error: unknown) { + reject(error); + }, + onError(error: unknown) { + responseStatusCode = 500; + // Log streaming rendering errors from inside the shell. Don't log + // errors encountered during initial shell rendering since they'll + // reject and get logged in handleDocumentRequest. + if (shellRendered) { + console.error(error); + } + }, + }, + ); + + setTimeout(abort, ABORT_DELAY); + }); +} diff --git a/packages/e2e-tests/test-applications/create-remix-app-v2/app/root.tsx b/packages/e2e-tests/test-applications/create-remix-app-v2/app/root.tsx new file mode 100644 index 000000000000..d4b2c07516eb --- /dev/null +++ b/packages/e2e-tests/test-applications/create-remix-app-v2/app/root.tsx @@ -0,0 +1,63 @@ +import { cssBundleHref } from '@remix-run/css-bundle'; +import { json, LinksFunction } from '@remix-run/node'; +import { + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, + useLoaderData, + useRouteError, +} from '@remix-run/react'; +import { captureRemixErrorBoundaryError, withSentry } from '@sentry/remix'; + +export const links: LinksFunction = () => [...(cssBundleHref ? [{ rel: 'stylesheet', href: cssBundleHref }] : [])]; + +export const loader = () => { + return json({ + ENV: { + SENTRY_DSN: process.env.E2E_TEST_DSN, + }, + }); +}; + +export function ErrorBoundary() { + const error = useRouteError(); + const eventId = captureRemixErrorBoundaryError(error); + + return ( +
+ ErrorBoundary Error + {eventId} +
+ ); +} + +function App() { + const { ENV } = useLoaderData(); + + return ( + + + + +