From 7ebe6aa08caac96ece5a53eb610d23dbfd25a276 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Mon, 23 Nov 2026 10:40:07 +0500 Subject: [PATCH 01/21] docs(javascript): add the JavaScript SDK documentation (beta) 58 pages under docs/sdk/javascript covering overview, installation, configuration, platforms, frameworks, backend adapters, data capture, privacy, session replay, issue detection, performance, source maps, the package catalogue, release notes and FAQ. Co-Authored-By: Claude Sonnet 5.5 Change-Id: I3d5abeb6dc6d40cc5b99eb6a5fd18b59a6ccf9d1 --- cspell.json | 23 ++ docs/index.md | 3 +- docs/sdk/javascript/backend/elysia.mdx | 125 +++++++ docs/sdk/javascript/backend/express.mdx | 143 ++++++++ docs/sdk/javascript/backend/fastify.mdx | 116 ++++++ docs/sdk/javascript/backend/hapi.mdx | 112 ++++++ docs/sdk/javascript/backend/hono.mdx | 107 ++++++ docs/sdk/javascript/backend/koa.mdx | 107 ++++++ docs/sdk/javascript/backend/nestjs.mdx | 137 +++++++ docs/sdk/javascript/backend/overview.mdx | 163 +++++++++ docs/sdk/javascript/breadcrumbs.md | 118 +++++++ docs/sdk/javascript/configuration.mdx | 333 ++++++++++++++++++ docs/sdk/javascript/events-and-traces.md | 100 ++++++ docs/sdk/javascript/faq.md | 140 ++++++++ docs/sdk/javascript/frameworks/angular.mdx | 164 +++++++++ docs/sdk/javascript/frameworks/astro.mdx | 132 +++++++ docs/sdk/javascript/frameworks/nextjs.mdx | 170 +++++++++ docs/sdk/javascript/frameworks/nuxt.mdx | 131 +++++++ docs/sdk/javascript/frameworks/react.mdx | 192 ++++++++++ docs/sdk/javascript/frameworks/remix.mdx | 148 ++++++++ docs/sdk/javascript/frameworks/solid.mdx | 162 +++++++++ docs/sdk/javascript/frameworks/svelte.mdx | 247 +++++++++++++ docs/sdk/javascript/frameworks/vue.mdx | 152 ++++++++ docs/sdk/javascript/installation.mdx | 246 +++++++++++++ .../issue-detection/diagnostics.mdx | 128 +++++++ .../issue-detection/errors-and-crashes.mdx | 88 +++++ docs/sdk/javascript/issue-detection/hangs.mdx | 88 +++++ .../issue-detection/http-errors.mdx | 63 ++++ .../javascript/issue-detection/overview.mdx | 60 ++++ docs/sdk/javascript/lifecycle.mdx | 194 ++++++++++ docs/sdk/javascript/logs.md | 119 +++++++ docs/sdk/javascript/manual/bug-reporting.md | 215 +++++++++++ .../manual/crash-error-reporting.md | 174 +++++++++ docs/sdk/javascript/network.md | 171 +++++++++ docs/sdk/javascript/opentelemetry.mdx | 96 +++++ docs/sdk/javascript/overview.mdx | 74 ++++ docs/sdk/javascript/packages.mdx | 142 ++++++++ docs/sdk/javascript/performance.mdx | 187 ++++++++++ docs/sdk/javascript/platforms/browser.mdx | 171 +++++++++ docs/sdk/javascript/platforms/bun.mdx | 130 +++++++ docs/sdk/javascript/platforms/cloudflare.mdx | 185 ++++++++++ docs/sdk/javascript/platforms/electron.mdx | 185 ++++++++++ docs/sdk/javascript/platforms/node.mdx | 170 +++++++++ docs/sdk/javascript/platforms/vercel-edge.mdx | 131 +++++++ docs/sdk/javascript/platforms/web-workers.mdx | 140 ++++++++ docs/sdk/javascript/privacy/breadcrumbs.md | 115 ++++++ docs/sdk/javascript/privacy/cleanup.md | 126 +++++++ docs/sdk/javascript/privacy/logs.md | 90 +++++ docs/sdk/javascript/privacy/network.md | 123 +++++++ docs/sdk/javascript/privacy/overview.md | 52 +++ docs/sdk/javascript/privacy/replay.md | 170 +++++++++ docs/sdk/javascript/privacy/report.md | 95 +++++ docs/sdk/javascript/release-notes.md | 52 +++ docs/sdk/javascript/report-handler.md | 156 ++++++++ docs/sdk/javascript/session-replay.md | 142 ++++++++ .../symbolication/bundler-plugins.mdx | 231 ++++++++++++ .../javascript/symbolication/environment.mdx | 84 +++++ docs/sdk/javascript/symbolication/manual.mdx | 156 ++++++++ .../sdk/javascript/symbolication/overview.mdx | 73 ++++ docs/sdk/javascript/user-session-data.md | 106 ++++++ docusaurus.config.ts | 2 + sidebars.ts | 309 ++++++++++++++++ 62 files changed, 8463 insertions(+), 1 deletion(-) create mode 100644 docs/sdk/javascript/backend/elysia.mdx create mode 100644 docs/sdk/javascript/backend/express.mdx create mode 100644 docs/sdk/javascript/backend/fastify.mdx create mode 100644 docs/sdk/javascript/backend/hapi.mdx create mode 100644 docs/sdk/javascript/backend/hono.mdx create mode 100644 docs/sdk/javascript/backend/koa.mdx create mode 100644 docs/sdk/javascript/backend/nestjs.mdx create mode 100644 docs/sdk/javascript/backend/overview.mdx create mode 100644 docs/sdk/javascript/breadcrumbs.md create mode 100644 docs/sdk/javascript/configuration.mdx create mode 100644 docs/sdk/javascript/events-and-traces.md create mode 100644 docs/sdk/javascript/faq.md create mode 100644 docs/sdk/javascript/frameworks/angular.mdx create mode 100644 docs/sdk/javascript/frameworks/astro.mdx create mode 100644 docs/sdk/javascript/frameworks/nextjs.mdx create mode 100644 docs/sdk/javascript/frameworks/nuxt.mdx create mode 100644 docs/sdk/javascript/frameworks/react.mdx create mode 100644 docs/sdk/javascript/frameworks/remix.mdx create mode 100644 docs/sdk/javascript/frameworks/solid.mdx create mode 100644 docs/sdk/javascript/frameworks/svelte.mdx create mode 100644 docs/sdk/javascript/frameworks/vue.mdx create mode 100644 docs/sdk/javascript/installation.mdx create mode 100644 docs/sdk/javascript/issue-detection/diagnostics.mdx create mode 100644 docs/sdk/javascript/issue-detection/errors-and-crashes.mdx create mode 100644 docs/sdk/javascript/issue-detection/hangs.mdx create mode 100644 docs/sdk/javascript/issue-detection/http-errors.mdx create mode 100644 docs/sdk/javascript/issue-detection/overview.mdx create mode 100644 docs/sdk/javascript/lifecycle.mdx create mode 100644 docs/sdk/javascript/logs.md create mode 100644 docs/sdk/javascript/manual/bug-reporting.md create mode 100644 docs/sdk/javascript/manual/crash-error-reporting.md create mode 100644 docs/sdk/javascript/network.md create mode 100644 docs/sdk/javascript/opentelemetry.mdx create mode 100644 docs/sdk/javascript/overview.mdx create mode 100644 docs/sdk/javascript/packages.mdx create mode 100644 docs/sdk/javascript/performance.mdx create mode 100644 docs/sdk/javascript/platforms/browser.mdx create mode 100644 docs/sdk/javascript/platforms/bun.mdx create mode 100644 docs/sdk/javascript/platforms/cloudflare.mdx create mode 100644 docs/sdk/javascript/platforms/electron.mdx create mode 100644 docs/sdk/javascript/platforms/node.mdx create mode 100644 docs/sdk/javascript/platforms/vercel-edge.mdx create mode 100644 docs/sdk/javascript/platforms/web-workers.mdx create mode 100644 docs/sdk/javascript/privacy/breadcrumbs.md create mode 100644 docs/sdk/javascript/privacy/cleanup.md create mode 100644 docs/sdk/javascript/privacy/logs.md create mode 100644 docs/sdk/javascript/privacy/network.md create mode 100644 docs/sdk/javascript/privacy/overview.md create mode 100644 docs/sdk/javascript/privacy/replay.md create mode 100644 docs/sdk/javascript/privacy/report.md create mode 100644 docs/sdk/javascript/release-notes.md create mode 100644 docs/sdk/javascript/report-handler.md create mode 100644 docs/sdk/javascript/session-replay.md create mode 100644 docs/sdk/javascript/symbolication/bundler-plugins.mdx create mode 100644 docs/sdk/javascript/symbolication/environment.mdx create mode 100644 docs/sdk/javascript/symbolication/manual.mdx create mode 100644 docs/sdk/javascript/symbolication/overview.mdx create mode 100644 docs/sdk/javascript/user-session-data.md diff --git a/cspell.json b/cspell.json index 1565e7f6..8b1f0385 100644 --- a/cspell.json +++ b/cspell.json @@ -2,6 +2,29 @@ "version": "0.2", "language": "en", "words": [ + "Rspack", + "rspack", + "Elysia", + "elysia", + "verylow", + "solidjs", + "navigations", + "workerd", + "traceresponse", + "rrweb", + "webtransport", + "unhandledrejection", + "speedscope", + "iban", + "ttfb", + "nitropack", + "melden", + "jsessionid", + "fastfail", + "bunx", + "Zusammenfassung", + "Senden", + "Kurze", "SIGSYS", "apptoken", "libbugsee", diff --git a/docs/index.md b/docs/index.md index 5c559391..67c450ac 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,6 +1,6 @@ --- title: "Overview" -description: "Overview of Bugsee SDK installation links and a feature comparison table across iOS, Android, React Native, Flutter, Unity, .NET, and Cordova." +description: "Overview of Bugsee SDK installation links and a feature comparison table across iOS, Android, React Native, Flutter, Unity, .NET, and Cordova (plus installation links for the JavaScript SDK)." sidebar_position: 0 slug: "/" --- @@ -14,6 +14,7 @@ Using Bugsee on mobile devices requires installation of Bugsee lightweight SDK: * [Installing Cordova SDK](/sdk/cordova/installation/) * [Installing React Native SDK](/sdk/react_native/v6/installation/) * [Installing Flutter SDK](/sdk/flutter/installation/) +* [Installing JavaScript SDK (Beta)](/sdk/javascript/installation/) — browsers, Node.js, Bun, Electron, edge runtimes and web frameworks * [Installing Unity SDK](/sdk/unity/installation/) * [Installing KMP SDK (Beta)](/sdk/kmp/installation/) * [Installing Xamarin SDK](/sdk/xamarin/installation/) — **deprecated**, use the [.NET SDK](/sdk/dotnet/installation/) for new projects diff --git a/docs/sdk/javascript/backend/elysia.mdx b/docs/sdk/javascript/backend/elysia.mdx new file mode 100644 index 00000000..bedfff18 --- /dev/null +++ b/docs/sdk/javascript/backend/elysia.mdx @@ -0,0 +1,125 @@ +--- +title: "Elysia" +description: "Report errors and trace requests in an Elysia app on Bun or Node.js with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 8 +slug: "/sdk/javascript/backend/elysia" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/elysia` adds a request context, an `http.server` transaction and error reporting to an Elysia app. It runs on Bun, and on Node.js through the app's fetch handler. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/elysia@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/elysia@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/elysia@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/elysia@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your Elysia app. On Node.js it needs Node.js 18 or newer. + +## Set up + +Call `launch()` at the top of your server entry, then pass the app to `setupElysia`: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupElysia } from '@bugsee/elysia'; +import { Elysia } from 'elysia'; + +launch(''); + +const app = new Elysia(); +setupElysia(app); + +// ... your routes ... +``` + +Hooks are scoped to the Elysia instance they are added to, so register `setupElysia` on the instance that owns your routes. + +If your Elysia app type does not unify with the adapter's structural type, cast it: + +```ts +import { type ElysiaAppLike, setupElysia } from '@bugsee/elysia'; + +setupElysia(app as unknown as ElysiaAppLike); +``` + +## Node.js and Bun + +On Bun, the full Elysia server works. + +On Node.js, Elysia's `.listen` is not supported. Use the app's fetch handler, `app.fetch`, instead. + +## What it does + +Elysia hooks are additive, so `setupElysia` adds three without replacing yours: + +| Hook | What it does | +| --- | --- | +| `onRequest` | Opens a request context, continues an inbound `traceparent` and starts an `http.server` transaction. | +| `onError` | Reports server errors, meaning a plain throw or a 5xx status. Framework control flow such as `NOT_FOUND` and `VALIDATION` is skipped. | +| `mapResponse` | Finishes the transaction without altering the response. | + +## Options + +Pass options as the second argument of `setupElysia`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(c) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | server errors only | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`c` is a structural view of the Elysia context: `request`, `set` and `route`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/elysia` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/express.mdx b/docs/sdk/javascript/backend/express.mdx new file mode 100644 index 00000000..07952a68 --- /dev/null +++ b/docs/sdk/javascript/backend/express.mdx @@ -0,0 +1,143 @@ +--- +title: "Express" +description: "Report errors and trace requests in an Express app with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 2 +slug: "/sdk/javascript/backend/express" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/express` adds a request context, an `http.server` transaction and error reporting to an Express app on Node.js. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your Express app (Express 4 or 5). + +## Set up + +Call `launch()` at the top of your server entry, then pass the app to `setupExpress`: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupExpress } from '@bugsee/express'; +import express from 'express'; + +launch(''); + +const app = express(); +setupExpress(app); + +// ... your routes ... + +app.listen(3000); +``` + +`setupExpress` installs the request middleware immediately, so call it before you register routes. It installs the error handler for you: + +- It wraps `app.listen`, so the handler is added when the server starts listening, after your routes exist. +- An app that never calls `app.listen` (for example one passed to `http.createServer`) gets the handler on its first request. +- The handler is placed in front of any error middleware you already registered, so an error-response middleware that ends the response without calling `next(err)` does not hide the error from Bugsee. + +## Place the error handler yourself + +To control the position, turn off the automatic handler and add it with `setupExpressErrorHandler`: + +```ts title="server.ts" +import { setupExpress, setupExpressErrorHandler } from '@bugsee/express'; + +setupExpress(app, { autoErrorHandler: false }); + +// ... your routes ... + +setupExpressErrorHandler(app); // reports, then calls next(err) + +app.use((err, req, res, next) => { + // your error response +}); +``` + +For full control, the two middlewares are also exported on their own: `requestHandler()` (mount it first) and `errorHandler()` (mount it after your routes). + +## What it does + +- Opens a request context for each request, so everything reported inside a route is tagged with that request. +- Continues an inbound `traceparent` header and records an `http.server` transaction named after the route pattern, such as `/users/:id`. +- Reports an error that reaches the error handler, with the request context merged in, and then passes it on with `next(err)`. Your own error handling still runs. +- Does nothing, and passes every request through, when no client is launched. + +By default an error with no status, or with a status of 500 or higher, is reported, and a 4xx is skipped. + +## Options + +Pass options as the second argument of `setupExpress`. `setupExpressErrorHandler`, `requestHandler` and `errorHandler` take the same options, without `autoErrorHandler`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(req) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | 5xx or no status | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | +| `autoErrorHandler` | `boolean` | `true` | Set `false` to place the error handler yourself. `setupExpress` only. | + +`req` is a structural view of the Express request: `method`, `url`, `originalUrl`, `route`, `baseUrl` and `headers`. Cast it to read fields added by your own middleware: + +```ts +setupExpress(app, { + user: (req) => (req as { user?: { id: string } }).user?.id, +}); +``` + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/express` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/fastify.mdx b/docs/sdk/javascript/backend/fastify.mdx new file mode 100644 index 00000000..88c7b8a2 --- /dev/null +++ b/docs/sdk/javascript/backend/fastify.mdx @@ -0,0 +1,116 @@ +--- +title: "Fastify" +description: "Report errors and trace requests in a Fastify app with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 3 +slug: "/sdk/javascript/backend/fastify" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/fastify` adds a request context, an `http.server` transaction and error reporting to a Fastify app on Node.js. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/fastify@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/fastify@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/fastify@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/fastify@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your Fastify instance. + +## Set up + +Call `launch()` at the top of your server entry, then pass the root Fastify instance to `setupFastify`: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupFastify } from '@bugsee/fastify'; +import Fastify from 'fastify'; + +launch(''); + +const app = Fastify(); +setupFastify(app); + +// ... your routes ... + +await app.listen({ port: 3000 }); +``` + +## What it does + +`setupFastify` installs lifecycle hooks: + +| Hook | What it does | +| --- | --- | +| `onRequest` | Opens a request context, continues an inbound `traceparent` and starts an `http.server` transaction. | +| `onError` | Reports an unhandled route error, with the request context merged in. | +| `onResponse` | Finishes the transaction with the route pattern, such as `/users/:id`, and the status. | +| `onRequestAbort` | Finishes the transaction as cancelled when the client aborts. | + +Fastify hooks are encapsulated per scope. Call `setupFastify` on the root instance and the hooks cover it and its child plugins. The order relative to your routes does not matter. + +By default an error with no status, or with a status of 500 or higher, is reported, and a 4xx is skipped. + +## Options + +Pass options as the second argument of `setupFastify`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(req) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | 5xx or no status | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`req` is a structural view of the Fastify request: `method`, `url`, `headers` and `routeOptions`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/fastify` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/hapi.mdx b/docs/sdk/javascript/backend/hapi.mdx new file mode 100644 index 00000000..e140fba4 --- /dev/null +++ b/docs/sdk/javascript/backend/hapi.mdx @@ -0,0 +1,112 @@ +--- +title: "hapi" +description: "Report errors and trace requests in a hapi server with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 7 +slug: "/sdk/javascript/backend/hapi" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/hapi` adds a request context, an `http.server` transaction and error reporting to a hapi server on Node.js. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/hapi@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/hapi@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/hapi@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/hapi@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your `@hapi/hapi` server. + +## Set up + +Call `launch()` at the top of your server entry, then pass the server to `setupHapi` before `server.start()`: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupHapi } from '@bugsee/hapi'; +import Hapi from '@hapi/hapi'; + +launch(''); + +const server = Hapi.server({ port: 3000 }); +setupHapi(server); + +// ... your routes ... + +await server.start(); +``` + +## What it does + +`setupHapi` registers two request extensions. They are added next to yours and never replace them. + +| Extension | What it does | +| --- | --- | +| `onRequest` | Opens a request context, continues an inbound `traceparent` and starts an `http.server` transaction. | +| `onPreResponse` | Reports a Boom error and finishes the transaction. The response is not altered. | + +By default server errors (5xx) are reported and client errors (4xx) are skipped. A client disconnect finishes the transaction as cancelled. + +## Options + +Pass options as the second argument of `setupHapi`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(req) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | 5xx or no status | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`req` is a structural view of the hapi request: `method`, `path`, `route`, `headers` and `response`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/hapi` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/hono.mdx b/docs/sdk/javascript/backend/hono.mdx new file mode 100644 index 00000000..b28ba75d --- /dev/null +++ b/docs/sdk/javascript/backend/hono.mdx @@ -0,0 +1,107 @@ +--- +title: "Hono" +description: "Report errors and trace requests in a Hono app on Node.js with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 5 +slug: "/sdk/javascript/backend/hono" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/hono` adds a request context, an `http.server` transaction and error reporting to a Hono app on Node.js. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +For Hono on an edge runtime, use the edge platform packages instead: [Cloudflare](/sdk/javascript/platforms/cloudflare) or [Vercel Edge](/sdk/javascript/platforms/vercel-edge). + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/hono@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/hono@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/hono@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/hono@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your Hono app. + +## Set up + +Call `launch()` at the top of your server entry, then pass the app to `setupHono` before you register routes: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupHono } from '@bugsee/hono'; +import { Hono } from 'hono'; + +launch(''); + +const app = new Hono(); +setupHono(app); + +// ... your routes ... +``` + +## What it does + +`setupHono` registers one middleware. It opens a request context, continues an inbound `traceparent`, starts an `http.server` transaction named after the route, and, after `next()`, reports a handled error that Hono stored in `c.error`. Your `app.onError` handler is not touched. + +A Hono `HTTPException` is deliberate control flow and is not reported. Any other error is reported. + +## Options + +Pass options as the second argument of `setupHono`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(c) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | skips `HTTPException` | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`c` is a structural view of the Hono context: `c.req`, `c.res` and `c.error`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/hono` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/koa.mdx b/docs/sdk/javascript/backend/koa.mdx new file mode 100644 index 00000000..ab1b6cd7 --- /dev/null +++ b/docs/sdk/javascript/backend/koa.mdx @@ -0,0 +1,107 @@ +--- +title: "Koa" +description: "Report errors and trace requests in a Koa app with the Bugsee JavaScript SDK: per-request context, http.server transactions and error capture." +sidebar_position: 6 +slug: "/sdk/javascript/backend/koa" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/koa` adds a request context, an `http.server` transaction and error reporting to a Koa app on Node.js. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/koa@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/koa@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/koa@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/koa@beta +``` + + + + +The adapter declares no peer dependency. It only relies on the shape of your Koa app. + +## Set up + +Call `launch()` at the top of your server entry, then pass the app to `setupKoa`. Register it before your other middleware so that it wraps the whole chain: + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; +import { setupKoa } from '@bugsee/koa'; +import Koa from 'koa'; + +launch(''); + +const app = new Koa(); +setupKoa(app); + +// ... your middleware and routes ... + +app.listen(3000); +``` + +## What it does + +`setupKoa` installs one middleware. It opens a request context, continues an inbound `traceparent`, starts an `http.server` transaction, and reports an error thrown downstream before re-throwing it untouched, so Koa's own `onerror` still formats the response. + +By default a plain throw or a 5xx is reported, and a 4xx such as `ctx.throw(404)` is skipped. With `@koa/router`, the transaction is named after the matched route. + +## Options + +Pass options as the second argument of `setupKoa`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(ctx) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | 5xx or no status | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`ctx` is a structural view of the Koa context: `method`, `path`, `url`, `status` and `headers`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/koa` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/nestjs.mdx b/docs/sdk/javascript/backend/nestjs.mdx new file mode 100644 index 00000000..6d06a68d --- /dev/null +++ b/docs/sdk/javascript/backend/nestjs.mdx @@ -0,0 +1,137 @@ +--- +title: "NestJS" +description: "Report errors and trace requests in a NestJS app with the Bugsee JavaScript SDK, and choose where errors are caught: interceptor, exception filter or both." +sidebar_position: 4 +slug: "/sdk/javascript/backend/nestjs" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/nestjs` adds a request context, an `http.server` transaction and error reporting to a NestJS app on the Express or Fastify platform. Read the [backend overview](/sdk/javascript/backend/overview) first for how context and trace correlation work. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/nestjs@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/nestjs@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/nestjs@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/nestjs@beta +``` + + + + +Peer dependencies: `@nestjs/common` and `@nestjs/core` (version 9, 10, 11 or 12) and `rxjs` 7. Node.js 18 or newer, and Node.js 20 or newer for Nest 12 itself. + +## Set up + +Call `launch()` at the top of your server entry, then pass the Nest application to `setupNest`: + +```ts title="main.ts" +import { launch } from '@bugsee/bugsee'; +import { setupNest } from '@bugsee/nestjs'; +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module'; + +launch(''); + +const app = await NestFactory.create(AppModule); +setupNest(app); +await app.listen(3000); +``` + +## What it does + +`setupNest` installs two things: + +- A **context middleware** that opens a request context for each request. +- By default, a **global interceptor** that starts an `http.server` transaction, continues an inbound `traceparent`, and reports a thrown error before re-throwing it untouched. Nest's own exception filters still format the response. + +A Nest `HttpException` is deliberate control flow and is not reported, whatever its status. Any other thrown error is reported. + +## Choose where errors are caught + +The `errorCapture` option picks the seam that catches errors. + +| `errorCapture` | Catches | Notes | +| --- | --- | --- | +| `'interceptor'` (default) | Route handlers, services and pipes | Reports and re-throws. Never conflicts with your own filter. Does not see errors thrown in guards. | +| `'filter'` | Also guards | Installs a global `ExceptionFilter`. Being a catch-all, it can collide with your own global filter. | +| `'both'` | Everything above | Interceptor and filter together. An error is reported once. | + +```ts +setupNest(app, { errorCapture: 'both' }); +``` + +If you already have a global exception filter, keep the default or decorate your filter's `catch` method with `BugseeExceptionCaptured` instead of using `'filter'` or `'both'`: + +```ts +import { BugseeExceptionCaptured } from '@bugsee/nestjs'; + +@Catch() +export class MyFilter extends BaseExceptionFilter { + @BugseeExceptionCaptured() + catch(exception: unknown, host: ArgumentsHost) { + // your handling + } +} +``` + +## Options + +Pass options as the second argument of `setupNest`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `errorCapture` | `'interceptor' \| 'filter' \| 'both'` | `'interceptor'` | Where errors are caught. See above. | +| `user` | `(req) => string \| undefined` | off | The end-user identity for reports raised during the request. | +| `shouldReport` | `(error) => boolean` | skips `HttpException` | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +`req` is a structural view of the request of your Nest platform (Express or Fastify): `method`, `url`, `originalUrl`, `route`, `routeOptions` and `headers`. + +## Launch options + +The adapter does not change the launch options. These are the ones that matter most on a server: + +| Option | Default | Description | +| --- | --- | --- | +| `instrumentIncomingRequests` | `true` | Automatic per-request context and `http.server` transaction. See the [backend overview](/sdk/javascript/backend/overview#incoming-request-instrumentation). | +| `captureLocalVariables` | `false` | Attach local variables to the stack frames of a reported error. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `false` | Attach the source lines around each stack frame. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `detectHangs` | `true` | Report event-loop hangs. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `false` | Attach a rolling CPU profile to reports. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | + +`@bugsee/nestjs` also re-exports everything from the Node entry of `@bugsee/bugsee`. + +## Related pages + +- [Backend overview](/sdk/javascript/backend/overview) — request context, trace correlation and incoming-request instrumentation +- [Issue detection](/sdk/javascript/issue-detection/overview) — what else is detected on a server +- [Performance](/sdk/javascript/performance) — transactions and spans diff --git a/docs/sdk/javascript/backend/overview.mdx b/docs/sdk/javascript/backend/overview.mdx new file mode 100644 index 00000000..cd481091 --- /dev/null +++ b/docs/sdk/javascript/backend/overview.mdx @@ -0,0 +1,163 @@ +--- +title: "Backend overview" +description: "How the Bugsee JavaScript SDK instruments Node.js and Bun servers: per-request context, trace correlation, automatic incoming-request instrumentation and the framework adapters." +sidebar_position: 1 +slug: "/sdk/javascript/backend/overview" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +On a server, Bugsee records what your process was doing around a failure and ties it to the request that was running. Each request gets a context and an `http.server` transaction, and an error reported while the request runs carries both. + +## What Bugsee records + +- **Per-request context.** A request context holds an id, the trace of the request and, if you provide it, the end-user identity. Everything Bugsee captures while the request runs (logs, network calls, breadcrumbs) is tagged with it. +- **An `http.server` transaction per request.** It is named after the route, carries the method and the response status, and continues the trace of the caller when the request has a `traceparent` header. See [Performance](/sdk/javascript/performance). +- **Errors.** A framework adapter reports an error your route throws, with the request context merged into the report. +- **Process-level signals.** Uncaught exceptions, unhandled rejections and event-loop hangs are detected for the whole process. See [Issue detection](/sdk/javascript/issue-detection/overview). + +## How it works + +Two layers cooperate: + +1. **Incoming-request instrumentation** is part of the SDK and needs no adapter. It is on by default and covers any server built on `node:http` or `Bun.serve`. +2. **A framework adapter** adds what the SDK cannot see from outside: reporting of errors that the framework catches, the route pattern as the transaction name, and your `user` getter. + +When both run, the first one to see a request owns its context and transaction. The other one refines them (route name, user, error report), so a request gets exactly one context and one transaction. + +## Request context + +A request context lives in Node's `AsyncLocalStorage`, so it follows the request through every `await`, timer and callback it starts. Concurrent requests each see their own context. + +Bugsee tags; it does not isolate. There is one capture buffer for the process. Every entry recorded while a context is active is stamped with the context id, and with the trace id and span id when the request has a trace. The entries of concurrent requests are interleaved in the same recording, and the stamp is what tells them apart. An entry recorded outside any request, such as a timer or a startup log, carries no stamp. + +When a report is created inside a context, it records the context id. The context's `user` and attributes are merged over the global ones for that report only, so a user set for one request never leaks into another. + +You do not create or enter a context yourself. The incoming-request instrumentation or the adapter does it. + +## Incoming-request instrumentation + +`instrumentIncomingRequests` is `true` by default. Set it to `false` to turn it off. + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + instrumentIncomingRequests: false, +}); +``` + +When it is on: + +- On Node.js and Bun, Bugsee patches `emit` on the `node:http` and `node:https` server prototypes. Every `request` event runs inside a context and a transaction. +- On Bun, it also wraps `Bun.serve` when you pass it a `fetch` handler. +- The transaction is named ` `, with the query string removed, until an adapter refines it to the route pattern, for example `/users/:id`. +- No headers and no bodies of the incoming request are captured by this layer. + +:::note +A framework that catches a thrown error and turns it into a 500 response hides it from `node:http`, so automatic instrumentation cannot report it. That is what the adapters are for. An error nobody catches is still detected as a crash. +::: + +## Trace correlation + +**Inbound.** When a request carries a valid W3C `traceparent` header, the `http.server` transaction continues that trace: it adopts the trace id, becomes a child of the caller's span and follows the caller's sampling decision. Entries recorded during the request are stamped with that trace id. + +**Outbound.** Bugsee adds `traceparent` to the outgoing requests your server makes, so the downstream service continues the same trace. `propagateTrace` is `true` by default, but a server has no same-origin concept, so nothing is sent until you list your own services in `tracePropagationTargets`. This keeps the trace from leaking to third-party APIs. + +```ts +launch('', { + tracePropagationTargets: ['https://billing.internal.example.com', /\.internal\.example\.com$/], +}); +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `instrumentIncomingRequests` | `boolean` | `true` | Open a context and an `http.server` transaction for each incoming request. | +| `propagateTrace` | `boolean` | `true` | Add `traceparent` to outgoing requests. Needs `tracePropagationTargets`. `false` turns it off. | +| `tracePropagationTargets` | `(string \| RegExp)[]` | none | Outgoing URLs allowed to receive the trace headers. A string matches as a substring. | +| `traceResponse` | `{ traceresponse?: boolean, serverTiming?: boolean }` | both off | Return the trace to the caller in a `traceresponse` header, a `Server-Timing` entry, or both. | + +`traceResponse` also accepts `timingAllowOrigin` and `exposeTraceresponse` for cross-origin browsers. + +## Framework adapters + +Install the adapter next to the `@bugsee/bugsee` package. The adapter re-exports the Node entry of `@bugsee/bugsee`, so you can import `launch` from either package. + +| Framework | Package | Setup call | Page | +| --- | --- | --- | --- | +| Express | `@bugsee/express` | `setupExpress(app)` | [Express](/sdk/javascript/backend/express) | +| Fastify | `@bugsee/fastify` | `setupFastify(app)` | [Fastify](/sdk/javascript/backend/fastify) | +| NestJS | `@bugsee/nestjs` | `setupNest(app)` | [NestJS](/sdk/javascript/backend/nestjs) | +| Hono | `@bugsee/hono` | `setupHono(app)` | [Hono](/sdk/javascript/backend/hono) | +| Koa | `@bugsee/koa` | `setupKoa(app)` | [Koa](/sdk/javascript/backend/koa) | +| hapi | `@bugsee/hapi` | `setupHapi(server)` | [hapi](/sdk/javascript/backend/hapi) | +| Elysia | `@bugsee/elysia` | `setupElysia(app)` | [Elysia](/sdk/javascript/backend/elysia) | + +Call `launch()` first, at the top of your server entry. If no client is launched, an adapter does nothing and passes every request through. + +### Adapter options + +Every adapter takes an options object as its second argument. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `user` | `(request) => string \| undefined` | off | The end-user identity for reports raised during the request. Nothing identifying is read unless you provide it. The argument is the framework's request or context object. | +| `shouldReport` | `(error) => boolean` | status-based | Decides whether a thrown error is reported. | +| `onError` | `(error) => void` | none | Receives a failure of the adapter itself. It never reaches the request. | + +The default `shouldReport` reports an error that has no HTTP status or a status of 500 or higher, and skips a 4xx. It reads the status from `getStatus()`, `status`, `statusCode` or `output.statusCode`. Some adapters add framework rules on top, described on their pages. + +An adapter never throws into your request pipeline. + +## Requirements + +- Node.js 18 or newer, or Bun 1.1.13 or newer. +- The `@bugsee/bugsee` package. On a server, `launch()` returns the client directly and does not return a promise. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/express@beta +``` + + + + +Replace `@bugsee/express` with the adapter for your framework. + +## Related pages + +- [Express](/sdk/javascript/backend/express) — the first adapter to read, with the most detail on error-handler placement +- [Issue detection](/sdk/javascript/issue-detection/overview) — crashes, hangs and HTTP errors on a server +- [Performance](/sdk/javascript/performance) — the transactions and spans the adapters create +- [OpenTelemetry](/sdk/javascript/opentelemetry) — export transactions to your own backend +- [Node.js platform](/sdk/javascript/platforms/node) — the options that apply to every Node process diff --git a/docs/sdk/javascript/breadcrumbs.md b/docs/sdk/javascript/breadcrumbs.md new file mode 100644 index 00000000..65fde2aa --- /dev/null +++ b/docs/sdk/javascript/breadcrumbs.md @@ -0,0 +1,118 @@ +--- +title: "Breadcrumbs" +description: "What breadcrumbs are in the Bugsee JavaScript SDK, which ones are recorded automatically, how to record your own with addBreadcrumb, and how to rewrite or drop them with setBreadcrumbFilter." +sidebar_position: 22 +slug: "/sdk/javascript/breadcrumbs" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Breadcrumbs are a short trail of steps leading up to an issue: a screen the user opened, a form they submitted, something your code decided. They appear on the report timeline. Unlike console logs, a breadcrumb is structured: it has a type, a category, a message and a data object. + +The examples use the client returned by `launch`, kept in a module of your own: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +## Turning breadcrumbs on or off + +Breadcrumb capture is **on by default** in the JavaScript SDK. The mobile Bugsee SDKs default it to off, because web UI breadcrumbs are a core signal. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureBreadcrumbs` | `boolean` | `true` | Record breadcrumbs: yours and the automatic ones. | +| `captureInteractions` | `boolean` | `true` | Browser. Also controls the automatic `ui.*` breadcrumbs, and the input stream. | + +```ts +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch('', { + captureBreadcrumbs: false, // no breadcrumb is recorded at all +}); +``` + +A malformed `captureBreadcrumbs` value turns capture off and is reported through the `onError` launch option. + +## Where breadcrumbs come from + +- **Your code**, with `addBreadcrumb`. +- **User interface changes in the browser.** The SDK records `ui.change`, `ui.submit` and `ui.focus` breadcrumbs when a form value changes, a form is submitted, or an element gets focus. Each carries the target's element id, class and tag in `data` (`view.id`, `view.class`, `view.tag`) and never reads a value or any text the user typed. A field the SDK treats as sensitive, such as a password, and anything inside an element with a `data-bugsee-hidden` attribute, produces no breadcrumb at all. +- **Framework adapters.** Some adapters add breadcrumbs for navigation. For example the Next.js client hook records the destination of a route change. + +During a [blackout](/sdk/javascript/lifecycle) the automatic `ui.*` breadcrumbs are not recorded. Breadcrumbs you add yourself still are. + +## Record your own breadcrumb + +```ts +import { bugsee } from './bugsee'; + +bugsee.addBreadcrumb({ + type: 'navigation', + category: 'checkout', + message: 'Opened the payment step', + level: 'info', + data: { step: 3, cartItems: 2 }, +}); +``` + +| Field | Type | Description | +| --- | --- | --- | +| `type` | `string` | A free-form kind, for example `navigation`, `user` or `http`. | +| `category` | `string` | A free-form group, for example `checkout` or `ui.click`. | +| `message` | `string` | A short description. | +| `level` | `'error' \| 'warning' \| 'info' \| 'debug' \| 'verbose'` | Severity of the step. | +| `data` | `Record` | Extra structured detail. Keep it small and JSON-friendly. | +| `timestamp` | `number` | Milliseconds since the epoch. The SDK stamps the current time when you omit it. | + +All fields are optional. The `Breadcrumb` and `BreadcrumbInput` types are exported by `@bugsee/bugsee`. + +:::caution +`addBreadcrumb` does not sanitize anything. A breadcrumb is application data, so a URL with a token in `message` or `data` is recorded as it is. Redact it yourself, or use a [breadcrumb filter](#filter-breadcrumbs). +::: + +### When nothing is recorded + +`addBreadcrumb` does nothing when `captureBreadcrumbs` is `false`, or once the collector has switched the SDK off for your app. + +## Filter breadcrumbs + +`setBreadcrumbFilter(filter)` installs a function that sees every breadcrumb before it is recorded: yours, the automatic ones and the adapters'. Return the breadcrumb, changed or not, to keep it, or `null` to drop it. Pass `null` to remove the filter. + +```ts +import { bugsee } from './bugsee'; + +const SECRET_PARAMS = /([?&](?:token|access_token|code|session)=)[^&#\s]*/gi; + +bugsee.setBreadcrumbFilter((crumb) => { + // Drop a whole category of your own breadcrumbs + if (crumb.category === 'auth') { + return null; + } + return { + ...crumb, + message: crumb.message?.replace(SECRET_PARAMS, '$1'), + // Remove data you do not want on a report + data: crumb.data === undefined ? undefined : { ...crumb.data, email: undefined }, + }; +}); +``` + +The filter receives a `Breadcrumb`, which is the fields above with `timestamp` always set. + +Rules: + +- **A filter that throws drops the breadcrumb.** The error goes to `onError`, and nothing unredacted is recorded. +- **There is one filter at a time.** A later call replaces it. Set it right after `launch`. Breadcrumbs recorded before the filter is installed are kept as they are. `relaunch()` returns a new client, so set the filter again on it. +- **Your network filter does not reach breadcrumbs.** If a breadcrumb of yours carries a URL, redact it here. See [Privacy: Breadcrumbs](/sdk/javascript/privacy/breadcrumbs). + +## Related pages + +- [Privacy: Breadcrumbs](/sdk/javascript/privacy/breadcrumbs) — keep sensitive data out of the trail. +- [Console logs](/sdk/javascript/logs) — unstructured log lines. +- [Events & traces](/sdk/javascript/events-and-traces) — your own named events and values. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/configuration.mdx b/docs/sdk/javascript/configuration.mdx new file mode 100644 index 00000000..8f756c76 --- /dev/null +++ b/docs/sdk/javascript/configuration.mdx @@ -0,0 +1,333 @@ +--- +title: "Configuration" +description: "Launch options of the Bugsee JavaScript SDK: shared options, then browser, Node.js and Bun, Electron, edge and worker options, extension options, invalid-value rules and reading options back." +sidebar_position: 2 +slug: "/sdk/javascript/configuration" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +You configure the SDK with the options object you pass as the second argument of `launch(appToken, options)`. Every option is optional. Option names are plain camelCase names, such as `captureNetwork`. The same names work on every runtime that has the option. + + + + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + appVersion: '1.4.2', + appBuild: '381', + captureNetworkBodies: false, + maxRecordingTime: 30, + onError: (error) => console.error(error), +}); +``` + + + + +```js +import { launch } from '@bugsee/bugsee'; + +launch('', { + appVersion: '1.4.2', + appBuild: '381', + captureNetworkBodies: false, + maxRecordingTime: 30, + onError: (error) => console.error(error), +}); +``` + + + + +Which options exist depends on the runtime. This page has a section for each: + +- [Shared options](#shared-options): every runtime. +- [Browser](#browser). +- [Node.js and Bun](#nodejs-and-bun). +- [Electron](#electron). +- [Edge and workers](#edge-and-workers): Cloudflare Workers, Vercel Edge, Web and Service Workers. +- [Extension options](#extension-options): performance, trace propagation and OpenTelemetry, from the umbrella package. + +The TypeScript types are the exact reference for your version: `BugseeLaunchOptionsWithPerformance` in the browser and `BugseeNodeLaunchOptions` on Node.js, both exported from `@bugsee/bugsee`. + +## Invalid values + +The SDK checks every option it reads. An invalid value never throws. It is reported through `onError`, and the option takes a safe value: + +- **On-by-default capture options turn off.** `captureLogs`, `captureNetwork`, `captureNetworkBodies`, `captureSystemTraces`, `captureSystemEvents` and `captureBreadcrumbs` are on by default. A value that is not `true` or `false` (`0`, `null`, `''`, `'false'`) turns the option off, so a mistake never leaves capture running. +- **Options that collect more data stay off.** Only `true` (or an options object, where one is accepted) turns on an option that defaults to off, such as `captureLocalVariables`, `captureSourceContext` and `captureUserIdle`. +- **Other options keep their default.** For instance `detectCrashes` and `captureNetworkDefaultSanitizer` keep their default, which is on. +- **Protective options stay protective.** `startInBlackout` and `diskProtection` treat any value other than `false` as on. + +Pass `onError` while you integrate, so you see these messages. + +## Shared options + +These options exist on every runtime. Where a default differs by runtime, the table says so. + +### App identity + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `endpoint` | `string` | `https://api.bugsee.com` | API origin, without a trailing slash. | +| `appId` | `string` | none | Package or bundle identifier of your app. | +| `appVersion` | `string` | detected | Version of your app. Detected from build-time constants, then the environment, then `package.json` (servers) or meta tags (browser). Falls back to `0.0.0`. See [Installation](/sdk/javascript/installation#app-version-and-build). | +| `appBuild` | `string` | detected | Build of your app, detected the same way. | +| `sdkVersion` | `string` | package version | SDK version reported in the environment. You rarely need to set it. | + +### Capture + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Capture console output as logs. See [Console logs](/sdk/javascript/logs). | +| `captureLogsLevel` | `'error' \| 'warning' \| 'info' \| 'debug' \| 'verbose'` or `1`-`5` | `'verbose'` | Lowest log level to capture. | +| `captureNetwork` | `boolean` | `true` | Capture network requests. See [Network events](/sdk/javascript/network). | +| `captureNetworkBodies` | `boolean` | `true` | Capture request and response bodies. | +| `maxNetworkBodySize` | `number` | `20480` | Largest body to capture, in bytes. | +| `captureNetworkBodyWithoutType` | `boolean` | `false` | Capture a body even when its `Content-Type` is missing or blank. | +| `captureNetworkDefaultSanitizer` | `boolean` | `true` | Apply the built-in redaction to URLs, headers, bodies and error text. A network filter you set replaces it; see [Privacy: Network](/sdk/javascript/privacy/network). | +| `captureBreadcrumbs` | `boolean` | `true` | Capture breadcrumbs. Mobile Bugsee SDKs default this to off; JavaScript keeps it on. See [Breadcrumbs](/sdk/javascript/breadcrumbs). | +| `captureSystemTraces` | `boolean` | `true` | Capture periodic system traces (memory, CPU, event-loop lag and so on, depending on the runtime). | +| `captureSystemEvents` | `boolean` | `true` | Capture system events (process or page lifecycle and similar). | +| `maxRecordingTime` | `number` | `60` | Rolling recording window, in seconds. | +| `maxDataSize` | `number` | `50` Node.js and Bun and Electron main, `20` browser (`30` with the IndexedDB store), `10` edge and workers | Size of the rolling capture buffer, in megabytes. | + +### Detection and reporting + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectCrashes` | `boolean` | `true` | Detect uncaught errors and unhandled promise rejections. See [Errors & crashes](/sdk/javascript/issue-detection/errors-and-crashes). | +| `detectHttpErrors` | `boolean` | `false` | Report HTTP 5xx responses as `error` reports, once per session for each method, templated URL and status. 4xx responses, transport failures and aborted requests are not reported. See [HTTP errors](/sdk/javascript/issue-detection/http-errors). | +| `reportDefaultCrashPriority` | priority | `'blocker'` | Severity a crash report starts with. | +| `reportDefaultErrorPriority` | priority | `'high'` | Severity an error report starts with. | +| `reportDefaultBugPriority` | priority | `'high'` | Severity a bug report starts with when none is given. The browser report dialog pre-selects it. | +| `notifyFlushDelay` | `number` | `0` | `notify()` batching window, in milliseconds. `0` sends as soon as the current tick ends. | + +A priority is one of `'verylow'`, `'low'`, `'medium'`, `'high'`, `'critical'` or `'blocker'`. + +### Callbacks + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `onError` | `(error: unknown) => void` | no-op | Receives internal SDK problems: invalid options, a failed provider, a repeated `launch()`, a missing token. | +| `lifecycleEventsListener` | `(eventType: string, data?: unknown) => void` | none | Observes launch, stop, blackout and report events, from the very first `Launching` event. See [Lifecycle & status](/sdk/javascript/lifecycle#lifecycle-events). | + +## Browser + +These options apply to the browser build, and so also to the browser side of the framework adapters and to Electron renderers. + +### Capture and persistence + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureInteractions` | `boolean` | `true` | Capture user interactions: presses become entries of the SDK's input stream, and changes, submits and focus become UI breadcrumbs. | +| `captureViewHierarchy` | `boolean` | `true` | Capture the DOM view hierarchy when a report is made. | +| `captureUrl` | `boolean` | `true` | Record the page address, sanitized, as the `url` system trace. Needs `captureSystemTraces`. | +| `urlSanitizer` | `(url: string) => string \| null` | none | Your own sanitizer for the `url` trace. It runs after the default one and gets its result. Return `null` to record nothing for that URL. A throw records nothing. | +| `captureAsyncOrigins` | `boolean` | `true` | Record where asynchronous platform calls (such as `video.play()`) were made, so a rejection with no stack still has a call site. Only `false` opts out. | +| `captureEnvironmentHints` | `boolean` | `true` | Observe hints such as a private-browsing heuristic, reported as a system event. | +| `captureUserIdle` | `boolean` | `false` | Record the `user_idle_state` trace. Only works when the page's idle-detection permission is already granted; the SDK never asks for it. | +| `persistUserIdentifier` | `boolean` | `false` | Keep the user identifier set with `setUserIdentifier` in `localStorage`, so it survives a reload. Off by default because the identifier is often personal data and a browser can be shared. Call `clearUserIdentifier()` on logout. | +| `startInBlackout` | `boolean` | `false` | Launch with a blackout already in force, so visual and interaction capture stays off until `endBlackout()`. See [Lifecycle & status](/sdk/javascript/lifecycle#blackout). | +| `persist` | `boolean` | on when the page has IndexedDB and Web Locks | Keep the capture window and the report queue in IndexedDB so they survive a reload. `true` forces it, `false` keeps everything in memory. | +| `recover` | `boolean` | `true` | Re-upload a report left behind by an earlier reload or crash. Needs a persistent store. | +| `captureDiskSpace` | `boolean` | `false` | Add low-storage states to the `capture` trace. Needs a durable store. | +| `diskProtection` | `boolean` | `true` | Stop persisting replay, log and network data when the browser's storage quota runs low. Only `false` opts out. | + +### Session replay + +`replay` is on by default and masks aggressively. Pass `false` to turn it off, or an object to tune it. See [Session replay](/sdk/javascript/session-replay) and [Privacy: Session replay](/sdk/javascript/privacy/replay). + +```ts +launch('', { + replay: { + maskTextSelector: '.account-balance', + blockSelector: '.secret-panel', + canvas: { fps: 2, quality: 0.6 }, + }, +}); +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `replay` | `boolean \| object` | `true` | `false` disables replay. An invalid value (`null`, `0`, a string, an array) turns it off and is reported. | +| `replay.maskAllText` | `boolean` | `true` | Mask every text node. | +| `replay.maskAllInputs` | `boolean` | `true` | Mask every input value. | +| `replay.blockAllMedia` | `boolean` | `true` | Block all media and iframes. | +| `replay.blockAllCanvas` | `boolean` | `false` | Block every canvas except those marked to show. | +| `replay.maskTextSelector` | `string` | none | CSS selector of extra elements whose text to mask. | +| `replay.blockSelector` | `string` | none | CSS selector of extra elements to block. | +| `replay.ignoreSelector` | `string` | none | CSS selector of elements whose input events to ignore. | +| `replay.checkoutEveryNms` | `number` | `60000` | Interval, in milliseconds, between full snapshots. It bounds the retained window. | +| `replay.canvas` | `boolean \| { fps?, quality?, imageType? }` | off | Opt-in canvas recording. Defaults when on: `fps` 2, `quality` 0.6, `imageType` `'image/webp'`. It records pixels without masking, so use it only for canvases without sensitive content. | + +Replay needs a DOM. In a DOM-less host, such as a server-side render pass, nothing is recorded whatever this option says. + +### Report dialog + +These options shape the dialog that `showReportDialog()` shows; see [Bug reporting](/sdk/javascript/manual/bug-reporting). + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `reportSummaryRequired` | `boolean` | `false` | The summary must be filled in before Send. | +| `reportDescriptionRequired` | `boolean` | `false` | The description must be filled in. | +| `reportEmailRequired` | `boolean` | `false` | The reporter's email must be filled in. | +| `reportLabelsEnabled` | `boolean` | `false` | Show the labels field. | +| `reportLabelsRequired` | `boolean` | `false` | At least one label is required. Only with `reportLabelsEnabled`. | +| `reportPrioritySelectorEnabled` | `boolean` | `false` | Show the severity picker. | + +## Node.js and Bun + +These options apply to `@bugsee/bugsee` on Node.js, to `@bugsee/bun`, and to the main process of Electron. Bun takes the same options as Node.js, with the exceptions noted. + +### Process and capture buffer + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appRoot` | `string` | `process.cwd()` | Application root, used to turn stack-frame paths into relative ones. Pass `''` to keep absolute paths. | +| `deviceId` | `string` | none | Device identifier. The SDK never generates or stores one on a server. | +| `appIdentitySource` | `() => { version?, build? } \| undefined` | none | An extra place to look for the version and build, consulted after build-time constants and before the environment and `package.json`. | +| `unhandledRejections` | `'preserve' \| 'warn' \| 'none'` | `'preserve'` | `'preserve'` captures the rejection, then reproduces Node.js's own outcome (print and exit with code 1). `'warn'` captures and prints but keeps the process alive. `'none'` installs no listener. | +| `exitOnUncaught` | `boolean` | `true` | Flush the crash report, then exit with code 1 after an uncaught exception. Does not affect rejections. | +| `shutdownTimeoutMs` | `number` | `3000` | Time budget, in milliseconds, to flush the crash report before exiting. | +| `recover` | `boolean` | `true` | Store each report durably before upload and re-upload any left behind by a crashed or killed run on the next launch. Needs the on-disk store. | +| `capturedDataStore` | `'disk' \| 'memory'` | `'disk'` | Where the rolling capture buffer lives. `'memory'` gives up durable capture and crash recovery. | +| `dataDir` | `string` | `/bugsee/...` | Directory for on-disk data. Several processes can share one directory safely; each uses its own subdirectory. | +| `dataRootBase` | `string` | `os.tmpdir()` | Base for the default data directory. Ignored when `dataDir` is set. | +| `captureWriter` | `'inline' \| 'worker'` | `'inline'` | `'worker'` writes capture data from a worker thread, so a slow disk never blocks your code. | +| `captureDiskSpace` | `boolean` | `false` | Report free and total disk space of the data volume as system traces. | +| `diskProtection` | `boolean` | `true` | Below 50 MiB free the on-disk store stops persisting replay, log and network data; below 10 MiB it persists nothing. The in-memory window is kept either way. Only `false` opts out. | + +### Diagnostics + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectHangs` | `boolean` | `true` | Detect a blocked event loop and report an `AppHang`. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `hangFairMs` | `number` | `3000` | Block duration, in milliseconds, reported as `AppHang::Fair`. | +| `hangMediumMs` | `number` | `5000` | Block duration reported as `AppHang::Medium`. | +| `hangSevereMs` | `number` | `10000` | Block duration reported as `AppHang::Severe`. | +| `profiling` | `boolean` | `false` | Attach a rolling V8 CPU profile (`profile.json`) to reports. Costs some overhead. | +| `profilingSamplingIntervalMicros` | `number` | `1000` | CPU profiler sampling interval, in microseconds. | +| `captureLocalVariables` | `boolean \| object` | `false` | Capture the local variables in scope at a throw, onto the stack frames. Always off on Bun. | +| `captureSourceContext` | `boolean \| object` | `false` | Attach the source lines around each throwing application frame. It uploads your source code, so it is opt-in. | + +`captureLocalVariables` costs about 3% steady-state because it enables the V8 debugger, and pausing on caught exceptions costs more on every throw. Variable names that look sensitive are redacted and values are truncated, but a variable can still hold personal data. Pass an object to tune it: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `includeCaught` | `boolean` | `false` | Also capture at caught exceptions, not only uncaught ones. Costly in code that uses exceptions for control flow. | +| `maxFrames` | `number` | `5` | Frames to capture. | +| `maxVariables` | `number` | `20` | Variables per frame. | +| `maxValueLength` | `number` | `120` | Longest captured value, in characters. | +| `maxCaughtPerSecond` | `number` | `50` | Rate limit for caught exceptions. Uncaught exceptions are never limited. | + +`captureSourceContext` takes an object with these keys: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `contextLines` | `number` | `5` | Lines before and after the throwing line. | +| `maxFrames` | `number` | `5` | Frames to attach source to. | +| `maxLineLength` | `number` | `200` | Longest line kept, in characters. | + +See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). + +### Incoming requests and trace propagation + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `instrumentIncomingRequests` | `boolean` | `true` | Instrument incoming requests on `node:http` servers and `Bun.serve`: a per-request context and an `http.server` transaction. Only `false` opts out; an invalid value is treated as off and reported. See [Backend overview](/sdk/javascript/backend/overview). | +| `propagateTrace` | `boolean` | `true` | Add the W3C `traceparent` header and a `bugsee` trace state to outgoing requests. Nothing is added unless the URL matches `tracePropagationTargets`. | +| `tracePropagationTargets` | `Array` | none | Which outgoing URLs may receive trace headers (substring or regular expression). List your own services only. | +| `traceResponse` | `{ traceresponse?, serverTiming?, timingAllowOrigin? }` | off | Add trace context to incoming responses so a browser frontend can adopt the backend's span. | + +## Electron + +`launchMain(appToken, options)` in the main process takes every Node.js option above, plus: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `ipcMain` | Electron `ipcMain` | required | Used to receive capture from renderers and to control them. | +| `app` | Electron `app` | none | Reports `app.getVersion()` as the app version, process metrics, and renderer-gone events. | +| `powerMonitor` | Electron `powerMonitor` | none | Enables power and thermal events and traces. | +| `screen` | Electron `screen` | none | Enables display events and the `displays` trace. Pass it after the app is ready. | +| `BrowserWindow` | Electron `BrowserWindow` | none | Tracks windows that already exist. | +| `gpuInfoType` | `'basic' \| 'complete'` | `'basic'` | Detail level of the GPU information read from `app.getGPUInfo`. | +| `captureWindowEvents` | `boolean` | `true` | Window focus, show and hide events and renderer responsiveness. Needs `app`. | +| `crashReporter` | Electron `crashReporter` | none | Enables native crash collection. | +| `crashReporterExtra` | `Record` | none | Extra fields sent with native crashes. | +| `video` | `{ source, ... }` | off | Opt-in pixel video next to the default DOM replay. | + +`launchRenderer(appToken, options)` takes the browser options above. Replay is on and streams to the main process. See [Electron](/sdk/javascript/platforms/electron). + +## Edge and workers + +Cloudflare Workers, Vercel Edge and Web or Service Workers take the shared options above, with these changes: `maxDataSize` defaults to `10` and there are no options for disk, hangs or profiling. Edge runtimes buffer in memory and upload only when an incident happens. + +| Option | Applies to | Type | Default | Description | +| --- | --- | --- | --- | --- | +| `partitionCaptureByTenant` | Cloudflare, Vercel Edge | `boolean` | `true` on Cloudflare, `false` on Vercel Edge | Keep a separate capture buffer for each tenant so one isolate serving several tenants never mixes their data. | +| `maxTenantPartitions` | Cloudflare, Vercel Edge | `number` | `8` | Tenant buffers kept. The `maxDataSize` budget is divided across them. | +| `asyncLocalStorage` | Cloudflare, Vercel Edge | object | probed from `globalThis` | The async store for per-request context. Supply it where the runtime does not expose one. | +| `platformType` | Vercel Edge, Cloudflare, Web and Service Workers | string | Vercel Edge `'edge-light'`, Cloudflare `'workers'`; workers are detected (`'service-worker'` inside a Service Worker, else `'web-worker'`) | Runtime identity reported with a report. Set `'service-worker'` explicitly if detection fails. | +| `persist` | Web Workers, Service Workers | `boolean` | `true` for Service Workers, `false` for Web Workers | Keep report bundles in IndexedDB and re-upload any a stopped worker left behind. | +| `recover` | Web Workers, Service Workers | `boolean` | `true` | Re-upload a bundle left behind by an earlier activation. | + +See [Cloudflare](/sdk/javascript/platforms/cloudflare), [Vercel Edge](/sdk/javascript/platforms/vercel-edge) and [Web Workers](/sdk/javascript/platforms/web-workers). + +## Extension options + +`@bugsee/bugsee` adds performance monitoring and OpenTelemetry on top of the platform build, and these options on top of the platform options. The bare platform packages do not have them. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `performanceMonitoring` | `boolean` | `true` | Master switch for web vitals and performance transactions. | +| `performanceSampleRate` | `number` | `1` | Fraction of transactions to keep, from 0 to 1. Errors are never sampled. | +| `performanceUploadMode` | `'batched' \| 'realtime'` | `'batched'` | Upload on an interval, or per transaction. | +| `performanceFlushIntervalMs` | `number` | `30000` | Interval for batched uploads, in milliseconds. | +| `pageName` | `string` | current path, or `pageload` | Name of the page-load transaction (browser). | +| `traceNavigations` | `boolean` | `true` | Open a `navigation` transaction for each single-page route change (browser). | +| `traceInteractions` | `boolean` | `true` | Open a `ui.interaction` transaction for slow user interactions (browser). | +| `propagateTrace` | `boolean` | browser `false`, server `true` | Add `traceparent` and trace state to outgoing requests. In the browser, same-origin requests propagate and other origins need `tracePropagationTargets`. | +| `tracePropagationTargets` | `Array` | none | URLs allowed to receive trace headers. | +| `tracePropagationOrigin` | `string` | `location.origin` | Browser: the origin treated as same-origin. | +| `appStartTimeMs` | `number` | process start time | Server: start time used for the startup transaction. | +| `otelExportUrl` | `string \| URL` | none | OTLP/HTTP JSON traces endpoint. When set, finished transactions are also exported there, and Bugsee still receives them. | +| `otelExportHeaders` | `Record` | none | Headers for the OTLP export, lowercase keys. | +| `otelExportResource` | `Record` | none | OTLP resource attributes. | +| `otelConsume` | `boolean` | `false` | Turn your OpenTelemetry spans into Bugsee transactions. | +| `onOtelSpanProcessor` | `(processor) => void` | none | Receives the span processor to register on your `TracerProvider`. | + +The performance and propagation options need `performanceMonitoring` on. See [Performance](/sdk/javascript/performance) and [OpenTelemetry](/sdk/javascript/opentelemetry). + +## Reading options back + +The client reports what is in effect: + +```ts +const bugsee = await launch('', { maxRecordingTime: 30 }); + +bugsee.getLaunchOptions(); // effective options, defaults applied +bugsee.getHostLaunchOptions(); // only the options you passed +``` + +Both return a plain object keyed by the canonical option identifier, `com.bugsee.option.*` (for example `com.bugsee.option.capture.network`), the names shared by the Bugsee SDKs on every platform. Option objects such as `replay` or `captureLocalVariables` appear as `true`. + +## Options kept by `relaunch()` + +`relaunch(options)` starts from defaults, as the mobile SDKs do: the options you pass replace the previous ones, and omitted options go back to their default. Identity and integration settings are kept from the previous launch: `endpoint`, `appId`, `appVersion`, `appBuild`, `appRoot`, `dataDir`, `onError`, and the network, log and breadcrumb filters and `urlSanitizer` you set. See [Lifecycle & status](/sdk/javascript/lifecycle#relaunch). + +## Related pages + +- [Installation](/sdk/javascript/installation) — add the package and launch the SDK. +- [Lifecycle & status](/sdk/javascript/lifecycle) — launch, stop, relaunch and events. +- [Privacy](/sdk/javascript/privacy/overview) — masking and redaction options. +- [Diagnostics](/sdk/javascript/issue-detection/diagnostics) — profiling, local variables and source context. +- [Packages](/sdk/javascript/packages) — which package takes which options. diff --git a/docs/sdk/javascript/events-and-traces.md b/docs/sdk/javascript/events-and-traces.md new file mode 100644 index 00000000..daf58138 --- /dev/null +++ b/docs/sdk/javascript/events-and-traces.md @@ -0,0 +1,100 @@ +--- +title: "Custom events & traces" +description: "Record your own events and traces on the report timeline with the Bugsee JavaScript SDK: event and trace, what the SDK records on its own, and the options that control system data." +sidebar_position: 23 +slug: "/sdk/javascript/events-and-traces" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Events and traces are the two ways to put your own data on the report timeline: + +- An **event** is something that happened at a moment in time: `checkout_started`, `coupon_applied`. It has a name and optional parameters. +- A **trace** is a named value that changes over time: `cart_size`, `queue_length`. Each call adds one point to the curve. + +The examples use the client returned by `launch`, kept in a module of your own: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +## Custom events + +```ts +import { bugsee } from './bugsee'; + +bugsee.event('checkout_started'); +bugsee.event('coupon_applied', { code: 'SPRING', discountPercent: 15 }); +``` + +`event(name, params?)` takes a `string` name and an optional object of parameters. The SDK stamps the time of the call. Parameters travel with the report as JSON, so keep them to strings, numbers, booleans, arrays and plain objects. + +## Custom traces + +```ts +import { bugsee } from './bugsee'; + +bugsee.trace('cart_size', 3); +bugsee.trace('queue_length', 120); +bugsee.trace('current_plan', 'pro'); +``` + +`trace(name, value)` takes a `string` name and a value. Use a number for a value you want to see as a curve. + +## What these calls do not do + +- They do nothing after the SDK has been switched off for your app. +- There is no filter for events and traces. Whatever you pass is recorded, so do not put personal data or secrets in names or parameters. +- The SDK validates nothing here. A name or value that cannot be serialized as JSON can be lost. + +:::note +Events and traces you record are kept apart from the ones the SDK records itself. The SDK never writes into your event and trace streams, and you never overwrite its own. +::: + +## What the SDK records by itself + +Besides your own data, the SDK records **system events** and **system traces**. They appear on the same timeline. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureSystemEvents` | `boolean` | `true` | Record system events, such as the process start and, in the browser, the page being hidden. | +| `captureSystemTraces` | `boolean` | `true` | Record system traces, such as memory use, in a browser also the sanitized page address, and on Node.js the process metrics. | + +```ts +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch('', { + captureSystemEvents: true, + captureSystemTraces: false, +}); +``` + +A malformed value turns the option off and is reported through the `onError` launch option. For the options that tune individual browser traces, see [Configuration](/sdk/javascript/configuration). + +## Route and view + +`setRoute(route)` and `setView(view)` record the screen the user is on as system traces. Framework adapters call them for you on every navigation. Call them yourself when your app has its own router. + +```ts +import { bugsee } from './bugsee'; + +// Pass the route PATTERN, never the URL with real ids +bugsee.setRoute('/orders/:id'); + +// A name, or a name and the type of view +bugsee.setView({ name: 'OrderDetails', type: 'page' }); +bugsee.setView(null); // no view +``` + +`setRoute` expects a router pattern. The SDK strips any query and fragment, redacts an email address in a path segment, and clips the string at 1024 characters. A value that is empty or not a string is ignored. These traces are written where the platform records a page or screen: the browser, and an Electron renderer. On Node.js and the edge runtimes the call is accepted and writes nothing. + +## Related pages + +- [Breadcrumbs](/sdk/javascript/breadcrumbs) — a structured trail of steps. +- [User & session data](/sdk/javascript/user-session-data) — attach an identifier and attributes to every report. +- [Console logs](/sdk/javascript/logs) — text lines on the timeline. +- [Performance](/sdk/javascript/performance) — transactions, spans and web vitals. diff --git a/docs/sdk/javascript/faq.md b/docs/sdk/javascript/faq.md new file mode 100644 index 00000000..f9bafecd --- /dev/null +++ b/docs/sdk/javascript/faq.md @@ -0,0 +1,140 @@ +--- +title: "FAQ" +description: "Practical questions and answers about the Bugsee JavaScript SDK (beta): runtimes, packages, tokens, privacy defaults, errors that are not reported and known beta behavior." +sidebar_position: 22 +slug: "/sdk/javascript/faq" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +**1. Which runtimes does the SDK support?** + +Browsers, Node.js 18 or later, and Bun 1.1.13 or later are the main targets. Electron, Cloudflare Workers, Vercel Edge, and Web and Service Workers are supported through their own packages. Deno is not supported. See [Overview](/sdk/javascript/overview#requirements). + +
+ +**2. Which package do I install?** + +For a browser app or a Node.js server, `@bugsee/bugsee`. For Bun, Electron, Cloudflare, Vercel Edge and workers, the package named for the runtime. Frameworks add an adapter. The table in [Installation](/sdk/javascript/installation#1-add-the-package) lists them all, and [Packages](/sdk/javascript/packages) explains the rest. + +
+ +**3. Should I install `@bugsee/browser`, `@bugsee/node` or `@bugsee/core`?** + +No. Those are the building blocks the umbrella and the other packages are made from. Their APIs can change without notice. Install `@bugsee/bugsee` or the package for your runtime. + +
+ +**4. Is there an SDK for React Native, or for web content inside a native app?** + +React Native has its own SDK; see the [React Native documentation](/sdk/react_native/overview). Web content shown in a native WebView is covered by the native Bugsee SDKs. + +
+ +**5. What do the npm `latest` and `beta` tags mean?** + +For now both point at the current beta, so installing with or without `@beta` gets the same version. Use `@beta` to keep following betas once a stable release exists, and keep all `@bugsee/*` packages at the same version. See [Release notes](/sdk/javascript/release-notes). + +
+ +**6. `launch()` does not throw, but nothing is captured.** + +A missing, empty or non-string token returns a disabled client and reports one message through `onError` (or `console.warn` when you gave none). Check that the token reaches your code at runtime; an environment variable that is not set, or that your bundler does not expose to browser code, is the usual cause. See [Installation](/sdk/javascript/installation#troubleshooting). + +
+ +**7. Why does `launch()` return a `Promise` in the browser but not on Node.js?** + +In the browser the launch is asynchronous, because part of the SDK (session replay) is loaded on demand. Servers, edge runtimes and workers return the client directly. Await the browser result only when you need the client right away; capture starts either way. See [Lifecycle & status](/sdk/javascript/lifecycle#launch). + +
+ +**8. I called `launch()` twice and my second options were ignored.** + +Bugsee is a per-process singleton. A second call returns the existing client and reports the repeat through `onError`. Use `relaunch(options)` to restart with new options; it starts from defaults, not from your previous options. See [Lifecycle & status](/sdk/javascript/lifecycle#relaunch). + +
+ +**9. What is captured by default, and is it safe for personal data?** + +Console logs, network requests (with request and response bodies), breadcrumbs, system traces and events, and in the browser a DOM replay and interactions. Replay masks all text and inputs and blocks media by default. Network URLs, headers and bodies pass through a built-in redaction (sensitive headers and keys, and secret-looking values). Redaction is a safety net, not a guarantee: review what your app sends, and use the filters. See [Privacy](/sdk/javascript/privacy/overview). + +
+ +**10. I set a network filter and sensitive data showed up.** + +A network filter you set with `setNetworkEventFilter` replaces the default redaction instead of adding to it. Compose your filter with the default one by calling `getDefaultNetworkSanitizer()` inside it. See [Privacy: Network](/sdk/javascript/privacy/network). + +
+ +**11. Breadcrumbs are on although the mobile SDKs default them to off.** + +Yes. In JavaScript, `captureBreadcrumbs` defaults to `true`, because UI interactions are a core signal on the web. Set `captureBreadcrumbs: false` to turn them off. See [Breadcrumbs](/sdk/javascript/breadcrumbs). + +
+ +**12. An error in my framework is not reported.** + +Many frameworks catch errors before they reach the global handler, so the SDK never sees them. Add the adapter for your framework: React needs its error boundary, Vue needs `installBugseeErrorHandler` in production, Angular needs `BugseeErrorHandler`, and backend frameworks need their adapter's error hook. On the backend, 4xx errors are skipped by default. See [Frameworks](/sdk/javascript/frameworks/react) and [Backend overview](/sdk/javascript/backend/overview). + +
+ +**13. My Node.js process exits after an uncaught exception. Is that the SDK?** + +The SDK flushes the crash report first, then exits with code 1, as Node.js would. That is `exitOnUncaught: true`, the default. Unhandled rejections follow `unhandledRejections`: the default `'preserve'` captures them and then reproduces Node.js's own outcome. See [Configuration](/sdk/javascript/configuration#process-and-capture-buffer). + +
+ +**14. A short script finishes before its report is uploaded.** + +Await `bugsee.flush()` or `bugsee.stop()` before exiting. A long-running server does not need to. See [Lifecycle & status](/sdk/javascript/lifecycle#flush-and-stop). + +
+ +**15. Where does the SDK write data on a server, and what if the filesystem is read-only or ephemeral?** + +By default on Node.js and Bun the SDK keeps its rolling capture buffer and report queue on disk under `/bugsee`, so a crash or kill still delivers its recording on the next launch. Set `dataDir` to move it. On a read-only or throwaway filesystem, set `capturedDataStore: 'memory'`, which gives up durable capture and recovery. See [Configuration](/sdk/javascript/configuration#process-and-capture-buffer). + +
+ +**16. Why is `captureLocalVariables` or `captureSourceContext` off?** + +Both are opt-in by design. Local variables cost steady overhead and can contain personal data, and source context uploads your source code. `captureLocalVariables` does not work on Bun at all. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). + +
+ +**17. My stack traces are minified.** + +Upload source maps for each release, with the same version and build you pass to `launch()`. The Vite and webpack plugins do it at build time; other build tools use `bugsee-cli`. Angular needs the CLI step. See [Symbolication](/sdk/javascript/symbolication/overview). + +
+ +**18. Reports show version `0.0.0`.** + +The SDK could not detect your app version. Pass `appVersion` to `launch()`, set `BUGSEE_APP_VERSION`, or give your `package.json` a version. See [Installation](/sdk/javascript/installation#app-version-and-build). + +
+ +**19. Does `RelaunchedAfterCrash` always mean a crash?** + +No. It is a hint based on evidence left on storage. It can report a crash that did not happen, and miss one that did. See [Lifecycle & status](/sdk/javascript/lifecycle#lifecycle-events). + +
+ +**20. `logException` seems to send fewer reports than I call it.** + +Identical errors are deduplicated, and `logException` is rate-limited to 100 reports per 60 seconds. Errors are not sampled; only performance transactions have a sample rate (`performanceSampleRate`). See [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting). + +
+ +**21. Which bundlers are supported for source maps?** + +Vite and webpack have dedicated plugins and are the best exercised. Rollup, esbuild and Rspack use the shared plugin engine and are less exercised. Other tools can use `bugsee-cli` directly. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). + +
+ +**22. Is the SDK stable?** + +It is in beta. APIs, options and defaults can change between betas, and the internal packages carry no stability promise at all. Read the [release notes](/sdk/javascript/release-notes) before updating. diff --git a/docs/sdk/javascript/frameworks/angular.mdx b/docs/sdk/javascript/frameworks/angular.mdx new file mode 100644 index 00000000..de5b82d2 --- /dev/null +++ b/docs/sdk/javascript/frameworks/angular.mdx @@ -0,0 +1,164 @@ +--- +title: "Angular" +description: "Set up the Bugsee JavaScript SDK in an Angular app with @bugsee/angular: the ErrorHandler, Router route names, and uploading source maps with the CLI." +sidebar_position: 3 +slug: "/sdk/javascript/frameworks/angular" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/angular` adds Angular-specific error reporting to the [browser SDK](/sdk/javascript/platforms/browser): an `ErrorHandler` that reports uncaught errors, and route naming from the Angular Router. + +## Requirements + +- Angular 16 or newer: `@angular/core` and `@angular/router` are peer dependencies. +- An application token. + +## Install + +Install the umbrella, which provides `launch()`, next to the adapter. + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/angular@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/angular@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/angular@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/angular@beta +``` + + + + +## Set up + +Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away. + +```ts title="main.ts" +import { launch } from '@bugsee/bugsee'; + +launch(''); +``` + +Register the Bugsee error handler in place of Angular's default `ErrorHandler`: + +```ts title="app.config.ts" +import { ErrorHandler } from '@angular/core'; +import { BugseeErrorHandler } from '@bugsee/angular'; + +bootstrapApplication(AppComponent, { + providers: [{ provide: ErrorHandler, useClass: BugseeErrorHandler }], +}); +``` + +`BugseeErrorHandler` reports the error to Bugsee, then runs Angular's default handler so the console output stays. It unwraps Angular's own error wrapper where one exists, so the report shows the real error. + +To chain a handler of your own instead, build one with `createAngularErrorHandler`: + +```ts +import { ErrorHandler } from '@angular/core'; +import { createAngularErrorHandler } from '@bugsee/angular'; + +providers: [ + { + provide: ErrorHandler, + useFactory: () => createAngularErrorHandler({ delegate: myHandler }), + }, +]; +``` + +### Route names (Angular Router) + +Name the active navigation after the matched route pattern. Call `setRouteNameFromRouter(router)` on each `NavigationEnd` event: + +```ts +import { NavigationEnd, Router } from '@angular/router'; +import { setRouteNameFromRouter } from '@bugsee/angular'; +import { filter } from 'rxjs'; + +constructor(router: Router) { + router.events + .pipe(filter((event) => event instanceof NavigationEnd)) + .subscribe(() => setRouteNameFromRouter(router)); +} +``` + +## API + +`@bugsee/angular` also re-exports everything from `@bugsee/bugsee`. + +| Export | Description | +| --- | --- | +| `BugseeErrorHandler` | `ErrorHandler` class that reports, then runs Angular's default handler. | +| `createAngularErrorHandler(options?)` | Builds an `ErrorHandler`-shaped object. The `delegate` option is the handler to run after reporting. | +| `reportAngularError(error, options?)` | Reports an error you caught yourself. | +| `setRouteNameFromRouter(router)` | Names the active navigation after the matched route. | +| `createBugseeRenderTracker()` | Records render timing for performance monitoring. | + +## Launch options + +`launch(appToken, options)` accepts all [browser options](/sdk/javascript/platforms/browser#browser-options). The most relevant: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Capture console output. | +| `captureNetwork` | `boolean` | `true` | Capture network requests. | +| `maxRecordingTime` | `number` | `60` | Seconds of recording to keep. | +| `replay` | `boolean` or object | `true` | Session replay settings, or `false` to turn replay off. | +| `captureInteractions` | `boolean` | `true` | Capture user interactions. | + +## Source maps + +The Angular builder does not accept bundler plugins, so there is no plugin for it. Add the Bugsee CLI as a step after `ng build`: it injects debug IDs into the built files and uploads the source maps. + +```bash +ng build --source-map +export BUGSEE_APP_TOKEN= +bugsee-cli sourcemaps inject dist//browser +bugsee-cli debug-files upload dist//browser --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD" +``` + +Run `inject` before you deploy. If you turn on `"subresourceIntegrity": true`, `inject` refuses to run unless you pass `--allow-sri`; see [Manual source map upload](/sdk/javascript/symbolication/manual) for details. + +## Verify + +Throw from a click handler or a component: + +```ts +onClick() { + throw new Error('Bugsee test error'); +} +``` + +Trigger it. The error shows up in the Bugsee dashboard. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — launch options, persistence and replay +- [Manual source map upload](/sdk/javascript/symbolication/manual) — the CLI recipe for Angular +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs +- [Privacy](/sdk/javascript/privacy/overview) — what replay masks diff --git a/docs/sdk/javascript/frameworks/astro.mdx b/docs/sdk/javascript/frameworks/astro.mdx new file mode 100644 index 00000000..dc7a1724 --- /dev/null +++ b/docs/sdk/javascript/frameworks/astro.mdx @@ -0,0 +1,132 @@ +--- +title: "Astro" +description: "Set up the Bugsee JavaScript SDK in an Astro app with the @bugsee/astro integration: browser launch on every page, server middleware, edge runtime and island hydration errors." +sidebar_position: 9 +slug: "/sdk/javascript/frameworks/astro" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/astro` is an Astro integration. It launches the browser client on every page and adds a server middleware that launches the server SDK, reports request errors and injects the trace. It is a single install: it bundles the browser, Node.js and Edge SDKs. + +## Requirements + +- Astro with the integration API (`integrations` in `astro.config.mjs`). +- Node.js 18 or newer for server code. +- An application token. + +## Install + + + + +```bash +npm install @bugsee/astro@beta +``` + + + + +```bash +pnpm add @bugsee/astro@beta +``` + + + + +```bash +yarn add @bugsee/astro@beta +``` + + + + +```bash +bun add @bugsee/astro@beta +``` + + + + +## Set up + +Add the integration to your Astro config. There is nothing else to wire. + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; +import { bugsee } from '@bugsee/astro'; + +export default defineConfig({ + integrations: [bugsee({ appToken: process.env.BUGSEE_TOKEN, runtime: 'node' })], +}); +``` + +Use `runtime: 'edge'` for Vercel or Cloudflare edge deployments. The default is the Node.js runtime. + +The token is inlined into the client script so the browser can launch. An application token is not a secret. + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appToken` | `string` | required | Your Bugsee application token. | +| `runtime` | `'node'` \| `'edge'` | `'node'` | The server runtime. Use `'edge'` for Vercel or Cloudflare edge deployments. | +| `client` | object | `{}` | Extra browser launch options, for example `{ replay: false }` or `{ maxRecordingTime: 30 }`. | +| `server` | object | `{}` | Extra server launch options, for example `{ captureLocalVariables: true }`. | + +```js title="astro.config.mjs" +bugsee({ + appToken: process.env.BUGSEE_TOKEN, + client: { captureNetwork: true }, + server: { instrumentIncomingRequests: true }, +}); +``` + +`client` takes the [browser options](/sdk/javascript/platforms/browser#browser-options). `server` takes the [Node.js options](/sdk/javascript/platforms/node#node-options), or the [Vercel Edge options](/sdk/javascript/platforms/vercel-edge#options) with `runtime: 'edge'`. `client` and `server` are serialized into the generated code, so pass plain values, not functions. + +## Entry points + +| Entry | Description | +| --- | --- | +| `@bugsee/astro` | The integration: `bugsee` (also the default export). | +| `@bugsee/astro/client` | `registerClient(appToken, options?)`, `relaunch`. | +| `@bugsee/astro/server` | `registerServer(appToken, options?)` for Node.js. | +| `@bugsee/astro/edge` | `registerServerEdge`, `createEdgeMiddleware`. | +| `@bugsee/astro/middleware` | `createBugseeMiddleware(options?)` and the generated `onRequest`. | + +You normally use only the integration. + +## Island hydration errors + +Astro catches an island's hydration failure itself and re-dispatches it as a cancelable `astro:hydration-error` event, plus a `console.error`. Nothing is rethrown, so the page's error handlers never see it. The browser launch listens for that event and reports the error without cancelling the event, so Astro's own console output is unchanged. + +For component errors during rendering, also add the adapter for your island framework: [React](/sdk/javascript/frameworks/react), [Vue](/sdk/javascript/frameworks/vue), [Svelte](/sdk/javascript/frameworks/svelte) or [Solid](/sdk/javascript/frameworks/solid). + +## Notes + +- **Source maps.** Astro builds with Vite. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). +- **Backend context.** Each server request gets a context so logs and errors tie to it. See [Backend](/sdk/javascript/backend/overview). + +## Verify + +Throw from a server-rendered page: + +```html title="src/pages/test.astro" +--- +throw new Error('Bugsee test error'); +--- +``` + +Open `/test`. The error shows up in the Bugsee dashboard. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — client launch options +- [Node.js](/sdk/javascript/platforms/node) — server launch options +- [Vercel Edge](/sdk/javascript/platforms/vercel-edge) — the edge runtime build +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite diff --git a/docs/sdk/javascript/frameworks/nextjs.mdx b/docs/sdk/javascript/frameworks/nextjs.mdx new file mode 100644 index 00000000..a3d2684b --- /dev/null +++ b/docs/sdk/javascript/frameworks/nextjs.mdx @@ -0,0 +1,170 @@ +--- +title: "Next.js" +description: "Set up the Bugsee JavaScript SDK in a Next.js app with @bugsee/nextjs: instrumentation.ts for Node.js and Edge, instrumentation-client.ts, middleware errors and trace correlation." +sidebar_position: 6 +slug: "/sdk/javascript/frameworks/nextjs" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/nextjs` reports server errors through `instrumentation.ts` (Node.js and Edge runtimes), captures the browser through `instrumentation-client.ts`, and reports errors thrown in middleware. It is a single install: it bundles the browser, Node.js and Edge SDKs and re-exports the React adapter from `@bugsee/nextjs/client`. + +## Requirements + +- Next.js with `instrumentation.ts`. The client file `instrumentation-client.ts` needs Next.js 15.3 or newer. +- Node.js 18 or newer for server code. +- `react` 18 or newer (optional peer dependency). +- An application token. + +For the automatic OpenTelemetry bridge, `@opentelemetry/api` plus your OpenTelemetry SDK are optional peer dependencies: `@opentelemetry/sdk-trace-base` (OTel JS 1.x and 2.x) or `@opentelemetry/sdk-trace` (OTel JS 2.9 or newer, required on 3.x). + +## Install + + + + +```bash +npm install @bugsee/nextjs@beta +``` + + + + +```bash +pnpm add @bugsee/nextjs@beta +``` + + + + +```bash +yarn add @bugsee/nextjs@beta +``` + + + + +```bash +bun add @bugsee/nextjs@beta +``` + + + + +## Set up + +### Server + +`register()` picks the Node.js or Edge SDK by runtime. Re-export `onRequestError` so Next.js reports server errors. + +```ts title="instrumentation.ts" +import { register as bugsee } from '@bugsee/nextjs'; + +export function register() { + return bugsee(process.env.BUGSEE_TOKEN!); +} + +export { onRequestError } from '@bugsee/nextjs'; +``` + +### Client + +Next.js 15.3 and later load `instrumentation-client.ts` in the browser before your app code. Export `onRouterTransitionStart` to record a breadcrumb for each client-side navigation. + +```ts title="instrumentation-client.ts" +import { registerClient } from '@bugsee/nextjs/client'; + +registerClient(process.env.NEXT_PUBLIC_BUGSEE_TOKEN!); + +export { onRouterTransitionStart } from '@bugsee/nextjs/client'; +``` + +`registerClient` returns a `Promise` of the client. An application token is not a secret, so it is fine in a `NEXT_PUBLIC_` variable. + +`@bugsee/nextjs/client` also re-exports the React adapter, so you can import `BugseeErrorBoundary` from there. See [React](/sdk/javascript/frameworks/react). + +### Middleware (optional) + +Errors thrown in Next.js middleware are not delivered to `onRequestError`. Wrap your middleware to capture them: + +```ts title="middleware.ts" +import { withBugseeMiddleware } from '@bugsee/nextjs/middleware'; + +export const middleware = withBugseeMiddleware((request, event) => { + // ... +}); +``` + +### One trace for server and browser (optional) + +`getBugseeTraceData()` returns the active server request's trace. Spread it into `generateMetadata()` so Next.js renders a `` tag. The browser client reads it on page load, so the server request and the initial page session become one trace. + +```ts title="app/layout.tsx" +import { getBugseeTraceData } from '@bugsee/nextjs'; + +export function generateMetadata() { + return { other: getBugseeTraceData() }; +} +``` + +It returns `{}` when no trace is active. + +## Entry points + +| Entry | Exports | +| --- | --- | +| `@bugsee/nextjs` | `register`, `onRequestError`, `createOnRequestError`, `getBugseeTraceData` | +| `@bugsee/nextjs/client` | `registerClient`, `onRouterTransitionStart`, plus the React adapter | +| `@bugsee/nextjs/middleware` | `withBugseeMiddleware` | +| `@bugsee/nextjs/server` | `registerServer` and the shared client exports. The Node.js composition that `register()` loads for you. | +| `@bugsee/nextjs/edge` | `registerEdge` and the shared client exports. The Edge composition that `register()` loads for you. | + +## Options + +`register(appToken, options)` and `registerClient(appToken, options)` accept the SDK launch options. The most relevant: + +| Where | Option | Default | Description | +| --- | --- | --- | --- | +| Server | `instrumentIncomingRequests` | `true` | Instrument incoming requests. | +| Server | `captureLocalVariables` | `false` | Capture local variables on errors. | +| Server | `detectHangs` | `true` | Event-loop hang detection. | +| Server | `setupOtelProvider` | `true` | Install Bugsee's OpenTelemetry provider. Set `false` if you manage OpenTelemetry yourself. | +| Client | `captureLogs`, `captureNetwork` | `true` | Console and network capture. | +| Client | `maxRecordingTime` | `60` | Seconds of recording to keep. | +| Client | `replay` | `true` | Session replay. Pass `false` to turn it off. | + +See [Browser](/sdk/javascript/platforms/browser#browser-options) and [Node.js](/sdk/javascript/platforms/node#node-options) for the full lists. + +## Navigation breadcrumbs + +`onRouterTransitionStart` writes one `navigation` breadcrumb per soft navigation. The address in it is sanitized first, so values such as `?code=...`, `?state=...` and `#access_token=...` never reach the report. Ids, emails and other values in a path segment are not redacted. + +## Notes + +- **Edge runtime.** `register()` picks the Edge SDK there. Edge capture is incident-driven: it uploads only when something goes wrong. See [Vercel Edge](/sdk/javascript/platforms/vercel-edge). +- **Source maps.** Next.js on webpack uses the webpack plugin. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). +- **Backend context.** Each server request gets a context so logs and errors tie to it. See [Backend](/sdk/javascript/backend/overview). + +## Verify + +Throw from a route handler or server component: + +```ts title="app/api/test/route.ts" +export function GET() { + throw new Error('Bugsee test error'); +} +``` + +Request `/api/test`. The error shows up in the Bugsee dashboard. + +## Related pages + +- [React](/sdk/javascript/frameworks/react) — the error boundary and route naming +- [Vercel Edge](/sdk/javascript/platforms/vercel-edge) — the Edge runtime build +- [Backend](/sdk/javascript/backend/overview) — request context and trace correlation +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from webpack diff --git a/docs/sdk/javascript/frameworks/nuxt.mdx b/docs/sdk/javascript/frameworks/nuxt.mdx new file mode 100644 index 00000000..39f4abb5 --- /dev/null +++ b/docs/sdk/javascript/frameworks/nuxt.mdx @@ -0,0 +1,131 @@ +--- +title: "Nuxt" +description: "Set up the Bugsee JavaScript SDK in a Nuxt 3 app with the @bugsee/nuxt module: one nuxt.config.ts entry wires the browser client, the Vue error handler and the Nitro server." +sidebar_position: 7 +slug: "/sdk/javascript/frameworks/nuxt" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/nuxt` is a Nuxt module that wires the browser client (with the Vue error handler) and the Nitro server from one entry in `nuxt.config.ts`. It is a single install: it bundles the browser, Node.js and Edge SDKs and the Vue adapter. + +## Requirements + +- Nuxt 3 or newer. `nuxt`, `@nuxt/kit` (3 or newer) and `nitropack` (2 or newer) are optional peer dependencies, normally already present in a Nuxt app. +- Node.js 18 or newer for server code. +- An application token. + +## Install + + + + +```bash +npm install @bugsee/nuxt@beta +``` + + + + +```bash +pnpm add @bugsee/nuxt@beta +``` + + + + +```bash +yarn add @bugsee/nuxt@beta +``` + + + + +```bash +bun add @bugsee/nuxt@beta +``` + + + + +## Set up + +Register the module and pass your token in the `bugsee` block. There is nothing else to wire. + +```ts title="nuxt.config.ts" +export default defineNuxtConfig({ + modules: ['@bugsee/nuxt'], + bugsee: { + appToken: process.env.BUGSEE_TOKEN, + }, +}); +``` + +The module adds a client plugin that launches the browser SDK and installs the Vue error handler, and a Nitro server plugin that launches the server SDK and reports Nitro errors. On an edge Nitro preset (for example Cloudflare or Vercel Edge) it ships the edge SDK instead of the Node.js one. + +The token is written to Nuxt's public runtime config so the browser can launch. An application token is not a secret. + +## Options + +The `bugsee` block takes: + +| Option | Type | Description | +| --- | --- | --- | +| `appToken` | `string` | Your Bugsee application token (required). | +| `client` | object | Extra browser launch options, for example `{ replay: false }` or `{ maxRecordingTime: 30 }`. | +| `server` | object | Extra Nitro (server) launch options, for example `{ captureLocalVariables: true }`. | + +```ts title="nuxt.config.ts" +export default defineNuxtConfig({ + modules: ['@bugsee/nuxt'], + bugsee: { + appToken: process.env.BUGSEE_TOKEN, + client: { captureNetwork: true }, + server: { instrumentIncomingRequests: true }, + }, +}); +``` + +`client` takes the [browser options](/sdk/javascript/platforms/browser#browser-options). `server` takes the [Node.js options](/sdk/javascript/platforms/node#node-options). Values you set under `runtimeConfig.public.bugsee` or `runtimeConfig.bugsee` directly, or through environment overrides, win over the module defaults. + +## Entry points + +| Entry | Description | +| --- | --- | +| `@bugsee/nuxt` | The module, with `ModuleOptions` and `setupBugseeModule`. | +| `@bugsee/nuxt/client` | `installBugseeClient(nuxtApp, options)`, used by the generated client plugin. | +| `@bugsee/nuxt/server` | `installBugseeNitro` and the shared client exports. | +| `@bugsee/nuxt/edge` | The edge build for edge Nitro presets. | + +You normally use only the module. + +## Notes + +- **The Vue error handler is installed for you.** On a plain Vue app it is required in production; see [Vue](/sdk/javascript/frameworks/vue). +- **Edge presets** use the incident-driven edge SDK. See [Vercel Edge](/sdk/javascript/platforms/vercel-edge). +- **Source maps.** The Nuxt build runs on Vite. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). +- **Backend context.** Each Nitro request gets a context so logs and errors tie to it. See [Backend](/sdk/javascript/backend/overview). + +## Verify + +Throw from a component or a server route: + +```ts title="server/api/test.get.ts" +export default defineEventHandler(() => { + throw new Error('Bugsee test error'); +}); +``` + +Request `/api/test`. The error shows up in the Bugsee dashboard. + +## Related pages + +- [Vue](/sdk/javascript/frameworks/vue) — the adapter this module installs +- [Browser](/sdk/javascript/platforms/browser) — client launch options +- [Node.js](/sdk/javascript/platforms/node) — server launch options +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite diff --git a/docs/sdk/javascript/frameworks/react.mdx b/docs/sdk/javascript/frameworks/react.mdx new file mode 100644 index 00000000..b93cf51f --- /dev/null +++ b/docs/sdk/javascript/frameworks/react.mdx @@ -0,0 +1,192 @@ +--- +title: "React" +description: "Set up the Bugsee JavaScript SDK in a React or Preact app with @bugsee/react: error boundary, React 19 root error handlers, react-router route names and component names." +sidebar_position: 1 +slug: "/sdk/javascript/frameworks/react" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/react` adds React-specific error reporting to the [browser SDK](/sdk/javascript/platforms/browser): an error boundary that reports render errors with the React component stack, root error handlers for React 19, a render profiler, and route naming for react-router. + +Using Next.js or Remix? Use [`@bugsee/nextjs`](/sdk/javascript/frameworks/nextjs) or [`@bugsee/remix`](/sdk/javascript/frameworks/remix) instead. They include this adapter. + +## Requirements + +- React 18 or newer (peer dependency), or Preact 10 or newer through `preact/compat`. +- An application token. + +## Install + +Install the umbrella, which provides `launch()`, next to the adapter. + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/react@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/react@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/react@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/react@beta +``` + + + + +## Set up + +Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away. + +```tsx title="main.tsx" +import { launch } from '@bugsee/bugsee'; + +launch(''); +``` + +Wrap your app in the error boundary. A render error is reported with the React component stack, and the fallback is shown. + +```tsx title="App.tsx" +import { BugseeErrorBoundary } from '@bugsee/react'; + +export function Root() { + return ( + }> + + + ); +} +``` + +A higher-order component does the same: + +```tsx +import { withBugseeErrorBoundary } from '@bugsee/react'; + +export default withBugseeErrorBoundary(App, { fallback: }); +``` + +### React 19 root handlers + +React 19 reports errors through callbacks on the root. Pass Bugsee's handlers to `createRoot` or `hydrateRoot`: + +```tsx +import { createRoot } from 'react-dom/client'; +import { createBugseeErrorHandlers } from '@bugsee/react'; + +createRoot(document.getElementById('root')!, createBugseeErrorHandlers()).render(); +``` + +The handlers cover both `onUncaughtError` and `onCaughtError`. + +### Route names (react-router) + +Name the active navigation after the matched route pattern (`/users/:id`) instead of the concrete URL. With a data router, wire it once: + +```tsx +import { createBrowserRouter } from 'react-router-dom'; +import { instrumentReactRouter } from '@bugsee/react'; + +const router = createBrowserRouter(routes); +instrumentReactRouter(router); +``` + +With a declarative router, call `instrumentRouterMatches(matchRoutes(routes, location))` on each navigation. + +### Component names in minified builds + +Install the Babel plugin so clicks and errors are attributed to the component that rendered them, even after minification. + +```bash +npm install --save-dev @bugsee/babel-plugin-component-annotate +``` + +```js title="babel.config.js" +module.exports = { + plugins: [['@bugsee/babel-plugin-component-annotate']], +}; +``` + +The plugin adds `data-bugsee-component` attributes. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). + +### Preact + +Preact 10 and newer works through this package via `preact/compat`. Alias `react` and `react-dom` to `preact/compat` in your bundler, as a Preact app already does, and use `@bugsee/react` as is. Under Preact the report carries the error but no React component stack. + +## API + +`@bugsee/react` also re-exports everything from `@bugsee/bugsee`, so you can import `launch` from either package. + +| Export | Description | +| --- | --- | +| `BugseeErrorBoundary` | Error boundary component. Props: `fallback` (a node, or a function of the error), `onError(error, componentStack)`, `getClient`, `children`. | +| `withBugseeErrorBoundary(Component, props?)` | Higher-order component version of the boundary. | +| `createBugseeErrorHandlers(options?)` | Returns `{ onUncaughtError, onCaughtError }` for React 19 `createRoot` and `hydrateRoot`. | +| `instrumentReactRouter(router)` | Names navigations after the matched route of a react-router data router. | +| `instrumentRouterMatches(matches)` | The same for a declarative router; call it on each navigation. | +| `BugseeProfiler` | A React `` that records `ui.render` spans. Takes an `id` prop. | +| `withBugseeProfiler(Component, id?, options?)` | Higher-order component version of the profiler. | +| `reportReactError(error, options?)` | Reports an error you caught yourself, linking the component stack when you pass it. | + +## Launch options + +`launch(appToken, options)` accepts all [browser options](/sdk/javascript/platforms/browser#browser-options). The most relevant: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Capture console output. | +| `captureNetwork` | `boolean` | `true` | Capture network requests. | +| `maxRecordingTime` | `number` | `60` | Seconds of recording to keep. | +| `replay` | `boolean` or object | `true` | Session replay settings, or `false` to turn replay off. | +| `captureInteractions` | `boolean` | `true` | Capture user interactions. | + +## Notes + +- **Server rendering.** `launch()` is browser code. Call it only on the client (for example in the client entry), never during server rendering. +- **Source maps.** Upload source maps so React stacks are readable. See [Symbolication](/sdk/javascript/symbolication/overview). +- **Sensitive content.** Session replay masks text and inputs by default. See [Privacy](/sdk/javascript/privacy/overview). + +## Verify + +Add a component that throws on render inside the boundary: + +```tsx +function Bomb(): never { + throw new Error('Bugsee test error'); +} + +Something went wrong.

}> + +
; +``` + +Load the page. The fallback appears, and the error shows up in the Bugsee dashboard with the component stack. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — launch options, persistence and replay +- [Next.js](/sdk/javascript/frameworks/nextjs) — React with server rendering +- [Remix and React Router](/sdk/javascript/frameworks/remix) — framework mode apps +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/frameworks/remix.mdx b/docs/sdk/javascript/frameworks/remix.mdx new file mode 100644 index 00000000..c65229dd --- /dev/null +++ b/docs/sdk/javascript/frameworks/remix.mdx @@ -0,0 +1,148 @@ +--- +title: "Remix and React Router" +description: "Set up the Bugsee JavaScript SDK in a Remix or React Router v7 and v8 framework mode app with @bugsee/remix: entry.server handleError, entry.client onError and Remix v2." +sidebar_position: 8 +slug: "/sdk/javascript/frameworks/remix" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/remix` is the adapter for Remix and for React Router v7 and v8 in framework mode. It reports server errors through `handleError` in `entry.server`, and captures the browser through `entry.client`. It is a single install: it bundles the browser and Node.js SDKs and re-exports the React adapter from `@bugsee/remix/client`. + +## Requirements + +- Remix, or React Router v7 or v8 in framework mode. +- Node.js 18 or newer for server code. +- `react` 18 or newer (optional peer dependency). +- An application token. + +## Install + + + + +```bash +npm install @bugsee/remix@beta +``` + + + + +```bash +pnpm add @bugsee/remix@beta +``` + + + + +```bash +yarn add @bugsee/remix@beta +``` + + + + +```bash +bun add @bugsee/remix@beta +``` + + + + +## Set up + +### Server + +Launch Bugsee on the server and export `handleError` so unhandled server errors are reported. + +```tsx title="app/entry.server.tsx" +import { registerServer } from '@bugsee/remix/server'; + +registerServer(process.env.BUGSEE_TOKEN!); + +export { handleError } from '@bugsee/remix'; +``` + +`registerServer` returns the started client directly. + +### Client + +Launch the browser SDK at the top of `entry.client` and pass `bugseeOnError` to the router, so React errors are reported with their component stack. + +```tsx title="app/entry.client.tsx" +import { registerClient, bugseeOnError } from '@bugsee/remix/client'; + +registerClient(import.meta.env.VITE_BUGSEE_TOKEN); + +hydrateRoot(document, ); +``` + +`registerClient` returns a `Promise` of the client. An application token is not a secret, so it is fine in a `VITE_` variable. + +### Remix v2 + +Remix v2 has no `onError` prop. Call `captureRemixErrorBoundaryError` from your root `ErrorBoundary`. Expected control flow, such as 404s, redirects and thrown responses, is skipped. + +```tsx title="app/root.tsx" +import { captureRemixErrorBoundaryError } from '@bugsee/remix/client'; +import { useRouteError } from '@remix-run/react'; + +export function ErrorBoundary() { + captureRemixErrorBoundaryError(useRouteError()); + return ; +} +``` + +## Entry points + +| Entry | Exports | +| --- | --- | +| `@bugsee/remix` | `handleError`, `createHandleError(options?)`, `getBugseeTraceMetaTags(options?)` | +| `@bugsee/remix/server` | `registerServer`, `getBugseeMetaTagTransformer`, the shared client exports and `relaunch` | +| `@bugsee/remix/client` | `registerClient`, `bugseeOnError`, `captureRemixErrorBoundaryError`, plus the React adapter | + +`getBugseeTraceMetaTags()` renders a `` tag for the active server request. The browser client reads it on page load, so the server request and the initial page session become one trace. + +## Options + +`registerServer(appToken, options)` and `registerClient(appToken, options)` accept the SDK launch options. The most relevant: + +| Where | Option | Default | Description | +| --- | --- | --- | --- | +| Server | `instrumentIncomingRequests` | `true` | Instrument incoming requests. | +| Server | `captureLocalVariables` | `false` | Capture local variables on errors. | +| Server | `detectHangs` | `true` | Event-loop hang detection. | +| Client | `captureLogs`, `captureNetwork` | `true` | Console and network capture. | +| Client | `maxRecordingTime` | `60` | Seconds of recording to keep. | +| Client | `replay` | `true` | Session replay. Pass `false` to turn it off. | + +See [Browser](/sdk/javascript/platforms/browser#browser-options) and [Node.js](/sdk/javascript/platforms/node#node-options) for the full lists. + +## Notes + +- **Source maps.** The Vite plugin uploads them as part of the build. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). +- **Backend context.** Each server request gets a context so logs and errors tie to it. See [Backend](/sdk/javascript/backend/overview). + +## Verify + +Throw from a loader: + +```ts title="app/routes/test.tsx" +export function loader() { + throw new Error('Bugsee test error'); +} +``` + +Open `/test`. The error shows up in the Bugsee dashboard. + +## Related pages + +- [React](/sdk/javascript/frameworks/react) — the error boundary and route naming +- [Browser](/sdk/javascript/platforms/browser) — client launch options +- [Node.js](/sdk/javascript/platforms/node) — server launch options +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite diff --git a/docs/sdk/javascript/frameworks/solid.mdx b/docs/sdk/javascript/frameworks/solid.mdx new file mode 100644 index 00000000..784812a0 --- /dev/null +++ b/docs/sdk/javascript/frameworks/solid.mdx @@ -0,0 +1,162 @@ +--- +title: "Solid" +description: "Set up the Bugsee JavaScript SDK in a SolidJS app with @bugsee/solid: error boundary reporting, @solidjs/router route names and component names in minified builds." +sidebar_position: 5 +slug: "/sdk/javascript/frameworks/solid" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/solid` adds Solid-specific error reporting to the [browser SDK](/sdk/javascript/platforms/browser). It reports errors from Solid's error primitives and names navigations after the matched `@solidjs/router` route. + +## Requirements + +- `solid-js` 1.6 or newer, and `@solidjs/router` 0.10 or newer for route names (both optional peer dependencies). +- An application token. + +## Install + +Install the umbrella, which provides `launch()`, next to the adapter. + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/solid@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/solid@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/solid@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/solid@beta +``` + + + + +## Set up + +Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away. + +```tsx title="index.tsx" +import { launch } from '@bugsee/bugsee'; + +launch(''); +``` + +Solid hands errors to a callback, so pass Bugsee's reporter to Solid's own error seam: + +```tsx title="App.tsx" +import { ErrorBoundary } from 'solid-js'; +import { solidErrorHandler } from '@bugsee/solid'; + +const report = solidErrorHandler(); + + { + report(err); + return ; + }} +> + +; +``` + +`catchError(() => , solidErrorHandler())` works the same way. + +:::note +These seams catch synchronous render and reactive errors. The SDK's global error capture covers asynchronous and event-handler errors. +::: + +### Route names (@solidjs/router) + +```ts +import { useCurrentMatches } from '@solidjs/router'; +import { createEffect } from 'solid-js'; +import { setRouteNameFromSolidMatches } from '@bugsee/solid'; + +const matches = useCurrentMatches(); +createEffect(() => setRouteNameFromSolidMatches(matches())); +``` + +### Component names in minified builds + +Install the Babel plugin so clicks and errors are attributed to the component that rendered them, even after minification. + +```bash +npm install --save-dev @bugsee/babel-plugin-component-annotate +``` + +```js title="babel.config.js" +module.exports = { + plugins: [['@bugsee/babel-plugin-component-annotate']], +}; +``` + +See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). + +## API + +`@bugsee/solid` also re-exports everything from `@bugsee/bugsee`. + +| Export | Description | +| --- | --- | +| `solidErrorHandler(options?)` | Returns a reporter function `(error) => void` for `ErrorBoundary` or `catchError`. | +| `reportSolidError(error, options?)` | Reports an error you caught yourself. | +| `setRouteNameFromSolidMatches(matches)` | Names the active navigation after the matched route. | + +## Launch options + +`launch(appToken, options)` accepts all [browser options](/sdk/javascript/platforms/browser#browser-options). The most relevant: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Capture console output. | +| `captureNetwork` | `boolean` | `true` | Capture network requests. | +| `maxRecordingTime` | `number` | `60` | Seconds of recording to keep. | +| `replay` | `boolean` or object | `true` | Session replay settings, or `false` to turn replay off. | +| `captureInteractions` | `boolean` | `true` | Capture user interactions. | + +## Notes + +- **Source maps.** Upload source maps so Solid stacks are readable. See [Symbolication](/sdk/javascript/symbolication/overview). +- **Sensitive content.** Session replay masks text and inputs by default. See [Privacy](/sdk/javascript/privacy/overview). + +## Verify + +Throw from a component inside the boundary: + +```tsx +function Bomb(): never { + throw new Error('Bugsee test error'); +} +``` + +Render it. The fallback appears, and the error shows up in the Bugsee dashboard. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — launch options, persistence and replay +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs +- [Privacy](/sdk/javascript/privacy/overview) — what replay masks diff --git a/docs/sdk/javascript/frameworks/svelte.mdx b/docs/sdk/javascript/frameworks/svelte.mdx new file mode 100644 index 00000000..58e38e46 --- /dev/null +++ b/docs/sdk/javascript/frameworks/svelte.mdx @@ -0,0 +1,247 @@ +--- +title: "Svelte and SvelteKit" +description: "Set up the Bugsee JavaScript SDK in a Svelte app with @bugsee/svelte, or in SvelteKit with @bugsee/sveltekit: client and server hooks, route names and component names." +sidebar_position: 4 +slug: "/sdk/javascript/frameworks/svelte" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Two packages cover the Svelte family: + +- **`@bugsee/svelte`**: Svelte and browser-only SvelteKit apps. It adds a `handleError` hook for client errors and route naming from SvelteKit navigation. +- **`@bugsee/sveltekit`**: SvelteKit apps with server code. It adds server hooks (`handle` and `handleError`) and client hooks, so one session covers the server request and the browser that triggered it. It is a single install that bundles the browser, Node.js and Edge SDKs and the Svelte adapter. + +If your SvelteKit app has server-side code, use `@bugsee/sveltekit`. + +## Requirements + +- `@bugsee/svelte`: Svelte 4 or newer, and `@sveltejs/kit` 2 or newer for the hooks (both optional peer dependencies). +- `@bugsee/sveltekit`: Node.js 18 or newer for the server adapter. SvelteKit 3 applications require Node.js 22.17 or newer. +- An application token. + +## Svelte and client-only SvelteKit + +### Install + +Install the umbrella, which provides `launch()`, next to the adapter. + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/svelte@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/svelte@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/svelte@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/svelte@beta +``` + + + + +### Set up + +Launch Bugsee as early as possible. In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away. + +```ts title="src/main.ts" +import { launch } from '@bugsee/bugsee'; + +launch(''); +``` + +In SvelteKit, wire the client error hook: + +```ts title="src/hooks.client.ts" +import { handleErrorWithBugsee } from '@bugsee/svelte'; + +export const handleError = handleErrorWithBugsee(); +``` + +`handleErrorWithBugsee(appHandler?)` reports the error with its route id, then calls your own handler if you pass one, and returns what it returns. Errors with a status below 500, such as a 404, are treated as expected and are not reported. + +### Route names + +Name the active navigation after the route id. Wire it once, after mount: + +```ts +import { afterNavigate } from '$app/navigation'; +import { instrumentSvelteKitNavigation } from '@bugsee/svelte'; + +afterNavigate(instrumentSvelteKitNavigation()); +``` + +## SvelteKit with server code + +### Install + + + + +```bash +npm install @bugsee/sveltekit@beta +``` + + + + +```bash +pnpm add @bugsee/sveltekit@beta +``` + + + + +```bash +yarn add @bugsee/sveltekit@beta +``` + + + + +```bash +bun add @bugsee/sveltekit@beta +``` + + + + +### Server hooks + +Launch Bugsee on the server, add the `handle` hook (it injects the trace into the page head) and the `handleError` hook. + +```ts title="src/hooks.server.ts" +import { sequence } from '@sveltejs/kit/hooks'; +import { registerServer } from '@bugsee/sveltekit/server'; +import { handle as bugseeHandle, handleErrorWithBugsee } from '@bugsee/sveltekit'; + +registerServer(process.env.BUGSEE_TOKEN!); + +export const handle = sequence(bugseeHandle); +export const handleError = handleErrorWithBugsee(); +``` + +Add your own handles to `sequence(...)` as usual. `registerServer` returns the started client directly. + +### Client hooks + +Launch the browser SDK in the client hooks file, which runs only in the browser, and wire the client error hook. + +```ts title="src/hooks.client.ts" +import { PUBLIC_BUGSEE_TOKEN } from '$env/static/public'; +import { registerClient, handleErrorWithBugsee } from '@bugsee/sveltekit/client'; + +registerClient(PUBLIC_BUGSEE_TOKEN); + +export const handleError = handleErrorWithBugsee(); +``` + +`registerClient` returns a `Promise` of the client. An application token is not a secret, so it is fine in a public variable. + +### Edge deployments + +For edge targets, use `registerServerEdge` and `createEdgeHandle` from `@bugsee/sveltekit/edge` in place of `registerServer` and `handle`. + +## Component names in minified builds + +Install the Svelte preprocessor so clicks and errors are attributed to the component that rendered them, even after minification. + +```bash +npm install --save-dev @bugsee/svelte-plugin-component-annotate +``` + +```js title="svelte.config.js" +import { componentAnnotatePreprocessor } from '@bugsee/svelte-plugin-component-annotate'; + +export default { + preprocess: [componentAnnotatePreprocessor()], +}; +``` + +On SvelteKit 3 there is no `svelte.config.js`. Pass `preprocess` to the `sveltekit()` Vite plugin instead: + +```ts title="vite.config.ts" +import { componentAnnotatePreprocessor } from '@bugsee/svelte-plugin-component-annotate'; +import { sveltekit } from '@sveltejs/kit/vite'; + +export default { + plugins: [sveltekit({ preprocess: [componentAnnotatePreprocessor()] })], +}; +``` + +## API + +| Package | Export | Description | +| --- | --- | --- | +| `@bugsee/svelte` | `handleErrorWithBugsee(appHandler?, options?)` | Client `handleError` hook. | +| `@bugsee/svelte` | `instrumentSvelteKitNavigation(options?)` | Returns an `afterNavigate` callback that names navigations after the route id. | +| `@bugsee/svelte` | `reportSvelteError(error, options?)` | Reports an error you caught yourself. | +| `@bugsee/svelte` | `startSvelteRenderSpan(name, options?)` | Records a component render span. The preprocessor injects it. | +| `@bugsee/sveltekit` | `handle`, `createHandle(options?)` | Server `handle` hook. | +| `@bugsee/sveltekit` | `handleErrorWithBugsee`, `handleError`, `createHandleServerError(options?)` | Server `handleError` hook. | +| `@bugsee/sveltekit/server` | `registerServer(appToken, options?)` | Launches the Node.js SDK. | +| `@bugsee/sveltekit/client` | `registerClient(appToken, options?)`, `handleErrorWithBugsee` | Launches the browser SDK and the client hook. | +| `@bugsee/sveltekit/edge` | `registerServerEdge`, `createEdgeHandle(options?)` | Edge runtime launch and `handle` hook. | + +Both packages also re-export the shared client exports (`getStatus`, `BugseeStatus`, `LifecycleEvents`, `addReportAttachment`, `getDefaultNetworkSanitizer`). + +## Launch options + +`launch(appToken, options)`, `registerServer` and `registerClient` accept the SDK launch options. The most relevant: + +| Where | Option | Default | Description | +| --- | --- | --- | --- | +| Server | `instrumentIncomingRequests` | `true` | Instrument incoming requests. | +| Server | `captureLocalVariables` | `false` | Capture local variables on errors. | +| Server | `detectHangs` | `true` | Event-loop hang detection. | +| Client | `captureLogs`, `captureNetwork` | `true` | Console and network capture. | +| Client | `maxRecordingTime` | `60` | Seconds of recording to keep. | +| Client | `replay` | `true` | Session replay. Pass `false` to turn it off. | + +See [Browser](/sdk/javascript/platforms/browser#browser-options) and [Node.js](/sdk/javascript/platforms/node#node-options) for the full lists. + +## Notes + +- **Source maps.** The Vite plugin uploads them as part of the build. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins). +- **Backend context.** On the server, each request gets a context so logs and errors tie to it. See [Backend](/sdk/javascript/backend/overview). + +## Verify + +Throw from a `load` function or a component: + +```ts title="src/routes/+page.ts" +export function load() { + throw new Error('Bugsee test error'); +} +``` + +Open the page. The error shows up in the Bugsee dashboard. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — client launch options and replay +- [Node.js](/sdk/javascript/platforms/node) — server launch options +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/frameworks/vue.mdx b/docs/sdk/javascript/frameworks/vue.mdx new file mode 100644 index 00000000..76cdd8e3 --- /dev/null +++ b/docs/sdk/javascript/frameworks/vue.mdx @@ -0,0 +1,152 @@ +--- +title: "Vue" +description: "Set up the Bugsee JavaScript SDK in a Vue 3 app with @bugsee/vue: the required error handler, vue-router route names and component names in minified builds." +sidebar_position: 2 +slug: "/sdk/javascript/frameworks/vue" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/vue` adds Vue-specific error reporting to the [browser SDK](/sdk/javascript/platforms/browser). It reports errors from Vue's error handler and names navigations after the matched vue-router route. + +Using Nuxt? Use [`@bugsee/nuxt`](/sdk/javascript/frameworks/nuxt) instead. It wires this adapter for you. + +## Requirements + +- Vue 3 (peer dependency). +- An application token. + +## Install + +Install the umbrella, which provides `launch()`, next to the adapter. + + + + +```bash +npm install @bugsee/bugsee@beta @bugsee/vue@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta @bugsee/vue@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta @bugsee/vue@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta @bugsee/vue@beta +``` + + + + +## Set up + +```ts title="main.ts" +import { launch } from '@bugsee/bugsee'; +import { installBugseeErrorHandler } from '@bugsee/vue'; +import { createApp } from 'vue'; +import App from './App.vue'; + +launch(''); + +const app = createApp(App); +installBugseeErrorHandler(app); +app.mount('#app'); +``` + +In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away. + +`installBugseeErrorHandler(app)` hooks `app.config.errorHandler` so Vue errors are reported to the launched client. It keeps any handler you set earlier: install it after your own handler and both run. If there is none, it keeps Vue's default behavior of logging the error to the console. + +:::caution[Required in production] +Vue swallows errors thrown in components, hooks, watchers and event handlers. A production build only logs them with `console.error` and never rethrows, and in any build the rejection of an async hook is caught by Vue itself, so neither `window.onerror` nor `unhandledrejection` sees it. Without `installBugseeErrorHandler(app)` (or your own `app.config.errorHandler` that reports them), Bugsee receives nothing from those errors. +::: + +### Route names (vue-router) + +Name the active navigation after the matched route pattern instead of the concrete URL. Call it once after `createRouter(...)`. + +```ts +import { instrumentVueRouter } from '@bugsee/vue'; + +instrumentVueRouter(router); +``` + +### Component names in minified builds + +Register the mixin so clicks and errors are attributed to the Vue component that rendered them, even after minification. It stamps each component's root element with a `data-bugsee-component` attribute. + +```ts title="main.ts" +import { createBugseeVueComponentMixin } from '@bugsee/vue'; + +app.mixin(createBugseeVueComponentMixin()); +``` + +## API + +`@bugsee/vue` also re-exports everything from `@bugsee/bugsee`. + +| Export | Description | +| --- | --- | +| `installBugseeErrorHandler(app, options?)` | Installs Bugsee on `app.config.errorHandler`, chaining an existing handler. | +| `reportVueError(error, options?)` | Reports an error you caught yourself. Accepts `info` and `instance`. | +| `instrumentVueRouter(router, options?)` | Names navigations after the matched route. | +| `createBugseeVueComponentMixin()` | Mixin that stamps component root elements with their names. | +| `createBugseeVueRenderMixin()` | Mixin that records render timing for performance monitoring. | + +## Launch options + +`launch(appToken, options)` accepts all [browser options](/sdk/javascript/platforms/browser#browser-options). The most relevant: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Capture console output. | +| `captureNetwork` | `boolean` | `true` | Capture network requests. | +| `maxRecordingTime` | `number` | `60` | Seconds of recording to keep. | +| `replay` | `boolean` or object | `true` | Session replay settings, or `false` to turn replay off. | +| `captureInteractions` | `boolean` | `true` | Capture user interactions. | + +## Notes + +- **Source maps.** Upload source maps so Vue stacks are readable. The Vite plugin does it as part of the build. See [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) and [Symbolication](/sdk/javascript/symbolication/overview). +- **Sensitive content.** Session replay masks text and inputs by default. See [Privacy](/sdk/javascript/privacy/overview). + +## Verify + +Throw from a component: + +```html title="Bomb.vue" + + + +``` + +Render the component. The error shows up in the Bugsee dashboard. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — launch options, persistence and replay +- [Nuxt](/sdk/javascript/frameworks/nuxt) — Vue with server rendering +- [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) — upload source maps from Vite +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/installation.mdx b/docs/sdk/javascript/installation.mdx new file mode 100644 index 00000000..cfe9c907 --- /dev/null +++ b/docs/sdk/javascript/installation.mdx @@ -0,0 +1,246 @@ +--- +title: "Installation" +description: "Installing the Bugsee JavaScript SDK with npm, pnpm, yarn or bun, getting an app token, launching it in a browser, Node.js, Bun or another runtime, and checking that reports arrive." +sidebar_position: 1 +slug: "/sdk/javascript/installation" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +This page covers the common case: `@bugsee/bugsee` in a browser app or a Node.js server. Bun, Electron, Cloudflare Workers, Vercel Edge, workers, frameworks and backend frameworks each have a dedicated page with the exact setup; see [Next steps](#next-steps). + +## Requirements + +| Runtime | Support | +| --- | --- | +| Browsers | Modern browsers. The package is built for ES2022. | +| Node.js | 18 or later | +| Bun | 1.1.13 or later (tested on 1.3), through `@bugsee/bun` | +| Other runtimes | Electron, Cloudflare Workers, Vercel Edge, Web and Service Workers: see [Packages](/sdk/javascript/packages) | + +Deno is not supported. + +## 1. Add the package + +Pick the package for where your code runs. Browsers and Node.js use `@bugsee/bugsee`. + +| Where your code runs | Install | +| --- | --- | +| Browser, Node.js | `@bugsee/bugsee` | +| Bun | `@bugsee/bun` | +| Electron | `@bugsee/electron` | +| Cloudflare Workers | `@bugsee/cloudflare` | +| Vercel Edge | `@bugsee/vercel-edge` | +| Web Worker, Service Worker | `@bugsee/webworker` | +| React, Vue, Angular, Svelte, Solid | `@bugsee/bugsee` plus the matching adapter | +| Next.js, Nuxt, Remix, SvelteKit, Astro | The matching adapter alone | +| Express, Fastify, NestJS, Hono, Koa, hapi, Elysia | `@bugsee/bugsee` plus the matching adapter | + +For the common case: + + + + +```bash +npm install @bugsee/bugsee@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta +``` + + + + +For now the npm `latest` and `beta` tags both point at the current beta, so installing without `@beta` gets the same version. The `@beta` form keeps following betas once a stable release exists. + +If your code runs on the Bun runtime, install `@bugsee/bun` instead (`bun add @bugsee/bun@beta`). Using Bun only as your package manager or bundler for a browser or Node.js app needs `@bugsee/bugsee`. + +## 2. Get your app token + +Create a JavaScript app in the Bugsee dashboard. The dashboard shows its app token. Pass it to `launch()` as the first argument. + +Treat the token as configuration: read it from an environment variable or your build settings instead of committing it. A browser app ships the token to every visitor, as with any client-side SDK key. + +If the token is missing, empty or not a string, `launch()` does not throw. It reports one error, "Bugsee: the app token is missing", through your `onError` option (or `console.warn` when you gave none), and returns a disabled client. Nothing is captured or uploaded and every method is safe to call. A later `launch()` with a valid token still works. + +## 3. Launch Bugsee + +Call `launch()` once, as early as you can: at the top of your entry module, before the code you want covered. Capture starts when it runs. + + + + +```ts title="main.ts" +import { launch } from '@bugsee/bugsee'; + +launch('', { + appVersion: '1.4.2', + appBuild: '381', +}); +``` + +In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away: + +```ts +const bugsee = await launch('', { appVersion: '1.4.2' }); + +bugsee.addBreadcrumb({ message: 'checkout started' }); +``` + + + + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; + +const bugsee = launch(process.env.BUGSEE_APP_TOKEN ?? '', { + appVersion: '1.4.2', +}); +``` + +On Node.js, `launch()` returns the client directly (not a `Promise`). Import the module that calls it before the rest of your application so that errors and requests from the start are covered. + + + + +```ts title="index.ts" +import { launch } from '@bugsee/bun'; + +const bugsee = launch(process.env.BUGSEE_APP_TOKEN ?? '', { + appVersion: '1.4.2', +}); +``` + +`@bugsee/bun` accepts the same options as the Node.js build. See [Bun](/sdk/javascript/platforms/bun). + + + + +Both `launch` signatures are `launch(appToken, options?)`. The options are all optional; [Configuration](/sdk/javascript/configuration) lists them. + +What happens on launch: + +- Capture of console output, network traffic and breadcrumbs starts, and in the browser session replay starts. +- Global handlers report uncaught errors and unhandled promise rejections. +- Performance monitoring starts (web vitals and transactions); pass `performanceMonitoring: false` to turn it off. +- Bugsee is a per-process singleton. A second `launch()` is ignored, reported through `onError`, and returns the existing client. To restart with other options, use `relaunch()`; see [Lifecycle & status](/sdk/javascript/lifecycle). + +:::note[Short-lived scripts] +A Node.js or Bun script that exits right after an error can end before the report is uploaded. Await `bugsee.flush()` (or `bugsee.stop()`) before exiting. A long-running server does not need to; on `SIGTERM`, `SIGINT` and `SIGHUP` the SDK flushes what it has captured. +::: + +## 4. Verify the first report + +Report a handled error and check that it shows up: + +```ts +const result = await bugsee.logException(new Error('Bugsee test error')); +console.log(result); +``` + +Then open your app in the Bugsee dashboard and look for the report. Reports upload in the background, and a report that cannot be uploaded right away is queued and retried. On a Node.js or Bun script, call `await bugsee.flush()` before the process exits. + +A repeated error with the same signature is deduplicated and `logException` is rate-limited (100 per 60 seconds), so change the message if you repeat the test. For a manual report that carries no exception, use `bugsee.upload({ summary: 'Test report' })`; see [Bug reporting](/sdk/javascript/manual/bug-reporting) and [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting). + +## App version and build + +Reports show the version and build of your app, so you can tell which release a problem belongs to. The most direct way is to pass them to `launch()`: + +```ts +launch('', { appVersion: '2.4.1', appBuild: '381' }); +``` + +If you leave them out, the SDK looks for them, and the first usable value for each wins: + +1. The `appVersion` and `appBuild` launch options. These always win. +2. Build-time constants, `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__`. The Bugsee Vite and webpack plugins inject them when you give the plugin an `appVersion` and `appBuild`, or set `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` in the build environment. You can also define the two constants yourself in your bundler, or set them as globals before launching. +3. On servers: the `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` environment variables. For the version, then the `version` field of the nearest `package.json`. For the build, then the commit variable your CI or host sets (such as `GITHUB_SHA` or `VERCEL_GIT_COMMIT_SHA`). +4. In the browser: `` and `` tags in the page. + +If no version is found, reports show version `0.0.0` and the SDK logs one warning. + +Keep the version and build the same as the ones you give the bundler plugin or `bugsee-cli` when you upload source maps. A mismatch is the most common reason a stack trace stays minified. See [Symbolication](/sdk/javascript/symbolication/overview) and [Symbolication environment](/sdk/javascript/symbolication/environment). + +## ESM and CommonJS + +Every package ships an ESM and a CommonJS build, selected by `exports` conditions, with TypeScript types for both. + +```js title="server.cjs" +const { launch } = require('@bugsee/bugsee'); + +launch(process.env.BUGSEE_APP_TOKEN ?? ''); +``` + +`@bugsee/bugsee` has these conditional entries: `browser`, `node`, `bun`, `workerd`, `edge-light`, `worker` and `default`. A bundler or runtime that honors `exports` conditions picks the right build with no configuration. For a tool that does not honor them, import an explicit subpath instead: + +| Subpath | Build | +| --- | --- | +| `@bugsee/bugsee/node` | Node.js | +| `@bugsee/bugsee/bun` | Bun | +| `@bugsee/bugsee/workerd` | Cloudflare Workers | +| `@bugsee/bugsee/edge-light` | Vercel Edge | +| `@bugsee/bugsee/worker` | Web and Service Workers | + +When you bundle a server application, keep the SDK launch in the entry that runs in Node.js, and make sure your bundler resolves the `node` condition for it. For browser bundles it must resolve `browser`. + +## Troubleshooting + +**Nothing arrives in the dashboard.** Check, in order: + +- The token is the one shown for your JavaScript app, with no stray whitespace. +- `onError` is set. Without it, SDK problems are silent. Pass `onError: (error) => console.error(error)` while you set up. +- The page or server can reach `https://api.bugsee.com`. A Content Security Policy needs it under `connect-src`, and a firewall or proxy must allow outbound HTTPS to it. If you set `endpoint`, use that origin instead. +- On a short-lived Node.js or Bun script, you await `flush()` before exit. +- `getStatus()` returns `BugseeStatus.Launched`; see [Lifecycle & status](/sdk/javascript/lifecycle). + +**"the app token is missing".** The value you passed was `undefined`, empty or not a string. A common cause is an environment variable that is not set at runtime, or one that a bundler does not expose to browser code. + +**A second `launch()` seems to do nothing.** That is by design: one client per process. Use `relaunch(options)` to change options. Options of a relaunch start from the defaults; they are not merged with the previous launch. See [Lifecycle & status](/sdk/javascript/lifecycle#relaunch). + +**Reports show version `0.0.0`.** The SDK could not find a version. Pass `appVersion`, set `BUGSEE_APP_VERSION`, or give your `package.json` a version. + +**Cloudflare Worker fails to start.** The SDK needs the `nodejs_compat` compatibility flag. See [Cloudflare](/sdk/javascript/platforms/cloudflare). + +**Errors in a framework are not reported.** Many frameworks catch errors before they reach the global handler. React, Vue and the others need their adapter; see [Frameworks](/sdk/javascript/frameworks/react). + +**Stack traces are minified.** Upload source maps with a bundler plugin or the CLI; see [Symbolication](/sdk/javascript/symbolication/overview). + +**Replay is missing in an SSR or pre-render pass.** Replay needs a DOM. In a DOM-less host the recorder does not start; it runs in the browser. + +## Next steps + +Your platform or framework has a dedicated page: + +- Platforms: [Browser](/sdk/javascript/platforms/browser), [Node.js](/sdk/javascript/platforms/node), [Bun](/sdk/javascript/platforms/bun), [Electron](/sdk/javascript/platforms/electron), [Cloudflare Workers](/sdk/javascript/platforms/cloudflare), [Vercel Edge](/sdk/javascript/platforms/vercel-edge), [Web Workers](/sdk/javascript/platforms/web-workers). +- Frameworks: [React](/sdk/javascript/frameworks/react), [Vue](/sdk/javascript/frameworks/vue), [Angular](/sdk/javascript/frameworks/angular), [Svelte](/sdk/javascript/frameworks/svelte), [Solid](/sdk/javascript/frameworks/solid), [Next.js](/sdk/javascript/frameworks/nextjs), [Nuxt](/sdk/javascript/frameworks/nuxt), [Remix](/sdk/javascript/frameworks/remix), [Astro](/sdk/javascript/frameworks/astro). +- Backend frameworks: [Backend overview](/sdk/javascript/backend/overview). + +Then: + +- [Configuration](/sdk/javascript/configuration) — every launch option. +- [Privacy](/sdk/javascript/privacy/overview) — masking and redaction. +- [Symbolication](/sdk/javascript/symbolication/overview) — readable production stack traces. +- [Lifecycle & status](/sdk/javascript/lifecycle) — launch, stop, relaunch and events. diff --git a/docs/sdk/javascript/issue-detection/diagnostics.mdx b/docs/sdk/javascript/issue-detection/diagnostics.mdx new file mode 100644 index 00000000..c45678dd --- /dev/null +++ b/docs/sdk/javascript/issue-detection/diagnostics.mdx @@ -0,0 +1,128 @@ +--- +title: "Diagnostics" +description: "Opt-in diagnostics for Node.js and Bun with the Bugsee JavaScript SDK: rolling CPU profiling, local variables on crash frames, and source lines around each frame." +sidebar_position: 5 +slug: "/sdk/javascript/issue-detection/diagnostics" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Three diagnostics add depth to what the [detectors](/sdk/javascript/issue-detection/overview) report on a server. All three are off by default, because each has a cost: CPU, or the exposure of data that a stack trace does not contain. + +| Diagnostic | Option | Default | Adds to a report | Node.js | Bun | +| --- | --- | --- | --- | --- | --- | +| CPU profiling | `profiling` | `false` | `profile.json`, and the blocking stack of a hang | Yes | Yes | +| Local variables | `captureLocalVariables` | `false` | The variables in scope on the stack frames | Yes | No | +| Source context | `captureSourceContext` | `false` | The source lines around each frame | Yes | Yes | + +These options are for servers and other Node.js and Bun processes. They have no effect in a browser. + +## CPU profiling + +Bugsee runs the V8 sampling profiler continuously and keeps the most recent window. When a report is created, the window is attached to it as `profile.json`, in the standard `.cpuprofile` format that Chrome DevTools and speedscope open. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `profiling` | `boolean` | `false` | Keep a rolling CPU profile and attach it to reports. | +| `profilingSamplingIntervalMicros` | `number` | `1000` | Sampling interval in microseconds. | + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + profiling: true, +}); +``` + +The window follows `maxRecordingTime` (60 seconds by default), so a long-running process never accumulates an unbounded profile. + +Cost, measured on Node.js 24 and Bun 1.3 on an Apple M4 Pro: + +| Sampling interval | CPU overhead | +| --- | --- | +| 10 ms | Under 1% | +| 1 ms (default) | Under 1% | +| 100 microseconds | About 4% on Node.js, 7% on Bun | + +A 60-second profile at the default interval is about 0.05 MB compressed. + +The profile is also what gives a [hang](/sdk/javascript/issue-detection/hangs) report its stack. + +## Local variables + +A stack trace says where an error was thrown. Local variables say what the code held at that moment. With `captureLocalVariables`, the variables in scope are attached to the stack frames of the crash or error. + +`true` turns it on with the defaults. Pass an object to tune it: + +```ts +launch('', { + captureLocalVariables: { + includeCaught: false, + maxFrames: 5, + maxVariables: 20, + maxValueLength: 120, + }, +}); +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `includeCaught` | `boolean` | `false` | Also capture at the throw site of exceptions that your code catches. Costly, see below. | +| `reportSite` | `boolean` | `true` | For an error you report with `logException`, also capture the scope the call was made from. | +| `maxFrames` | `number` | `5` | How many frames, from the top, get their variables. | +| `maxVariables` | `number` | `20` | How many variables per frame. | +| `maxValueLength` | `number` | `120` | The longest value kept, in characters. Longer values are truncated. | +| `maxCaughtPerSecond` | `number` | `50` | With `includeCaught`, how many caught throws per second may be captured. Above that, capture falls back to uncaught errors for a while. | +| `maxCached` | `number` | `20` | How many captured exceptions are held before the oldest is dropped. | + +By default Bugsee captures at uncaught exceptions, which costs almost nothing, and at the `logException` call site. + +:::caution[Cost] +The feature uses the V8 debugger. Merely enabling it costs a few percent of CPU in steady state. With `includeCaught`, every caught exception pauses the process for a few hundred microseconds, so an app that throws in a hot path pays continuously. Measure before you enable it in production. +::: + +:::caution[Privacy] +Variables hold whatever your code held. Names that match the SDK's sensitive-key list are redacted, and values are truncated, but a variable named `row` can still contain a customer record. That is why the feature is opt-in. +::: + +On Bun, `captureLocalVariables` is always off: Bun refuses the debugger domain it needs without an active inspector. + +## Source context + +With `captureSourceContext`, Bugsee reads the source of each application frame at report time and attaches the line that threw plus the lines around it. Reports then show code next to the stack, even when you have not uploaded source maps with embedded sources. + +Only application frames are read. Dependency frames are skipped. + +`true` turns it on with the defaults. Pass an object to tune it: + +```ts +launch('', { + captureSourceContext: { + contextLines: 5, + maxFrames: 5, + }, +}); +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `contextLines` | `number` | `5` | Lines on each side of the throwing line. | +| `maxFrames` | `number` | `5` | How many frames, from the top, get source context. | +| `maxLineLength` | `number` | `200` | The longest line kept, in characters. A minified bundle is one very long line. | +| `maxCachedFiles` | `number` | `50` | How many files are kept in memory after they are read. | +| `appRoot` | `string` | `process.cwd()` | Where relative frame paths are resolved from. | + +:::caution[Privacy] +Source context uploads your own source code, which a stack trace does not. That is why it is off by default. If you use source maps without embedded sources, source context reads the files from the running process, not from the maps. +::: + +The files must exist on the machine that runs the service. If you ship only a bundle, the frames point into the bundle, and the lines read from it are the bundle's lines. + +## Related pages + +- [Hangs](/sdk/javascript/issue-detection/hangs) — the report that uses the CPU profile +- [Errors and crashes](/sdk/javascript/issue-detection/errors-and-crashes) — the reports that carry local variables and source context +- [Symbolication](/sdk/javascript/symbolication/overview) — map minified frames to your source +- [Backend overview](/sdk/javascript/backend/overview) — where these options apply diff --git a/docs/sdk/javascript/issue-detection/errors-and-crashes.mdx b/docs/sdk/javascript/issue-detection/errors-and-crashes.mdx new file mode 100644 index 00000000..b8c1c85b --- /dev/null +++ b/docs/sdk/javascript/issue-detection/errors-and-crashes.mdx @@ -0,0 +1,88 @@ +--- +title: "Errors and crashes" +description: "How the Bugsee JavaScript SDK detects uncaught errors and unhandled promise rejections in the browser, Node.js and Bun, and how to control what happens to the process." +sidebar_position: 2 +slug: "/sdk/javascript/issue-detection/errors-and-crashes" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee detects two kinds of unhandled failure and reports each one with the recent logs, network calls and breadcrumbs. + +| Source | Report type | Default priority | +| --- | --- | --- | +| An uncaught error: the `error` event of the window, or `uncaughtException` of the process | Crash | `blocker` | +| An unhandled promise rejection: the `unhandledrejection` event of the window, or `unhandledRejection` of the process | Error | `high` | + +Both are controlled by `detectCrashes`, which is `true` by default. Set it to `false` to turn both detectors off. + +## Browser + +Bugsee listens for `error` and `unhandledrejection` on the window. It reads the message and the stack from the thrown value. A value that is not an `Error`, such as a thrown string or object, is still reported, with a summary built from it. + +Nothing changes for the page. Bugsee does not call `preventDefault`, so the browser still logs the error to the console. + +On a framework with its own error handling, for example Vue, which catches component errors, add the matching adapter so that the errors reach Bugsee. See the framework pages, starting with [Frameworks](/sdk/javascript/frameworks/react). + +## Node.js and Bun + +Bugsee listens for `uncaughtException` and `unhandledRejection` on the process. The launch options decide what happens to the process afterwards. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectCrashes` | `boolean` | `true` | Install the two process listeners. | +| `exitOnUncaught` | `boolean` | `true` | After an uncaught exception, flush the report and exit with code 1. | +| `unhandledRejections` | `'preserve' \| 'warn' \| 'none'` | `'preserve'` | What to do with an unhandled rejection. See below. | +| `shutdownTimeoutMs` | `number` | `3000` | How long to wait for the report to flush before exiting. | + +### Uncaught exceptions + +Bugsee writes the crash, waits up to `shutdownTimeoutMs` for the report to flush, then exits with code 1, as Node.js would have done. It prints the error to standard error first, because installing a listener removes Node.js's own message. + +Bugsee exits only when it is the sole `uncaughtException` listener. If your app or another library installed its own handler, that handler decides the outcome and Bugsee only reports. + +Set `exitOnUncaught: false` to keep the process alive after an uncaught exception. + +### Unhandled rejections + +Since Node.js 15, an unhandled rejection ends the process. A passive listener would silently turn a crashing service into one that runs on and exits with code 0, so Bugsee gives you three modes: + +| Mode | Behavior | +| --- | --- | +| `'preserve'` (default) | Reports the rejection, prints it, flushes, and then ends the process the way Node.js would. If you run with `--unhandled-rejections=warn` or `none`, the process stays alive. | +| `'warn'` | Reports and prints the rejection, and keeps the process alive. | +| `'none'` | Installs no listener. Node.js behaves as if Bugsee were absent, and rejections are not reported. | + +`exitOnUncaught` does not affect rejections. Use `unhandledRejections` for them. + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + unhandledRejections: 'warn', + exitOnUncaught: true, +}); +``` + +### Delivery after a crash + +The capture buffer of a Node.js or Bun process is on disk by default. The report is stored before it is uploaded, so a crash that kills the process before the upload finishes is delivered on the next launch (`recover` is `true` by default). See [Node.js](/sdk/javascript/platforms/node) for the storage options. + +## Stack traces + +When the build carries debug IDs, each frame is stamped with the ID of the bundle it came from, and Bugsee maps it back to your source. See [Symbolication](/sdk/javascript/symbolication/overview). + +On Node.js and Bun, two [diagnostics](/sdk/javascript/issue-detection/diagnostics) options add more to the frames: `captureLocalVariables` and `captureSourceContext`. + +## Other runtimes + +Service workers, web workers, edge runtimes and Electron have their own detectors. See the page of your runtime under [Platforms](/sdk/javascript/platforms/browser). + +## Related pages + +- [Issue detection overview](/sdk/javascript/issue-detection/overview) — all detectors and their defaults +- [Crash and error reporting](/sdk/javascript/manual/crash-error-reporting) — report errors you catch yourself +- [Diagnostics](/sdk/javascript/issue-detection/diagnostics) — local variables and source context on crash frames +- [Symbolication](/sdk/javascript/symbolication/overview) — readable stack traces from minified code diff --git a/docs/sdk/javascript/issue-detection/hangs.mdx b/docs/sdk/javascript/issue-detection/hangs.mdx new file mode 100644 index 00000000..04e81a18 --- /dev/null +++ b/docs/sdk/javascript/issue-detection/hangs.mdx @@ -0,0 +1,88 @@ +--- +title: "Hangs" +description: "Detect event-loop hangs in Node.js and Bun services with the Bugsee JavaScript SDK: escalating thresholds, the AppHang report and how to get the blocking stack." +sidebar_position: 3 +slug: "/sdk/javascript/issue-detection/hangs" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +A hang is a stretch of time in which the event loop is blocked. A synchronous loop, a huge `JSON.parse` or a blocking call keeps every request of the process waiting, and nothing is thrown, so no crash detector can see it. Bugsee detects it with a watchdog and reports it as an error. + +Hang detection runs on Node.js and Bun. It is on by default. + +## How it works + +The main thread writes a heartbeat into a shared buffer about once a second. A separate watchdog worker thread reads that buffer. A blocked event loop cannot write, so the heartbeat goes stale, and the worker notices. + +The worker is `unref`'d, so it never keeps a process alive. It uses about 12 MB of memory on Node.js and about 5 MB on Bun in our measurements, with negligible CPU. + +## Thresholds and levels + +A hang escalates through three levels as it gets longer. Each level reports once per hang. When the loop recovers, the detector re-arms, so a service that hangs again later reports again. + +| Level | Option | Default | Domain | +| --- | --- | --- | --- | +| Fair | `hangFairMs` | `3000` | `AppHang::Fair` | +| Medium | `hangMediumMs` | `5000` | `AppHang::Medium` | +| Severe | `hangSevereMs` | `10000` | `AppHang::Severe` | + +The thresholds must be positive and strictly increasing. If they are not, Bugsee falls back to the defaults for all three. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectHangs` | `boolean` | `true` | Turn hang detection on or off. | +| `hangFairMs` | `number` | `3000` | Stall length of the first level, in milliseconds. | +| `hangMediumMs` | `number` | `5000` | Stall length of the second level. | +| `hangSevereMs` | `number` | `10000` | Stall length of the third level. | + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + hangFairMs: 1000, + hangMediumMs: 3000, + hangSevereMs: 8000, +}); +``` + +## The report + +| Field | Value | +| --- | --- | +| Type | Error, with the error priority (`reportDefaultErrorPriority`) | +| Summary | `Main thread hang detected` | +| Description | `Event loop blocked for ms (AppHang::Fair)`, with the level of the report | +| Label | The domain, for example `AppHang::Fair` | + +## Get the blocking stack + +Nothing throws during a hang, so the report has no stack of its own. V8 keeps sampling while the loop is blocked, so the CPU profile of the stall shows where the code was stuck. + +Turn on `profiling` to use it: + +```ts +launch('', { + profiling: true, +}); +``` + +With profiling on, Bugsee takes the hottest stack of the stall window from the profile and attaches it to the hang report as its stack frames. Hangs are then grouped by where they block, and the report carries a `profile.json` as well. The profile is rolling, covers the last `maxRecordingTime` seconds, and opens in Chrome DevTools or speedscope. + +If the profile is not ready within five seconds, the report goes out without frames. + +Without `profiling`, every hang of a given level has the same signature, such as `AppHang::Fair`, and they are all grouped together. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics) for the profiler options and their cost. + +## Not covered + +- Browsers have no hang detector in this SDK. +- Cloudflare, Vercel Edge and worker runtimes do not run the watchdog. + +## Related pages + +- [Issue detection overview](/sdk/javascript/issue-detection/overview) — all detectors and their defaults +- [Diagnostics](/sdk/javascript/issue-detection/diagnostics) — CPU profiling +- [Node.js platform](/sdk/javascript/platforms/node) — Node.js launch options +- [Bun platform](/sdk/javascript/platforms/bun) — Bun launch options diff --git a/docs/sdk/javascript/issue-detection/http-errors.mdx b/docs/sdk/javascript/issue-detection/http-errors.mdx new file mode 100644 index 00000000..e0bf1958 --- /dev/null +++ b/docs/sdk/javascript/issue-detection/http-errors.mdx @@ -0,0 +1,63 @@ +--- +title: "HTTP errors" +description: "Report failing backend calls as errors with the Bugsee JavaScript SDK: 5xx responses from fetch, XHR and node:http, deduplicated per endpoint and status." +sidebar_position: 4 +slug: "/sdk/javascript/issue-detection/http-errors" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Network capture already records every request in the bundle of any report. With HTTP error detection, a request that comes back with a server error also files a report of its own. + +HTTP error detection is off by default. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectHttpErrors` | `boolean` | `false` | Report HTTP responses with a status from 500 to 599. | + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + detectHttpErrors: true, +}); +``` + +It needs network capture (`captureNetwork`, on by default). It watches the requests made by the app: `fetch` and XHR in a browser, `fetch` and `node:http` on a server. + +## What is reported + +| Response | Reported | +| --- | --- | +| 500 to 599 | Yes | +| 4xx | No. Validation errors, auth challenges and conditional requests are expected. | +| A failed or aborted request with no HTTP status | No | +| WebSocket, server-sent events, WebTransport and beacons | No | + +## Deduplication + +Each combination of method, endpoint and status is reported once per session, so a retry loop or a polling request does not file the same report again. The endpoint is the URL without its query, fragment and credentials, and path segments that look like identifiers or tokens (numeric ids, UUIDs, long hexadecimal strings, e-mail addresses and similar) are replaced by a placeholder. So `/orders/1` and `/orders/2` count as one endpoint. + +As a backstop, at most 20 reports are filed in any 60-second window, and at most 1000 distinct combinations are remembered per session. + +## The report + +| Field | Value | +| --- | --- | +| Type | Error, with the priority `high` | +| Summary | `HTTP `, for example `HTTP 503 Service Unavailable` | +| Domain | `HttpError::Server` | +| Grouping | One synthetic stack frame, ` `, so reports group by endpoint and exact status | +| Attributes | `http_status_code`, `http_method`, `http_url` and, when present, `http_status_text` | + +The priority is fixed. `reportDefaultErrorPriority` does not change it. + +The URL in the report has its query removed and goes through the default URL redaction. + +## Related pages + +- [Issue detection overview](/sdk/javascript/issue-detection/overview) — all detectors and their defaults +- [Network capture](/sdk/javascript/network) — what is recorded for each request +- [Backend overview](/sdk/javascript/backend/overview) — errors your own server returns diff --git a/docs/sdk/javascript/issue-detection/overview.mdx b/docs/sdk/javascript/issue-detection/overview.mdx new file mode 100644 index 00000000..a5ded6a2 --- /dev/null +++ b/docs/sdk/javascript/issue-detection/overview.mdx @@ -0,0 +1,60 @@ +--- +title: "Issue detection overview" +description: "What the Bugsee JavaScript SDK detects on its own: uncaught errors and crashes, unhandled promise rejections, event-loop hangs and failing HTTP requests." +sidebar_position: 1 +slug: "/sdk/javascript/issue-detection/overview" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Issue detection files a report without any code from you. When a detector fires, Bugsee assembles a bundle of the recent logs, network calls, breadcrumbs and (in a browser) the session replay, and uploads it. + +## What it detects + +| Detector | Runtime | Default | Report type | Page | +| --- | --- | --- | --- | --- | +| Uncaught error or exception | Browser, Node.js, Bun | On | Crash | [Errors and crashes](/sdk/javascript/issue-detection/errors-and-crashes) | +| Unhandled promise rejection | Browser, Node.js, Bun | On | Error | [Errors and crashes](/sdk/javascript/issue-detection/errors-and-crashes) | +| Event-loop hang | Node.js, Bun | On | Error | [Hangs](/sdk/javascript/issue-detection/hangs) | +| HTTP 5xx response | Browser, Node.js, Bun and the edge and worker runtimes | Off | Error | [HTTP errors](/sdk/javascript/issue-detection/http-errors) | + +A **crash** is something that ended or would have ended the process or page. An **error** is a problem the app survived. The two have separate default priorities: `reportDefaultCrashPriority` is `blocker` and `reportDefaultErrorPriority` is `high`. + +Errors you catch and report yourself with `logException` go through the same pipeline. See [Crash and error reporting](/sdk/javascript/manual/crash-error-reporting). + +## How it works + +- **Detectors are providers.** Each one watches a source: the `error` and `unhandledrejection` events of the window, the `uncaughtException` and `unhandledRejection` events of the process, a watchdog on the event loop, or the network capture. +- **Errors you report yourself are rate limited.** `logException` drops the same thrown object when it is reported twice, and accepts at most 100 calls in any 60-second window. HTTP errors have their own limits, described on their page. +- **Reports are delivered durably.** On Node.js and Bun, and in a browser with IndexedDB, a report is stored before it is uploaded. A report left behind by a process that was killed is uploaded on the next launch. +- **Stack traces are symbolicated.** Minified frames are mapped back to your source when you upload source maps. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Switches + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `detectCrashes` | `boolean` | `true` | Detect uncaught errors and unhandled rejections. | +| `detectHangs` | `boolean` | `true` | Detect event-loop hangs. Node.js and Bun only. | +| `detectHttpErrors` | `boolean` | `false` | Report HTTP 5xx responses. | + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + detectCrashes: true, + detectHangs: true, + detectHttpErrors: true, +}); +``` + +On a server, the [diagnostics](/sdk/javascript/issue-detection/diagnostics) options add local variables, source lines and a CPU profile to what these detectors report. + +## Related pages + +- [Errors and crashes](/sdk/javascript/issue-detection/errors-and-crashes) — uncaught errors and unhandled rejections +- [Hangs](/sdk/javascript/issue-detection/hangs) — Node.js and Bun event-loop hangs +- [HTTP errors](/sdk/javascript/issue-detection/http-errors) — report failing backend calls +- [Diagnostics](/sdk/javascript/issue-detection/diagnostics) — profiling, local variables and source context +- [Backend overview](/sdk/javascript/backend/overview) — per-request context for server errors diff --git a/docs/sdk/javascript/lifecycle.mdx b/docs/sdk/javascript/lifecycle.mdx new file mode 100644 index 00000000..1b93359a --- /dev/null +++ b/docs/sdk/javascript/lifecycle.mdx @@ -0,0 +1,194 @@ +--- +title: "Lifecycle & status" +description: "Launching, stopping, flushing and relaunching the Bugsee JavaScript SDK, reading its status, pausing visual capture with blackout, and observing lifecycle events." +sidebar_position: 3 +slug: "/sdk/javascript/lifecycle" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +The SDK can be launched, flushed, stopped and relaunched at runtime. You can read its status at any time and observe its lifecycle events, such as launch, stop, blackout and report upload. + +## Launch + +`launch(appToken, options?)` starts the SDK and returns the client. + +| Runtime | Returns | +| --- | --- | +| Browser | `Promise` | +| Node.js, Bun, Electron main, Cloudflare Workers, Vercel Edge, Web and Service Workers | the client, directly | +| Electron renderer | `Promise` of the client | + +Bugsee is a per-process singleton, so launch it once: + +- A second `launch()` is ignored. It returns the existing client, and reports "called more than once in this process" through `onError`. Its options are not applied; use [`relaunch()`](#relaunch) for that. +- A missing, empty or non-string token does not throw. `launch()` returns a disabled client, reports the problem once through `onError` (or `console.warn` when you gave none), and captures nothing. A later `launch()` with a valid token still works. + +## Status + +Read the state of the SDK with `getStatus()`, or ask a client with `bugsee.getStatus()` and `bugsee.isLaunched()`. The top-level `getStatus()` works at any time, including while a launch is still in progress and after the client is gone. + +```ts +import { BugseeStatus, getStatus } from '@bugsee/bugsee'; + +if (getStatus() === BugseeStatus.Launched) { + // capture is running +} +``` + +| `BugseeStatus` | Value | Meaning | +| --- | --- | --- | +| `Stopped` | `0` | Not running, or stopped. | +| `Launching` | `1` | A launch is in flight. Observable in the browser, where the launch is asynchronous. | +| `Launched` | `2` | Running. | +| `Stopping` | `3` | `stop()` is draining pending uploads. | + +`isLaunched()` is the quick check; `getStatus()` also tells you about the two transitions. + +## Flush and stop + +```ts +await bugsee.flush(); // wait for pending uploads +await bugsee.stop(); // stop capture and detection, then drain uploads +``` + +| Method | Resolves to | Description | +| --- | --- | --- | +| `flush(timeout?)` | `Promise` | Waits for pending uploads, including reports being assembled. `true` when everything drained within `timeout` milliseconds. | +| `stop(timeout?)` | `Promise` | Stops capture and detection, removes the handlers the SDK installed (process handlers, page-hide flush, server instrumentation), then drains pending uploads. `true` when they drained within `timeout`. | + +After `stop()`, the client is finished: `logException` and other manual capture calls do nothing, and the stopped client cannot be restarted. The process singleton is released, so calling `launch()` again builds a fresh client. + +Typical uses: + +- **Short-lived scripts:** `await bugsee.flush()` before the process exits, so the last report is uploaded. +- **Consent:** the SDK has no separate consent switch. Call `launch()` only after the user consents, and `stop()` to withdraw consent. +- **Tests:** `stop()` between tests releases the singleton. + +There is no pause and resume. To stop recording what is on screen for a while, use [blackout](#blackout). + +## Relaunch + +`relaunch(options?)` stops the running client and launches again with the same app token. + +```ts +import { relaunch } from '@bugsee/bugsee'; + +await relaunch({ captureNetworkBodies: false }); +``` + +- It returns a `Promise` of the new client on every runtime. +- Like the mobile SDKs, a relaunch starts from the defaults: the options you pass are the new options, and omitted options go back to their default. A few settings are kept from the previous launch: your `endpoint`, `appId`, `appVersion` and `appBuild`, `appRoot`, `dataDir`, `onError`, and the network, log and breadcrumb filters, `urlSanitizer` and report handler you set. See [Configuration](/sdk/javascript/configuration#options-kept-by-relaunch). +- A launch that is still in progress is waited for first. +- The previous client is drained for up to 5 seconds, so a stuck upload cannot hang the relaunch. +- It rejects when nothing has been launched yet, because there is no token to reuse. +- Your lifecycle listener survives the relaunch. + +`relaunch` is exported by the packages you install directly (`@bugsee/bugsee`, `@bugsee/bun`, `@bugsee/cloudflare`, `@bugsee/vercel-edge`, `@bugsee/webworker`). It is not available in `@bugsee/electron`, whose main process needs the Electron objects again; stop and call `launchMain` instead. + +## Blackout + +A blackout suppresses visual and interaction capture while a sensitive view is on screen: session replay, input presses, UI-interaction breadcrumbs and the view hierarchy. Logs, network, traces and events carry on. + +```ts +bugsee.startBlackout(); +// ... the user is on a screen that must not be recorded +bugsee.endBlackout(); + +bugsee.isBlackout(); // true while a blackout is in force +``` + +- `startBlackout()` is idempotent and not counted: one `endBlackout()` ends any number of calls. +- Both calls do nothing while the client is not launched, and they are not remembered. To be dark from the first moment, use the `startInBlackout` launch option in the browser. +- Call `endBlackout()` only after the sensitive view is gone. Replay resumes with a fresh snapshot taken from the live page, so a view still on screen would be recorded. +- `BlackoutStarted` and `BlackoutEnded` lifecycle events fire when it begins and ends. + +## Lifecycle events + +Lifecycle events are coarse milestones of the SDK. You observe them through one listener. Set it at launch to see the very first event, or later: + + + + +```ts +import { launch, LifecycleEvents } from '@bugsee/bugsee'; + +launch('', { + lifecycleEventsListener: (eventType, data) => { + if (eventType === LifecycleEvents.AfterReportUploaded) { + console.log('uploaded', data); + } + }, +}); + +// or later; pass null to remove it +bugsee.setLifecycleEventsListener((eventType, data) => { + /* ... */ +}); +``` + + + + +```js +import { launch, LifecycleEvents } from '@bugsee/bugsee'; + +launch('', { + lifecycleEventsListener: (eventType, data) => { + if (eventType === LifecycleEvents.AfterReportUploaded) { + console.log('uploaded', data); + } + }, +}); + +// or later; pass null to remove it +bugsee.setLifecycleEventsListener((eventType, data) => { + /* ... */ +}); +``` + + + + +The event names are the constants of `LifecycleEvents`, and they match the names used on the Bugsee mobile SDKs, so a handler can be shared across platforms. + +| Event | When | +| --- | --- | +| `Launching` | A launch begins. | +| `Launched` | The SDK is running. | +| `Stopping` | `stop()` begins draining. | +| `Stopped` | The SDK has stopped. | +| `BlackoutStarted`, `BlackoutEnded` | A blackout begins or ends. | +| `RelaunchedAfterCrash` | A launch found evidence that the previous run did not end cleanly. See the note below. | +| `BeforeReportShown`, `AfterReportShown` | The browser report dialog is shown and closed. `AfterReportShown` carries `{ sent }`. | +| `BeforeReportAssembled`, `AfterReportAssembled`, `ReportAssemblyFailed` | A report is being built from the captured data. The data carries `{ reportId }`; a failure also carries `error`. | +| `BeforeReportUploaded` | An assembled report is handed to the uploader. | +| `AfterReportUploaded` | The upload succeeded. The data carries `{ reportId, result }`. | +| `ReportUploadFailed` | The upload failed and will not be retried. | +| `ReportUploadFailedWithFutureRetry` | The upload failed, but the report is stored and the next launch retries it. | + +How the listener behaves: + +- It observes only. It cannot veto or change anything. +- A listener that throws, or returns a rejecting promise, is routed to `onError` and otherwise ignored. +- It is safe to call `launch()`, `stop()` or `startBlackout()` from inside it. Events caused that way are queued and delivered in order after the listener returns. +- There is one listener per process, and it applies to every client the process builds. + +Report events follow reports that go through the live path of the running client: detected errors, `logException`, `upload` and the report dialog. A report delivered another way is not announced: one re-uploaded from the durable queue on the next launch, a native crash collected by Electron, a queue overflow, or a hand-off from an Electron renderer. + +:::caution[RelaunchedAfterCrash is a hint] +The SDK emits `RelaunchedAfterCrash` only when a launch finds evidence on storage that the previous run did not end cleanly. It can be wrong in both directions. On Node.js, the commonest crash, an uncaught exception, uploads its report before the process exits and leaves no evidence, so the next launch stays silent. A script that exits normally while a report upload is still in flight, without calling `stop()`, looks like a crash. In the browser, closing a tab normally after a failed upload leaves the same evidence. The event is not sent on edge runtimes or anywhere else that keeps nothing durable across runs. If you need certainty, keep your own "clean exit" flag. +::: + +## Related pages + +- [Installation](/sdk/javascript/installation) — launch the SDK for the first time. +- [Configuration](/sdk/javascript/configuration) — every launch option. +- [Report handler](/sdk/javascript/report-handler) — change or veto a report before it is assembled. +- [Bug reporting](/sdk/javascript/manual/bug-reporting) — upload reports and show the report dialog. +- [Privacy](/sdk/javascript/privacy/overview) — what is masked by default. diff --git a/docs/sdk/javascript/logs.md b/docs/sdk/javascript/logs.md new file mode 100644 index 00000000..93d9ac8d --- /dev/null +++ b/docs/sdk/javascript/logs.md @@ -0,0 +1,119 @@ +--- +title: "Console logs" +description: "How the Bugsee JavaScript SDK captures console output, how to write your own lines with log, the capture level, and how to rewrite or drop lines with setLogEventFilter." +sidebar_position: 21 +slug: "/sdk/javascript/logs" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee records your console output and shows it on the report timeline, in time order with the recording and network events. Capture is on by default and needs no code. The SDK wraps the console methods, records each call, and then runs the original method, so your console output is unchanged. + +## What is captured + +| Console method | Recorded level | +| --- | --- | +| `console.error` | `error` | +| `console.warn` | `warning` | +| `console.log` | `info` | +| `console.info` | `info` | +| `console.debug` | `debug` | +| `console.trace` | `verbose`, with the call stack appended to the message | + +Arguments are joined with a space. Strings are kept as they are, an `Error` becomes its stack, and objects are written as JSON. There is no `%s` style substitution. Output written straight to `process.stdout` is not captured. + +Each captured line has a `timestamp`, a `level`, a `source` (`console` for console output, `logger` for lines you write with `log`) and a `message`. + +## Capture options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureLogs` | `boolean` | `true` | Record console output. | +| `captureLogsLevel` | `'error' \| 'warning' \| 'info' \| 'debug' \| 'verbose'` or `1` to `5` | `'verbose'` | The least severe level to record. Less severe lines are dropped. | + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = await launch('', { + captureLogsLevel: 'warning', // keep warnings and errors only +}); +``` + +The numeric form follows the mobile SDKs: `1` is `error`, `2` is `warning`, `3` is `info`, `4` is `debug` and `5` is `verbose`. A malformed value for `captureLogs` turns capture off and is reported through the `onError` launch option. An unrecognized `captureLogsLevel` is reported and everything is kept. + +The level applies to the lines you write with `log` as well as to console output. + +## Write your own lines + +The examples on this page use the client returned by `launch`, kept in a module of your own: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +`log(message, level?, timestamp?)` adds a line to the log stream. The level defaults to `'info'`. + +```ts +import { bugsee } from './bugsee'; + +bugsee.log('Checkout started'); +bugsee.log('Payment declined', 'warning'); +bugsee.log('Replayed from queue', 'debug', Date.now() - 5000); +``` + +`log` goes through the same level setting and the same filter as console output. It does nothing after the SDK has been switched off for your app. + +## Filter log lines + +`setLogEventFilter(filter)` installs a function that sees each line before it is recorded. Return the line, changed or not, to keep it, or `null` to drop it. Pass `null` to remove the filter. + +```ts +import { bugsee } from './bugsee'; + +const TOKEN = /\b(?:Bearer|Token)\s+[A-Za-z0-9._~+/-]+=*/gi; +const EMAIL = /[\w.%+-]+@[\w-]+(?:\.[\w-]+)+/g; + +bugsee.setLogEventFilter((line) => { + // Drop noisy third-party output + if (line.message.startsWith('[HMR]')) { + return null; + } + // Redact secrets in everything else + return { + ...line, + message: line.message.replace(TOKEN, '').replace(EMAIL, ''), + }; +}); +``` + +The filter receives a `LogEvent`: + +| Field | Type | Description | +| --- | --- | --- | +| `timestamp` | `number` | Milliseconds since the epoch. | +| `level` | `'error' \| 'warning' \| 'info' \| 'debug' \| 'verbose'` | The friendly level name. The SDK converts it to the numeric wire level after your filter has run. | +| `source` | `string` | `console` or `logger`. | +| `tag` | `string \| undefined` | An optional tag. | +| `message` | `string` | The formatted line. | + +Rules: + +- **A filter that throws drops the line.** The error goes to the `onError` launch option and the line is not recorded unredacted. +- **The level setting runs first.** The filter only sees lines at or above `captureLogsLevel`. +- **There is one filter at a time.** A later call replaces it. Set it right after `launch`. Lines logged before the filter is installed are recorded as they are. `relaunch()` returns a new client, so set the filter again on it. +- **The original console output is not affected.** The filter changes what Bugsee records, not what your console prints. + +:::tip +The most reliable control is not to log secrets. A filter is a safety net. See [Privacy: Console logs](/sdk/javascript/privacy/logs). +::: + +## Related pages + +- [Privacy: Console logs](/sdk/javascript/privacy/logs) — turn capture off and keep sensitive lines out. +- [Breadcrumbs](/sdk/javascript/breadcrumbs) — structured trail entries. +- [Network events](/sdk/javascript/network) — the other automatic capture stream. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/manual/bug-reporting.md b/docs/sdk/javascript/manual/bug-reporting.md new file mode 100644 index 00000000..f888f604 --- /dev/null +++ b/docs/sdk/javascript/manual/bug-reporting.md @@ -0,0 +1,215 @@ +--- +title: "Bug reporting" +description: "Let users and your code file bug reports with the Bugsee JavaScript SDK: the browser report dialog, silent upload with attachments, and prepareUpload for a report that freezes the recording first." +sidebar_position: 1 +slug: "/sdk/javascript/manual/bug-reporting" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +A bug report covers something that is wrong but did not throw. You can open the built-in report dialog in the browser, or send a report from your own code with `upload`, on every runtime. Crashes and handled exceptions are covered in [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting). + +All examples use the client returned by `launch`. Keep it in a module of your own: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +`launch` returns a promise in the browser and the client itself on Node.js and Bun. `await` works for both. + +## Show the report dialog + +`showReportDialog` is available in the browser only. It opens a form over the page, sends what the user fills in as a bug report, and resolves with the upload result, or `null` when the user cancels, a dialog is already open, or the SDK is not running. It never throws into your page. + +```ts +import { bugsee } from './bugsee'; + +document.querySelector('#report-bug')?.addEventListener('click', async () => { + const result = await bugsee.showReportDialog({ + summary: 'Checkout is broken', + labels: ['checkout'], + theme: 'auto', + }); + if (result?.ok) { + console.log('Report sent', result.issueId); + } +}); +``` + +The recording is frozen the moment you call `showReportDialog`, before the form appears. What the user types or does while filling in the form is not part of the report. + +### Dialog options + +Pass these per call. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `summary` | `string` | none | Pre-fill the summary. | +| `description` | `string` | none | Pre-fill the description. | +| `severity` | `'verylow' \| 'low' \| 'medium' \| 'high' \| 'critical' \| 'blocker'` | `reportDefaultBugPriority` (`high`) | Pre-select the severity. | +| `labels` | `string[]` | `[]` | Pre-fill the labels. | +| `theme` | `'auto' \| 'light' \| 'dark'` | `'auto'` | `auto` follows the system color scheme. | +| `strings` | `Partial` | English | Override any text in the dialog. This is how you localize it. | +| `css` | `string` | none | Extra CSS appended inside the dialog's shadow root. Write rules against the `bugsee-reporting-dialog-*` classes. | + +### Launch options for the form + +These launch options shape the form. They apply to the browser SDK. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `reportSummaryRequired` | `boolean` | `false` | The user must enter a summary. | +| `reportDescriptionRequired` | `boolean` | `false` | The user must enter a description. | +| `reportEmailRequired` | `boolean` | `false` | The user must enter an email. | +| `reportLabelsEnabled` | `boolean` | `false` | Show the labels field. | +| `reportLabelsRequired` | `boolean` | `false` | Require at least one label. Only with `reportLabelsEnabled`. | +| `reportPrioritySelectorEnabled` | `boolean` | `false` | Show the severity picker. | +| `reportDefaultBugPriority` | severity | `'high'` | Severity a bug report starts with. | + +```ts +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch('', { + reportSummaryRequired: true, + reportLabelsEnabled: true, + reportPrioritySelectorEnabled: true, +}); +``` + +The email field is the global user identifier. A changed value is saved with `setUserIdentifier`, and an emptied one is cleared. No format check is applied, because the identifier is often not an email address. See [User & session data](/sdk/javascript/user-session-data). + +### Translate the dialog + +```ts +import { bugsee } from './bugsee'; + +await bugsee.showReportDialog({ + strings: { + title: 'Ein Problem melden', + send: 'Senden', + summaryPlaceholder: 'Kurze Zusammenfassung', + }, +}); +``` + +The strings you can override are `title`, `close`, `summaryPlaceholder`, `descriptionPlaceholder`, `labelsPlaceholder`, `emailPlaceholder`, `severityLegend`, `severityLow`, `severityMedium`, `severityHigh`, `severityCritical`, `severityBlocker`, `send`, `sending`, `summaryRequired`, `descriptionRequired`, `emailRequired`, `labelsRequired`, `discardTitle`, `discardBody`, `discardKeep`, `discardConfirm` and `poweredBy`. + +The dialog fires the `BeforeReportShown` and `AfterReportShown` [lifecycle events](/sdk/javascript/lifecycle). + +## Upload a report without UI + +`upload` sends a bug report straight away. It works on every runtime, and it is neither de-duplicated nor rate limited: every call is a report you or a user asked for. It does run the [report handler](/sdk/javascript/report-handler). + +```ts +import { bugsee } from './bugsee'; + +const result = await bugsee.upload({ + summary: 'Export produced an empty file', + description: 'The user clicked Export on a project with 3 sheets.', + severity: 'medium', + labels: ['export'], + email: 'user@example.com', +}); + +if (result.ok) { + console.log('Report', result.issueId); +} else { + console.warn('Upload failed', result.error?.message); +} +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `summary` | `string` | none | Short title. | +| `description` | `string` | none | Longer text. | +| `severity` | severity | `reportDefaultBugPriority` (`high`) | `verylow`, `low`, `medium`, `high`, `critical` or `blocker`. | +| `labels` | `string[]` | none | Labels on the issue. | +| `email` | `string` | the user identifier | Reporter email. | +| `attachments` | `ReportAttachmentInput[]` | none | Files to attach, see below. | + +`upload` resolves with an `UploadResult`: + +| Field | Type | Description | +| --- | --- | --- | +| `ok` | `boolean` | `true` when the report was accepted. | +| `issueId` | `string \| undefined` | The id of the created issue. | +| `recordingId` | `string \| undefined` | The id of the recording. | +| `error` | `BugseeError \| undefined` | Why it failed. | + +After `stop()`, or once the collector has switched the SDK off for your app, `upload` is a silent no-op that resolves `{ ok: false }`. A report that cannot be sent right now is kept in the durable queue and sent on a later launch where the platform persists data; see [Privacy: Cleanup](/sdk/javascript/privacy/cleanup). + +### Attachments + +A report carries up to **3** attachments of up to **3 MB** each. An attachment over the limit, a malformed one, and any beyond the third are dropped and reported through the `onError` launch option. They are never thrown. + +```ts +import { bugsee } from './bugsee'; + +const cart = { items: 3, total: 42.5 }; + +await bugsee.upload({ + summary: 'Wrong total in cart', + attachments: [ + { + name: 'Cart state', + data: JSON.stringify(cart, null, 2), + mimeType: 'application/json', + fileName: 'cart.json', + }, + { name: 'Screenshot', data: new Uint8Array([137, 80, 78, 71]), mimeType: 'image/png' }, + ], +}); +``` + +| Field | Type | Description | +| --- | --- | --- | +| `name` | `string` | Label shown for the attachment. Required. | +| `data` | `Uint8Array \| string` | The content. A string is encoded as UTF-8. | +| `mimeType` | `string` | Defaults to `text/plain` for a string and `application/octet-stream` for bytes. | +| `fileName` | `string` | Suggested download name. Directory parts are stripped. Derived from `name` when omitted. | + +To attach a file to every report, or only to some, use `addReportAttachment` in a callback of the [report handler](/sdk/javascript/report-handler#attach-a-file). + +:::caution +Attachment content is not redacted. Keep secrets out of the data you attach. +::: + +## Freeze the recording first with prepareUpload + +`prepareUpload` freezes the recording now and returns a handle you can send later. Use it when you collect information from the user first, for example in your own form: the minutes they spend typing do not push the incident out of the rolling window. + +```ts +import { bugsee } from './bugsee'; + +async function reportFromMyForm(readForm: () => Promise<{ summary: string } | null>): Promise { + const prepared = bugsee.prepareUpload(); + if (prepared === null) { + return; // the SDK is stopped or switched off + } + const form = await readForm(); + if (form === null) { + prepared.discard(); // release the frozen recording, send nothing + return; + } + const result = await prepared.send({ summary: form.summary, severity: 'high' }); + console.log(result.ok); +} +``` + +- `prepareUpload()` returns `null` after `stop()` or once the SDK is switched off. +- `send(options?)` takes the same options as `upload`. It sends at most once: a second call resolves `{ ok: false }`. +- `discard()` releases the frozen recording without sending anything. + +The built-in report dialog uses this mechanism. + +## Related pages + +- [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting) — send handled exceptions with `logException`. +- [Report handler](/sdk/javascript/report-handler) — change or veto every report before it is sent. +- [User & session data](/sdk/javascript/user-session-data) — the identifier and attributes a report carries. +- [Lifecycle](/sdk/javascript/lifecycle) — report events such as `AfterReportUploaded`. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/manual/crash-error-reporting.md b/docs/sdk/javascript/manual/crash-error-reporting.md new file mode 100644 index 00000000..5872dd88 --- /dev/null +++ b/docs/sdk/javascript/manual/crash-error-reporting.md @@ -0,0 +1,174 @@ +--- +title: "Crash & error reporting" +description: "Report handled exceptions from code with the Bugsee JavaScript SDK: logException with severity, labels, domain and skipFrames, de-duplication and the rate limit, notify, and how to test crash capture." +sidebar_position: 2 +slug: "/sdk/javascript/manual/crash-error-reporting" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee reports uncaught errors and unhandled promise rejections on its own; see [Errors & crashes](/sdk/javascript/issue-detection/errors-and-crashes). This page covers the errors you catch yourself. A `try`/`catch` that swallows an exception hides it from automatic detection, so pass it to `logException` and it becomes a report with the recording that led up to it. + +The examples use the client returned by `launch`: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +## Report a handled exception + +```ts +import { bugsee } from './bugsee'; + +async function loadProject(id: string): Promise { + try { + await fetch(`/api/projects/${id}`).then((response) => { + if (!response.ok) throw new Error(`Project request failed: ${response.status}`); + }); + } catch (error) { + await bugsee.logException(error, { + severity: 'medium', + labels: ['projects'], + }); + } +} +``` + +`logException(error, options?)` accepts any thrown value, not only an `Error`. It returns a promise of an `UploadResult` (`ok`, `issueId`, `recordingId`, `error`), the same shape `upload` returns. For an `Error`, the report summary is its message and the description is its stack followed by the `cause` chain. Other values are described as text, and the stack starts at your `logException` call. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `severity` | `'verylow' \| 'low' \| 'medium' \| 'high' \| 'critical' \| 'blocker'` | `reportDefaultErrorPriority` (`high`) | Severity of the issue. | +| `labels` | `string[]` | none | Labels on the issue. | +| `domain` | `string` | none | A short category such as `checkout`. Sent with the exception. JavaScript reports are not grouped by it yet. | +| `skipFrames` | `number` | `0` | Leave the top N frames of the error's own stack out of issue grouping. | + +An invalid `domain` (not a non-empty string) or `skipFrames` (not a non-negative integer) is ignored and reported through the `onError` launch option. + +### Frames to skip + +Use `skipFrames` when you create the error, or log a non-`Error`, inside a helper, so errors do not all group at that helper. + +```ts +import { bugsee } from './bugsee'; + +function fail(message: string): never { + const error = new Error(message); + void bugsee.logException(error, { domain: 'validation', skipFrames: 1 }); + throw error; +} +``` + +The skipped frames stay visible in the stack trace. They are only left out of grouping. A caught error's stack does not contain your `logException` call, so skipping frames there hides where it was thrown. + +## De-duplication and the rate limit + +`logException` protects you from error storms: + +- **The same thrown object is reported once.** Logging an error object again, for example from a catch block that rethrows through several layers, does nothing and resolves `{ ok: false }`. +- **At most 100 reports in a rolling 60 seconds** per client. Further calls in that window are dropped and resolve `{ ok: false }`. +- **After `stop()`, and once the collector has switched the SDK off for your app,** `logException` is a silent no-op that resolves `{ ok: false }`. + +Errors are rate limited, not sampled: every error that passes these checks is reported. + +`upload` is different: it is neither de-duplicated nor rate limited, because every call is something a person asked for. See [Bug reporting](/sdk/javascript/manual/bug-reporting). + +## Change or drop reports + +The [report handler](/sdk/javascript/report-handler) sees every report, including the ones `logException` creates. Use its `before` callback to add labels or attributes, change the severity, or veto a report. + +```ts +import { bugsee } from './bugsee'; + +bugsee.setReportHandler({ + before: (request) => { + // Skip errors thrown by a browser extension + if (request.report.description?.includes('chrome-extension://')) { + return null; + } + return request; + }, +}); +``` + +## Send a message instead of a report + +`notify` relays a message to the messaging integrations you configured for the app, such as Slack or a webhook. It skips the report pipeline: no recording, logs or events, only the message. + +```ts +import { bugsee } from './bugsee'; + +bugsee.notify( + 'Payment provider is down', + 'Charges have failed for the last 5 minutes.', + 'critical', + { provider: 'example-pay', region: 'eu' }, + true, +); +``` + +| Argument | Type | Description | +| --- | --- | --- | +| `title` | `string` | Required. An empty title is ignored. | +| `body` | `string` | Optional text. | +| `severity` | severity | Optional. | +| `fields` | `Record` | Optional. Only string values are kept. | +| `urgent` | `boolean` | Send this message at once, ahead of the batching window. | + +Notifications are queued and sent in batches, and retried with backoff. The window is the `notifyFlushDelay` launch option, in milliseconds. It defaults to `0`, which sends at the end of the current tick. A call before `launch` or after `stop` does nothing. + +Unlike the mobile SDKs, the queue is in memory. A page closed with an unsent message loses it. `flush()` and `stop()` deliver what is pending. + +## Reports from your own server code + +On Node.js and Bun the process can exit before a report is delivered. Wait for it: + +```ts +import { bugsee } from './bugsee'; + +async function main(): Promise { + try { + await runJob(); + } catch (error) { + await bugsee.logException(error, { labels: ['nightly-job'] }); + await bugsee.flush(3000); + process.exitCode = 1; + } +} + +async function runJob(): Promise { + throw new Error('Job failed'); +} + +void main(); +``` + +`flush(timeout)` resolves `true` when pending uploads were drained within the timeout, in milliseconds. For uncaught exceptions, the SDK flushes before it exits the process; see the `shutdownTimeoutMs` and `exitOnUncaught` options in [Configuration](/sdk/javascript/configuration). + +Framework adapters call `logException` for you on the errors their framework catches. See [Backend overview](/sdk/javascript/backend/overview). + +## Test crash reporting + +Throw an error outside any `try`/`catch`, after `launch` has finished: + +```ts +setTimeout(() => { + throw new Error('Bugsee test crash'); +}, 0); +``` + +In the browser this is a `window` error and shows up as a crash. On Node.js it is an uncaught exception, and the SDK flushes and then exits the process unless you set `exitOnUncaught: false`. To test a handled error without ending anything, call `logException(new Error('Bugsee test error'))`. + +The default severity of a crash report is `blocker`, controlled by `reportDefaultCrashPriority`. The default for an error report is `high`, controlled by `reportDefaultErrorPriority`. + +## Related pages + +- [Errors & crashes](/sdk/javascript/issue-detection/errors-and-crashes) — what Bugsee detects without any code. +- [HTTP errors](/sdk/javascript/issue-detection/http-errors) — turn 5xx responses into error reports. +- [Bug reporting](/sdk/javascript/manual/bug-reporting) — user-initiated reports, `upload` and the dialog. +- [Report handler](/sdk/javascript/report-handler) — inspect, change or veto every report. +- [Lifecycle](/sdk/javascript/lifecycle) — `flush`, `stop` and report events. diff --git a/docs/sdk/javascript/network.md b/docs/sdk/javascript/network.md new file mode 100644 index 00000000..1d6c006b --- /dev/null +++ b/docs/sdk/javascript/network.md @@ -0,0 +1,171 @@ +--- +title: "Network events" +description: "How the Bugsee JavaScript SDK records fetch, XMLHttpRequest, WebSocket, SSE and node:http traffic, the capture options, the built-in redaction, and setNetworkEventFilter with getDefaultNetworkSanitizer." +sidebar_position: 20 +slug: "/sdk/javascript/network" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee records the network requests your app makes, with their headers, bodies and status codes, and shows them on the report timeline next to the recording and logs. Capture is on by default and needs no code. + +## What is captured + +The SDK patches the network APIs of the runtime when it launches, and restores them when it stops. + +| Mechanism (`event.mechanism`) | Source | Where | +| --- | --- | --- | +| `fetch` | Global `fetch` | Every runtime | +| `xhr` | `XMLHttpRequest` | Browsers | +| `ws` | `WebSocket` | Where `WebSocket` exists | +| `sse` | `EventSource` | Where `EventSource` exists | +| `webtransport` | `WebTransport` | Where `WebTransport` exists | +| `sendBeacon` | `navigator.sendBeacon` | Browsers | +| `http` | `node:http` and `node:https` clients, which libraries such as axios and got use | Node.js and Bun | + +Each request produces several events that share an `id`, one per stage: `before`, `complete`, `redirect`, `error`, `abort` and `timing` for requests, and `open`, `message` and `close` for WebSocket, SSE and WebTransport connections. The SDK's own traffic to Bugsee is not recorded. + +Network capture keeps running during a [blackout](/sdk/javascript/lifecycle). Only visual and interaction capture stop. + +## Capture options + +Set these in the options object you pass to `launch`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureNetwork` | `boolean` | `true` | Record network requests and responses. | +| `captureNetworkBodies` | `boolean` | `true` | Record request and response bodies. When `false`, no body is kept. | +| `maxNetworkBodySize` | `number` | `20480` | Largest body kept, in bytes of UTF-8. A larger body is dropped. | +| `captureNetworkBodyWithoutType` | `boolean` | `false` | Also keep bodies that declare no `Content-Type`. | +| `captureNetworkDefaultSanitizer` | `boolean` | `true` | Apply the built-in redaction. See [below](#built-in-redaction). | +| `detectHttpErrors` | `boolean` | `false` | Turn HTTP 5xx responses into error reports. See [HTTP errors](/sdk/javascript/issue-detection/http-errors). | + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = await launch('', { + captureNetworkBodies: true, + maxNetworkBodySize: 10240, +}); +``` + +A body that is dropped by the size or content-type rule is recorded as `null` with a reason, `size_too_large` or `no_content_type`, in `custom.no_body_reason`. + +A malformed boolean (for example `captureNetwork: 'false'`) turns the option **off** and is reported through the `onError` launch option, rather than leaving capture on by accident. + +## Built-in redaction + +With `captureNetworkDefaultSanitizer` on, every event is redacted before it is stored. The redacted value is ``. + +- **Headers.** The value of a sensitive header is replaced. The match is on the exact name, case-insensitive. The list includes `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `x-csrf-token`, `x-forwarded-for`, `x-real-ip` and a set of cloud and vendor token headers. +- **URL.** Values of sensitive query and fragment parameters, matrix parameters, and the password in `user:password@host` are replaced. The same pass runs on the error text of a failed request. +- **Bodies.** JSON, form-encoded, multipart, XML and `key: value` bodies have the values of sensitive keys replaced. Keys match by case-insensitive substring after separators are ignored, so `userPassword`, `api-key` and `oauth_token` all match. Substrings include `password`, `secret`, `token`, `auth`, `key`-style names such as `api_key`, card and bank fields such as `cvv` and `iban`, and national-id fields such as `ssn`. This is deliberately broad and can redact more than you need. +- **Secret shapes.** Values that look like a JSON Web Token or a well-known provider secret are replaced even under an innocent key name. + +Card numbers in free text are not redacted by shape. A card field is redacted by its key name only. + +## Filter network events + +`setNetworkEventFilter(filter)` installs a function that sees each event before it is recorded. Return the event, changed or not, to keep it, or `null` to drop it. Pass `null` to remove the filter. + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = await launch(''); + +bugsee.setNetworkEventFilter((event) => { + // Drop health checks + if (event.url.includes('/health')) { + return null; + } + return event; +}); +``` + +:::caution +A network filter **replaces** the built-in redaction. It does not run on top of it. From the moment a filter is set, URLs, headers, bodies and error text are recorded exactly as they are unless your filter redacts them. The example above ships `Authorization` headers. +::: + +### Keep the built-in redaction and add rules + +Compose with `getDefaultNetworkSanitizer()`. Call `sanitize` inside your filter, then add your own rules. + +```ts +import { getDefaultNetworkSanitizer, launch } from '@bugsee/bugsee'; + +const bugsee = await launch(''); +const defaults = getDefaultNetworkSanitizer(); + +bugsee.setNetworkEventFilter((event) => { + // Drop analytics and health checks, at every stage + if (event.url.includes('/health') || event.url.startsWith('https://analytics.example.com/')) { + return null; + } + + // Built-in redaction first + const sanitized = defaults.sanitize(event); + + // Then your own rules: remove a tenant header entirely + const headers = sanitized.custom?.headers; + if (headers === undefined) { + return sanitized; + } + const kept = Object.fromEntries( + Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'x-tenant-id'), + ); + return { ...sanitized, custom: { ...sanitized.custom, headers: kept } }; +}); +``` + +`getDefaultNetworkSanitizer()` returns a frozen object with three functions: + +| Function | Description | +| --- | --- | +| `sanitize(event)` | Redacts the URL, headers, body and error text of an event. Returns a new event, or the same one when nothing changed. Does not mutate its input. | +| `sanitizeUrl(url)` | Redacts sensitive query and fragment parameters and `user:password@` credentials in a URL. | +| `sanitizeErrorMessage(message)` | Redacts URLs and secrets quoted inside free text. | + +### Rules for filters + +- **A filter runs once per stage.** A request produces a `before` event, then a `complete` or `error` event, and so on. To drop a request, return `null` for every stage you recognize. Vetoing one stage does not hide the others. Match on `event.url`, or remember `event.id`. +- **A filter that throws drops the event.** The error goes to `onError`, and nothing unredacted is recorded. +- **The URL is made absolute first.** In a page or worker, a relative URL is completed with the document address before the filter runs. +- **The body policy runs first.** The filter sees the body after the size and content-type rules, so a dropped body is already `null`. +- **There is one filter at a time.** A later call replaces it. Set it right after `launch`, because events captured before the filter is installed are recorded with the built-in redaction. `relaunch()` returns a new client, so set the filter again on it. + +### The event + +The filter receives a `NetworkEvent`. These are the fields you will use most: + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | Shared by all events of one request or connection. | +| `mechanism` | `'fetch' \| 'xhr' \| 'ws' \| 'sse' \| 'sendBeacon' \| 'webtransport' \| 'http'` | What recorded it. | +| `type` | `'before' \| 'complete' \| 'redirect' \| 'error' \| 'abort' \| 'timing' \| 'open' \| 'message' \| 'close'` | The stage. | +| `url` | `string` | The request or connection URL. | +| `method` | `string` | The HTTP method. | +| `status` | `number \| undefined` | The response status. | +| `statusText` | `string \| undefined` | The response reason phrase. | +| `customError` | `string \| null \| undefined` | Error text of a failed request. | +| `custom.headers` | `Record \| undefined` | Request or response headers. | +| `custom.body` | `string \| null \| undefined` | The body as text. | +| `custom.no_body_reason` | `'size_too_large' \| 'no_content_type' \| 'unsupported_content_type' \| 'cant_read_data' \| null \| undefined` | Why a body is missing. | + +Streamed connections also carry `direction`, `event`, `code`, `reason` and `channel`. + +## Other places a URL can appear + +Your network filter applies to network events only. A URL can also appear in: + +- **Breadcrumbs.** See [Privacy: Breadcrumbs](/sdk/javascript/privacy/breadcrumbs). +- **The page address trace.** In the browser the SDK records the sanitized page address. The `urlSanitizer` launch option adds your own rule on top of the built-in one. +- **Performance spans.** With performance monitoring on, requests also become spans. Use `setSpanFilter` to change or drop them. See [Performance](/sdk/javascript/performance). + +## Related pages + +- [Privacy: Network](/sdk/javascript/privacy/network) — keep sensitive traffic out of reports. +- [HTTP errors](/sdk/javascript/issue-detection/http-errors) — report 5xx responses. +- [Console logs](/sdk/javascript/logs) — the other automatic capture stream. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/opentelemetry.mdx b/docs/sdk/javascript/opentelemetry.mdx new file mode 100644 index 00000000..bfa2c49a --- /dev/null +++ b/docs/sdk/javascript/opentelemetry.mdx @@ -0,0 +1,96 @@ +--- +title: "OpenTelemetry" +description: "Export Bugsee performance transactions to your own OpenTelemetry backend as OTLP, and feed your OpenTelemetry spans into Bugsee, from the JavaScript SDK." +sidebar_position: 21 +slug: "/sdk/javascript/opentelemetry" +--- + + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee works with OpenTelemetry in two directions: + +- **Export.** Finished Bugsee [performance transactions](/sdk/javascript/performance) are also sent to your OTLP endpoint. +- **Consume.** Spans recorded by your own OpenTelemetry SDK become Bugsee transactions. + +Both run in browsers and in Node.js. You do not install a Bugsee package for them: `@bugsee/opentelemetry` is a dependency of `@bugsee/bugsee`, and `launch()` wires it in when you set the options below. + +Both directions need performance monitoring to stay on, which is the default. + +## Export transactions to OTLP + +Set `otelExportUrl` to the OTLP/HTTP traces endpoint of your backend: + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + otelExportUrl: 'https://api.honeycomb.io/v1/traces', + otelExportHeaders: { 'x-honeycomb-team': '' }, + otelExportResource: { 'service.name': 'web' }, +}); +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `otelExportUrl` | `string \| URL` | none | The full OTLP/HTTP traces endpoint, for example `https://collector.example.com/v1/traces`. An empty value means no export. Any other type is reported through `onError` and also means no export. | +| `otelExportHeaders` | `Record` | none | Headers sent with each export, such as an API key. Use lowercase keys. | +| `otelExportResource` | `Record` | none | OTLP resource attributes, such as `service.name`. | + +How the export works: + +- It is a copy. Bugsee still receives the transactions. +- Transactions go to your endpoint in the same batches as the Bugsee upload. See `performanceUploadMode` and `performanceFlushIntervalMs` on the [performance page](/sdk/javascript/performance#upload). +- The body is OTLP JSON, posted with the content type `application/json`. +- Delivery is best effort. A failed export is reported through `onError` and the batch is not retried. +- Sampling applies. A transaction that is not sampled is not exported. +- Durations are derived from the start and end times, so sub-millisecond precision is lost. +- The Bugsee device id is added to the resource as `device_id`, unless your resource already names one. + +## Consume OpenTelemetry spans + +Register the span processor that Bugsee gives you on your own `TracerProvider`. Set `otelConsume` and receive the processor in `onOtelSpanProcessor`: + +```ts +import { launch, type BugseeSpanProcessor } from '@bugsee/bugsee'; + +await launch('', { + otelConsume: true, + onOtelSpanProcessor: (processor: BugseeSpanProcessor) => { + // Register `processor` on your OpenTelemetry TracerProvider. + }, +}); +``` + +How you register the processor depends on your OpenTelemetry SDK version. For example, pass it in the `spanProcessors` option of the provider's constructor. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `otelConsume` | `boolean` | `false` | Turn on span consumption. Needs `onOtelSpanProcessor`. | +| `onOtelSpanProcessor` | `(processor: BugseeSpanProcessor) => void` | none | Receives the span processor to register on your provider. | + +The OpenTelemetry SDK itself is your own dependency. Install the packages for your version, as shown below. + +| Your OpenTelemetry JS | Install | +| --- | --- | +| 1.x or 2.x | `@opentelemetry/api` and `@opentelemetry/sdk-trace-base` | +| 3.x (Node.js 22.15 or newer) | `@opentelemetry/api` and `@opentelemetry/sdk-trace`. Version 3 removed `sdk-trace-base`. `sdk-trace` also exists on 2.9 and later. | + +How consumption works: + +- Spans arrive one at a time, children usually first. Bugsee collects them by trace and creates one transaction when the root span of the trace ends. A child that ends after its root is not part of the transaction. +- A trace whose root never ends is dropped after a time limit, and the number of traces held at once is capped. +- Consumed transactions ride the same upload as native ones, and the same export if you set `otelExportUrl`. +- Span filters apply, and consumed spans are the main reason to have one. An instrumentation can attach raw SQL or request bodies to its spans. Use `setSpanFilter` to scrub or drop them. See [Performance](/sdk/javascript/performance#filter-or-drop-spans). + +## Trace propagation + +Bugsee propagates the W3C `traceparent` header on its own, without OpenTelemetry. `propagateTrace` and `tracePropagationTargets` are described on the [performance page](/sdk/javascript/performance#link-frontend-and-backend-traces) and the [backend overview](/sdk/javascript/backend/overview#trace-correlation). + +## Related pages + +- [Performance](/sdk/javascript/performance) — the transactions that are exported +- [Backend overview](/sdk/javascript/backend/overview) — trace continuation on a server +- [Privacy](/sdk/javascript/privacy/overview) — redaction and filters diff --git a/docs/sdk/javascript/overview.mdx b/docs/sdk/javascript/overview.mdx new file mode 100644 index 00000000..6ae1724e --- /dev/null +++ b/docs/sdk/javascript/overview.mdx @@ -0,0 +1,74 @@ +--- +title: "Overview" +description: "What the Bugsee JavaScript SDK records and detects, how one package covers browsers, Node.js, Bun, Electron, edge and worker runtimes, and what your app needs to run it." +sidebar_position: 0 +slug: "/sdk/javascript/overview" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +The Bugsee JavaScript SDK captures what happened before a bug: console logs, network traffic, breadcrumbs and, in the browser, a replay of the page. It attaches that timeline to crash, error and bug reports you can inspect in the Bugsee dashboard. + +One SDK covers every JavaScript runtime: browsers, Node.js, Bun, Electron, Cloudflare Workers, Vercel Edge, and Web and Service Workers. In most projects you install `@bugsee/bugsee` and call `launch()`. Runtimes and frameworks that need more have their own package; see [Packages](/sdk/javascript/packages). + +## What Bugsee records + +Every report carries a synchronized timeline of the session that led up to it: + +- **Console logs**: `console.*` output is captured and still prints as before; see [Console logs](/sdk/javascript/logs). +- **Network**: `fetch`, `XMLHttpRequest`, WebSocket, server-sent events and WebTransport requests, plus `node:http` on servers. URLs, headers and bodies pass through a default redaction first; see [Network events](/sdk/javascript/network) and [Privacy: Network](/sdk/javascript/privacy/network). +- **Breadcrumbs**: automatic UI-interaction breadcrumbs in the browser, plus breadcrumbs you add; see [Breadcrumbs](/sdk/javascript/breadcrumbs). +- **Session replay (browser and Electron)**: a replay of the page DOM, on by default and masked by default. An opt-in add-on records canvas content, and Electron can record pixel video; see [Session replay](/sdk/javascript/session-replay) and [Privacy: Session replay](/sdk/javascript/privacy/replay). +- **System traces and events**: memory, CPU, event-loop and other runtime state, and events such as process start and page hide. +- **Custom events, traces and attributes**: see [Custom events & traces](/sdk/javascript/events-and-traces) and [User & session data](/sdk/javascript/user-session-data). +- **Performance (APM)**: web vitals, page-load and navigation transactions, and spans you start yourself; see [Performance](/sdk/javascript/performance). + +## What Bugsee detects + +The SDK turns problems into reports automatically: + +- **Uncaught errors and unhandled promise rejections** in every runtime. See [Errors & crashes](/sdk/javascript/issue-detection/errors-and-crashes). +- **Hangs** on Node.js and Bun: a watchdog reports a blocked event loop as an `AppHang` report; see [Hangs](/sdk/javascript/issue-detection/hangs). +- **HTTP errors**: opt-in reporting of 5xx responses; see [HTTP errors](/sdk/javascript/issue-detection/http-errors). +- **Native crashes in Electron**, collected through Electron's built-in `crashReporter`; see [Electron](/sdk/javascript/platforms/electron). +- **Handled errors** you report yourself with `logException`; see [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting). +- **Manual reports** you send with `upload()`, or collect with the browser report dialog; see [Bug reporting](/sdk/javascript/manual/bug-reporting). + +## How it works + +- **One package, the right build.** `@bugsee/bugsee` resolves to the browser, Node.js, Bun, Cloudflare, Vercel Edge or worker build through package `exports` conditions, so the same import works everywhere. +- **Launch once, early.** `launch(appToken, options)` starts the SDK; see [Installation](/sdk/javascript/installation) and [Lifecycle & status](/sdk/javascript/lifecycle). In the browser it returns a `Promise` of the client; on servers, edge and workers it returns the client directly. +- **Adapters for your framework.** Frontend adapters report render errors and name routes, meta-framework adapters cover the server and the browser in one install, and backend adapters add per-request context and trace correlation. Each has its own page: [Platforms](/sdk/javascript/platforms/browser), [Frameworks](/sdk/javascript/frameworks/react) and [Backend](/sdk/javascript/backend/overview). +- **Privacy at capture time.** Replay masks text and inputs by default, network data is redacted by default, and you can filter or drop network, log and breadcrumb data before it is recorded; see [Privacy](/sdk/javascript/privacy/overview). +- **Readable production stack traces.** The Vite and webpack plugins, or the `bugsee-cli` tool, stamp debug IDs into your bundles and upload source maps; see [Symbolication](/sdk/javascript/symbolication/overview). +- **Reports survive failures.** Reports are queued durably where the runtime has storage (disk on Node.js and Bun, IndexedDB in the browser) and are re-uploaded with backoff on the next launch if an upload was interrupted. Edge runtimes buffer in memory and upload only when an incident happens. + +## Requirements + +| Runtime | Support | +| --- | --- | +| Browsers | Modern evergreen browsers. The package is built for ES2022. | +| Node.js | 18 or later | +| Bun | 1.1.13 or later; tested on 1.3 | +| Electron | Main process, renderers and native crashes through one package | +| Cloudflare Workers | With the `nodejs_compat` flag | +| Vercel Edge | Edge functions and other Web-API-only isolates | +| Web Workers, Service Workers | Dedicated, shared and service workers | + +The packages ship both ESM and CommonJS builds. Deno is not supported. + +Some features need a capability the runtime may lack. Persistence across reloads in the browser needs IndexedDB and Web Locks, session replay needs a DOM, and local variable capture needs the Node.js inspector (it is always off on Bun). + +## Get started + +Head to [Installation](/sdk/javascript/installation) to add the package, get an app token and send a first report. [Configuration](/sdk/javascript/configuration) lists every launch option. + +## Related pages + +- [Installation](/sdk/javascript/installation) — add the package, launch the SDK and verify a report. +- [Configuration](/sdk/javascript/configuration) — launch options for every runtime. +- [Lifecycle & status](/sdk/javascript/lifecycle) — launch, stop, relaunch and lifecycle events. +- [Packages](/sdk/javascript/packages) — which packages to install and which are internal. +- [Privacy](/sdk/javascript/privacy/overview) — what is masked and redacted by default. diff --git a/docs/sdk/javascript/packages.mdx b/docs/sdk/javascript/packages.mdx new file mode 100644 index 00000000..75959947 --- /dev/null +++ b/docs/sdk/javascript/packages.mdx @@ -0,0 +1,142 @@ +--- +title: "Packages" +description: "Catalogue of the 49 Bugsee JavaScript SDK packages: which ones you install for each runtime, framework and build tool, and which are internal building blocks." +sidebar_position: 20 +slug: "/sdk/javascript/packages" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +The SDK is published as 49 npm packages under the `@bugsee` scope. You install only a few of them. The rest are building blocks that the packages you install depend on, and their APIs can change without notice. + +All packages share one version (currently 0.1.0-beta.8), ship ESM and CommonJS builds, and target ES2022. Keep every `@bugsee/*` package in your project at the same version. Install with the `beta` tag, for example `npm install @bugsee/bugsee@beta`. + +## Which packages do I install? + +| Where your code runs | Install | Launch from | +| --- | --- | --- | +| Browser, Node.js | `@bugsee/bugsee` | `@bugsee/bugsee` | +| Bun | `@bugsee/bun` | `@bugsee/bun` | +| Electron | `@bugsee/electron` | `@bugsee/electron/main`, `/preload`, `/renderer` | +| Cloudflare Workers | `@bugsee/cloudflare` | `@bugsee/cloudflare` | +| Vercel Edge | `@bugsee/vercel-edge` | `@bugsee/vercel-edge` | +| Web Worker, Service Worker | `@bugsee/webworker` | `@bugsee/webworker` | +| React | `@bugsee/bugsee` and `@bugsee/react` | `@bugsee/bugsee` | +| Vue, Angular, Svelte, Solid | `@bugsee/bugsee` and the matching adapter | `@bugsee/bugsee` | +| Next.js, Nuxt, Remix, SvelteKit, Astro | the matching adapter alone | the adapter package | +| Express, Fastify, NestJS, Hono, Koa, hapi, Elysia | `@bugsee/bugsee` and the matching adapter | `@bugsee/bugsee` | + +See [Installation](/sdk/javascript/installation) for the steps. + +## Packages you install + +### Core SDK and runtimes + +| Package | Use it for | Page | +| --- | --- | --- | +| `@bugsee/bugsee` | The main entry point. It resolves to the browser, Node.js, Bun, Cloudflare, Vercel Edge or worker build, and turns on performance monitoring and OpenTelemetry interop. It also has explicit subpaths: `/node`, `/bun`, `/workerd`, `/edge-light` and `/worker`. | [Installation](/sdk/javascript/installation) | +| `@bugsee/bun` | Bun. Runs the Node.js pipeline and identifies the runtime as Bun. | [Bun](/sdk/javascript/platforms/bun) | +| `@bugsee/electron` | Electron: main process, preload and renderer in one session, with native crashes. Takes the Electron objects as arguments and has no dependency on `electron`. | [Electron](/sdk/javascript/platforms/electron) | +| `@bugsee/cloudflare` | Cloudflare Workers and Durable Objects. Needs the `nodejs_compat` flag. | [Cloudflare](/sdk/javascript/platforms/cloudflare) | +| `@bugsee/vercel-edge` | Vercel Edge Functions and other Web-API-only isolates. | [Vercel Edge](/sdk/javascript/platforms/vercel-edge) | +| `@bugsee/webworker` | Web Workers and Service Workers, which need their own launch because they are separate JavaScript contexts. | [Web Workers](/sdk/javascript/platforms/web-workers) | + +### Frontend adapters + +Install these next to `@bugsee/bugsee`. Each re-exports the umbrella's launch API, and requires the framework as a peer dependency. + +| Package | Framework | Page | +| --- | --- | --- | +| `@bugsee/react` | React 18 or later, and Preact: error boundary, root error handlers, profiler, router naming. | [React](/sdk/javascript/frameworks/react) | +| `@bugsee/vue` | Vue 3: error handler and vue-router naming. | [Vue](/sdk/javascript/frameworks/vue) | +| `@bugsee/angular` | Angular 16 or later: `ErrorHandler` and router naming. | [Angular](/sdk/javascript/frameworks/angular) | +| `@bugsee/svelte` | Svelte 4 or later and SvelteKit 2 or later: `handleError` hook and navigation naming. | [Svelte](/sdk/javascript/frameworks/svelte) | +| `@bugsee/solid` | Solid 1.6 or later: error primitives and router naming. | [Solid](/sdk/javascript/frameworks/solid) | + +### Meta-framework adapters + +Each is a single install. It wires the browser client and the server (and the edge, where the framework has one) together, so one session covers the request and the browser that made it. + +| Package | Framework | Page | +| --- | --- | --- | +| `@bugsee/nextjs` | Next.js: `instrumentation.ts`, `instrumentation-client.ts`, middleware, Node.js and Edge runtimes. | [Next.js](/sdk/javascript/frameworks/nextjs) | +| `@bugsee/nuxt` | Nuxt module, with the Vue error handler and the Nitro server. | [Nuxt](/sdk/javascript/frameworks/nuxt) | +| `@bugsee/remix` | Remix and React Router v7: `handleError` and the client entry. | [Remix](/sdk/javascript/frameworks/remix) | +| `@bugsee/sveltekit` | SvelteKit server and client hooks, and an edge entry. | [Svelte](/sdk/javascript/frameworks/svelte) | +| `@bugsee/astro` | Astro integration: browser launch on every page, plus a server middleware. | [Astro](/sdk/javascript/frameworks/astro) | + +### Backend adapters + +Install these next to `@bugsee/bugsee` on Node.js 18 or later (or Bun). Each adds per-request context, an `http.server` transaction, and error reporting for its framework. + +| Package | Framework | Page | +| --- | --- | --- | +| `@bugsee/express` | Express | [Express](/sdk/javascript/backend/express) | +| `@bugsee/fastify` | Fastify | [Fastify](/sdk/javascript/backend/fastify) | +| `@bugsee/nestjs` | NestJS, on the Express and Fastify platforms | [NestJS](/sdk/javascript/backend/nestjs) | +| `@bugsee/hono` | Hono, hosted on Node.js or Bun | [Hono](/sdk/javascript/backend/hono) | +| `@bugsee/koa` | Koa | [Koa](/sdk/javascript/backend/koa) | +| `@bugsee/hapi` | hapi | [Hapi](/sdk/javascript/backend/hapi) | +| `@bugsee/elysia` | Elysia, on Bun and Node.js | [Elysia](/sdk/javascript/backend/elysia) | + +### Build tooling + +Install these as development dependencies. They upload source maps and stamp debug IDs so production stack traces resolve to your source; see [Symbolication](/sdk/javascript/symbolication/overview). + +| Package | Use it for | Page | +| --- | --- | --- | +| `@bugsee/vite-plugin` | Vite. | [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) | +| `@bugsee/webpack-plugin` | webpack. | [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) | +| `@bugsee/bundler-plugin-core` | The engine behind the two plugins. Install it directly only for the Rollup, esbuild and Rspack plugins (`bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`), which are less exercised than Vite and webpack. | [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) | +| `@bugsee/babel-plugin-component-annotate` | Optional. Labels DOM elements of React, Preact and Solid components with the component name (`data-bugsee-component`), so clicks and errors are attributed to a component even after minification. | [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) | +| `@bugsee/svelte-plugin-component-annotate` | Optional. The same labels for Svelte and SvelteKit, as a Svelte preprocessor. | [Bundler plugins](/sdk/javascript/symbolication/bundler-plugins) | + +The `bugsee-cli` command-line tool, which the plugins run, is a separate package, `@bugsee/cli`. See [Symbolication: manual](/sdk/javascript/symbolication/manual). + +## Packages you do not install + +### Extensions pulled in by the umbrella + +These are dependencies of `@bugsee/bugsee` and are switched on or off through launch options. Do not add them yourself. + +| Package | What it does | Controlled by | +| --- | --- | --- | +| `@bugsee/performance` | Performance monitoring: web vitals, page-load and navigation transactions, HTTP spans and the manual span API. On by default. | `performanceMonitoring`. See [Performance](/sdk/javascript/performance). | +| `@bugsee/opentelemetry` | OpenTelemetry interop: export Bugsee transactions as OTLP/JSON, and consume your own OpenTelemetry spans. | `otelExportUrl`, `otelConsume`. See [OpenTelemetry](/sdk/javascript/opentelemetry). | +| `@bugsee/replay` | Session replay for the browser. Loaded lazily; on by default. | `replay`. See [Session replay](/sdk/javascript/session-replay). | +| `@bugsee/replay-canvas` | Opt-in canvas recording for replay. Loaded lazily; off by default. | `replay.canvas`. | + +### Platform builds + +`@bugsee/browser` and `@bugsee/node` are the platform builds the umbrella wraps and selects for you by `exports` condition. Other packages (the adapters, Bun and Electron) build on them. Install `@bugsee/bugsee` instead. + +### Internal building blocks + +These packages are implementation details. Their READMEs say the API may change, so do not depend on them. + +| Package | Role | +| --- | --- | +| `@bugsee/core` | The SDK kernel: client, capture and storage, report and upload pipelines, extension registry. | +| `@bugsee/capture` | Cross-runtime capture sources (console, network) and capture providers. | +| `@bugsee/protocol` | The wire contract: shapes the SDK uploads and the rules for sanitizing them. | +| `@bugsee/types` | TypeScript types shared across packages. No runtime code. | +| `@bugsee/util` | Pure, runtime-portable helpers. | +| `@bugsee/logger` | The SDK's own diagnostic logger. | +| `@bugsee/service` | The service container used for dependency injection inside the SDK. | +| `@bugsee/trackers` | Foundation for the domain trackers over system and runtime APIs. | +| `@bugsee/node-utils` | Node.js HTTP transport and file-system storage, shared by Node.js, Bun and Electron main. | +| `@bugsee/browser-utils` | `fetch` transport, IndexedDB storage and DOM helpers, shared by browser and worker builds. | +| `@bugsee/rrweb` | Thin wrapper over the record path of Bugsee's hardened rrweb fork, used by session replay. | +| `@bugsee/integration-shims` | No-op stand-ins for DOM-only integrations on runtimes without a DOM. | +| `@bugsee/web-adapter` | Shared plumbing for the frontend framework adapters. | +| `@bugsee/adapter-kit` | Shared primitives for the meta-framework adapters. | +| `@bugsee/webview` | The JavaScript side of Bugsee for web content in native WebViews. The native Bugsee SDK ships and injects it; you do not install it in a web app. | + +## Related pages + +- [Installation](/sdk/javascript/installation) — add a package and launch the SDK. +- [Overview](/sdk/javascript/overview) — what the SDK records and detects. +- [Configuration](/sdk/javascript/configuration) — launch options by runtime. +- [Release notes](/sdk/javascript/release-notes) — what changed in each beta. diff --git a/docs/sdk/javascript/performance.mdx b/docs/sdk/javascript/performance.mdx new file mode 100644 index 00000000..903138b2 --- /dev/null +++ b/docs/sdk/javascript/performance.mdx @@ -0,0 +1,187 @@ +--- +title: "Performance monitoring" +description: "Application performance monitoring in the Bugsee JavaScript SDK: Core Web Vitals, page-load, navigation and request transactions, the manual transaction and span API, and sampling." +sidebar_position: 20 +slug: "/sdk/javascript/performance" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Application performance monitoring (APM) records how long your app's work takes, as a tree of transactions and spans. Bugsee attaches the transactions to reports and uploads them continuously. + +APM is on by default when you launch through the `@bugsee/bugsee` package. It is not part of the bare platform packages. `performanceMonitoring` is its master switch: with `false`, nothing is recorded, and the manual API returns a no-op object that is safe to call. + +## Concepts + +- A **transaction** is the root of a trace. It has a name, such as `checkout`, an operation, such as `ui.action`, attributes and a status. +- A **span** is a unit of work inside a transaction. Spans form a tree. Each one has an operation, an optional description, attributes and a status. + +A span ends with one of these statuses: `OK`, `ERROR`, `TIMEOUT`, `CANCELLED`, `DEADLINE_EXCEEDED` or `UNKNOWN`. + +## Automatic instrumentation + +### In a browser + +| What | Operation | Details | +| --- | --- | --- | +| Page load | `pageload` | One transaction per page load, named after the path of the page. It carries the Core Web Vitals, the navigation timing and a child span per resource, and finishes when the page is hidden. | +| Route change | `navigation` | One transaction per route change of a single-page app, detected through the History and Navigation APIs. It finishes after a period without activity, or when the next navigation starts. Needs `traceNavigations`. | +| Interaction | `ui.interaction` | One short transaction per user interaction slower than 40 ms, the unit of Interaction to Next Paint. An interaction that triggers a navigation is not counted twice. Needs `traceInteractions`. | +| Requests | `http.client` | A child span for each `fetch` and XHR request made while a transaction is active. | + +A pageload transaction carries these attributes: + +| Attribute | Content | +| --- | --- | +| `web_vital..value` and `web_vital..rating` | Time to First Byte (`ttfb`), First Contentful Paint (`fcp`), Largest Contentful Paint (`lcp`), Cumulative Layout Shift (`cls`) and Interaction to Next Paint (`inp`), each with its rating. | +| `nav._ms` | The phases of the navigation timing: redirect, DNS, connect, TLS, request, response, DOM interactive, DOM content loaded and load. A phase that did not happen is left out. | + +Child spans of a pageload: + +| Operation | Content | +| --- | --- | +| `resource.` | One span per loaded asset, with the query and fragment removed from its URL. At most 100 per page. `fetch` and XHR are covered by `http.client`. | +| `ui.long-task` | One span per main-thread task longer than 50 ms. | + +Each transaction gets at most 100 `http.client` spans. + +### On a server + +| What | Operation | Details | +| --- | --- | --- | +| Startup | `app.start` | One transaction from process start to `launch()`. Set `appStartTimeMs` to override the start time. | +| Incoming request | `http.server` | One transaction per request, created by the backend instrumentation. See the [backend overview](/sdk/javascript/backend/overview). | +| Outgoing requests | `http.client` | A child span for each outgoing request made while a request transaction is active. | + +On a server the active transaction is tracked per request, so concurrent requests never share a trace and an outgoing call is attached to the request that issued it. + +## Transactions and spans + +Wrap a flow in a transaction to measure it end to end, and break it into spans for detail. Finish every span and transaction you start. + + + + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = await launch(''); + +const transaction = bugsee.startTransaction('checkout', 'ui.action', { cart_size: 3 }); + +const load = bugsee.startSpan('db.query', 'Load cart'); +// ... load the cart ... +load.finish(); + +const charge = bugsee.startSpan('http.client', 'POST /charge'); +// ... call the payment endpoint ... +charge.finish('ERROR'); + +transaction.finish(); +``` + + + + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = launch(''); + +const transaction = bugsee.startTransaction('nightly-sync', 'job', { source: 'crm' }); + +const load = bugsee.startSpan('db.query', 'Load customers'); +// ... load the customers ... +load.finish(); + +transaction.finish(); +``` + + + + +| Call | Description | +| --- | --- | +| `startTransaction(name, operation, attributes?)` | Starts a transaction. `attributes` is an object of initial attributes. | +| `startSpan(operation, description?)` | Starts a span. When a span is active, the new one is its child. Otherwise it becomes the root of a new transaction named after the description, or the operation. | +| `getActiveSpan()` | Returns the active span, or `undefined`. | + +A transaction or span has these methods: + +| Method | Description | +| --- | --- | +| `setName(name)` | Renames it. | +| `setDescription(description)` | Sets the description. | +| `setAttribute(key, value)` | Sets an attribute. | +| `setStatus(status)` | Sets the status. | +| `startChildSpan(operation, description?)` | Starts a child span of this one. | +| `recordChildSpan(operation, options)` | Records a child span that already ended, with `startTimestampMs`, `endTimestampMs`, and optionally `description` and `attributes`. | +| `finish(status?)` | Ends it, optionally with a final status. Calling it twice is harmless. | +| `getSpanId()`, `getTraceId()`, `getStatus()`, `getOperation()`, `getDescription()`, `getAttributes()`, `isFinished()` | Read its state. | + +A transaction adds `getName()` and `isSampled()`. + +## Sampling + +`performanceSampleRate` is a head sampling rate from 0 to 1. The decision is made once for each transaction when it starts. A transaction that is not sampled is not recorded. + +- `1`, the default, records every transaction. `0` records none. +- A transaction that continues an inbound trace follows the sampling decision of the caller, so both sides of a distributed trace keep or drop it together. + +Sampling applies only to transactions. Errors and crashes are never sampled. + +## Upload + +Finished transactions are buffered and uploaded in the background. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `performanceMonitoring` | `boolean` | `true` | Master switch for transactions and Web Vitals. | +| `performanceSampleRate` | `number` | `1` | Head sampling rate, from 0 to 1. | +| `performanceUploadMode` | `'batched' \| 'realtime'` | `'batched'` | Upload every flush interval, or each transaction as it finishes. | +| `performanceFlushIntervalMs` | `number` | `30000` | The interval of batched uploads, in milliseconds. | +| `traceNavigations` | `boolean` | `true` | Browser. A transaction per route change. | +| `traceInteractions` | `boolean` | `true` | Browser. A transaction per slow interaction. | +| `pageName` | `string` | the current path | Browser. The name of the pageload transaction. | +| `appStartTimeMs` | `number` | process start | Server. The start time of the `app.start` transaction. | +| `propagateTrace` | `boolean` | off in a browser, on on a server | Add `traceparent` to outgoing requests. | +| `tracePropagationTargets` | `(string \| RegExp)[]` | none | Outgoing URLs allowed to receive the trace headers. | +| `tracePropagationOrigin` | `string` | `location.origin` | Browser. The origin treated as same-origin. | + +```ts +launch('', { + performanceSampleRate: 0.25, + performanceUploadMode: 'realtime', +}); +``` + +## Link frontend and backend traces + +With `propagateTrace`, Bugsee adds the W3C `traceparent` header to your outgoing requests, and the backend transaction continues the trace of the frontend. + +- In a browser, `propagateTrace` is off by default. Same-origin requests then receive the header, and cross-origin requests only when their URL matches `tracePropagationTargets`. +- On a server, `propagateTrace` is on by default, but nothing is sent until you set `tracePropagationTargets`. See the [backend overview](/sdk/javascript/backend/overview#trace-correlation). + +```ts +launch('', { + propagateTrace: true, + tracePropagationTargets: ['https://api.example.com'], +}); +``` + +## Filter or drop spans + +`setSpanFilter` runs over every finished transaction, your own and any consumed from OpenTelemetry. Return the span, changed or not, to keep it, or `null` to drop it. A filter that throws drops the span it threw on. + +A span filter replaces the built-in span sanitizer. See [Privacy](/sdk/javascript/privacy/overview). + +## Related pages + +- [OpenTelemetry](/sdk/javascript/opentelemetry) — export transactions to your own backend, or feed in your OpenTelemetry spans +- [Backend overview](/sdk/javascript/backend/overview) — request transactions and trace propagation on a server +- [Privacy](/sdk/javascript/privacy/overview) — what is redacted by default diff --git a/docs/sdk/javascript/platforms/browser.mdx b/docs/sdk/javascript/platforms/browser.mdx new file mode 100644 index 00000000..f83e0366 --- /dev/null +++ b/docs/sdk/javascript/platforms/browser.mdx @@ -0,0 +1,171 @@ +--- +title: "Browser" +description: "Set up the Bugsee JavaScript SDK in a web app: install @bugsee/bugsee, launch it, and learn the browser-specific options, persistence, session replay and report dialog." +sidebar_position: 1 +slug: "/sdk/javascript/platforms/browser" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +In the browser, `@bugsee/bugsee` captures global errors and unhandled rejections, console output, network requests, user interactions, the page URL and session replay. It keeps a rolling recording window and uploads it as a report when something goes wrong or when the user reports a bug. + +If you use a UI framework, start from its page under [Frameworks](/sdk/javascript/frameworks/react) instead. They all build on what is described here. + +## Requirements + +- A browser with ES2022 support. +- An application token from the Bugsee dashboard. +- For persistence across reloads, IndexedDB and Web Locks (`navigator.locks`). Web Locks needs a secure context (`https://` or `localhost`). Without them the SDK keeps its data in memory. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta +``` + + + + +You install only `@bugsee/bugsee`. It selects the browser build through package `exports` conditions. `@bugsee/browser` is an internal building block that you do not install. + +## Launch + +Call `launch()` as early as possible, at the top of your entry module. + +```ts title="main.ts" +import { launch } from '@bugsee/bugsee'; + +launch('', { appVersion: '1.4.2', appBuild: '381' }); +``` + +In the browser `launch()` returns a `Promise` of the client. Await it only if you need the client right away: + +```ts +const bugsee = await launch(''); + +bugsee.addBreadcrumb({ message: 'checkout started' }); +``` + +A second `launch()` in the same page is ignored with a warning and returns the existing client. A missing or empty token does not throw: the SDK reports one error through `onError` (or `console.warn`) and returns a disabled client. + +### App version and build + +Reports carry your app's version and build. Bugsee resolves them in this order: + +1. The `appVersion` and `appBuild` launch options. +2. The build-time constants `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__`. The [Vite and webpack plugins](/sdk/javascript/symbolication/bundler-plugins) inject them when you give the plugin `appVersion` and `appBuild`, or set `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` in the build environment. +3. Meta tags in the page: + +```html + + +``` + +If no version is found, the SDK logs one warning and reports version `0.0.0` and build `0`. + +## What is exported + +`@bugsee/bugsee` exports: + +| Export | Description | +| --- | --- | +| `launch(appToken, options?)` | Starts the SDK. In the browser it returns `Promise`. | +| `relaunch(options?)` | Restarts the SDK, optionally with new options. | +| `getStatus()` | Returns the current `BugseeStatus`. | +| `BugseeStatus` | The status values `getStatus()` returns. | +| `LifecycleEvents` | The lifecycle event names. See [Lifecycle](/sdk/javascript/lifecycle). | +| `addReportAttachment(input)` | Adds an attachment to reports. | +| `getDefaultNetworkSanitizer()` | The default network redaction, to compose with your own filter. | + +The client has methods for [user data](/sdk/javascript/user-session-data), [breadcrumbs](/sdk/javascript/breadcrumbs), [events and traces](/sdk/javascript/events-and-traces) and [manual reports](/sdk/javascript/manual/bug-reporting). + +## Browser options + +`launch(appToken, options)` accepts the [common options](/sdk/javascript/configuration). These apply to the browser only: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `replay` | `boolean` or object | `true` | Session replay. `false` turns it off. See [Session replay](/sdk/javascript/session-replay). | +| `captureInteractions` | `boolean` | `true` | Record clicks, key presses and other interactions. | +| `captureViewHierarchy` | `boolean` | `true` | Record the DOM view hierarchy. | +| `captureUrl` | `boolean` | `true` | Record the sanitized page URL as the `url` trace. | +| `urlSanitizer` | `(url: string) => string \| null` | none | Runs after the default URL sanitizer. Return `null` to write nothing for that URL. | +| `captureUserIdle` | `boolean` | `false` | Record user idle periods. | +| `persist` | `boolean` | IndexedDB when available | Keep the capture window and the report queue in IndexedDB. `false` keeps everything in memory. | +| `persistUserIdentifier` | `boolean` | `false` | Keep the user identifier across page loads. | +| `startInBlackout` | `boolean` | `false` | Start with capture paused. See [Lifecycle](/sdk/javascript/lifecycle). | +| `maxDataSize` | `number` | 20 MB (30 MB with IndexedDB) | Size cap of the recording, in megabytes. | +| `diskProtection` | `boolean` | `true` | Stop writing when the origin's storage quota runs low. | +| `captureDiskSpace` | `boolean` | `false` | Add low-disk telemetry to the `capture` system trace. | + +The report dialog has its own options: `reportSummaryRequired`, `reportDescriptionRequired`, `reportEmailRequired`, `reportLabelsEnabled`, `reportLabelsRequired` and `reportPrioritySelectorEnabled`, all `false` by default. Open the dialog with `client.showReportDialog()`; see [Bug reporting](/sdk/javascript/manual/bug-reporting). + +## Persistence + +By default the rolling capture window and the queue of reports waiting to upload live in IndexedDB. After a reload or browser restart the recent past is still there, and a report interrupted mid-upload is sent on the next visit. + +The default applies only when the page exposes both IndexedDB and Web Locks. Otherwise the SDK stays in memory. Pass `persist: true` to store anyway, or `persist: false` to force memory. If the browser refuses to store data (over quota, some private modes), writes fail best effort and the error goes to `onError`. + +When storage headroom drops below 50 MiB, the SDK stops writing replay, logs and network data to IndexedDB. Below 10 MiB it writes nothing. Set `diskProtection: false` to opt out. + +## Gotchas + +- **Content Security Policy.** Allow `connect-src https://api.bugsee.com` (or your own `endpoint`) so uploads can leave the page. +- **Session replay records the DOM.** Text and inputs are masked by default. Review [Privacy](/sdk/javascript/privacy/overview) before you ship. +- **Separate contexts.** A worker is a separate JavaScript context with its own launch; use [Web and Service Workers](/sdk/javascript/platforms/web-workers) for workers. +- **Single page apps.** Route names make reports easier to read. The framework adapters set them for you; without one, call `client.setRoute('/orders/:id')` with the route pattern, not the concrete URL. + +## Source maps + +Minified stack traces need source maps. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Start your app with the launch call in place. +2. Report a test error from your code: + +```ts +const bugsee = await launch(''); +bugsee.logException(new Error('Bugsee test error')); +``` + +3. Open the Bugsee dashboard. The report appears within a minute, with the console, network and replay data. + +If nothing arrives, pass an `onError` callback to `launch` and check the browser's network panel for blocked requests to `api.bugsee.com`. + +## Related pages + +- [Installation](/sdk/javascript/installation) — install and launch for every runtime +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Session replay](/sdk/javascript/session-replay) — DOM replay, masking and the canvas add-on +- [Privacy](/sdk/javascript/privacy/overview) — what is masked and how to change it +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/platforms/bun.mdx b/docs/sdk/javascript/platforms/bun.mdx new file mode 100644 index 00000000..372efb7b --- /dev/null +++ b/docs/sdk/javascript/platforms/bun.mdx @@ -0,0 +1,130 @@ +--- +title: "Bun" +description: "Set up the Bugsee JavaScript SDK in a Bun app with @bugsee/bun: launch, Bun.serve instrumentation, crash recovery, and the differences from Node.js." +sidebar_position: 3 +slug: "/sdk/javascript/platforms/bun" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/bun` is the SDK for Bun. It runs the same pipeline as the [Node.js](/sdk/javascript/platforms/node) SDK (crash and error capture, console and network capture, on-disk capture with crash recovery, hang detection and profiling) and adds automatic instrumentation of `Bun.serve` requests. It only changes how the runtime is identified in reports: `bun` and its version. + +## Requirements + +- Bun 1.1.13 or newer. The SDK is tested on Bun 1.3. +- An application token from the Bugsee dashboard. + +## Install + + + + +```bash +npm install @bugsee/bun@beta +``` + + + + +```bash +pnpm add @bugsee/bun@beta +``` + + + + +```bash +yarn add @bugsee/bun@beta +``` + + + + +```bash +bun add @bugsee/bun@beta +``` + + + + +Install `@bugsee/bun` instead of `@bugsee/bugsee` in a Bun project. It does not include the umbrella's extensions (performance monitoring and OpenTelemetry). + +## Launch + +Call `launch()` at the top of your entry file. It returns the client directly, not a `Promise`. + +```ts title="index.ts" +import { launch } from '@bugsee/bun'; + +const bugsee = launch('', { appVersion: '1.4.2' }); + +Bun.serve({ + port: 3000, + fetch() { + return new Response('ok'); + }, +}); +``` + +Incoming `Bun.serve` requests are instrumented automatically. Each request gets its own request context. Pass `instrumentIncomingRequests: false` to opt out. Frameworks that run on `node:http` are covered by the `node:http` instrumentation; see [Backend](/sdk/javascript/backend/overview). + +## What is exported + +`@bugsee/bun` re-exports everything from the Node build (`@bugsee/node`) and adds the following: + +| Export | Description | +| --- | --- | +| `launch(appToken, options?)` | Starts the SDK and returns the client synchronously. | +| `relaunch(options?)` | Restarts the SDK, optionally with new options. | +| `launchCore` | The composition root behind `launch`. Returns more than the client. | +| `createBunServeInterceptor` | The `Bun.serve` instrumentation that `launch` installs. | +| `bunSystemProbe`, `createBunSystemProbe` | The probe that identifies the runtime as `bun`. | + +## Options + +`launch(appToken, options)` takes the same options as on Node.js. See [Node.js options](/sdk/javascript/platforms/node#node-options) and [Configuration](/sdk/javascript/configuration). Common ones: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appVersion`, `appBuild`, `appId` | `string` | resolved | Identify your release in reports. | +| `captureLogs`, `captureNetwork`, `captureNetworkBodies` | `boolean` | `true` | Capture streams. | +| `maxRecordingTime` | `number` | `60` | Rolling recording window, in seconds. | +| `dataDir` | `string` | `/bugsee` | Directory for the on-disk buffer. | +| `detectHangs` | `boolean` | `true` | Event-loop hang detection. | +| `profiling` | `boolean` | `false` | Rolling CPU profile attached to reports. | +| `instrumentIncomingRequests` | `boolean` | `true` | Automatic `Bun.serve` request instrumentation. | + +## Differences from Node.js + +- **`captureLocalVariables` is always off.** Bun refuses the debugger API that the feature needs unless an inspector is open, so the SDK forces the option off even if you set it. +- **Some system traces are omitted rather than reported as zero.** On Bun, the event-loop utilization and garbage-collection data are not reliable, and V8 heap figures do not apply, so the SDK leaves those traces out of Bun reports. +- **Both `Bun.serve` and `node:http` are instrumented.** The Node `node:http` instrumentation also runs under Bun when `instrumentIncomingRequests` is on. + +## Source maps + +If you bundle with `bun build`, inject debug IDs and upload the maps yourself. See [Manual source map upload](/sdk/javascript/symbolication/manual). + +## Verify + +1. Launch the SDK with a real token. +2. Report a test error: + +```ts +const bugsee = launch(''); +bugsee.logException(new Error('Bugsee test error')); +await bugsee.flush(); +``` + +3. Open the Bugsee dashboard. The report appears within a minute, with `bun` and its version in the environment. + +## Related pages + +- [Node.js](/sdk/javascript/platforms/node) — the options and behavior Bun shares +- [Backend](/sdk/javascript/backend/overview) — request context and framework adapters +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/platforms/cloudflare.mdx b/docs/sdk/javascript/platforms/cloudflare.mdx new file mode 100644 index 00000000..19b81d1e --- /dev/null +++ b/docs/sdk/javascript/platforms/cloudflare.mdx @@ -0,0 +1,185 @@ +--- +title: "Cloudflare Workers" +description: "Set up the Bugsee JavaScript SDK in a Cloudflare Worker with @bugsee/cloudflare: withBugsee, Durable Objects, the nodejs_compat flag and incident-driven uploads." +sidebar_position: 5 +slug: "/sdk/javascript/platforms/cloudflare" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/cloudflare` captures errors, logs and network calls inside your Worker, Durable Objects, and Cron, Queue, Email and Tail handlers, and uploads a report when something goes wrong. + +Edge isolates run only Web APIs, so capture is incident-driven. Data is buffered in memory and uploaded only when an incident happens: a handled `logException`, a thrown handler error, or an unhandled rejection. A clean request uploads nothing. + +## Requirements + +- A Cloudflare Worker (`workerd`). +- The `nodejs_compat` compatibility flag. The SDK imports `node:async_hooks` for per-request context, and without the flag your Worker fails to start. +- An application token, stored as a Worker secret. + +## Install + + + + +```bash +npm install @bugsee/cloudflare@beta +``` + + + + +```bash +pnpm add @bugsee/cloudflare@beta +``` + + + + +```bash +yarn add @bugsee/cloudflare@beta +``` + + + + +```bash +bun add @bugsee/cloudflare@beta +``` + + + + +Install `@bugsee/cloudflare` directly. It builds on `@bugsee/vercel-edge`, which you do not install separately. + +## Enable Node.js compatibility + +```toml title="wrangler.toml" +compatibility_flags = ["nodejs_compat"] +``` + +If your project uses `wrangler.jsonc`, set `"compatibility_flags": ["nodejs_compat"]` there instead. + +## Wrap your handlers + +Wrap everything your Worker exports with `withBugsee`. The first argument is a function that receives `env`, because Cloudflare exposes secrets only inside handlers. The client launches on the first invocation and is cached for the isolate's lifetime. + +```ts title="src/index.ts" +import { withBugsee } from '@bugsee/cloudflare'; + +export default withBugsee((env) => env.BUGSEE_APP_TOKEN, { + fetch: async (request, env, ctx) => new Response('ok'), + scheduled: async (controller, env, ctx) => { + /* Cron */ + }, + queue: async (batch, env, ctx) => { + /* Queue consumer */ + }, + email: async (message, env, ctx) => { + /* Email */ + }, + tail: async (events, env, ctx) => { + /* Tail Worker */ + }, +}); +``` + +Add the secret with `wrangler secret put BUGSEE_APP_TOKEN`. + +Each handler runs in its own Bugsee context. Errors are captured and rethrown, and the upload is flushed through that handler's `ctx.waitUntil`, so it survives the isolate freezing after the response. Each non-fetch trigger is labeled (cron, queue, email, tail), so a report says which trigger fired. Email addresses and message bodies are never captured. For `fetch`, the report includes Cloudflare's coarse geo and network metadata from `request.cf` (colo, country, city, timezone, ASN, TLS version). + +`withBugsee` also accepts a `WorkerEntrypoint` class. Pass `{ instrumentRpcMethods: true }` to wrap its RPC methods too. + +## Durable Objects + +A Durable Object is bound separately from the module handlers, so wrap its export with `instrumentDurableObject`. + +```ts title="src/counter.ts" +import { instrumentDurableObject } from '@bugsee/cloudflare'; + +class CounterBase extends DurableObject { + async fetch(request: Request) { + /* ... */ + } + async alarm() { + /* ... */ + } +} + +export const Counter = instrumentDurableObject((env) => env.BUGSEE_APP_TOKEN, CounterBase, { + instrumentRpcMethods: true, // optional, also wraps RPC methods (default off) +}); +``` + +## Options + +Instead of a token string, the callback passed to `withBugsee` or `instrumentDurableObject` may return an options object that includes `appToken`: + +```ts +export default withBugsee( + (env) => ({ appToken: env.BUGSEE_APP_TOKEN, appVersion: '1.4.2' }), + { fetch: async () => new Response('ok') }, +); +``` + +The options are the same as for `launch(appToken, options)`. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appVersion`, `appBuild`, `appId` | `string` | resolved | Identify your release in reports. | +| `captureLogs`, `captureNetwork`, `captureNetworkBodies` | `boolean` | `true` | Capture streams. | +| `maxDataSize` | `number` | 10 MB | Size of the in-memory buffer, divided across the partitions below. | +| `partitionCaptureByTenant` | `boolean` | `true` on Cloudflare | Keep each Durable Object's capture in its own partition, so an incident uploads only the faulting tenant's data. Setting `false` turns that isolation off and logs a warning. | +| `maxTenantPartitions` | `number` | `8` | Number of tenant partitions. The `maxDataSize` budget is divided across `maxTenantPartitions + 1` buffers. Lower it if your Workers host few tenants. | + +See [Configuration](/sdk/javascript/configuration) for the shared options. + +## What is exported + +`@bugsee/cloudflare` re-exports everything from `@bugsee/vercel-edge` and adds the following: + +| Export | Description | +| --- | --- | +| `withBugsee(config, handlers)` | Instruments a handler object or a `WorkerEntrypoint` class. | +| `instrumentDurableObject(config, Class, options?)` | Instruments a Durable Object class. | +| `launch(appToken, options?)` | Launches the client directly, with the platform identity set to Cloudflare. Returns the client synchronously. | +| `relaunch` | Restarts the SDK. | +| `cfAttributes`, `cloudflareRequestAttributes` | Read Cloudflare's `request.cf` metadata into report attributes. | +| `getStatus`, `BugseeStatus`, `LifecycleEvents`, `addReportAttachment`, `getDefaultNetworkSanitizer` | The shared client exports. | + +## App version and build + +Pass `appVersion` and `appBuild` in the options. The Vite and webpack plugins can also inject `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__` at build time, and the `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` environment variables apply below those constants. If none is found, reports show version `0.0.0` and build `0`. + +## Source maps + +Upload source maps for your Worker bundle so stack traces are readable. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Deploy the Worker (or run `wrangler dev`) with the secret set. +2. Trigger an error in a handler: + +```ts +export default withBugsee((env) => env.BUGSEE_APP_TOKEN, { + fetch: async () => { + throw new Error('Bugsee test error'); + }, +}); +``` + +3. Open the Bugsee dashboard. The report appears with the request, logs and `request.cf` metadata. + +If the Worker fails to start, check that `nodejs_compat` is set. + +## Related pages + +- [Vercel Edge](/sdk/javascript/platforms/vercel-edge) — the edge build that this package wraps +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Manual crash and error reporting](/sdk/javascript/manual/crash-error-reporting) — `logException` for handled errors +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/platforms/electron.mdx b/docs/sdk/javascript/platforms/electron.mdx new file mode 100644 index 00000000..83f5b0e8 --- /dev/null +++ b/docs/sdk/javascript/platforms/electron.mdx @@ -0,0 +1,185 @@ +--- +title: "Electron" +description: "Set up the Bugsee JavaScript SDK in an Electron app with @bugsee/electron: main process, preload bridge, renderers, native crashes, sandboxed renderers and video capture." +sidebar_position: 4 +slug: "/sdk/javascript/platforms/electron" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/electron` joins the main process (Node.js), the renderer processes (Chromium) and native crashes into one Bugsee session. A report carries console output, network calls, logs and session replay from every process. + +The main process owns the session and uploads reports. Renderers stream their capture up to it over IPC, and the main process drives them back down with a control channel. Native crashes are collected through Electron's built-in `crashReporter` and attached to the same session. + +## Requirements + +- Electron with Node.js 18 or newer in the main process. +- An application token from the Bugsee dashboard. +- A preload script in every window that should be recorded. + +The package has no dependency on `electron`. You pass Electron objects in, so it works with whichever Electron version you use. + +## Install + + + + +```bash +npm install @bugsee/electron@beta +``` + + + + +```bash +pnpm add @bugsee/electron@beta +``` + + + + +```bash +yarn add @bugsee/electron@beta +``` + + + + +```bash +bun add @bugsee/electron@beta +``` + + + + +Install `@bugsee/electron` directly. You do not need `@bugsee/bugsee`. + +## Set up + +There are three entry points, one for each process type. + +### 1. Main process + +Launch it early. Pass `ipcMain` (required), `app` (to catch renderer processes that die) and `crashReporter` (for native crashes). + +```ts title="main.ts" +import { launchMain } from '@bugsee/electron/main'; +import { app, crashReporter, ipcMain } from 'electron'; + +launchMain('', { ipcMain, app, crashReporter }); +``` + +`launchMain` returns the client directly. + +### 2. Preload script + +The preload exposes the IPC bridge through `contextBridge`, so it works with context isolation. + +```ts title="preload.ts" +import { registerBugseePreload } from '@bugsee/electron/preload'; +import electron from 'electron'; + +registerBugseePreload(electron); +``` + +### 3. Renderer + +```ts title="renderer.ts" +import { launchRenderer } from '@bugsee/electron/renderer'; + +launchRenderer(''); +``` + +`launchRenderer` returns a `Promise` of the client. Session replay is on by default and streams to the main process. + +## What is exported + +| Entry | Exports | +| --- | --- | +| `@bugsee/electron/main` | `launchMain`, the Electron tracker and crash helpers, the shared client exports (`getStatus`, `BugseeStatus`, `LifecycleEvents`, `addReportAttachment`, `getDefaultNetworkSanitizer`) and the video source helpers. | +| `@bugsee/electron/preload` | `registerBugseePreload` and the bridge constants and types. | +| `@bugsee/electron/renderer` | `launchRenderer` and the shared client exports. | + +`@bugsee/electron/main` has no `relaunch`: `launchMain` needs the app's `ipcMain`, so launch again from your own code if you must. + +## Options + +`launchMain(appToken, options)` takes these Electron options, plus every [Node.js option](/sdk/javascript/platforms/node#node-options) (`appVersion`, `captureLogs`, `captureNetwork`, `maxRecordingTime`, `dataDir` and others). + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `ipcMain` | Electron `ipcMain` | required | Carries capture from renderers and control messages back. | +| `app` | Electron `app` | none | Watches for renderer processes that die, reports window and renderer events, and supplies `app.getVersion()` as the app version. | +| `crashReporter` | Electron `crashReporter` | none | Collects native crashes (minidumps) into the session. | +| `crashReporterExtra` | `Record` | none | Extra fields sent with native crash dumps. | +| `powerMonitor` | Electron `powerMonitor` | none | Records power events, thermal state and CPU speed limit. | +| `screen` | Electron `screen` | none | Records display events and the `displays` trace. Pass it after the app is ready. | +| `BrowserWindow` | Electron `BrowserWindow` | none | Lets the SDK track windows that already exist. | +| `gpuInfoType` | `'basic'` \| `'complete'` | `'basic'` | The `app.getGPUInfo` argument used for hardware information. | +| `captureWindowEvents` | `boolean` | `true` | Record window focus, show and hide events, and renderer hang events. Needs `app`. | +| `video` | object | none | Opt-in pixel video capture. See [Video capture](#video-capture). | + +`launchRenderer(appToken, options)` takes the browser launch options. Pass `replay: false` to turn replay off. See [Browser](/sdk/javascript/platforms/browser#browser-options). + +## Sandboxed renderers + +A window with `sandbox: true` loads its preload as CommonJS, and that preload's `require` can load only Electron's built-in modules. It cannot load an external package or a sibling file. Bundle `@bugsee/electron/preload` into your single preload file with esbuild, webpack or Vite. Copying `dist/preload.cjs` next to your preload does not work. + +```ts title="preload.ts (bundled to one file)" +import { registerBugseePreload } from '@bugsee/electron/preload'; +import electron from 'electron'; + +registerBugseePreload(electron); +``` + +:::caution[One file] +A preload that does `require('./other.cjs')` fails with "module not found" in a sandboxed renderer. Bundle everything the preload needs into one file. +::: + +## Native crashes + +Pass Electron's `crashReporter` to `launchMain`. Crash dumps are attached to the session with session-correlated extra fields, so a native crash shows up next to the console and replay data of the same run. + +On Windows, Electron 45 adds a Windows Error Reporting helper (`_wer.dll`, next to the executable) so that `crashReporter` also sees crashes such as `__fastfail`. Make sure your packager keeps that file in the install directory. If you rename `electron.exe`, rename the helper to match. + +## Video capture + +Session replay (DOM replay) is the default visual capture and needs nothing extra. To add pixel video next to it, pass `video: { source }` to `launchMain`. You supply the capture source; the SDK records the one you give it. The package provides helpers for the two source kinds: `capturePage` (`createCapturePageVideoSource`) and `MediaRecorder` (`createMediaRecorderVideoSource`). `hasPermission` is an optional gate that returns `false` to keep video inert, for example when macOS Screen Recording permission is missing. + +From Electron 45, screen, window and tab capture requests (`getDisplayMedia()` and `getUserMedia()` with `chromeMediaSource`) reach `session.setPermissionRequestHandler` as `display-capture`, not `media`. If your app allows only `media`, a `getDisplayMedia`-based source is denied. Allow `display-capture` for the window that hosts your source, and in `session.setPermissionCheckHandler` too if you install one. The `capturePage` source needs no permission. + +See [Session replay](/sdk/javascript/session-replay) for the replay options. + +## App version and build + +If you pass `app` to `launchMain`, the SDK reports `app.getVersion()` as the app version, so a packaged app shows the version from its `package.json` without extra setup. The `appVersion` and `appBuild` options always win. + +## Source maps + +Upload source maps for your renderer and main bundles so stack traces are readable. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Start the app with all three entry points in place. +2. Log from a renderer and report a test error from the main process: + +```ts +const bugsee = launchMain('', { ipcMain, app, crashReporter }); +bugsee.logException(new Error('Bugsee test error')); +``` + +3. Open the Bugsee dashboard. The report appears with the main process data and the renderer console output in one session. + +If renderer data is missing, check that the preload ran in that window (no `preload-error` in the main process log) and, in a sandboxed window, that the preload is a single bundled file. + +## Related pages + +- [Node.js](/sdk/javascript/platforms/node) — options the main process shares with Node +- [Browser](/sdk/javascript/platforms/browser) — options the renderers share with the browser +- [Session replay](/sdk/javascript/session-replay) — DOM replay and video +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/platforms/node.mdx b/docs/sdk/javascript/platforms/node.mdx new file mode 100644 index 00000000..2195ddf3 --- /dev/null +++ b/docs/sdk/javascript/platforms/node.mdx @@ -0,0 +1,170 @@ +--- +title: "Node.js" +description: "Set up the Bugsee JavaScript SDK in a Node.js service: launch, crash capture, on-disk recovery, hang detection, profiling and the Node-specific launch options." +sidebar_position: 2 +slug: "/sdk/javascript/platforms/node" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +On Node.js, `@bugsee/bugsee` captures uncaught exceptions and unhandled rejections, console output and `node:http` traffic, instruments incoming requests, and keeps its recording on disk so a crash report survives the crash. It can also detect event-loop hangs and attach a CPU profile. + +Running an HTTP framework? Start here, then add its adapter from [Backend](/sdk/javascript/backend/overview). + +## Requirements + +- Node.js 18 or newer. +- An application token from the Bugsee dashboard. +- A writable directory for the on-disk capture buffer. By default it is `/bugsee`. + +## Install + + + + +```bash +npm install @bugsee/bugsee@beta +``` + + + + +```bash +pnpm add @bugsee/bugsee@beta +``` + + + + +```bash +yarn add @bugsee/bugsee@beta +``` + + + + +```bash +bun add @bugsee/bugsee@beta +``` + + + + +You install only `@bugsee/bugsee`. It selects the Node build through package `exports` conditions, for both ESM and CommonJS. `@bugsee/node` is an internal building block that you do not install. + +## Launch + +Call `launch()` at the top of your entry file, before the code you want to observe. + + + + +```ts title="server.ts" +import { launch } from '@bugsee/bugsee'; + +const bugsee = launch('', { appVersion: '1.4.2' }); +``` + + + + +```js title="server.js" +const { launch } = require('@bugsee/bugsee'); + +const bugsee = launch('', { appVersion: '1.4.2' }); +``` + + + + +On Node `launch()` returns the client directly, not a `Promise`. A second `launch()` in the same process is ignored with a warning and returns the existing client. Use `relaunch(options?)` to restart, or `stop()` to release the singleton. A missing or empty token does not throw: the SDK reports one error through `onError` (or `console.warn`) and returns a disabled client. + +Read the token from your environment rather than hard-coding it: + +```ts +launch(process.env.BUGSEE_APP_TOKEN); +``` + +### App version and build + +The SDK picks the first usable value in this order: + +1. The `appVersion` and `appBuild` launch options. +2. Build-time constants `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__`. +3. The `appIdentitySource` option, a function returning `{ version?, build? }`. +4. For the version: the `BUGSEE_APP_VERSION` environment variable, then the `version` field of the nearest `package.json`, searched upward from `appRoot` or the working directory. +5. For the build: the `BUGSEE_APP_BUILD` environment variable, then the commit variable of your CI or host, such as `GITHUB_SHA` or `VERCEL_GIT_COMMIT_SHA`. + +If no version is found, reports show `0.0.0` and the SDK prints one warning. + +## What is exported + +| Export | Description | +| --- | --- | +| `launch(appToken, options?)` | Starts the SDK and returns the client synchronously. | +| `relaunch(options?)` | Restarts the SDK, optionally with new options. | +| `getStatus()` | Returns the current `BugseeStatus`. | +| `BugseeStatus` | The status values `getStatus()` returns. | +| `LifecycleEvents` | The lifecycle event names. See [Lifecycle](/sdk/javascript/lifecycle). | +| `addReportAttachment(input)` | Adds an attachment to reports. | +| `getDefaultNetworkSanitizer()` | The default network redaction, to compose with your own filter. | + +## Node options + +`launch(appToken, options)` accepts the [common options](/sdk/javascript/configuration). These apply to Node (and Bun): + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appRoot` | `string` | working directory | Where to start looking for `package.json`. | +| `unhandledRejections` | `'preserve'` \| `'warn'` \| `'none'` | `'preserve'` | `preserve` captures the rejection, then reproduces Node's outcome (print and exit 1). `warn` captures and prints but keeps the process alive. `none` installs no listener. | +| `exitOnUncaught` | `boolean` | `true` | Call `process.exit(1)` after flushing an uncaught exception. Does not affect rejections. | +| `shutdownTimeoutMs` | `number` | `3000` | Time budget to flush the crash report before exiting. | +| `recover` | `boolean` | `true` | Persist each report before upload and re-upload leftovers from a crashed run on the next launch. | +| `capturedDataStore` | `'disk'` \| `'memory'` | `'disk'` | Where the recording lives. `memory` disables crash recovery. | +| `dataDir` | `string` | `/bugsee` | Directory for the on-disk buffer. | +| `maxDataSize` | `number` | 50 MB | Size cap of the recording. | +| `detectHangs` | `boolean` | `true` | Event-loop hang detection. See [Hangs](/sdk/javascript/issue-detection/hangs). | +| `profiling` | `boolean` | `false` | Rolling V8 CPU profile attached to reports. | +| `captureLocalVariables` | `boolean` or object | `false` | Local variables of the throwing frames. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). | +| `captureSourceContext` | `boolean` or object | `false` | Source lines around each frame. | +| `instrumentIncomingRequests` | `boolean` | `true` | Instrument incoming `node:http` requests automatically. | + +The remaining Node options (`deviceId`, `captureWriter`, `captureDiskSpace`, `diskProtection`, trace propagation) are in [Configuration](/sdk/javascript/configuration). + +## Behavior to know about + +- **Crashes end the process.** After an uncaught exception the SDK flushes the report and exits with code 1, as Node would. Set `exitOnUncaught: false` only if you handle process lifetime yourself. +- **Crash recovery needs a persistent directory.** If the process is killed, the next launch uploads what the previous run left in `dataDir`. On a read-only or ephemeral filesystem, set `dataDir` to a writable path or accept in-memory capture. +- **Several processes or worker threads can share one `dataDir`.** Each instance writes its own subdirectory, and a new launch recovers the data of dead siblings. +- **Incoming requests are instrumented by default.** Each request gets its own context so logs and errors can be tied to it. See [Backend](/sdk/javascript/backend/overview). +- **Serverless and short-lived scripts.** Call `await bugsee.flush()` before the process ends so pending uploads finish. + +## Source maps + +If you ship bundled or transpiled server code, upload source maps so stack traces are readable. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Launch the SDK with a real token. +2. Report a test error: + +```ts +const bugsee = launch(''); +bugsee.logException(new Error('Bugsee test error')); +await bugsee.flush(); +``` + +3. Open the Bugsee dashboard. The report appears within a minute, with the process environment and the captured logs. + +## Related pages + +- [Installation](/sdk/javascript/installation) — install and launch for every runtime +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Backend](/sdk/javascript/backend/overview) — request context and framework adapters +- [Hangs](/sdk/javascript/issue-detection/hangs) — event-loop hang detection +- [Bun](/sdk/javascript/platforms/bun) — the Bun runtime diff --git a/docs/sdk/javascript/platforms/vercel-edge.mdx b/docs/sdk/javascript/platforms/vercel-edge.mdx new file mode 100644 index 00000000..d2f4a0d0 --- /dev/null +++ b/docs/sdk/javascript/platforms/vercel-edge.mdx @@ -0,0 +1,131 @@ +--- +title: "Vercel Edge" +description: "Set up the Bugsee JavaScript SDK in Vercel Edge Functions and other edge isolates with @bugsee/vercel-edge: withBugseeFetch, incident-driven uploads and options." +sidebar_position: 6 +slug: "/sdk/javascript/platforms/vercel-edge" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/vercel-edge` is the SDK for Vercel Edge Functions and other edge isolate runtimes that offer only Web APIs (`fetch`, `Request`, `Response`, `crypto.subtle`, no `node:*`). + +Capture is incident-driven. Data is buffered in memory and uploaded only when an incident happens: a handled `logException`, a thrown handler error, or an unhandled rejection. A clean request uploads nothing. + +Pick the package that matches your platform: + +- Standalone Vercel Edge function or another edge isolate: this page. +- Cloudflare Workers: [`@bugsee/cloudflare`](/sdk/javascript/platforms/cloudflare), which builds on this package. +- Next.js: [`@bugsee/nextjs`](/sdk/javascript/frameworks/nextjs), which uses this package on the Edge runtime for you. + +## Requirements + +- An edge runtime with Web APIs. +- An application token. + +## Install + + + + +```bash +npm install @bugsee/vercel-edge@beta +``` + + + + +```bash +pnpm add @bugsee/vercel-edge@beta +``` + + + + +```bash +yarn add @bugsee/vercel-edge@beta +``` + + + + +```bash +bun add @bugsee/vercel-edge@beta +``` + + + + +## Launch + +```ts title="api/edge.ts" +import { launch, withBugseeFetch } from '@bugsee/vercel-edge'; + +const bugsee = launch(process.env.BUGSEE_APP_TOKEN!); + +export default { + fetch: withBugseeFetch(bugsee, async (request: Request) => { + // ... your handler ... + return new Response('ok'); + }), +}; +``` + +`launch()` returns the client directly, not a `Promise`. `withBugseeFetch` runs each request in its own Bugsee context, captures any error your handler throws and rethrows it (the platform still produces its error response), and flushes the upload through `waitUntil`, because an edge isolate freezes as soon as the response is returned. On Vercel Edge `waitUntil` is found automatically. Elsewhere it is read from the `ctx` argument. + +## What is exported + +| Export | Description | +| --- | --- | +| `launch(appToken, options?)` | Starts the SDK and returns the client synchronously. | +| `relaunch` | Restarts the SDK. | +| `withBugseeFetch(client, handler)` | Wraps a `fetch` handler so each request has its own context and errors are reported. | +| `runInEdgeContext` | Runs your own function in a Bugsee request context. | +| `getStatus`, `BugseeStatus`, `LifecycleEvents`, `addReportAttachment`, `getDefaultNetworkSanitizer` | The shared client exports. | + +## Options + +`launch(appToken, options)` accepts, among others: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appVersion`, `appBuild`, `appId` | `string` | resolved | Identify your release in reports. | +| `captureLogs`, `captureNetwork`, `captureNetworkBodies` | `boolean` | `true` | Capture streams. | +| `maxDataSize` | `number` | 10 MB | Size of the in-memory buffer, in megabytes. | +| `maxTenantPartitions` | `number` | `8` | Number of per-tenant capture partitions, used when one isolate serves several tenants. | +| `partitionCaptureByTenant` | `boolean` | `false` | Keep each tenant's capture separate. | +| `asyncLocalStorage` | async store | probed | The store behind per-request context. Supply it on runtimes where `globalThis.AsyncLocalStorage` is missing. | + +See [Configuration](/sdk/javascript/configuration) for the shared options. + +## App version and build + +Pass `appVersion` and `appBuild` to `launch`. The Vite and webpack plugins can also inject `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__` at build time, and the `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` environment variables apply below those constants. On Vercel, if no build is given by an option, a build-time constant or `BUGSEE_APP_BUILD`, the deployed commit (`VERCEL_GIT_COMMIT_SHA`) is used as the build. If no version is found, reports show `0.0.0`. + +## Source maps + +Upload source maps for your function bundle so stack traces are readable. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Deploy the function (or run it locally) with the token set. +2. Trigger an error in the handler: + +```ts +fetch: withBugseeFetch(bugsee, async () => { + throw new Error('Bugsee test error'); +}), +``` + +3. Open the Bugsee dashboard. The report appears with the request context and the captured logs. + +## Related pages + +- [Cloudflare Workers](/sdk/javascript/platforms/cloudflare) — Workers, Durable Objects and `nodejs_compat` +- [Next.js](/sdk/javascript/frameworks/nextjs) — Edge runtime support inside Next.js +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/platforms/web-workers.mdx b/docs/sdk/javascript/platforms/web-workers.mdx new file mode 100644 index 00000000..e4459f9b --- /dev/null +++ b/docs/sdk/javascript/platforms/web-workers.mdx @@ -0,0 +1,140 @@ +--- +title: "Web and Service Workers" +description: "Set up the Bugsee JavaScript SDK inside Web Workers and Service Workers with @bugsee/webworker: launch, withBugseeEvent, persistence and what a worker can capture." +sidebar_position: 7 +slug: "/sdk/javascript/platforms/web-workers" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +`@bugsee/webworker` is the SDK for Web Workers (dedicated and shared) and Service Workers. It captures console output, network traffic, and global error and unhandled-rejection events in a worker context that has no DOM. + +A worker is a separate JavaScript context, so it needs its own launch. Your page code keeps using `@bugsee/bugsee`; call `@bugsee/webworker` from inside the worker script. + +## Requirements + +- A browser with worker support. Service Workers also need a secure context. +- An application token. + +## Install + + + + +```bash +npm install @bugsee/webworker@beta +``` + + + + +```bash +pnpm add @bugsee/webworker@beta +``` + + + + +```bash +yarn add @bugsee/webworker@beta +``` + + + + +```bash +bun add @bugsee/webworker@beta +``` + + + + +## Web Worker + +`launch()` returns the client directly, not a `Promise`. + +```ts title="worker.ts" +import { launch } from '@bugsee/webworker'; + +const bugsee = launch(''); +``` + +The SDK captures console output, `fetch` and `WebSocket` traffic (also `XMLHttpRequest` in dedicated workers), and global `error` and `unhandledrejection` events on the worker. + +A worker has no DOM, so these are not captured: clicks, key presses, navigation, the view hierarchy and session replay. + +## Service Worker + +A Service Worker is stopped when idle, so wrap event handlers with `withBugseeEvent`. It hands the upload to `event.waitUntil`, so the worker stays alive until a report is sent. + +```ts title="sw.ts" +import { launch, withBugseeEvent } from '@bugsee/webworker'; + +const bugsee = launch('', { platformType: 'service-worker' }); + +self.addEventListener( + 'fetch', + withBugseeEvent(bugsee, (event) => { + event.respondWith(fetch(event.request)); + }), +); +``` + +The SDK detects a Service Worker from its runtime, so `platformType` is only needed to override the detection. + +`withBugseeEvent` never changes your handler's outcome: your own error is rethrown, and SDK failures go to an optional third argument: + +```ts +withBugseeEvent(bugsee, handler, (error) => console.debug(error)); +``` + +## What is exported + +| Export | Description | +| --- | --- | +| `launch(appToken, options?)` | Starts the SDK and returns the client synchronously. | +| `withBugseeEvent(client, handler, onError?)` | Wraps an event handler so the upload runs inside `event.waitUntil`. | +| `relaunch` | Restarts the SDK. | +| `getStatus`, `BugseeStatus`, `LifecycleEvents`, `addReportAttachment`, `getDefaultNetworkSanitizer` | The shared client exports. | + +## Options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `platformType` | `'web-worker'` \| `'service-worker'` | detected | Which kind of worker this is. It also decides the `persist` default. | +| `persist` | `boolean` | `true` for Service Workers, `false` for Web Workers | Keep assembled report bundles in IndexedDB and re-upload any that a stopped worker left behind. | +| `recover` | `boolean` | `true` | Re-upload bundles that a previous activation left behind, on the next launch. | +| `appVersion`, `appBuild`, `appId` | `string` | resolved | Identify your release in reports. | +| `captureLogs`, `captureNetwork` | `boolean` | `true` | Capture streams. | + +See [Configuration](/sdk/javascript/configuration) for the shared options. + +## App version and build + +Pass `appVersion` and `appBuild` to `launch`. The Vite and webpack plugins can also inject `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__` at build time, or you can set them as globals on `self` before launching. If none is found, the SDK logs one warning and reports version `0.0.0` and build `0`. + +## Source maps + +Workers are separate bundles, so make sure your bundler plugin covers the worker entry. See [Symbolication](/sdk/javascript/symbolication/overview). + +## Verify + +1. Launch the SDK in the worker script. +2. Report a test error from the worker: + +```ts +bugsee.logException(new Error('Bugsee test error')); +``` + +3. Open the Bugsee dashboard. The report appears with the worker's console and network data. + +## Related pages + +- [Browser](/sdk/javascript/platforms/browser) — the SDK for page code +- [Configuration](/sdk/javascript/configuration) — all launch options +- [Symbolication](/sdk/javascript/symbolication/overview) — source maps and debug IDs diff --git a/docs/sdk/javascript/privacy/breadcrumbs.md b/docs/sdk/javascript/privacy/breadcrumbs.md new file mode 100644 index 00000000..76cb1ea6 --- /dev/null +++ b/docs/sdk/javascript/privacy/breadcrumbs.md @@ -0,0 +1,115 @@ +--- +title: "Privacy: Breadcrumbs" +description: "How to keep sensitive data out of the breadcrumbs the Bugsee JavaScript SDK records: the breadcrumb options, what the automatic ui breadcrumbs contain, and redacting or dropping breadcrumbs with setBreadcrumbFilter." +sidebar_position: 4 +slug: "/sdk/javascript/privacy/breadcrumbs" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Breadcrumbs record the steps leading up to an issue: the ones you add with `addBreadcrumb`, the automatic `ui.*` breadcrumbs in the browser, and the navigation breadcrumbs some framework adapters add. A message or data object can carry a URL with a token in it, an identifier, or a value from your own code. See [Breadcrumbs](/sdk/javascript/breadcrumbs) for how they are recorded. This page covers keeping sensitive data out. + +## Breadcrumb options + +Breadcrumb capture is **on by default** in the JavaScript SDK, unlike the mobile SDKs. Turning it off is the simplest control. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureBreadcrumbs` | `boolean` | `true` | Record breadcrumbs. When `false`, no breadcrumb is recorded, yours or the SDK's. | +| `captureInteractions` | `boolean` | `true` | Browser. When `false`, the automatic `ui.*` breadcrumbs and the input stream are not recorded. | + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + captureBreadcrumbs: true, + captureInteractions: false, // keep your own breadcrumbs, drop the automatic ui.* ones +}); +``` + +## What the automatic breadcrumbs contain + +The browser records `ui.change`, `ui.submit` and `ui.focus` breadcrumbs. Each has the element's id, class and tag name in `data`. They never contain a value or text the user typed. A sensitive field (password, phone, card, one-time code) and any element inside an element with a `data-bugsee-hidden` attribute produce no breadcrumb at all. + +Mark an area you want left out of these breadcrumbs. The input stream describes such an element only as masked: + +```html +
+ +
+``` + +During a [blackout](/sdk/javascript/privacy/replay#blackout) these breadcrumbs are not recorded. + +## Breadcrumbs are not sanitized + +`addBreadcrumb` applies no sanitizer. A URL you put in `message` or `data` is recorded as it is, and **your network filter does not reach breadcrumbs.** If you record a navigation or a request, scrub the URL yourself or in the filter below. The Next.js adapter sanitizes the destination it records, for example. Do the same for your own breadcrumbs. + +## Redact with a filter + +`setBreadcrumbFilter` sees every breadcrumb before it is recorded: yours, the automatic ones and the adapters'. Return the breadcrumb, redacted, to keep it, or `null` to drop it. + +The example scrubs every string in a breadcrumb, whatever its category: + +```ts +import { bugsee } from './bugsee'; + +const SECRET_PARAMS = /([?&](?:token|access_token|code|session)=)[^&#\s]*/gi; +const EMAIL = /[\w.%+-]+@[\w-]+(?:\.[\w-]+)+/g; + +function scrub(text: string): string { + return text.replace(SECRET_PARAMS, '$1').replace(EMAIL, ''); +} + +// Scrubs every string in a breadcrumb's data, at any depth +function scrubValue(value: unknown): unknown { + if (typeof value === 'string') { + return scrub(value); + } + if (Array.isArray(value)) { + return value.map(scrubValue); + } + if (value !== null && typeof value === 'object') { + const out: Record = {}; + for (const [key, item] of Object.entries(value)) { + out[key] = scrubValue(item); + } + return out; + } + return value; +} + +bugsee.setBreadcrumbFilter((crumb) => { + // Drop a whole category of your own breadcrumbs + if (crumb.category === 'auth') { + return null; + } + return { + ...crumb, + message: crumb.message === undefined ? undefined : scrub(crumb.message), + data: crumb.data === undefined ? undefined : (scrubValue(crumb.data) as Record), + }; +}); +``` + +Where `bugsee` is the client `launch` returned: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +What to know: + +- **The filter fails closed.** If it throws, the breadcrumb is dropped, and the error goes to the `onError` launch option. +- **Install it right after `launch`.** Breadcrumbs recorded before the filter is installed are kept as they were. +- **One filter at a time.** A later call replaces it. `setBreadcrumbFilter(null)` removes it. After `relaunch()`, install it again on the new client. + +## Related pages + +- [Breadcrumbs](/sdk/javascript/breadcrumbs) — how breadcrumbs are recorded. +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [Privacy: Network](/sdk/javascript/privacy/network) — keep URLs and bodies out of network events. diff --git a/docs/sdk/javascript/privacy/cleanup.md b/docs/sdk/javascript/privacy/cleanup.md new file mode 100644 index 00000000..6ccf27a9 --- /dev/null +++ b/docs/sdk/javascript/privacy/cleanup.md @@ -0,0 +1,126 @@ +--- +title: "Privacy: Cleanup" +description: "Where the Bugsee JavaScript SDK stores captured data in the browser and on Node.js and Bun, how long it stays, and how to limit it with persist, capturedDataStore, recover and sign-out calls." +sidebar_position: 7 +slug: "/sdk/javascript/privacy/cleanup" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +The JavaScript SDK has no call that deletes everything it has collected. What you control is where captured data is kept in the first place, how long it is kept, and what identifies the user. This page lists those controls, and what is stored where. + +## Where data is kept + +| Runtime | Rolling capture | Reports waiting for upload | +| --- | --- | --- | +| Browser | IndexedDB when the page has IndexedDB and Web Locks, otherwise memory. | IndexedDB, or memory when persistence is off. | +| Node.js and Bun | Files under a data directory (default), or memory. | The same data directory. | +| Edge runtimes and Cloudflare | Memory. | Memory. A report is sent when an incident happens. | + +Data in memory is gone when the page or process ends. Data on disk or in IndexedDB is kept so that a crash does not lose the recording that led to it. On the next launch the SDK finds what a previous run left behind, sends it, and deletes it. + +## Keep everything in memory + +If your policy says captured data must never be written to the device, keep it in memory. + +```ts +import { launch } from '@bugsee/bugsee'; + +// Browser: no IndexedDB, nothing survives a reload +await launch('', { persist: false }); +``` + +```ts +import { launch } from '@bugsee/bugsee'; + +// Node.js and Bun: no files, nothing survives a restart +launch('', { capturedDataStore: 'memory' }); +``` + +The cost is the same in both: if the page or process dies before a report is assembled, the recording is lost, and a report that could not be sent is not retried at the next launch. + +| Option | Runtime | Type | Default | Description | +| --- | --- | --- | --- | --- | +| `persist` | Browser | `boolean` | `true` where IndexedDB and Web Locks exist | Keep the capture window and report queue in IndexedDB. `false` keeps them in memory. | +| `capturedDataStore` | Node.js, Bun | `'disk' \| 'memory'` | `'disk'` | Where the capture buffer lives. | +| `recover` | Browser, Node.js, Bun | `boolean` | `true` | Persist each report before upload and send those left by a previous run at the next launch. It needs a persistent location. | +| `maxRecordingTime` | All | `number` | `60` | Seconds of history kept in the rolling window. | +| `maxDataSize` | All | `number` | `20` in the browser (30 with IndexedDB), `50` on Node.js and Bun | The most captured data kept, in megabytes. | + +A shorter `maxRecordingTime` and a smaller `maxDataSize` mean less data at rest and in a report. + +## Node.js and Bun: the data directory + +By default the SDK writes under `/bugsee/`. Each running instance (a process, or a worker thread) writes its own subdirectory inside it, so several instances can share the directory safely. A subdirectory left by an instance that is no longer alive is recovered by a later launch, its reports are sent, and it is removed. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `dataDir` | `string` | `/bugsee/...` | Put the data in a directory you choose, for example one that is encrypted or cleaned on a schedule. | +| `dataRootBase` | `string` | `os.tmpdir()` | The base of the default directory. Ignored when `dataDir` is set. | + +```ts +import { launch } from '@bugsee/bugsee'; + +launch('', { + dataDir: '/var/lib/myapp/bugsee', + maxDataSize: 20, +}); +``` + +The default directory is checked for ownership and permissions before use. If it is not safe, the SDK falls back to memory. An explicit `dataDir` is your decision and is not checked, so make sure only your service can read it. + +Capture files hold the same data as a report: console output, network events and so on, as recorded after your filters and redaction. + +## Pending reports + +A report that could not be sent, for example when the network is down, waits in a durable queue and is retried with backoff and at the next launch. + +- The queue holds up to **32** reports and **64 MiB**. When it is full, the oldest are dropped. +- A report older than **7 days** is dropped. +- A report the collector refuses permanently is deleted. + +## Disk and storage pressure + +With `diskProtection` on (the default), the browser SDK watches the storage quota and stops writing when headroom runs low: below 50 MiB it stops persisting replay, logs and network data, and below 10 MiB it persists nothing. The in-memory window is kept, so a live report is still complete. + +## What identifies the user + +| Stored item | Where | How to remove it | +| --- | --- | --- | +| User identifier | Memory. In the browser, `localStorage` too when `persistUserIdentifier` is `true`. | `clearUserIdentifier()` | +| Attributes | Memory only. | `clearAttribute(key)` or `clearAllAttributes()` | +| Device id | Browser only: a random UUID kept in `localStorage`, a first-party cookie, IndexedDB and the Cache API, so that it survives a cleared store. | Clear the site data in the browser. There is no SDK call. | + +Call both clear methods at sign-out: + +```ts +import { bugsee } from './bugsee'; + +function onSignOut(): void { + bugsee.clearUserIdentifier(); + bugsee.clearAllAttributes(); +} +``` + +Where `bugsee` is the client `launch` returned: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +Clearing applies to reports created afterwards. A report that is already assembled and waiting in the queue, and the recovery record of an incident that has not been delivered, keep the identifier they were created with until they are uploaded or expire. + +## Stop capture + +`stop()` stops capture and drains the pending uploads. It does not delete data that is waiting for a later launch. See [Lifecycle](/sdk/javascript/lifecycle). + +## Related pages + +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [Privacy: Report](/sdk/javascript/privacy/report) — what a report carries. +- [User & session data](/sdk/javascript/user-session-data) — identifier and attributes. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/privacy/logs.md b/docs/sdk/javascript/privacy/logs.md new file mode 100644 index 00000000..08104f76 --- /dev/null +++ b/docs/sdk/javascript/privacy/logs.md @@ -0,0 +1,90 @@ +--- +title: "Privacy: Console logs" +description: "How to keep sensitive data out of the console logs the Bugsee JavaScript SDK records: turning capture off, the capture level, and redacting or dropping lines with setLogEventFilter." +sidebar_position: 3 +slug: "/sdk/javascript/privacy/logs" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +The SDK records your console output and the lines you write with `log`. Nothing redacts them for you: a line is recorded as it is printed. A log line can carry a token, an email address or a response body that your code printed while debugging. See [Console logs](/sdk/javascript/logs) for how capture works. This page covers keeping sensitive data out. + +## Turn log capture off + +Turning it off is the simplest control. No console line and no `log` line is recorded. + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { captureLogs: false }); +``` + +## Record fewer lines + +`captureLogsLevel` drops lines less severe than the level you set. Debug output is where secrets most often appear, so a production build can keep only warnings and errors. + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { captureLogsLevel: 'warning' }); +``` + +| Level | Keeps | +| --- | --- | +| `'error'` | `console.error` | +| `'warning'` | `console.error`, `console.warn` | +| `'info'` | the above and `console.log`, `console.info` | +| `'debug'` | the above and `console.debug` | +| `'verbose'` (default) | everything, including `console.trace` | + +## Redact with a filter + +`setLogEventFilter` sees every line before it is recorded. Return the line to keep it, or `null` to drop it. Redact in the filter rather than relying on remembering what you print. + +```ts +import { bugsee } from './bugsee'; + +const PATTERNS: Array<[RegExp, string]> = [ + [/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, ''], + [/[\w.%+-]+@[\w-]+(?:\.[\w-]+)+/g, ''], + [/\b(?:\d[ -]?){13,19}\b/g, ''], + [/(["']?(?:password|token|secret)["']?\s*[:=]\s*)["']?[^\s,"'}]+/gi, '$1'], +]; + +bugsee.setLogEventFilter((line) => { + // Never record lines from a module that prints user data + if (line.message.startsWith('[user-service]')) { + return null; + } + let message = line.message; + for (const [pattern, replacement] of PATTERNS) { + message = message.replace(pattern, replacement); + } + return { ...line, message }; +}); +``` + +Where `bugsee` is the client `launch` returned: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +What to know: + +- **The filter fails closed.** If it throws, the line is dropped, and the error goes to the `onError` launch option. +- **Install it right after `launch`.** Lines printed before the filter is installed are recorded as they were. +- **It does not change your console.** The filter shapes what Bugsee records. The original console output is unchanged. +- **One filter at a time.** A later call replaces it. `setLogEventFilter(null)` removes it. After `relaunch()`, install it again on the new client. +- **Objects are already text.** The message is the formatted line, with objects written as JSON, so your patterns run on the final text. +- **Stack traces in `console.error` are in the message.** An `Error` passed to the console is recorded as its stack, so redact file paths there if they are sensitive. + +## Related pages + +- [Console logs](/sdk/javascript/logs) — how capture works, and writing your own lines. +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [Privacy: Network](/sdk/javascript/privacy/network) — the other automatic stream. diff --git a/docs/sdk/javascript/privacy/network.md b/docs/sdk/javascript/privacy/network.md new file mode 100644 index 00000000..dab24504 --- /dev/null +++ b/docs/sdk/javascript/privacy/network.md @@ -0,0 +1,123 @@ +--- +title: "Privacy: Network" +description: "How to keep sensitive data out of the network events the Bugsee JavaScript SDK records: capture and body options, the built-in redaction, and a setNetworkEventFilter that composes with getDefaultNetworkSanitizer." +sidebar_position: 5 +slug: "/sdk/javascript/privacy/network" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Network events carry URLs, headers and bodies, which can hold tokens, personal data and payment details. Unlike logs and breadcrumbs, the SDK redacts network events for you by default. See [Network events](/sdk/javascript/network) for how capture works. This page covers the controls. + +## Network options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `captureNetwork` | `boolean` | `true` | Record network traffic. `false` records none. | +| `captureNetworkBodies` | `boolean` | `true` | Record request and response bodies. `false` keeps headers and URLs only. | +| `maxNetworkBodySize` | `number` | `20480` | Largest body kept, in bytes. Larger bodies are dropped. | +| `captureNetworkBodyWithoutType` | `boolean` | `false` | Keep bodies with no `Content-Type`. Leave it off to drop them. | +| `captureNetworkDefaultSanitizer` | `boolean` | `true` | Apply the built-in redaction. `false` records events as they are. | + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + captureNetworkBodies: false, // never record bodies +}); +``` + +Turning bodies off is the strongest control for payloads. A malformed boolean for a capture option turns it **off** and is reported through the `onError` launch option. + +## What the built-in redaction does + +With `captureNetworkDefaultSanitizer` on, every event is redacted before it is stored. The marker is ``. + +| Part | What is redacted | +| --- | --- | +| Headers | Sensitive header values, matched by exact name, case-insensitive: `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `x-csrf-token`, `x-forwarded-for`, `x-real-ip` and a list of cloud and vendor token headers. Other header values get the secret-shape pass. | +| URL | Values of sensitive query and fragment parameters, `;` path parameters such as `;jsessionid=`, and the password in `user:password@host`. | +| Error text | URLs and secrets quoted in the message of a failed request. | +| JSON, form, multipart, XML and `key: value` bodies | The value of every sensitive key. Keys match by case-insensitive substring, ignoring `-`, `_`, `.` and spaces. | +| Secret shapes | JSON Web Tokens and well-known provider secrets, in any value, under any key name. | + +Sensitive key substrings include `password`, `secret`, `token`, `auth`, `api_key`, `credit_card`, `cvv`, `ssn`, `iban` and `jwt`. The match is intentionally broad, so a key such as `author` is redacted too. + +What it does **not** do: + +- It does not redact card numbers in free text. A card field is redacted by its key name only. +- It does not recognize sensitive data in a field with an innocent key name, for example a name or an address under `value`. Use a filter for those. + +## Redact with a filter + +`setNetworkEventFilter` sees every event before it is recorded. Return the event to keep it, or `null` to drop it. + +:::caution +Installing a network filter **replaces** the built-in redaction. From that moment nothing is redacted unless your filter does it. Compose your filter with `getDefaultNetworkSanitizer()` to keep both. +::: + +```ts +import { getDefaultNetworkSanitizer } from '@bugsee/bugsee'; +import { bugsee } from './bugsee'; + +const defaults = getDefaultNetworkSanitizer(); + +const SKIP = ['/health', '/metrics']; +const THIRD_PARTY = ['https://analytics.example.com/', 'https://ads.example.net/']; + +bugsee.setNetworkEventFilter((event) => { + // Drop the whole request, at every stage (before, complete, error, ...) + if (SKIP.some((path) => event.url.includes(path))) { + return null; + } + if (THIRD_PARTY.some((origin) => event.url.startsWith(origin))) { + return null; + } + + // Built-in redaction first + const sanitized = defaults.sanitize(event); + + // Then yours: never record response bodies of the profile API + if (sanitized.url.includes('/api/profile') && sanitized.custom !== undefined) { + return { + ...sanitized, + custom: { ...sanitized.custom, body: null, no_body_reason: 'unsupported_content_type' }, + }; + } + return sanitized; +}); +``` + +Where `bugsee` is the client `launch` returned: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +What to know: + +- **One call per stage.** A request produces a `before` event, then `complete`, `error` or `abort`, and so on, and your filter runs for each one. Return `null` for every stage of a request you want gone. Match on `event.url`, or remember `event.id`. +- **The filter fails closed.** If it throws, the event is dropped, and the error goes to the `onError` launch option. +- **Install it right after `launch`.** Events recorded before the filter is installed keep the built-in redaction. +- **One filter at a time.** A later call replaces it. `setNetworkEventFilter(null)` removes it, and the built-in redaction applies again. After `relaunch()`, install it again on the new client. +- **The body policy runs first.** Size and content-type rules apply before the filter sees the event. +- **The helper functions.** `defaults.sanitizeUrl(url)` and `defaults.sanitizeErrorMessage(message)` redact a single string. Use them in your own code, for example before you put a URL in a breadcrumb. + +## Other places a URL can appear + +A network filter changes network events only. A URL can also be recorded in: + +- **Breadcrumbs.** A breadcrumb you add is recorded as it is. Use [`setBreadcrumbFilter`](/sdk/javascript/privacy/breadcrumbs). +- **The page address trace** in the browser. The SDK records a sanitized address. The `urlSanitizer` launch option adds your own rule after the built-in one. It receives the already sanitized address, and returns the string to record, or `null` to record nothing. +- **Performance spans.** With performance monitoring on, requests also become spans. `setSpanFilter` changes or drops them. See [Performance](/sdk/javascript/performance). +- **Replay.** `href` and `src` attributes are recorded as the page has them. See [Privacy: Replay](/sdk/javascript/privacy/replay#what-can-still-leak). + +## Related pages + +- [Network events](/sdk/javascript/network) — how capture works and the event shape. +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [HTTP errors](/sdk/javascript/issue-detection/http-errors) — what HTTP error reports contain. diff --git a/docs/sdk/javascript/privacy/overview.md b/docs/sdk/javascript/privacy/overview.md new file mode 100644 index 00000000..a4f258b9 --- /dev/null +++ b/docs/sdk/javascript/privacy/overview.md @@ -0,0 +1,52 @@ +--- +title: "Privacy overview" +description: "The privacy controls of the Bugsee JavaScript SDK: what a report can contain, and where to mask, filter, redact or limit it before it leaves the device or server." +sidebar_position: 1 +slug: "/sdk/javascript/privacy/overview" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Bugsee does not stream data continuously. The SDK keeps what it captures in a rolling buffer, as long as the `maxRecordingTime` launch option (60 seconds by default), and sends it only when a report is created: by a crash or an error, from the report dialog, or from your code. The data in a report (session replay, console logs, network traffic, breadcrumbs, your attributes and the user identifier) can contain personal data, so the SDK gives you a control at each point where that data is recorded. + +The controls work in four places: + +- **On the page.** Replay masks text and inputs and blocks media by default. CSS classes and selectors refine that, and `startBlackout()` stops visual capture for a sensitive flow. +- **At record time.** A log, network or breadcrumb filter sees each event before it is recorded, and can rewrite or drop it. A filter that throws drops the event rather than recording it unfiltered. +- **Before upload.** A report handler can change the summary, description, severity, labels and attachments of a report, or veto it. +- **At rest.** Launch options turn whole streams off and choose whether captured data is kept in memory, in IndexedDB or on disk. + +| Page | Covers | +| --- | --- | +| [Replay](/sdk/javascript/privacy/replay) | Default masking, the always-masked fields, the CSS classes, selectors, canvas and blackout. | +| [Console logs](/sdk/javascript/privacy/logs) | Turning log capture off, `captureLogsLevel`, and redacting lines with `setLogEventFilter`. | +| [Network](/sdk/javascript/privacy/network) | Capture options, the built-in redaction, and `setNetworkEventFilter` with `getDefaultNetworkSanitizer`. | +| [Breadcrumbs](/sdk/javascript/privacy/breadcrumbs) | Breadcrumb options and redacting with `setBreadcrumbFilter`. | +| [Report](/sdk/javascript/privacy/report) | What a report carries, the report handler, attributes and the user identifier. | +| [Cleanup](/sdk/javascript/privacy/cleanup) | Where captured data is stored, how long it stays, and how to limit it. | + +## Defaults at a glance + +| Stream | Captured by default | Built-in protection | +| --- | --- | --- | +| Replay (browser, Electron) | Yes | Masks all text and inputs, blocks media and iframes, always masks password, phone, card and one-time-code fields. | +| Console logs | Yes | None. Redact with a filter. | +| Network | Yes, with bodies up to 20 KB | Redacts sensitive headers, URL parameters, body keys and secret shapes. | +| Breadcrumbs | Yes | None. Redact with a filter. | +| Attributes, user identifier | Only what you set | None. | +| Typed text | No | Input values are masked, and typed characters are not recorded as input events. | + +## Things to know + +- **Install filters right after `launch`.** A filter applies to what is recorded after it is installed. Events recorded before that are kept as they are, except network events, which get the built-in redaction. Install filters and the report handler first thing after `launch` returns. +- **A network filter replaces the built-in redaction.** It does not add to it. Compose with `getDefaultNetworkSanitizer()` to keep both. See [Privacy: Network](/sdk/javascript/privacy/network). +- **Filters belong to a client.** `relaunch()` returns a new client, so install the filters again on it. +- **Filters are one per stream.** A later call replaces the earlier filter. +- **Breadcrumbs, logs, events and attributes are not sanitized for you.** `addBreadcrumb`, `log`, `event`, `trace` and `setAttribute` record what you pass. +- **Your network filter does not reach everything.** A URL can also appear in breadcrumbs, the page-address trace and performance spans. See [Privacy: Network](/sdk/javascript/privacy/network#other-places-a-url-can-appear). +- **The report handler is not a redaction boundary for every stream.** It cannot remove logs, network events, breadcrumbs or replay from a report. Keep sensitive data out where it is recorded. +- **Performance spans.** With performance monitoring on, requests also become spans. `setSpanFilter` changes or drops them, and replaces the built-in span sanitizer when you set it. See [Performance](/sdk/javascript/performance). + +It remains the responsibility of the application developer to keep sensitive data out of reports before they leave the device. diff --git a/docs/sdk/javascript/privacy/replay.md b/docs/sdk/javascript/privacy/replay.md new file mode 100644 index 00000000..5ebdb4b0 --- /dev/null +++ b/docs/sdk/javascript/privacy/replay.md @@ -0,0 +1,170 @@ +--- +title: "Privacy: Replay" +description: "How to keep sensitive content out of Bugsee JavaScript SDK session replay: the default masking, the always-masked fields, the bugsee-mask, bugsee-block, bugsee-ignore, bugsee-unmask and bugsee-show classes, selectors, and blackout." +sidebar_position: 2 +slug: "/sdk/javascript/privacy/replay" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +[Session replay](/sdk/javascript/session-replay) records the DOM of your page. The SDK masks what it records **before** it leaves the page, and the masking is fail closed: you opt content in, not out. This page covers the controls. + +## Turn replay off + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { replay: false }); +``` + +With `replay: false` the replay recorder is never loaded. For a single sensitive flow, use a [blackout](#blackout) instead. + +## Defaults + +| Option | Default | Effect | +| --- | --- | --- | +| `maskAllText` | `true` | Every text node is recorded as masked characters, with its length kept so the layout does not change. Attribute values are masked too, except the ones the page needs to render. | +| `maskAllInputs` | `true` | Every input value is masked. | +| `blockAllMedia` | `true` | `img`, `svg`, `video`, `audio`, `picture`, `object`, `embed`, `map`, `source` and `iframe` are recorded as empty placeholders of the same size. | +| `blockAllCanvas` | `false` | Canvas content is recorded only when the canvas add-on is on. See [Canvas](#canvas). | + +You can relax a default, for example `maskAllText: false` to see page text. Elements you mark with `bugsee-mask` stay masked. + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + replay: { + maskAllText: false, // record page text... + maskAllInputs: true, // ...but never input values + blockAllMedia: true, + }, +}); +``` + +## Always masked + +These inputs are masked whatever the options and the markup say. No option and no class lifts it: + +| Field | Selector it matches | +| --- | --- | +| Passwords | `type="password"`, `autocomplete` containing `password` | +| Phone numbers | `type="tel"` | +| Payment cards | `autocomplete` containing `cc-` (`cc-number`, `cc-csc`, `cc-name` and the rest) | +| One-time codes | `autocomplete="one-time-code"` | + +Matching is case-insensitive. The input events of these fields are not recorded either, so a changed value does not reach the replay even if `maskAllInputs` is `false`. + +Use the right `type` and `autocomplete` values on your own sensitive fields. For other sensitive fields, add a `bugsee-mask` class. + +## CSS classes + +Mark elements in your markup with a class or a data attribute. Both forms work: `class="bugsee-mask"` and `data-bugsee-mask`. + +| Class | Data attribute | Effect | Applies to | +| --- | --- | --- | --- | +| `bugsee-mask` | `data-bugsee-mask` | Mask the text and attribute values. | The element and everything inside it. | +| `bugsee-block` | `data-bugsee-block` | Record an empty placeholder of the same size. Nothing inside is recorded. | The element and everything inside it. | +| `bugsee-ignore` | `data-bugsee-ignore` | Ignore input events on the element. | The element. | +| `bugsee-unmask` | `data-bugsee-unmask` | Record text unmasked, when `maskAllText` is on. Sensitive inputs stay masked. | Text: the element and its content. An input value: the element only. | +| `bugsee-show` | `data-bugsee-show` | Record media, an iframe or a canvas that would be blocked. | The element only. | + +```html +
+

Payment details

+

Nothing in this section reaches the replay.

+
+ +

Hello, Ada Lovelace

+ +

Orders

+ +Company logo + + +``` + +:::caution +`bugsee-show` applies to the marked element only, not to its children. To record a canvas, put `bugsee-show` on the `` itself. And `bugsee-unmask` on a container un-masks its text, but not the values of the inputs inside it. Mark each input. +::: + +## Selectors + +For content you cannot mark in markup, for example from a third-party widget, pass CSS selectors: + +| Option | Effect | +| --- | --- | +| `maskTextSelector` | Mask the text of matching elements, in addition to `bugsee-mask`. | +| `blockSelector` | Block matching elements, in addition to `bugsee-block`. | +| `ignoreSelector` | Ignore input events of matching elements, in addition to `bugsee-ignore`. | + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + replay: { + maskTextSelector: '.chat-message, [data-pii]', + blockSelector: '#third-party-widget', + ignoreSelector: 'input.internal-notes', + }, +}); +``` + +An invalid selector cannot disable privacy. It is dropped and reported through the `onError` launch option, and where dropping it would weaken masking, the strictest setting for that kind of option is used instead. + +## Iframes + +An iframe is blocked by default, as a placeholder. Its document is never recorded, even when it is on your own origin. Add `bugsee-show` to an iframe to record it, and its content is then masked by the same rules as the rest of the page. + +## Canvas + +Canvas content is recorded only when you turn on the canvas add-on. It records pixels, and **canvas pixels are not masked**. Enable it only for canvases that never show sensitive data, and consider `blockAllCanvas: true` to record only the canvases you mark with `bugsee-show`: + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + replay: { + canvas: { fps: 2 }, + blockAllCanvas: true, // only is recorded + }, +}); +``` + +## Blackout + +`startBlackout()` stops all visual and interaction capture (replay, input, the automatic `ui.*` breadcrumbs and the view hierarchy) until `endBlackout()`. Logs, network, traces and events continue. + +```ts +import { bugsee } from './bugsee'; + +async function showCardForm(): Promise { + bugsee.startBlackout(); + try { + await openCardForm(); // resolves when the form has been removed from the page + } finally { + bugsee.endBlackout(); + } +} + +declare function openCardForm(): Promise; +``` + +- A blackout is on or off. Calling `startBlackout()` twice and then `endBlackout()` once ends it. +- `startBlackout()` before the SDK has launched, or after `stop()`, does nothing and is not remembered. To start dark from the first frame, set `startInBlackout: true` in the launch options. +- `endBlackout()` resumes replay with a fresh full snapshot of the **live** page. If the sensitive view is still on screen then, the snapshot contains it. End the blackout only after the view is gone. +- `isBlackout()` tells you whether one is in force. + +## What can still leak + +- **URL attributes.** The values of `href`, `src` and `srcset` are recorded as the page has them. A signed link or an email address inside a URL is not masked by replay. Do not put secrets in URLs of links and images, or block the element. +- **Class names and ids.** They are recorded as they are. Do not put personal data in them. +- **Network and logs.** They are separate streams with their own controls. See [Network](/sdk/javascript/privacy/network) and [Console logs](/sdk/javascript/privacy/logs). + +## Related pages + +- [Session replay](/sdk/javascript/session-replay) — how replay works and its options. +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [Lifecycle](/sdk/javascript/lifecycle) — blackout events. diff --git a/docs/sdk/javascript/privacy/report.md b/docs/sdk/javascript/privacy/report.md new file mode 100644 index 00000000..ef973259 --- /dev/null +++ b/docs/sdk/javascript/privacy/report.md @@ -0,0 +1,95 @@ +--- +title: "Privacy: Report" +description: "What a Bugsee JavaScript SDK report carries, what a report handler can and cannot change before upload, and how to keep attributes, the user identifier and attachments free of sensitive data." +sidebar_position: 6 +slug: "/sdk/javascript/privacy/report" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +A report is a bundle: the rolling capture window at the moment of the incident, plus the details of the incident itself. This page lists what is in it, and the controls you have over each part. + +## What a report carries + +| Part | Contents | Control | +| --- | --- | --- | +| Report details | Summary, description, severity, labels, the source of the report, and the reporter email or user identifier. | [Report handler](/sdk/javascript/report-handler) | +| Session replay | The page DOM and its changes, in the browser and Electron. | [Privacy: Replay](/sdk/javascript/privacy/replay) | +| Input | Pointer presses and named key presses, with a description of the target element. Typed characters are not recorded. | `captureInteractions` | +| Console logs | Console output and lines you write with `log`. | [Privacy: Console logs](/sdk/javascript/privacy/logs) | +| Network | Requests, responses, headers and bodies. | [Privacy: Network](/sdk/javascript/privacy/network) | +| Breadcrumbs | Your breadcrumbs and the automatic ones. | [Privacy: Breadcrumbs](/sdk/javascript/privacy/breadcrumbs) | +| Events and traces | Your `event` and `trace` calls, and the system events and traces the SDK records. | `captureSystemEvents`, `captureSystemTraces` | +| View hierarchy | A description of the DOM at report time, in the browser. | `captureViewHierarchy` | +| Crash detail | For an error or crash, the structured stack with source positions. | None. It is the stack of the error. | +| Environment | App id, version and build, the runtime and operating system, device and screen details. | Launch options for the identity fields | +| User and attributes | The user identifier and the attributes you set. | [Below](#attributes-and-the-user-identifier) | +| Attachments | Files you add, up to 3 of 3 MB each. | [Below](#attachments) | +| Performance | Transactions and spans, with the performance extension. | `performanceMonitoring`, `setSpanFilter` | + +On Node.js and Bun a report can also carry a CPU profile and the local variables of a stack frame, but only when you turn those diagnostics on. They are off by default. See [Diagnostics](/sdk/javascript/issue-detection/diagnostics). + +## What a report handler can change + +A [report handler](/sdk/javascript/report-handler) can change the report details: summary, description, severity, labels, email and attachments. It can also veto the report. + +```ts +import { bugsee } from './bugsee'; + +bugsee.setReportHandler({ + before: (request) => { + const { report } = request; + // Never send the stack text of a certain error + if (report.summary?.includes('PaymentError')) { + report.description = undefined; + } + // Do not report on behalf of staff accounts + if (report.email?.endsWith('@example.com')) { + return null; + } + return request; + }, +}); +``` + +Where `bugsee` is the client `launch` returned: + +```ts title="bugsee.ts" +import { launch } from '@bugsee/bugsee'; + +export const bugsee = await launch(''); +``` + +### What it cannot do + +- It cannot remove console logs, network events, breadcrumbs, replay or traces from the bundle. Control these where they are recorded, with the filters and options on the pages above. +- It does not change the structured crash detail. The error message and stack are in the report's summary, description and crash detail, so keep personal data out of error messages. + +## Attributes and the user identifier + +Both are uploaded with every report, and neither is redacted. You decide what they contain. + +- Use an opaque id, not an email address, in `setUserIdentifier`. The identifier is sent as the reporter email unless a report has its own email. +- Do not put secrets or personal data in `setAttribute`. +- Call `clearUserIdentifier()` and `clearAllAttributes()` at sign-out, so the next reports do not carry them. +- A report carries the identifier and attributes as they were when the report was created. Clearing them later does not rewrite a report that has already been created and is waiting in the upload queue. +- In the browser, the identifier stays in memory unless you set `persistUserIdentifier: true`. + +See [User & session data](/sdk/javascript/user-session-data). + +## Attachments + +An attachment is exactly what you pass. It is not redacted, masked or filtered. Do not attach files that hold secrets, and review what a helper such as a config dump contains. + +## Error messages + +The summary and description of an error report come from the error's message and stack. A message such as `User jane@example.com not found` ends up in the report. Keep personal data out of error messages, or redact them in the report handler. + +## Related pages + +- [Report handler](/sdk/javascript/report-handler) — the callbacks and examples. +- [Privacy overview](/sdk/javascript/privacy/overview) — all privacy controls. +- [User & session data](/sdk/javascript/user-session-data) — identifier and attributes. +- [Privacy: Cleanup](/sdk/javascript/privacy/cleanup) — where data is stored and how to limit it. diff --git a/docs/sdk/javascript/release-notes.md b/docs/sdk/javascript/release-notes.md new file mode 100644 index 00000000..9b4fdbc8 --- /dev/null +++ b/docs/sdk/javascript/release-notes.md @@ -0,0 +1,52 @@ +--- +title: "Release notes" +description: "Release history for the Bugsee JavaScript SDK (beta): what changed in each 0.1.0 beta release." +sidebar_position: 21 +slug: "/sdk/javascript/release-notes" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Release history for the Bugsee JavaScript SDK. All packages (`@bugsee/bugsee`, the platform packages, the framework adapters, the bundler plugins and the internal packages) are released together and share one version number. See [Packages](/sdk/javascript/packages) for the list. + +The npm `latest` and `beta` tags both point at the newest beta, so `npm install @bugsee/bugsee` and `npm install @bugsee/bugsee@beta` install the same version. Keep every `@bugsee/*` package you use at the same version. + +## 0.1.0-beta.8 (November 20 2026) + +A fix for stack traces of thrown values that are not `Error` objects. + +**Changes** + +- **Debug IDs on caller-site frames of a thrown non-`Error`.** When your code throws a value that is not an `Error` (a string or a plain object, for example), the frames of the call site now carry the debug IDs of your bundles, so the stack trace resolves against uploaded source maps like any other. See [Symbolication](/sdk/javascript/symbolication/overview). + +## 0.1.0-beta.7 (November 19 2026) + +**Changes** + +- **`launch()` with a missing token no longer throws.** A missing, empty or non-string token returns a disabled client and reports one error through `onError` (or `console.warn` when you gave none). Nothing is captured or uploaded and every method is safe to call. See [Installation](/sdk/javascript/installation#2-get-your-app-token). +- **Bundler plugins read `.env.bugsee-build-plugin`.** The plugins depend on `@bugsee/cli` and read `BUGSEE_APP_TOKEN`, `BUGSEE_APP_VERSION` and `BUGSEE_APP_BUILD` from a `.env.bugsee-build-plugin` file. Real environment variables take precedence. See [Symbolication environment](/sdk/javascript/symbolication/environment). +- **Hang reports carry the blocking stack.** An `AppHang` report on Node.js and Bun includes a `crash.json` with the stack that blocked the event loop. See [Hangs](/sdk/javascript/issue-detection/hangs). +- **Angular builds.** A fix in `@bugsee/rrweb` for Angular's esbuild builder: the inlined replay worker no longer ends with a stray `sourceMappingURL` line that broke the build. + +## 0.1.0-beta.1 to 0.1.0-beta.6 + +The initial public beta line. These releases introduced the SDK across browsers, Node.js, Bun, Electron, Cloudflare Workers, Vercel Edge and Web and Service Workers, with the framework, meta-framework and backend adapters, session replay, performance monitoring, OpenTelemetry interop and the source-map tooling. Per-release details are not listed here. + +## Compatibility + +| | | +| --- | --- | +| Node.js | 18 or later | +| Bun | 1.1.13 or later (tested on 1.3) | +| Module formats | ESM and CommonJS | +| Language level | ES2022 | + +Upgrading between betas: update every `@bugsee/*` package together, and check these notes for behavior changes. Betas can change between releases. + +## Related pages + +- [Installation](/sdk/javascript/installation) — add the package and launch the SDK. +- [Packages](/sdk/javascript/packages) — which packages to install. +- [FAQ](/sdk/javascript/faq) — practical questions and answers. diff --git a/docs/sdk/javascript/report-handler.md b/docs/sdk/javascript/report-handler.md new file mode 100644 index 00000000..3349e408 --- /dev/null +++ b/docs/sdk/javascript/report-handler.md @@ -0,0 +1,156 @@ +--- +title: "Report handler" +description: "Inspect, enrich, redact or veto every report before the Bugsee JavaScript SDK sends it: setReportHandler, its before and after callbacks, the report fields you can change, and attachments." +sidebar_position: 9 +slug: "/sdk/javascript/report-handler" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +A **report handler** is the one place to inspect or change a report before Bugsee sends it. It sees every kind of report: crashes and errors the SDK detects, handled exceptions from [`logException`](/sdk/javascript/manual/crash-error-reporting), and bug reports from [`upload`](/sdk/javascript/manual/bug-reporting) and the report dialog. That makes it the hook for anything that must apply to all of them: labels, a severity rule, an attachment, redacted text, or dropping a report you do not want. + +```ts +import { launch } from '@bugsee/bugsee'; + +const bugsee = await launch(''); + +bugsee.setReportHandler({ + before: (request) => { + request.report.labels.push('beta-build'); + return request; + }, +}); +``` + +## Install it + +Call `setReportHandler(handler)` on the client `launch` returned, as soon as you have it. A handler applies to reports created after it is installed. + +There is one handler at a time. A later call replaces it, and `setReportHandler(null)` removes it. `relaunch()` returns a new client, so install the handler again on that client. + +## The two callbacks + +| Callback | When it runs | Return value | +| --- | --- | --- | +| `before(request)` | Before the report is queued. | The request (changed or not) to keep the report, or `null` to veto it. | +| `after(request)` | After the report is created, before its bundle is assembled and uploaded. | Nothing. | + +Both are optional and both must be synchronous. Keep them fast: for a crash they run while the page or process is already in trouble. + +- **`before` can drop a report.** Returning `null` discards it: it is never sent, and `upload` or `logException` resolve `{ ok: false }`. A `before` that **throws** also drops the report, and the error goes to the `onError` launch option. A report that may not have been scrubbed is never sent by accident. +- **`after` can still change the report.** It runs once the report exists, so it can set labels, change the summary or add attachments, and the bundle carries the result. It is not called when no report was created: a veto, a report the queue refused, or an SDK that has been stopped. A throwing `after` goes to `onError` and does not stop the report. +- **How an upload ended** is not reported to `after`. Observe it with the `AfterReportUploaded` and `ReportUploadFailed` [lifecycle events](/sdk/javascript/lifecycle). + +## The request + +Both callbacks receive a `ReportingRequest`: + +| Field | Type | Description | +| --- | --- | --- | +| `id` | `string` | The report id. Read-only. | +| `source.type` | `string` | What triggered the report: `crash`, `error`, `code_upload`, `code_dialog` and others. Read-only. | +| `source.mechanism` | `string \| undefined` | How the error was caught: `uncaught`, `unhandledrejection`, `programmatic`, `http-error`, `hang` and others. | +| `report.type` | `'bug' \| 'error' \| 'crash'` | The issue type. | +| `report.summary` | `string \| undefined` | The title. | +| `report.description` | `string \| undefined` | The text. For an error this is its stack, followed by the `cause` chain. | +| `report.severity` | `'verylow' \| 'low' \| 'medium' \| 'high' \| 'critical' \| 'blocker'` | The severity. A severity the SDK derived from the report type is already replaced by `reportDefaultCrashPriority`, `reportDefaultErrorPriority` or `reportDefaultBugPriority` when `before` runs. | +| `report.labels` | `string[]` | Labels. | +| `report.email` | `string \| undefined` | Reporter email. When unset, the user identifier is used. | +| `report.userAttachments` | `ReportAttachmentInput[] \| undefined` | Files the application attaches. | + +Change fields on `request.report` in place and return the same request, or return a new one. + +## Add labels and change severity + +```ts +import { bugsee } from './bugsee'; + +bugsee.setReportHandler({ + before: (request) => { + const { report, source } = request; + report.labels.push('beta-build'); + if (source.mechanism === 'unhandledrejection') { + report.severity = 'medium'; + } + return request; + }, +}); +``` + +An explicit severity you passed to `logException` or `upload` is yours: the handler sees it and can still change it. + +## Veto a report + +```ts +import { bugsee } from './bugsee'; + +bugsee.setReportHandler({ + before: (request) => { + const text = `${request.report.summary ?? ''}\n${request.report.description ?? ''}`; + if (text.includes('ResizeObserver loop')) { + return null; // known benign browser warning + } + return request; + }, +}); +``` + +## Redact text + +The summary and description of an error come from the error message and stack. If your messages can carry personal data, scrub them here: + +```ts +import { bugsee } from './bugsee'; + +const EMAIL = /[\w.%+-]+@[\w-]+(?:\.[\w-]+)+/g; + +bugsee.setReportHandler({ + before: (request) => { + const { report } = request; + if (report.summary !== undefined) { + report.summary = report.summary.replace(EMAIL, ''); + } + if (report.description !== undefined) { + report.description = report.description.replace(EMAIL, ''); + } + return request; + }, +}); +``` + +This changes the report's summary and description only. It does not change the logs, network events, breadcrumbs, replay or the structured stack that travel in the same report. Keep that data clean where it is recorded; see [Privacy: Report](/sdk/javascript/privacy/report). + +## Attach a file + +`addReportAttachment(report, attachment)` appends a file to a report. It is exported by `@bugsee/bugsee`, and is the helper form of writing `report.userAttachments` yourself. + +```ts +import { addReportAttachment } from '@bugsee/bugsee'; +import { bugsee } from './bugsee'; + +bugsee.setReportHandler({ + after: (request) => { + addReportAttachment(request.report, { + name: 'App config', + data: JSON.stringify({ build: 'beta', flags: ['new-checkout'] }), + mimeType: 'application/json', + }); + }, +}); +``` + +A report carries up to 3 attachments of up to 3 MB each. See the limits in [Bug reporting](/sdk/javascript/manual/bug-reporting#attachments). + +## What a handler cannot do + +- It cannot remove logs, network events, breadcrumbs or replay from the bundle. Use the [filters](/sdk/javascript/privacy/overview) and the replay masking options for that. +- It is not the only privacy control to rely on. Keep sensitive data out where it is recorded. + +## Related pages + +- [Bug reporting](/sdk/javascript/manual/bug-reporting) — `upload`, `prepareUpload` and the report dialog. +- [Crash & error reporting](/sdk/javascript/manual/crash-error-reporting) — `logException` and the rate limit. +- [Privacy: Report](/sdk/javascript/privacy/report) — what a report carries and how to keep it clean. +- [Lifecycle](/sdk/javascript/lifecycle) — report events such as `AfterReportUploaded`. diff --git a/docs/sdk/javascript/session-replay.md b/docs/sdk/javascript/session-replay.md new file mode 100644 index 00000000..34c1ba26 --- /dev/null +++ b/docs/sdk/javascript/session-replay.md @@ -0,0 +1,142 @@ +--- +title: "Session replay" +description: "How the Bugsee JavaScript SDK records DOM session replay in the browser and Electron, the replay options, the canvas add-on, blackout, and the opt-in pixel video for Electron." +sidebar_position: 25 +slug: "/sdk/javascript/session-replay" +--- + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +Session replay shows what the user saw in the minutes before a report: the page, the clicks and the scrolling, played back next to the logs and network events. Bugsee records the **DOM**, not pixels. It stores the page structure and each change to it, and the viewer rebuilds the page from that. This keeps the recording small and lets the SDK mask text before it leaves the page. + +## What you get + +| Runtime | Replay | +| --- | --- | +| Browser | On by default. Recorded in the page. | +| Electron | On by default in each renderer. The renderers stream to the main process, which owns the session. | +| Node.js, Bun, edge runtimes | Not applicable. There is no DOM. | + +Replay needs a DOM. During server rendering, for example in a meta-framework's server pass, nothing is recorded, whatever the option says. + +Replay is recorded in a rolling window, the length of the `maxRecordingTime` launch option (60 seconds by default), and goes into a report when one is created. It is not streamed continuously. + +## Turn replay off or customize it + +The `replay` launch option takes `false`, `true` or an options object. + +```ts +import { launch } from '@bugsee/bugsee'; + +// Replay on, with defaults +await launch(''); + +// Replay off. The replay code is never loaded. +await launch('', { replay: false }); +``` + +A value that is not a boolean or a plain object (`0`, `null`, `'false'`) turns replay **off** and is reported through the `onError` launch option. Replay captures page content, so it never stays on by accident. + +The replay recorder is loaded as a separate chunk only when replay runs, so `replay: false` keeps it out of your page entirely. + +## Replay options + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `maskAllText` | `boolean` | `true` | Mask every text node. | +| `maskAllInputs` | `boolean` | `true` | Mask every input value. | +| `blockAllMedia` | `boolean` | `true` | Block images, video, audio, SVG and iframes. A blocked element becomes an empty placeholder of the same size. | +| `blockAllCanvas` | `boolean` | `false` | Block every ``, except the ones you mark with `bugsee-show`. | +| `maskTextSelector` | `string` | none | Extra CSS selector whose text is masked. | +| `blockSelector` | `string` | none | Extra CSS selector whose elements are blocked. | +| `ignoreSelector` | `string` | none | Extra CSS selector whose input events are ignored. | +| `checkoutEveryNms` | `number` | `60000` | Interval of a full page snapshot, in milliseconds. It bounds the length of the window that can be kept. | +| `canvas` | `boolean \| { fps?, quality?, imageType? }` | off | Record `` content. See [below](#record-canvas-content). | + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + replay: { + maskAllText: true, + blockSelector: '.private-panel', + ignoreSelector: '.secret-input', + }, +}); +``` + +Masking is fail closed. Text, input values and media are masked or blocked unless you relax that. An invalid CSS selector is dropped and reported, and where dropping it would weaken privacy the strictest setting is used instead. Masking rules, the CSS classes and the always-masked fields are on the [Privacy: Replay](/sdk/javascript/privacy/replay) page. + +## Mark elements in your markup + +You can control single elements with a class or a data attribute, without code: + +```html +
Account number: 12345
+
+Order #1042 +Logo +``` + +See [Privacy: Replay](/sdk/javascript/privacy/replay#css-classes) for what each class does. + +## Record canvas content + +A `` is a bitmap, so by default it is empty in the replay. The canvas add-on records its pixels. It is off by default, and it is loaded only when you enable it. + +```ts +import { launch } from '@bugsee/bugsee'; + +await launch('', { + replay: { + canvas: { fps: 2, quality: 0.6, imageType: 'image/webp' }, + }, +}); + +// Or with the defaults: +// replay: { canvas: true } +``` + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `fps` | `number \| 'all'` | `2` | Snapshots per second, clamped to 1 through 60. `'all'` records every draw call and is heavier. | +| `quality` | `number` | `0.6` | Image quality from 0 to 1. | +| `imageType` | `'image/webp' \| 'image/jpeg'` | `'image/webp'` | Image format. | + +:::caution +Canvas pixels are recorded **unmasked**. Enable the add-on only for canvases that never show sensitive data. To record only some canvases, set `blockAllCanvas: true` and add the `bugsee-show` class, or a `data-bugsee-show` attribute, to each canvas you want. Put it on the `` element itself. +::: + +## Blackout + +A blackout stops visual and interaction capture until you end it: replay, input, the automatic `ui.*` breadcrumbs and the view hierarchy. Logs, network events, traces and events carry on. + +```ts +import { bugsee } from './bugsee'; + +bugsee.startBlackout(); +// ... show the sensitive screen ... +bugsee.endBlackout(); +``` + +When the blackout ends, replay resumes with a fresh full snapshot taken from the live page. End the blackout only **after** the sensitive view has gone, or the snapshot contains it. To start dark from the first frame, set the `startInBlackout` launch option. See [Lifecycle](/sdk/javascript/lifecycle). + +## Pixel video in Electron + +Electron records DOM replay by default, like the browser. It also offers an opt-in pixel video, for apps where DOM replay cannot show what matters, for example a window drawn by native code. You supply a capture source in the `video` option of `launchMain`. The video is taken when a report is created, and the OS may ask for screen capture permission. See [Electron](/sdk/javascript/platforms/electron). + +## What replay does not record + +- **Typed characters.** Input values are masked, and keystrokes are not recorded as text. Sensitive fields are always masked and their input events are ignored. +- **The report dialog.** The recording is frozen before the dialog opens, so what the user types into it is not in the replay of that report. +- **Iframes**, by default. A blocked iframe is an empty placeholder: its document is never recorded. Mark an iframe `bugsee-show` to record it. Its content is then masked like the rest of the page. + +## Related pages + +- [Privacy: Replay](/sdk/javascript/privacy/replay) — masking rules and CSS classes. +- [Browser](/sdk/javascript/platforms/browser) — the browser SDK. +- [Electron](/sdk/javascript/platforms/electron) — main and renderer setup. +- [Lifecycle](/sdk/javascript/lifecycle) — blackout and the SDK states. +- [Configuration](/sdk/javascript/configuration) — every launch option. diff --git a/docs/sdk/javascript/symbolication/bundler-plugins.mdx b/docs/sdk/javascript/symbolication/bundler-plugins.mdx new file mode 100644 index 00000000..d32618bb --- /dev/null +++ b/docs/sdk/javascript/symbolication/bundler-plugins.mdx @@ -0,0 +1,231 @@ +--- +title: "Bundler plugins" +description: "Upload source maps from your build with the Bugsee plugins for Vite, webpack, Rollup, esbuild and Rspack, and label components with the annotate plugins. All options explained." +sidebar_position: 2 +slug: "/sdk/javascript/symbolication/bundler-plugins" +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +:::warning[Beta] +This page documents the Bugsee JavaScript SDK, which is in beta (0.1.x) and can change between betas. +::: + +A bundler plugin does the whole [symbolication](/sdk/javascript/symbolication/overview) job at the end of the build: it stamps the bundles and maps with a debug ID, uploads the maps, and deletes the local `.map` files so they are not deployed. The plugins run the Bugsee CLI, which is installed with them. See [Source maps](/cli/sourcemaps) for what the CLI does. + +Without an app token, a plugin does nothing, so local builds are unaffected. + +## Set up + +Turn on source maps in your bundler, add the plugin and give it your app token. + + + + +```bash +npm install --save-dev @bugsee/vite-plugin +``` + +```ts title="vite.config.ts" +import { defineConfig } from 'vite'; +import { bugseeVitePlugin } from '@bugsee/vite-plugin'; + +export default defineConfig({ + build: { sourcemap: true }, + plugins: [bugseeVitePlugin({ appToken: process.env.BUGSEE_APP_TOKEN })], +}); +``` + +Use this plugin for frameworks that build on Vite as well. + + + + +```bash +npm install --save-dev @bugsee/webpack-plugin +``` + +```js title="webpack.config.js" +const { bugseeWebpackPlugin } = require('@bugsee/webpack-plugin'); + +module.exports = { + devtool: 'source-map', + plugins: [bugseeWebpackPlugin({ appToken: process.env.BUGSEE_APP_TOKEN })], +}; +``` + +With ES modules, use `import { bugseeWebpackPlugin } from '@bugsee/webpack-plugin';`. Next.js on webpack uses this plugin. + + + + +The Rollup, esbuild and Rspack plugins have no package of their own. Install `@bugsee/bundler-plugin-core` and import them from it. They are less exercised than the Vite and webpack plugins. + +```bash +npm install --save-dev @bugsee/bundler-plugin-core +``` + +```js title="rollup.config.js" +import { bugseeRollupPlugin } from '@bugsee/bundler-plugin-core'; + +export default { + input: 'src/index.js', + output: { dir: 'dist', sourcemap: true }, + plugins: [bugseeRollupPlugin({ appToken: process.env.BUGSEE_APP_TOKEN })], +}; +``` + +The plugin runs at `writeBundle`. + + + + +```bash +npm install --save-dev @bugsee/bundler-plugin-core +``` + +```js title="build.mjs" +import { build } from 'esbuild'; +import { bugseeEsbuildPlugin } from '@bugsee/bundler-plugin-core'; + +await build({ + entryPoints: ['src/index.ts'], + bundle: true, + outdir: 'dist', + sourcemap: 'external', + plugins: [bugseeEsbuildPlugin({ appToken: process.env.BUGSEE_APP_TOKEN })], +}); +``` + +The plugin runs when the build ends and hands the CLI the files that this build wrote. See [esbuild notes](#esbuild-notes). + + + + +```bash +npm install --save-dev @bugsee/bundler-plugin-core +``` + +```js title="rspack.config.js" +const { bugseeRspackPlugin } = require('@bugsee/bundler-plugin-core'); + +module.exports = { + devtool: 'source-map', + plugins: [bugseeRspackPlugin({ appToken: process.env.BUGSEE_APP_TOKEN })], +}; +``` + +Rspack emits no source maps by default in production (`devtool: false`), so the plugin finds nothing to upload and says so. Set `devtool`. + + + + +## Options + +All options are optional. A token is needed to upload, and it may come from the environment. See [Environment and variables](/sdk/javascript/symbolication/environment) for the lookup order and the `.env.bugsee-build-plugin` file. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appToken` | `string` | `BUGSEE_APP_TOKEN` | Your app token. Without one, the plugin does nothing. | +| `appVersion` | `string` | `BUGSEE_APP_VERSION`, then the `version` of the nearest `package.json`, else `0.0.0` | The version recorded with the upload. A real value is also baked into the bundle for the SDK. | +| `appBuild` | `string` | `BUGSEE_APP_BUILD`, then the commit id of your CI, else `0` | The build recorded with the upload. A real value is also baked into the bundle for the SDK. | +| `endpoint` | `string` | `BUGSEE_ENDPOINT`, else `https://api.bugsee.com` | The API endpoint. | +| `deleteMaps` | `boolean` | `true` | Delete the `.map` files from the output after a successful upload. | +| `stripSourcesContent` | `boolean` | `false` | Upload the maps without the embedded source code. Positions still resolve, but reports show no source lines. The maps on disk are not changed. | +| `dryRun` | `boolean` | `false` | Run the CLI in dry-run mode: nothing is uploaded or deleted, and the notices say what was captured. | +| `disabled` | `boolean` | `false` | Turn the plugin off, for example in development builds. | +| `failOnError` | `boolean` | `false` | Fail the build when the upload fails. By default a failed upload only warns, so a telemetry problem never breaks a deploy. | +| `registerBuild` | `'release' \| 'always' \| false` | `BUGSEE_REGISTER_BUILD`, else `'release'` | Which builds are registered with Bugsee. See [Build registration](#build-registration). | +| `packageId` | `string` | the `name` of the nearest `package.json`, scope included | The package id of the registered build. | +| `vcs` | `boolean` | `true` | Capture the commit, branch and repository of the build. `false` records nothing, even an explicit `commit`. | +| `commit` | `string` | `BUGSEE_BUILD_COMMIT`, else detected | The commit SHA of the build, 7 to 64 hexadecimal characters. An explicit value skips the dirty-tree check. | +| `allowDirtyCommit` | `boolean` | `false` | Record the commit even when tracked files have uncommitted changes. | +| `projectRoot` | `string` | the working directory | The repository root that commit detection inspects. It does not change where the version is read from. | +| `uploadInDevelopment` | `boolean` | `false` | esbuild and Rspack only. Upload from builds the bundler calls development. | +| `onError` | `(error) => void` | a console warning | Receives a failure that was contained. | +| `onNotice` | `(message) => void` | `console.warn` | Receives notices about configuration, such as a skipped upload or a dropped commit. Notices are strings, not errors. | + +The version and build are also baked into your bundle as `__BUGSEE_APP_VERSION__` and `__BUGSEE_APP_BUILD__`, so the SDK reports the same release without you passing `appVersion` to `launch()`. This happens even without a token. `disabled: true` turns it off. See [Environment and variables](/sdk/javascript/symbolication/environment#version-and-build). + +## Build registration + +At the end of a production build, the plugin also registers the build with Bugsee. Registration records the build only. No files are uploaded with it. + +| `registerBuild` | Registers | +| --- | --- | +| `'release'` | A build that the bundler calls production: the resolved production flag in Vite, `mode: 'production'` or an unset `mode` in webpack, otherwise `NODE_ENV=production`. | +| `'always'` | Every build. | +| `false` | No build. | + +A failed registration never fails the build unless `failOnError` is set. Registration happens once for each output folder, so a build that writes two folders registers two builds. + +## Commit information + +With `vcs` on, the plugin asks the CLI for the commit SHA, branch and repository of the build, reading your CI environment and falling back to `git`. It never fails a build: with no `git`, no repository or no commits, nothing is recorded. + +If tracked files have uncommitted changes, the SHA no longer describes what was built, so it is dropped and the reason is printed. The check runs after the build wrote its output and covers the whole repository. A repository that commits generated files, or has an unrelated dirty package in a monorepo, can look dirty on every build. Pass `allowDirtyCommit: true`, or commit the generated files before building. + +For a build made from an artifact, with no working tree, pass `commit` or set `BUGSEE_BUILD_COMMIT`. + +## Behavior to know + +- **Development builds.** The Vite, webpack and Rollup plugins upload every build they run. Set `disabled` for builds you do not want uploaded. The esbuild and Rspack plugins skip builds that the bundler calls development, and leave the local maps alone, unless you set `uploadInDevelopment: true`. esbuild states no mode, so only `NODE_ENV=development` marks a development build there. +- **Subresource Integrity.** The stamp rewrites each bundle, which would invalidate script hashes in your HTML. When the stamp happens inside the build, as in webpack, the plugin checks for hashes that no longer match and warns. When it runs after the output is written, it refuses to stamp a build whose HTML pins a hash of a script. The page stays as the bundler emitted it, and the maps are not uploaded. +- **Source maps are deleted** after a fully successful upload, which is why the browser no longer finds them. Set `deleteMaps: false` to keep them. A dry run deletes nothing. +- **Watch mode.** The plugins keep no state between rebuilds, and builds that share an output folder do not wait for each other. + +### esbuild notes + +- If you did not set `sourcemap`, the plugin sets it to `'external'`. An explicit value is kept. With `sourcemap: false` there is nothing to upload, and the plugin says so. +- The plugin asks esbuild for its metafile and uploads only the bundles and maps of this build. It never walks the output folder, so it never deletes a file it did not upload. +- It works with any tool that takes esbuild plugins and lets esbuild write the files. **tsup is not covered**: tsup tells esbuild not to write, and writes the files itself afterwards, so nothing is on disk when the plugin runs. Use the [CLI recipe](/sdk/javascript/symbolication/manual#tsup) instead. +- A build with `sourcemap: 'inline'` has no map files. With `failOnError`, it fails. Otherwise the plugin only says so. + +### What the plugins do not cover + +- **Angular.** Its builder does not accept esbuild plugins. Use the [CLI recipe](/sdk/javascript/symbolication/manual#angular). +- **Bun's bundler, `tsc` and `swc`.** They have no hook. Use the [CLI recipe](/sdk/javascript/symbolication/manual). + +## Annotate plugins + +These optional plugins label the DOM elements that a component renders with the component's name, in a `data-bugsee-component` attribute. Bugsee reads it to attribute clicks and errors to a component even when minification mangled the names. Without them, everything is still captured. + +| Framework | Package | How | +| --- | --- | --- | +| React, Preact, Solid | `@bugsee/babel-plugin-component-annotate` | A Babel plugin with no options. Needs `@babel/core` 7. | +| Svelte, SvelteKit | `@bugsee/svelte-plugin-component-annotate` | A Svelte preprocessor. Needs `svelte` 4 or newer. | +| Vue | `@bugsee/vue` | A runtime mixin instead of a build plugin. See [Vue](/sdk/javascript/frameworks/vue). | + +```bash +npm install --save-dev @bugsee/babel-plugin-component-annotate +``` + +```js title="babel.config.js" +module.exports = { + plugins: [['@bugsee/babel-plugin-component-annotate']], +}; +``` + +The Babel plugin adds `data-bugsee-component=""` to each host element, such as a `