@belvador/cloudflare 0.1.0 → 0.3.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/README.md CHANGED
@@ -30,8 +30,9 @@ response (status, headers, streamed body) is returned unchanged and sending fini
30
30
 
31
31
  ## What it sends
32
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.
33
+ Errors (exceptions, messages, breadcrumbs you turn on, attachments if you enable them) and
34
+ the job check-ins you send with `withMonitor`. No spans, session replay, logs or profiling —
35
+ those items are dropped inside your app.
35
36
 
36
37
  Before anything leaves your app the SDK removes `Authorization`, `Cookie` and `Set-Cookie`
37
38
  headers, request bodies and cookies, client IP headers, and masks credentials in URLs, query
@@ -44,6 +45,48 @@ each attempt times out after 10 s, failed sends retry at most 5 times, `429` rat
44
45
  respected, and a revoked key (`401`/`403`) stops sending for the life of the page or isolate.
45
46
  Every public function catches its own errors.
46
47
 
48
+ ## Monitor background work
49
+
50
+ Errors alone cannot tell you that a job never ran. Wrap scheduled and queued work in
51
+ `withMonitor` (Sentry-compatible check-ins): Belvador sees each run start and finish, and
52
+ opens an incident when a run fails, times out or never happens.
53
+
54
+ ```ts
55
+ import { withMonitor } from "@belvador/cloudflare";
56
+
57
+ export default withBelvador((env) => ({ release: env.BELVADOR_RELEASE }), {
58
+ async scheduled(controller, env, ctx) {
59
+ await withMonitor("nightly-invoices", async (run) => {
60
+ const due = await loadDueInvoices(env);
61
+ if (due.length === 0) return run.skip("nothing_due");
62
+ await sendInvoices(env, due);
63
+ }, { schedule: { type: "crontab", value: "0 2 * * *" }, timezone: "Europe/Berlin" });
64
+ },
65
+ });
66
+ ```
67
+
68
+ Your function's result and errors come back unchanged (a synchronous function stays
69
+ synchronous); an error is also reported as a normal issue with the monitor's slug. For queue
70
+ consumers pass `runId` (your message id), `attempt` and `willRetry` so retries count as one
71
+ run. `captureCheckIn()` and `heartbeat()` cover manual start/finish and "still alive" checks.
72
+ Check-ins are sent only from server code. See https://belvador.dev/docs/monitors/setup
73
+
74
+ ## Link requests with one trace
75
+
76
+ Off by default. `tracePropagation: { targets: ["https://api.example.com"] }` adds
77
+ `traceparent` and `sentry-trace` headers to `fetch` calls to those URLs, so an error in the
78
+ called service and its job check-ins show up with the same trace id. An incoming
79
+ `traceparent` (or `sentry-trace`) is continued. No spans or transactions are sent; `baggage`
80
+ only with `baggage: true`. See https://belvador.dev/docs/sdk/tracing
81
+
82
+ ## Check the connection
83
+
84
+ "No errors" is not proof that errors arrive. Call `verifyIntegration()` from `@belvador/cloudflare` inside a request handled by `withBelvador`:
85
+ it sends one marked test error (never an issue), reads it back and resolves to
86
+ `{ outcome: "verified" | "problem" | "unconfirmed", checks, docsUrl, … }`. It never throws.
87
+ Requests the visitor cancelled (`AbortError`) are not reported unless you set `captureAborted: true`.
88
+ See https://belvador.dev/docs/sdk/verify
89
+
47
90
  ## Status
48
91
 
49
92
  `0.x` — used by Belvador's own apps first. The API may still change before `1.0`.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { CloudflareOptions as EngineCloudflareOptions } from "@sentry/cloudflare";
2
- import { type BelvadorOptions } from "@belvador/core";
3
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, lastEventId, setContext, setTag, setTags, setUser, withScope, type BelvadorBreadcrumb, type BelvadorEvent, type BelvadorEventHint, type Scope, type SeverityLevel, } from "@belvador/core";
2
+ import { type BelvadorOptions, type VerificationResult, type VerifyOptions } from "@belvador/core";
3
+ export { SDK_VERSION, addBreadcrumb, captureCheckIn, captureException, captureMessage, close, flush, heartbeat, withMonitor, getDiagnostics, lastEventId, setContext, setTag, setTags, setUser, withScope, type BelvadorBreadcrumb, type BelvadorEvent, type BelvadorEventHint, type CheckInInput, type Diagnostic, type DiagnosticCode, type DiagnosticsSnapshot, type MonitorConfigInput, type MonitorSchedule, type RunHandle, type Scope, type SeverityLevel, type TracePropagationOptions, type VerificationResult, type VerifyOptions, type WithMonitorOptions, } from "@belvador/core";
4
4
  export type WorkerOptions = Omit<BelvadorOptions, "dsn"> & {
5
5
  /** Defaults to the BELVADOR_DSN binding. */
6
6
  dsn?: string;
@@ -27,3 +27,9 @@ export declare function wrapHandler<Env, H>(optionsCallback: (env: Env) => Worke
27
27
  * untouched, sending finished in waitUntil after the response.
28
28
  */
29
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 CHANGED
@@ -3,8 +3,8 @@
3
3
  // privacy and sending rules. Needs the `nodejs_compat` (or `nodejs_als`)
4
4
  // compatibility flag so every request gets its own scope.
5
5
  import { consoleIntegration, dedupeIntegration, eventFiltersIntegration, fetchIntegration, linkedErrorsIntegration, requestDataIntegration, withSentry, } from "@sentry/cloudflare";
6
- import { buildEngineOptions } from "@belvador/core";
7
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, lastEventId, setContext, setTag, setTags, setUser, withScope, } from "@belvador/core";
6
+ import { TRACE_OPTION, buildEngineOptions, currentHooks, installTracePropagation, markHooked, noteClientAbort, runVerification, withIncomingTraceparent, } from "@belvador/core";
7
+ export { SDK_VERSION, addBreadcrumb, captureCheckIn, captureException, captureMessage, close, flush, heartbeat, withMonitor, getDiagnostics, lastEventId, setContext, setTag, setTags, setUser, withScope, } from "@belvador/core";
8
8
  function binding(env, name) {
9
9
  if (env === null || typeof env !== "object")
10
10
  return undefined;
@@ -76,8 +76,11 @@ export function workerEngineOptions(options, env, runtime = "cloudflare") {
76
76
  ];
77
77
  if (o.instrument?.console === true)
78
78
  integrations.push(consoleIntegration());
79
+ // Breadcrumbs only: trace headers come from Belvador's own hook, never the engine's.
79
80
  if (o.instrument?.fetch === true)
80
- integrations.push(fetchIntegration({ breadcrumbs: true }));
81
+ integrations.push(fetchIntegration({ breadcrumbs: true, shouldCreateSpanForRequest: () => false }));
82
+ if (base[TRACE_OPTION])
83
+ installTracePropagation();
81
84
  return {
82
85
  ...base,
83
86
  // 0, not undefined: an undefined value would let SENTRY_TRACES_SAMPLE_RATE turn tracing on.
@@ -89,9 +92,58 @@ export function workerEngineOptions(options, env, runtime = "cloudflare") {
89
92
  return OFF;
90
93
  }
91
94
  }
95
+ const HANDLER_METHODS = ["fetch", "scheduled", "queue", "email", "tail"];
96
+ /**
97
+ * Marks each invocation of an object handler as running inside the wrapper (integration
98
+ * health: `verifyIntegration` can tell), and notes a fetch that failed after its client
99
+ * disconnected so the error counts as a cancellation. Class handlers pass through unchanged.
100
+ */
101
+ function marked(handler) {
102
+ if (handler === null || typeof handler !== "object")
103
+ return handler;
104
+ const out = { ...handler };
105
+ for (const name of HANDLER_METHODS) {
106
+ const fn = handler[name];
107
+ if (typeof fn !== "function")
108
+ continue;
109
+ out[name] = function (...args) {
110
+ markHooked("wrapper");
111
+ const signal = name === "fetch" ? signalOf(args[0]) : undefined;
112
+ if (!signal)
113
+ return fn.apply(handler, args);
114
+ const failed = (error) => {
115
+ noteClientAbort(error, signal);
116
+ throw error;
117
+ };
118
+ let result;
119
+ try {
120
+ result = fn.apply(handler, args);
121
+ }
122
+ catch (error) {
123
+ return failed(error);
124
+ }
125
+ return isThenable(result) ? Promise.resolve(result).then(undefined, failed) : result;
126
+ };
127
+ }
128
+ return out;
129
+ }
130
+ function signalOf(request) {
131
+ try {
132
+ const signal = request?.signal;
133
+ return typeof AbortSignal !== "undefined" && signal instanceof AbortSignal ? signal : undefined;
134
+ }
135
+ catch {
136
+ return undefined;
137
+ }
138
+ }
139
+ function isThenable(value) {
140
+ return (value !== null &&
141
+ (typeof value === "object" || typeof value === "function") &&
142
+ typeof value.then === "function");
143
+ }
92
144
  /** Shared with @belvador/tanstack-start so its server events carry its own SDK name. */
93
145
  export function wrapHandler(optionsCallback, handler, runtime) {
94
- return withSentry((env) => {
146
+ const wrapped = withSentry((env) => {
95
147
  let options;
96
148
  try {
97
149
  options = optionsCallback(env);
@@ -100,7 +152,25 @@ export function wrapHandler(optionsCallback, handler, runtime) {
100
152
  return OFF;
101
153
  }
102
154
  return workerEngineOptions(options, env, runtime);
103
- }, handler);
155
+ }, marked(handler));
156
+ return incomingTrace(wrapped);
157
+ }
158
+ /**
159
+ * Spec 06 §5: an incoming W3C `traceparent` (without `sentry-trace`) continues the same
160
+ * trace; the request is otherwise passed through untouched.
161
+ */
162
+ function incomingTrace(handler) {
163
+ if (handler === null || typeof handler !== "object")
164
+ return handler;
165
+ const fetch = handler["fetch"];
166
+ if (typeof fetch !== "function")
167
+ return handler;
168
+ return {
169
+ ...handler,
170
+ fetch(request, ...rest) {
171
+ return fetch.call(handler, withIncomingTraceparent(request), ...rest);
172
+ },
173
+ };
104
174
  }
105
175
  /**
106
176
  * Wraps a Worker's exported handler (fetch, scheduled, queue, email, tail):
@@ -110,3 +180,17 @@ export function wrapHandler(optionsCallback, handler, runtime) {
110
180
  export function withBelvador(optionsCallback, handler) {
111
181
  return wrapHandler(optionsCallback, handler, "cloudflare");
112
182
  }
183
+ /**
184
+ * Proves this Worker reports to Belvador. Call it inside a request handled by
185
+ * withBelvador (for example a temporary `/verify-belvador` path): it checks the wrapper,
186
+ * sends one verification error and reads it back. Never automatic; always resolves.
187
+ */
188
+ export function verifyIntegration(options) {
189
+ return runVerification({
190
+ surface: "server",
191
+ hook: () => {
192
+ const hooks = currentHooks();
193
+ return { ok: hooks.has("wrapper") || hooks.has("middleware") };
194
+ },
195
+ }, options);
196
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@belvador/cloudflare",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Belvador error tracking for Cloudflare Workers: per-request scope, errors only, private by default.",
5
5
  "license": "MIT",
6
6
  "author": "Belvador (https://belvador.dev)",
@@ -32,7 +32,7 @@
32
32
  "node": ">=18"
33
33
  },
34
34
  "dependencies": {
35
- "@belvador/core": "0.1.0",
35
+ "@belvador/core": "0.3.0",
36
36
  "@sentry/cloudflare": "10.76.2"
37
37
  },
38
38
  "publishConfig": {