@belvador/cloudflare 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Belvador
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ This software depends on the Sentry JavaScript SDK (https://github.com/getsentry/sentry-javascript),
26
+ which is distributed under its own MIT License (Copyright (c) Functional Software, Inc. dba Sentry)
27
+ in each of its npm packages. Belvador is not affiliated with or endorsed by Sentry.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # @belvador/cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Error tracking for Cloudflare Workers, sending to your [Belvador](https://belvador.dev) node.
4
+
5
+ ```sh
6
+ npm install @belvador/cloudflare
7
+ ```
8
+
9
+ ```ts
10
+ import { withBelvador } from "@belvador/cloudflare";
11
+
12
+ export default withBelvador(
13
+ (env) => ({ release: env.BELVADOR_RELEASE }),
14
+ {
15
+ async fetch(request, env, ctx) {
16
+ return new Response("ok");
17
+ },
18
+ },
19
+ );
20
+ ```
21
+
22
+ Set the DSN as a secret: `wrangler secret put BELVADOR_DSN`. The SDK also reads
23
+ `BELVADOR_RELEASE` (else `CF_VERSION_METADATA.id`), `BELVADOR_ENVIRONMENT` and
24
+ `BELVADOR_DISABLED=1`. It never reads `SENTRY_*` variables.
25
+
26
+ Requires the `nodejs_compat` compatibility flag so every request gets its own scope (user,
27
+ tags and context never leak between requests). Errors are reported and re-thrown; your
28
+ response (status, headers, streamed body) is returned unchanged and sending finishes in
29
+ `waitUntil` after the response.
30
+
31
+ ## What it sends
32
+
33
+ Errors only (exceptions, messages, breadcrumbs you turn on, attachments if you enable them).
34
+ No tracing, session replay, logs or profiling — those items are dropped inside your app.
35
+
36
+ Before anything leaves your app the SDK removes `Authorization`, `Cookie` and `Set-Cookie`
37
+ headers, request bodies and cookies, client IP headers, and masks credentials in URLs, query
38
+ strings, tags, contexts, extra data and breadcrumbs (passwords, tokens, API keys, JWTs, card
39
+ numbers, e-mail addresses). Only `user.id` is kept from `setUser`. Your Belvador node scrubs
40
+ again on its own.
41
+
42
+ Sending never slows down or breaks your app: at most 30 envelopes / 1 MB wait to be sent,
43
+ each attempt times out after 10 s, failed sends retry at most 5 times, `429` rate limits are
44
+ respected, and a revoked key (`401`/`403`) stops sending for the life of the page or isolate.
45
+ Every public function catches its own errors.
46
+
47
+ ## Check the connection
48
+
49
+ "No errors" is not proof that errors arrive. Call `verifyIntegration()` from `@belvador/cloudflare` inside a request handled by `withBelvador`:
50
+ it sends one marked test error (never an issue), reads it back and resolves to
51
+ `{ outcome: "verified" | "problem" | "unconfirmed", checks, docsUrl, … }`. It never throws.
52
+ Requests the visitor cancelled (`AbortError`) are not reported unless you set `captureAborted: true`.
53
+ See https://belvador.dev/docs/sdk/verify
54
+
55
+ ## Status
56
+
57
+ `0.x` — used by Belvador's own apps first. The API may still change before `1.0`.
58
+
59
+ Built on the open-source [Sentry JavaScript SDK](https://github.com/getsentry/sentry-javascript)
60
+ (MIT), pinned to one audited version, with Belvador's privacy and sending rules. Events go only
61
+ to your Belvador DSN; no Sentry account is involved. Belvador is not affiliated with Sentry.
62
+
63
+ License: MIT · https://belvador.dev
@@ -0,0 +1,35 @@
1
+ import type { CloudflareOptions as EngineCloudflareOptions } from "@sentry/cloudflare";
2
+ import { type BelvadorOptions, type VerificationResult, type VerifyOptions } from "@belvador/core";
3
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, getDiagnostics, lastEventId, setContext, setTag, setTags, setUser, withScope, type BelvadorBreadcrumb, type BelvadorEvent, type BelvadorEventHint, type Diagnostic, type DiagnosticCode, type DiagnosticsSnapshot, type Scope, type SeverityLevel, type VerificationResult, type VerifyOptions, } from "@belvador/core";
4
+ export type WorkerOptions = Omit<BelvadorOptions, "dsn"> & {
5
+ /** Defaults to the BELVADOR_DSN binding. */
6
+ dsn?: string;
7
+ /** Breadcrumb sources, off by default. */
8
+ instrument?: {
9
+ console?: boolean;
10
+ fetch?: boolean;
11
+ };
12
+ };
13
+ /** Bindings the SDK reads (values returned by your options callback win). */
14
+ export type BelvadorEnv = {
15
+ BELVADOR_DSN?: string;
16
+ BELVADOR_RELEASE?: string;
17
+ BELVADOR_ENVIRONMENT?: string;
18
+ BELVADOR_DISABLED?: string;
19
+ };
20
+ /** Engine options for one Worker invocation (exported for tests and @belvador/tanstack-start). */
21
+ export declare function workerEngineOptions(options: WorkerOptions | undefined, env: unknown, runtime?: "cloudflare" | "tanstack-start"): EngineCloudflareOptions;
22
+ /** Shared with @belvador/tanstack-start so its server events carry its own SDK name. */
23
+ export declare function wrapHandler<Env, H>(optionsCallback: (env: Env) => WorkerOptions | undefined, handler: H, runtime: "cloudflare" | "tanstack-start"): H;
24
+ /**
25
+ * Wraps a Worker's exported handler (fetch, scheduled, queue, email, tail):
26
+ * one client per invocation, errors reported and re-thrown, responses
27
+ * untouched, sending finished in waitUntil after the response.
28
+ */
29
+ export declare function withBelvador<Env, H>(optionsCallback: (env: Env) => WorkerOptions | undefined, handler: H): H;
30
+ /**
31
+ * Proves this Worker reports to Belvador. Call it inside a request handled by
32
+ * withBelvador (for example a temporary `/verify-belvador` path): it checks the wrapper,
33
+ * sends one verification error and reads it back. Never automatic; always resolves.
34
+ */
35
+ export declare function verifyIntegration(options?: VerifyOptions): Promise<VerificationResult>;
package/dist/index.js ADDED
@@ -0,0 +1,175 @@
1
+ // @belvador/cloudflare — errors from Cloudflare Workers to your Belvador node.
2
+ // Built on the open-source Sentry JavaScript SDK (MIT), with Belvador's
3
+ // privacy and sending rules. Needs the `nodejs_compat` (or `nodejs_als`)
4
+ // compatibility flag so every request gets its own scope.
5
+ import { consoleIntegration, dedupeIntegration, eventFiltersIntegration, fetchIntegration, linkedErrorsIntegration, requestDataIntegration, withSentry, } from "@sentry/cloudflare";
6
+ import { buildEngineOptions, currentHooks, markHooked, noteClientAbort, runVerification, } from "@belvador/core";
7
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, getDiagnostics, lastEventId, setContext, setTag, setTags, setUser, withScope, } from "@belvador/core";
8
+ function binding(env, name) {
9
+ if (env === null || typeof env !== "object")
10
+ return undefined;
11
+ try {
12
+ const v = env[name];
13
+ return typeof v === "string" && v.length > 0 ? v : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ function versionId(env) {
20
+ if (env === null || typeof env !== "object")
21
+ return undefined;
22
+ try {
23
+ const meta = env["CF_VERSION_METADATA"];
24
+ const id = meta && typeof meta === "object" ? meta["id"] : undefined;
25
+ return typeof id === "string" && id ? id : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ /**
32
+ * Options for a client that never sends. Every key the engine would otherwise
33
+ * read from SENTRY_* bindings is set explicitly.
34
+ */
35
+ const OFF = {
36
+ dsn: "",
37
+ enabled: false,
38
+ tunnel: "",
39
+ spotlight: false,
40
+ debug: false,
41
+ release: undefined,
42
+ environment: "production",
43
+ tracesSampleRate: 0,
44
+ defaultIntegrations: false,
45
+ integrations: [],
46
+ };
47
+ /** Engine options for one Worker invocation (exported for tests and @belvador/tanstack-start). */
48
+ export function workerEngineOptions(options, env, runtime = "cloudflare") {
49
+ try {
50
+ const o = options ?? {};
51
+ const disabled = o.disabled === true || /^(1|true)$/i.test(binding(env, "BELVADOR_DISABLED") ?? "");
52
+ const base = buildEngineOptions({
53
+ ...o,
54
+ dsn: o.dsn ?? binding(env, "BELVADOR_DSN") ?? "",
55
+ disabled,
56
+ release: o.release ?? binding(env, "BELVADOR_RELEASE") ?? versionId(env),
57
+ environment: o.environment ?? binding(env, "BELVADOR_ENVIRONMENT"),
58
+ }, runtime === "tanstack-start" ? "tanstack-start" : "cloudflare", { browser: false });
59
+ if (!base)
60
+ return OFF;
61
+ const integrations = [
62
+ dedupeIntegration(),
63
+ eventFiltersIntegration(),
64
+ linkedErrorsIntegration(),
65
+ // Request URL, method and headers (scrubbed later); never cookies, bodies or IPs.
66
+ requestDataIntegration({
67
+ include: {
68
+ cookies: false,
69
+ data: false,
70
+ ip: false,
71
+ headers: true,
72
+ query_string: true,
73
+ url: true,
74
+ },
75
+ }),
76
+ ];
77
+ if (o.instrument?.console === true)
78
+ integrations.push(consoleIntegration());
79
+ if (o.instrument?.fetch === true)
80
+ integrations.push(fetchIntegration({ breadcrumbs: true }));
81
+ return {
82
+ ...base,
83
+ // 0, not undefined: an undefined value would let SENTRY_TRACES_SAMPLE_RATE turn tracing on.
84
+ tracesSampleRate: 0,
85
+ integrations,
86
+ };
87
+ }
88
+ catch {
89
+ return OFF;
90
+ }
91
+ }
92
+ const HANDLER_METHODS = ["fetch", "scheduled", "queue", "email", "tail"];
93
+ /**
94
+ * Marks each invocation of an object handler as running inside the wrapper (integration
95
+ * health: `verifyIntegration` can tell), and notes a fetch that failed after its client
96
+ * disconnected so the error counts as a cancellation. Class handlers pass through unchanged.
97
+ */
98
+ function marked(handler) {
99
+ if (handler === null || typeof handler !== "object")
100
+ return handler;
101
+ const out = { ...handler };
102
+ for (const name of HANDLER_METHODS) {
103
+ const fn = handler[name];
104
+ if (typeof fn !== "function")
105
+ continue;
106
+ out[name] = function (...args) {
107
+ markHooked("wrapper");
108
+ const signal = name === "fetch" ? signalOf(args[0]) : undefined;
109
+ if (!signal)
110
+ return fn.apply(handler, args);
111
+ const failed = (error) => {
112
+ noteClientAbort(error, signal);
113
+ throw error;
114
+ };
115
+ let result;
116
+ try {
117
+ result = fn.apply(handler, args);
118
+ }
119
+ catch (error) {
120
+ return failed(error);
121
+ }
122
+ return isThenable(result) ? Promise.resolve(result).then(undefined, failed) : result;
123
+ };
124
+ }
125
+ return out;
126
+ }
127
+ function signalOf(request) {
128
+ try {
129
+ const signal = request?.signal;
130
+ return typeof AbortSignal !== "undefined" && signal instanceof AbortSignal ? signal : undefined;
131
+ }
132
+ catch {
133
+ return undefined;
134
+ }
135
+ }
136
+ function isThenable(value) {
137
+ return (value !== null &&
138
+ (typeof value === "object" || typeof value === "function") &&
139
+ typeof value.then === "function");
140
+ }
141
+ /** Shared with @belvador/tanstack-start so its server events carry its own SDK name. */
142
+ export function wrapHandler(optionsCallback, handler, runtime) {
143
+ return withSentry((env) => {
144
+ let options;
145
+ try {
146
+ options = optionsCallback(env);
147
+ }
148
+ catch {
149
+ return OFF;
150
+ }
151
+ return workerEngineOptions(options, env, runtime);
152
+ }, marked(handler));
153
+ }
154
+ /**
155
+ * Wraps a Worker's exported handler (fetch, scheduled, queue, email, tail):
156
+ * one client per invocation, errors reported and re-thrown, responses
157
+ * untouched, sending finished in waitUntil after the response.
158
+ */
159
+ export function withBelvador(optionsCallback, handler) {
160
+ return wrapHandler(optionsCallback, handler, "cloudflare");
161
+ }
162
+ /**
163
+ * Proves this Worker reports to Belvador. Call it inside a request handled by
164
+ * withBelvador (for example a temporary `/verify-belvador` path): it checks the wrapper,
165
+ * sends one verification error and reads it back. Never automatic; always resolves.
166
+ */
167
+ export function verifyIntegration(options) {
168
+ return runVerification({
169
+ surface: "server",
170
+ hook: () => {
171
+ const hooks = currentHooks();
172
+ return { ok: hooks.has("wrapper") || hooks.has("middleware") };
173
+ },
174
+ }, options);
175
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@belvador/cloudflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Belvador error tracking for Cloudflare Workers: per-request scope, errors only, private by default.",
5
+ "license": "MIT",
6
+ "author": "Belvador (https://belvador.dev)",
7
+ "homepage": "https://belvador.dev",
8
+ "keywords": [
9
+ "belvador",
10
+ "error-tracking",
11
+ "errors",
12
+ "monitoring"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "dependencies": {
35
+ "@belvador/core": "0.2.0",
36
+ "@sentry/cloudflare": "10.76.2"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "tag": "latest"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.json"
44
+ }
45
+ }