@sentry/cloudflare 10.28.0-alpha.0 → 10.28.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.
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const core = require('@sentry/core');
4
+ const debugBuild = require('./debug-build.js');
4
5
 
5
6
  /**
6
7
  * The Sentry Cloudflare SDK Client.
@@ -10,6 +11,10 @@ const core = require('@sentry/core');
10
11
  */
11
12
  class CloudflareClient extends core.ServerRuntimeClient {
12
13
 
14
+ __init() {this._pendingSpans = new Set();}
15
+ __init2() {this._spanCompletionPromise = null;}
16
+ __init3() {this._resolveSpanCompletion = null;}
17
+
13
18
  /**
14
19
  * Creates a new Cloudflare SDK instance.
15
20
  * @param options Configuration options for this SDK.
@@ -27,14 +32,41 @@ class CloudflareClient extends core.ServerRuntimeClient {
27
32
  // TODO: Add server name
28
33
  };
29
34
 
30
- super(clientOptions);
31
- this._flushLock = flushLock;
35
+ super(clientOptions);CloudflareClient.prototype.__init.call(this);CloudflareClient.prototype.__init2.call(this);CloudflareClient.prototype.__init3.call(this); this._flushLock = flushLock;
36
+
37
+ // Track span lifecycle to know when to flush
38
+ this.on('spanStart', span => {
39
+ const spanId = span.spanContext().spanId;
40
+ debugBuild.DEBUG_BUILD && core.debug.log('[CloudflareClient] Span started:', spanId);
41
+ this._pendingSpans.add(spanId);
42
+
43
+ if (!this._spanCompletionPromise) {
44
+ this._spanCompletionPromise = new Promise(resolve => {
45
+ this._resolveSpanCompletion = resolve;
46
+ });
47
+ }
48
+ });
49
+
50
+ this.on('spanEnd', span => {
51
+ const spanId = span.spanContext().spanId;
52
+ debugBuild.DEBUG_BUILD && core.debug.log('[CloudflareClient] Span ended:', spanId);
53
+ this._pendingSpans.delete(spanId);
54
+
55
+ // If no more pending spans, resolve the completion promise
56
+ if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {
57
+ debugBuild.DEBUG_BUILD && core.debug.log('[CloudflareClient] All spans completed, resolving promise');
58
+ this._resolveSpanCompletion();
59
+ this._resetSpanCompletionPromise();
60
+ }
61
+ });
32
62
  }
33
63
 
34
64
  /**
35
65
  * Flushes pending operations and ensures all data is processed.
36
66
  * If a timeout is provided, the operation will be completed within the specified time limit.
37
67
  *
68
+ * It will wait for all pending spans to complete before flushing.
69
+ *
38
70
  * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
39
71
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
40
72
  */
@@ -42,8 +74,37 @@ class CloudflareClient extends core.ServerRuntimeClient {
42
74
  if (this._flushLock) {
43
75
  await this._flushLock.finalize();
44
76
  }
77
+
78
+ if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {
79
+ debugBuild.DEBUG_BUILD &&
80
+ core.debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');
81
+
82
+ const timeoutMs = timeout ?? 5000;
83
+ const spanCompletionRace = Promise.race([
84
+ this._spanCompletionPromise,
85
+ new Promise(resolve =>
86
+ setTimeout(() => {
87
+ debugBuild.DEBUG_BUILD &&
88
+ core.debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');
89
+ resolve(undefined);
90
+ }, timeoutMs),
91
+ ),
92
+ ]);
93
+
94
+ await spanCompletionRace;
95
+ }
96
+
45
97
  return super.flush(timeout);
46
98
  }
99
+
100
+ /**
101
+ * Resets the span completion promise and resolve function.
102
+ */
103
+ _resetSpanCompletionPromise() {
104
+ this._pendingSpans.clear();
105
+ this._spanCompletionPromise = null;
106
+ this._resolveSpanCompletion = null;
107
+ }
47
108
  }
48
109
 
49
110
  exports.CloudflareClient = CloudflareClient;
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, ServerRuntimeClient } from '@sentry/core';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n return super.flush(timeout);\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * This feature adds runtime overhead as it wraps methods at the prototype level.\n * Only enable this if you need automatic instrumentation of prototype methods.\n *\n * @default false\n * @example\n * ```ts\n * // Instrument all prototype methods\n * instrumentPrototypeMethods: true\n *\n * // Instrument only specific methods\n * instrumentPrototypeMethods: ['myMethod', 'anotherMethod']\n * ```\n */\n instrumentPrototypeMethods?: boolean | string[];\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContext;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata"],"mappings":";;;;AAKA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyBA,wBAAA,CAAoB;;AAG1D;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAA2B;AACvD,IAAIC,qBAAgB,CAAC,OAAO,EAAE,YAAY,CAAC;AAC3C,IAAI,OAAO,CAAC,SAAA,GAAY,OAAO,CAAC,SAAA,IAAa,EAAE;AAC/C,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,aAAA,EAAc,GAAI,OAAO;;AAEnD,IAAI,MAAM,aAAa,GAA+B;AACtD,MAAM,GAAG,aAAa;AACtB,MAAM,QAAQ,EAAE,YAAY;AAC5B;AACA,MAAM,OAAO,EAAE,EAAE,IAAI,EAAE,cAAc;AACrC;AACA,KAAK;;AAEL,IAAI,KAAK,CAAC,aAAa,CAAC;AACxB,IAAI,IAAI,CAAC,UAAA,GAAa,SAAS;AAC/B,EAAE;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAS,MAAM,KAAK,CAAC,OAAO,EAA6B;AACzD,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,MAAM,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;AACtC,IAAI;AACJ,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AAC/B,EAAE;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n return super.flush(timeout);\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * This feature adds runtime overhead as it wraps methods at the prototype level.\n * Only enable this if you need automatic instrumentation of prototype methods.\n *\n * @default false\n * @example\n * ```ts\n * // Instrument all prototype methods\n * instrumentPrototypeMethods: true\n *\n * // Instrument only specific methods\n * instrumentPrototypeMethods: ['myMethod', 'anotherMethod']\n * ```\n */\n instrumentPrototypeMethods?: boolean | string[];\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContext;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug"],"mappings":";;;;;AAMA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyBA,wBAAA,CAAoB;;AAE1D,kBAAU,aAAa,GAAgB,IAAI,GAAG,GAAC;AAC/C,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAyB,KAAA;AACzD,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAwB,KAAA;;AAExD;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAA2B;AACvD,IAAIC,qBAAgB,CAAC,OAAO,EAAE,YAAY,CA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AAC9B,IAAI;;AAEJ,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AAC/B,EAAE;;AAEF;AACA;AACA;AACA,GAAU,2BAA2B,GAAS;AAC9C,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AAC9B,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,EAAE;AACF;;;;"}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
3
  const core = require('@sentry/core');
4
4
  const scopeUtils = require('./scope-utils.js');
5
5
  const sdk = require('./sdk.js');
6
+ const streaming = require('./utils/streaming.js');
6
7
 
7
8
  /**
8
9
  * Wraps a cloudflare request handler in Sentry instrumentation
@@ -68,26 +69,76 @@ function wrapRequestHandler(
68
69
  // Note: This span will not have a duration unless I/O happens in the handler. This is
69
70
  // because of how the cloudflare workers runtime works.
70
71
  // See: https://developers.cloudflare.com/workers/runtime-apis/performance/
71
- return core.startSpan(
72
- {
73
- name,
74
- attributes,
75
- },
76
- async span => {
72
+
73
+ // Use startSpanManual to control when span ends (needed for streaming responses)
74
+ return core.startSpanManual({ name, attributes }, async span => {
75
+ let res;
76
+
77
+ try {
78
+ res = await handler();
79
+ core.setHttpStatus(span, res.status);
80
+
81
+ // After the handler runs, the span name might have been updated by nested instrumentation
82
+ // (e.g., Remix parameterizing routes). The span should already have the correct name
83
+ // from that instrumentation, so we don't need to do anything here.
84
+ } catch (e) {
85
+ span.end();
86
+ if (captureErrors) {
87
+ core.captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });
88
+ }
89
+ waitUntil?.(core.flush(2000));
90
+ throw e;
91
+ }
92
+
93
+ // Classify response to detect actual streaming
94
+ const classification = streaming.classifyResponseStreaming(res);
95
+
96
+ if (classification.isStreaming && res.body) {
97
+ // Streaming response detected - monitor consumption to keep span alive
77
98
  try {
78
- const res = await handler();
79
- core.setHttpStatus(span, res.status);
80
- return res;
99
+ const [clientStream, monitorStream] = res.body.tee();
100
+
101
+ // Monitor stream consumption and end span when complete
102
+ const streamMonitor = (async () => {
103
+ const reader = monitorStream.getReader();
104
+
105
+ try {
106
+ let done = false;
107
+ while (!done) {
108
+ const result = await reader.read();
109
+ done = result.done;
110
+ }
111
+ } catch {
112
+ // Stream error or cancellation - will end span in finally
113
+ } finally {
114
+ reader.releaseLock();
115
+ span.end();
116
+ waitUntil?.(core.flush(2000));
117
+ }
118
+ })();
119
+
120
+ // Keep worker alive until stream monitoring completes (otherwise span won't end)
121
+ waitUntil?.(streamMonitor);
122
+
123
+ // Return response with client stream
124
+ return new Response(clientStream, {
125
+ status: res.status,
126
+ statusText: res.statusText,
127
+ headers: res.headers,
128
+ });
81
129
  } catch (e) {
82
- if (captureErrors) {
83
- core.captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });
84
- }
85
- throw e;
86
- } finally {
130
+ // tee() failed (e.g stream already locked) - fall back to non-streaming handling
131
+ span.end();
87
132
  waitUntil?.(core.flush(2000));
133
+ return res;
88
134
  }
89
- },
90
- );
135
+ }
136
+
137
+ // Non-streaming response - end span immediately and return original
138
+ span.end();
139
+ waitUntil?.(core.flush(2000));
140
+ return res;
141
+ });
91
142
  },
92
143
  );
93
144
  });
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n flush,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpan,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\n\ninterface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n context: ExecutionContext;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(attributes, httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)));\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n return startSpan(\n {\n name,\n attributes,\n },\n async span => {\n try {\n const res = await handler();\n setHttpStatus(span, res.status);\n return res;\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n },\n );\n },\n );\n });\n}\n"],"names":["withIsolationScope","init","parseStringToURLObject","getHttpSpanDetailsFromUrlObject","httpHeadersToSpanAttributes","winterCGHeadersToDict","SEMANTIC_ATTRIBUTE_SENTRY_OP","addCloudResourceContext","addRequest","addCultureContext","captureException","flush","continueTrace","startSpan","setHttpStatus"],"mappings":";;;;;;AAmCA;AACA;AACA;AACO,SAAS,kBAAkB;AAClC,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAqB;AACrB,EAAE,OAAOA,uBAAkB,CAAC,MAAM,kBAAkB;AACpD,IAAI,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,aAAA,GAAgB,IAAA,EAAK,GAAI,cAAc;;AAErE;AACA;AACA;AACA,IAAI,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEnC,IAAI,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAEzD,IAAI,MAAM,MAAA,GAASC,QAAI,CAAC,EAAE,GAAG,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACrD,IAAI,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC;;AAEpC,IAAI,MAAM,YAAYC,2BAAsB,CAAC,OAAO,CAAC,GAAG,CAAC;AACzD,IAAI,M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,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,sBAAA,EAAuB,EAAG,CAAC;AAC9F,QAAQ;AACR,QAAQ,MAAM,CAAC;AACf,MAAM,UAAU;AAChB,QAAQ,SAAS,GAAGC,UAAK,CAAC,IAAI,CAAC,CAAC;AAChC,MAAM;AACN,IAAI;;AAEJ,IAAI,OAAOC,kBAAa;AACxB,MAAM,EAAE,WAAW,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAA,IAAK,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAA,EAAG;AACzG,MAAM,MAAM;AACZ;AACA;AACA;AACA,QAAQ,OAAOC,cAAS;AACxB,UAAU;AACV,YAAY,IAAI;AAChB,YAAY,UAAU;AACtB,WAAW;AACX,UAAU,MAAM,QAAQ;AACxB,YAAY,IAAI;AAChB,cAAc,MAAM,GAAA,GAAM,MAAM,OAAO,EAAE;AACzC,cAAcC,kBAAa,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC;AAC7C,cAAc,OAAO,GAAG;AACxB,YAAY,CAAA,CAAE,OAAO,CAAC,EAAE;AACxB,cAAc,IAAI,aAAa,EAAE;AACjC,gBAAgBJ,qBAAgB,CAAC,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,sBAAA,EAAuB,EAAG,CAAC;AACpG,cAAc;AACd,cAAc,MAAM,CAAC;AACrB,YAAY,UAAU;AACtB,cAAc,SAAS,GAAGC,UAAK,CAAC,IAAI,CAAC,CAAC;AACtC,YAAY;AACZ,UAAU,CAAC;AACX,SAAS;AACT,MAAM,CAAC;AACP,KAAK;AACL,EAAE,CAAC,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n flush,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\nimport { classifyResponseStreaming } from './utils/streaming';\n\ninterface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n context: ExecutionContext;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(attributes, httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)));\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n waitUntil?.(flush(2000));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n // Streaming response detected - monitor consumption to keep span alive\n try {\n const [clientStream, monitorStream] = res.body.tee();\n\n // Monitor stream consumption and end span when complete\n const streamMonitor = (async () => {\n const reader = monitorStream.getReader();\n\n try {\n let done = false;\n while (!done) {\n const result = await reader.read();\n done = result.done;\n }\n } catch {\n // Stream error or cancellation - will end span in finally\n } finally {\n reader.releaseLock();\n span.end();\n waitUntil?.(flush(2000));\n }\n })();\n\n // Keep worker alive until stream monitoring completes (otherwise span won't end)\n waitUntil?.(streamMonitor);\n\n // Return response with client stream\n return new Response(clientStream, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch (e) {\n // tee() failed (e.g stream already locked) - fall back to non-streaming handling\n span.end();\n waitUntil?.(flush(2000));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n waitUntil?.(flush(2000));\n return res;\n });\n },\n );\n });\n}\n"],"names":["withIsolationScope","init","parseStringToURLObject","getHttpSpanDetailsFromUrlObject","httpHeadersToSpanAttributes","winterCGHeadersToDict","SEMANTIC_ATTRIBUTE_SENTRY_OP","addCloudResourceContext","addRequest","addCultureContext","captureException","flush","continueTrace","startSpanManual","setHttpStatus","classifyResponseStreaming"],"mappings":";;;;;;;AAoCA;AACA;AACA;AACO,SAAS,kBAAkB;AAClC,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAqB;AACrB,EAAE,OAAOA,uBAAkB,CAAC,MAAM,kBAAkB;AACpD,IAAI,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,aAAA,GAAgB,IAAA,EAAK,GAAI,cAAc;;AAErE;AACA;AACA;AACA,IAAI,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEnC,IAAI,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAEzD,IAAI,MAAM,MAAA,GAASC,QAAI,CAAC,EAAE,GAAG,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACrD,IAAI,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC;;AAEpC,IAAI,MAAM,YAAYC,2BAAsB,CAAC,OAAO,CAAC,GAAG,CAAC;AACzD,IAAI,MAAM,CAAC,IAAI,EAAE,UAAU,IAAIC,oCAA+B,CAAC,SAAS,EAAE,QAAQ,EAAE,sBAAsB,EAAE,OAAO,CAAC;;AAEpH,IAAI,MAAM,aAAA,GAAgB,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;AAC/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,KAAK;AAClC,kBAAkB,OAAO,CAAC,IAAI,EAAE;AAChC,oBAAoB,MAAM,SAAS,MAAM,MAAM,CAAC,IAAI,EAAE;AACtD,oBAAoB,IAAA,GAAO,MAAM,CAAC,IAAI;AACtC,kBAAkB;AAClB,gBAAgB,EAAE,MAAM;AACxB;AACA,gBAAgB,UAAU;AAC1B,kBAAkB,MAAM,CAAC,WAAW,EAAE;AACtC,kBAAkB,IAAI,CAAC,GAAG,EAAE;AAC5B,kBAAkB,SAAS,GAAGJ,UAAK,CAAC,IAAI,CAAC,CAAC;AAC1C,gBAAgB;AAChB,cAAc,CAAC,GAAG;;AAElB;AACA,cAAc,SAAS,GAAG,aAAa,CAAC;;AAExC;AACA,cAAc,OAAO,IAAI,QAAQ,CAAC,YAAY,EAAE;AAChD,gBAAgB,MAAM,EAAE,GAAG,CAAC,MAAM;AAClC,gBAAgB,UAAU,EAAE,GAAG,CAAC,UAAU;AAC1C,gBAAgB,OAAO,EAAE,GAAG,CAAC,OAAO;AACpC,eAAe,CAAC;AAChB,YAAY,CAAA,CAAE,OAAO,CAAC,EAAE;AACxB;AACA,cAAc,IAAI,CAAC,GAAG,EAAE;AACxB,cAAc,SAAS,GAAGA,UAAK,CAAC,IAAI,CAAC,CAAC;AACtC,cAAc,OAAO,GAAG;AACxB,YAAY;AACZ,UAAU;;AAEV;AACA,UAAU,IAAI,CAAC,GAAG,EAAE;AACpB,UAAU,SAAS,GAAGA,UAAK,CAAC,IAAI,CAAC,CAAC;AAClC,UAAU,OAAO,GAAG;AACpB,QAAQ,CAAC,CAAC;AACV,MAAM,CAAC;AACP,KAAK;AACL,EAAE,CAAC,CAAC;AACJ;;;;"}
@@ -78,7 +78,7 @@ function makeCloudflareTransport(options) {
78
78
  };
79
79
 
80
80
  return core.suppressTracing(() => {
81
- return fetch(options.url, requestOptions).then(response => {
81
+ return (options.fetch ?? fetch)(options.url, requestOptions).then(response => {
82
82
  return {
83
83
  statusCode: response.status,
84
84
  headers: {
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sources":["../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n oldTaskProducers.map(taskProducer =>\n taskProducer().then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n };\n\n return suppressTracing(() => {\n return fetch(options.url, requestOptions).then(response => {\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));\n}\n"],"names":["SENTRY_BUFFER_FULL_ERROR","suppressTracing","createTransport"],"mappings":";;;;AAQA,MAAM,6BAAA,GAAgC,EAAE;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,qBAAA,CAAsB;AACnC;AACA;;AAOA,GAAS,WAAW,CAAC,WAAA,GAAc,6BAA6B,EAAE;AAClE,IAAI,IAAI,CAAC,CAAA,GAAI,EAAE;AACf,IAAI,IAAI,CAAC,cAAA,GAAiB,EAAE;AAC5B,IAAI,IAAI,CAAC,WAAA,GAAc,WAAW;AAClC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,GAAG,CAAC,YAAY,EAA8F;AACvH,IAAI,IAAI,IAAI,CAAC,cAAc,CAAC,MAAA,IAAU,IAAI,CAAC,WAAW,EAAE;AACxD,MAAM,OAAO,OAAO,CAAC,MAAM,CAACA,6BAAwB,CAAC;AACrD,IAAI;;AAEJ,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;AAC1C,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;AAC9B,EAAE;;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Q,CAAC,MAAM;AACrC,UAAU,OAAO,EAAE;AACnB,YAAY,sBAAsB,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;AAChF,YAAY,aAAa,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAC9D,WAAW;AACX,SAAS;AACT,MAAM,CAAC,CAAC;AACR,IAAI,CAAC,CAAC;AACN,EAAE;;AAEF,EAAE,OAAOC,oBAAe,CAAC,OAAO,EAAE,WAAW,EAAE,IAAI,qBAAqB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC7F;;;;;"}
1
+ {"version":3,"file":"transport.js","sources":["../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n oldTaskProducers.map(taskProducer =>\n taskProducer().then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(response => {\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));\n}\n"],"names":["SENTRY_BUFFER_FULL_ERROR","suppressTracing","createTransport"],"mappings":";;;;AAUA,MAAM,6BAAA,GAAgC,EAAE;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,qBAAA,CAAsB;AACnC;AACA;;AAOA,GAAS,WAAW,CAAC,WAAA,GAAc,6BAA6B,EAAE;AAClE,IAAI,IAAI,C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O,SAAS,uBAAuB,CAAC,OAAO,EAAyC;AACxF,EAAE,SAAS,WAAW,CAAC,OAAO,EAA+D;AAC7F,IAAI,MAAM,cAAc,GAAgB;AACxC,MAAM,IAAI,EAAE,OAAO,CAAC,IAAI;AACxB,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,OAAO,EAAE,OAAO,CAAC,OAAO;AAC9B,MAAM,GAAG,OAAO,CAAC,YAAY;AAC7B,KAAK;;AAEL,IAAI,OAAOC,oBAAe,CAAC,MAAM;AACjC,MAAM,OAAO,CAAC,OAAO,CAAC,KAAA,IAAS,KAAK,EAAE,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,IAAI,CAAC,YAAY;AACpF,QAAQ,OAAO;AACf,UAAU,UAAU,EAAE,QAAQ,CAAC,MAAM;AACrC,UAAU,OAAO,EAAE;AACnB,YAAY,sBAAsB,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;AAChF,YAAY,aAAa,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAC9D,WAAW;AACX,SAAS;AACT,MAAM,CAAC,CAAC;AACR,IAAI,CAAC,CAAC;AACN,EAAE;;AAEF,EAAE,OAAOC,oBAAe,CAAC,OAAO,EAAE,WAAW,EAAE,IAAI,qBAAqB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC7F;;;;;"}
@@ -0,0 +1,42 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ /**
4
+ * Classifies a Response as streaming or non-streaming.
5
+ *
6
+ * Heuristics:
7
+ * - No body → not streaming
8
+ * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)
9
+ * - text/plain without Content-Length → streaming (some AI APIs)
10
+ * - Otherwise → not streaming (conservative default, including HTML/SSR)
11
+ *
12
+ * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)
13
+ * or SSR streams that may not have data ready immediately.
14
+ */
15
+ function classifyResponseStreaming(res) {
16
+ if (!res.body) {
17
+ return { isStreaming: false };
18
+ }
19
+
20
+ const contentType = res.headers.get('content-type') ?? '';
21
+ const contentLength = res.headers.get('content-length');
22
+
23
+ // Streaming: Known streaming content types
24
+ // - text/event-stream: Server-Sent Events (Vercel AI SDK, real-time APIs)
25
+ // - application/x-ndjson, application/ndjson: Newline-delimited JSON
26
+ // - application/stream+json: JSON streaming
27
+ // - text/plain (without Content-Length): Some AI APIs use this for streaming text
28
+ if (
29
+ /^text\/event-stream\b/i.test(contentType) ||
30
+ /^application\/(x-)?ndjson\b/i.test(contentType) ||
31
+ /^application\/stream\+json\b/i.test(contentType) ||
32
+ (/^text\/plain\b/i.test(contentType) && !contentLength)
33
+ ) {
34
+ return { isStreaming: true };
35
+ }
36
+
37
+ // Default: treat as non-streaming
38
+ return { isStreaming: false };
39
+ }
40
+
41
+ exports.classifyResponseStreaming = classifyResponseStreaming;
42
+ //# sourceMappingURL=streaming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.js","sources":["../../../src/utils/streaming.ts"],"sourcesContent":["export type StreamingGuess = {\n isStreaming: boolean;\n};\n\n/**\n * Classifies a Response as streaming or non-streaming.\n *\n * Heuristics:\n * - No body → not streaming\n * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)\n * - text/plain without Content-Length → streaming (some AI APIs)\n * - Otherwise → not streaming (conservative default, including HTML/SSR)\n *\n * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)\n * or SSR streams that may not have data ready immediately.\n */\nexport function classifyResponseStreaming(res: Response): StreamingGuess {\n if (!res.body) {\n return { isStreaming: false };\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n const contentLength = res.headers.get('content-length');\n\n // Streaming: Known streaming content types\n // - text/event-stream: Server-Sent Events (Vercel AI SDK, real-time APIs)\n // - application/x-ndjson, application/ndjson: Newline-delimited JSON\n // - application/stream+json: JSON streaming\n // - text/plain (without Content-Length): Some AI APIs use this for streaming text\n if (\n /^text\\/event-stream\\b/i.test(contentType) ||\n /^application\\/(x-)?ndjson\\b/i.test(contentType) ||\n /^application\\/stream\\+json\\b/i.test(contentType) ||\n (/^text\\/plain\\b/i.test(contentType) && !contentLength)\n ) {\n return { isStreaming: true };\n }\n\n // Default: treat as non-streaming\n return { isStreaming: false };\n}\n"],"names":[],"mappings":";;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,yBAAyB,CAAC,GAAG,EAA4B;AACzE,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE;AACjB,IAAI,OAAO,EAAE,WAAW,EAAE,OAAO;AACjC,EAAE;;AAEF,EAAE,MAAM,WAAA,GAAc,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAA,IAAK,EAAE;AAC3D,EAAE,MAAM,aAAA,GAAgB,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;;AAEzD;AACA;AACA;AACA;AACA;AACA,EAAE;AACF,IAAI,wBAAwB,CAAC,IAAI,CAAC,WAAW,CAAA;AAC7C,IAAI,8BAA8B,CAAC,IAAI,CAAC,WAAW,CAAA;AACnD,IAAI,+BAA+B,CAAC,IAAI,CAAC,WAAW,CAAA;AACpD,KAAK,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAA,IAAK,CAAC,aAAa;AAC1D,IAAI;AACJ,IAAI,OAAO,EAAE,WAAW,EAAE,MAAM;AAChC,EAAE;;AAEF;AACA,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO;AAC/B;;;;"}
@@ -1,4 +1,5 @@
1
- import { ServerRuntimeClient, applySdkMetadata } from '@sentry/core';
1
+ import { ServerRuntimeClient, applySdkMetadata, debug } from '@sentry/core';
2
+ import { DEBUG_BUILD } from './debug-build.js';
2
3
 
3
4
  /**
4
5
  * The Sentry Cloudflare SDK Client.
@@ -8,6 +9,10 @@ import { ServerRuntimeClient, applySdkMetadata } from '@sentry/core';
8
9
  */
9
10
  class CloudflareClient extends ServerRuntimeClient {
10
11
 
12
+ __init() {this._pendingSpans = new Set();}
13
+ __init2() {this._spanCompletionPromise = null;}
14
+ __init3() {this._resolveSpanCompletion = null;}
15
+
11
16
  /**
12
17
  * Creates a new Cloudflare SDK instance.
13
18
  * @param options Configuration options for this SDK.
@@ -25,14 +30,41 @@ class CloudflareClient extends ServerRuntimeClient {
25
30
  // TODO: Add server name
26
31
  };
27
32
 
28
- super(clientOptions);
29
- this._flushLock = flushLock;
33
+ super(clientOptions);CloudflareClient.prototype.__init.call(this);CloudflareClient.prototype.__init2.call(this);CloudflareClient.prototype.__init3.call(this); this._flushLock = flushLock;
34
+
35
+ // Track span lifecycle to know when to flush
36
+ this.on('spanStart', span => {
37
+ const spanId = span.spanContext().spanId;
38
+ DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);
39
+ this._pendingSpans.add(spanId);
40
+
41
+ if (!this._spanCompletionPromise) {
42
+ this._spanCompletionPromise = new Promise(resolve => {
43
+ this._resolveSpanCompletion = resolve;
44
+ });
45
+ }
46
+ });
47
+
48
+ this.on('spanEnd', span => {
49
+ const spanId = span.spanContext().spanId;
50
+ DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);
51
+ this._pendingSpans.delete(spanId);
52
+
53
+ // If no more pending spans, resolve the completion promise
54
+ if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {
55
+ DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, resolving promise');
56
+ this._resolveSpanCompletion();
57
+ this._resetSpanCompletionPromise();
58
+ }
59
+ });
30
60
  }
31
61
 
32
62
  /**
33
63
  * Flushes pending operations and ensures all data is processed.
34
64
  * If a timeout is provided, the operation will be completed within the specified time limit.
35
65
  *
66
+ * It will wait for all pending spans to complete before flushing.
67
+ *
36
68
  * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
37
69
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
38
70
  */
@@ -40,8 +72,37 @@ class CloudflareClient extends ServerRuntimeClient {
40
72
  if (this._flushLock) {
41
73
  await this._flushLock.finalize();
42
74
  }
75
+
76
+ if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {
77
+ DEBUG_BUILD &&
78
+ debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');
79
+
80
+ const timeoutMs = timeout ?? 5000;
81
+ const spanCompletionRace = Promise.race([
82
+ this._spanCompletionPromise,
83
+ new Promise(resolve =>
84
+ setTimeout(() => {
85
+ DEBUG_BUILD &&
86
+ debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');
87
+ resolve(undefined);
88
+ }, timeoutMs),
89
+ ),
90
+ ]);
91
+
92
+ await spanCompletionRace;
93
+ }
94
+
43
95
  return super.flush(timeout);
44
96
  }
97
+
98
+ /**
99
+ * Resets the span completion promise and resolve function.
100
+ */
101
+ _resetSpanCompletionPromise() {
102
+ this._pendingSpans.clear();
103
+ this._spanCompletionPromise = null;
104
+ this._resolveSpanCompletion = null;
105
+ }
45
106
  }
46
107
 
47
108
  export { CloudflareClient };
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, ServerRuntimeClient } from '@sentry/core';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n return super.flush(timeout);\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * This feature adds runtime overhead as it wraps methods at the prototype level.\n * Only enable this if you need automatic instrumentation of prototype methods.\n *\n * @default false\n * @example\n * ```ts\n * // Instrument all prototype methods\n * instrumentPrototypeMethods: true\n *\n * // Instrument only specific methods\n * instrumentPrototypeMethods: ['myMethod', 'anotherMethod']\n * ```\n */\n instrumentPrototypeMethods?: boolean | string[];\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContext;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":[],"mappings":";;AAKA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyB,mBAAA,CAAoB;;AAG1D;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAA2B;AACvD,IAAI,gBAAgB,CAAC,OAAO,EAAE,YAAY,CAAC;AAC3C,IAAI,OAAO,CAAC,SAAA,GAAY,OAAO,CAAC,SAAA,IAAa,EAAE;AAC/C,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,aAAA,EAAc,GAAI,OAAO;;AAEnD,IAAI,MAAM,aAAa,GAA+B;AACtD,MAAM,GAAG,aAAa;AACtB,MAAM,QAAQ,EAAE,YAAY;AAC5B;AACA,MAAM,OAAO,EAAE,EAAE,IAAI,EAAE,cAAc;AACrC;AACA,KAAK;;AAEL,IAAI,KAAK,CAAC,aAAa,CAAC;AACxB,IAAI,IAAI,CAAC,UAAA,GAAa,SAAS;AAC/B,EAAE;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAS,MAAM,KAAK,CAAC,OAAO,EAA6B;AACzD,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,MAAM,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;AACtC,IAAI;AACJ,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AAC/B,EAAE;AACF;;;;"}
1
+ {"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, ServerRuntimeClientOptions } from '@sentry/core';\nimport { applySdkMetadata, debug, ServerRuntimeClient } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n\n // Track span lifecycle to know when to flush\n this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, resolving promise');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n * If a timeout is provided, the operation will be completed within the specified time limit.\n *\n * It will wait for all pending spans to complete before flushing.\n *\n * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n if (this._flushLock) {\n await this._flushLock.finalize();\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n return super.flush(timeout);\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility\n * via a custom trace provider.\n * This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.\n * HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.\n * This should be good enough for many, but not all integrations.\n *\n * If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.\n *\n * @default false\n */\n skipOpenTelemetrySetup?: boolean;\n\n /**\n * Enable instrumentation of prototype methods for DurableObjects.\n *\n * When `true`, the SDK will wrap all methods on the DurableObject prototype chain\n * to automatically create spans and capture errors for RPC method calls.\n *\n * When an array of strings is provided, only the specified method names will be instrumented.\n *\n * This feature adds runtime overhead as it wraps methods at the prototype level.\n * Only enable this if you need automatic instrumentation of prototype methods.\n *\n * @default false\n * @example\n * ```ts\n * // Instrument all prototype methods\n * instrumentPrototypeMethods: true\n *\n * // Instrument only specific methods\n * instrumentPrototypeMethods: ['myMethod', 'anotherMethod']\n * ```\n */\n instrumentPrototypeMethods?: boolean | string[];\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContext;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":[],"mappings":";;;AAMA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,gBAAA,SAAyB,mBAAA,CAAoB;;AAE1D,kBAAU,aAAa,GAAgB,IAAI,GAAG,GAAC;AAC/C,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAyB,KAAA;AACzD,GAAE,OAAA,GAAA,CAAA,IAAA,CAAQ,sBAAsB,GAAwB,KAAA;;AAExD;AACA;AACA;AACA;AACA,GAAS,WAAW,CAAC,OAAO,EAA2B;AACvD,IAAI,gBAAgB,CAAC,OAAO,EAAE,YAAY,CAAC;AAC3C,IAAI,OAAO,CAAC,SAAA,GAAY,OAAO,CAAC,SAAA,IAAa,EAAE;AAC/C,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,aAAA,EAAc,GAAI,OAAO;;AAEnD,IAAI,MAAM,aAAa,GAA+B;AACtD,MAAM,GAAG,aAAa;AACtB,MAAM,QAAQ,EAAE,YAAY;AAC5B;AACA,MAAM,OAAO,EAAE,EAAE,IAAI,EAAE,cAAc;AACrC;AACA,KAAK;;AAEL,IAAI,KAAK,CAAC,aAAa,CAAA,CAAA,gBAAA,CAAA,SAAA,CAAA,MAAA,CAAA,IAAA,CAAA,IAAA,CAAA,CAAA,gBAAA,CAAA,SAAA,CAAA,OAAA,CAAA,IAAA,CAA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;AACzD,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,MAAM,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;AACtC,IAAI;;AAEJ,IAAI,IAAI,IAAI,CAAC,aAAa,CAAC,IAAA,GAAO,CAAA,IAAK,IAAI,CAAC,sBAAsB,EAAE;AACpE,MAAM,WAAA;AACN,QAAQ,KAAK,CAAC,GAAG,CAAC,gCAAgC,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,8BAA8B,CAAC;;AAE5G,MAAM,MAAM,SAAA,GAAY,OAAA,IAAW,IAAI;AACvC,MAAM,MAAM,kBAAA,GAAqB,OAAO,CAAC,IAAI,CAAC;AAC9C,QAAQ,IAAI,CAAC,sBAAsB;AACnC,QAAQ,IAAI,OAAO,CAAC,OAAA;AACpB,UAAU,UAAU,CAAC,MAAM;AAC3B,YAAY,WAAA;AACZ,cAAc,KAAK,CAAC,GAAG,CAAC,kDAAkD,EAAE,SAAS,EAAE,qBAAqB,CAAC;AAC7G,YAAY,OAAO,CAAC,SAAS,CAAC;AAC9B,UAAU,CAAC,EAAE,SAAS,CAAC;AACvB,SAAS;AACT,OAAO,CAAC;;AAER,MAAM,MAAM,kBAAkB;AAC9B,IAAI;;AAEJ,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AAC/B,EAAE;;AAEF;AACA;AACA;AACA,GAAU,2BAA2B,GAAS;AAC9C,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE;AAC9B,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,IAAI,IAAI,CAAC,sBAAA,GAAyB,IAAI;AACtC,EAAE;AACF;;;;"}
@@ -1 +1 @@
1
- {"type":"module","version":"10.28.0-alpha.0","sideEffects":false}
1
+ {"type":"module","version":"10.28.0","sideEffects":false}
@@ -1,6 +1,7 @@
1
- import { withIsolationScope, parseStringToURLObject, getHttpSpanDetailsFromUrlObject, httpHeadersToSpanAttributes, winterCGHeadersToDict, SEMANTIC_ATTRIBUTE_SENTRY_OP, captureException, flush, continueTrace, startSpan, setHttpStatus } from '@sentry/core';
1
+ import { withIsolationScope, parseStringToURLObject, getHttpSpanDetailsFromUrlObject, httpHeadersToSpanAttributes, winterCGHeadersToDict, SEMANTIC_ATTRIBUTE_SENTRY_OP, captureException, flush, continueTrace, startSpanManual, setHttpStatus } from '@sentry/core';
2
2
  import { addCloudResourceContext, addRequest, addCultureContext } from './scope-utils.js';
3
3
  import { init } from './sdk.js';
4
+ import { classifyResponseStreaming } from './utils/streaming.js';
4
5
 
5
6
  /**
6
7
  * Wraps a cloudflare request handler in Sentry instrumentation
@@ -66,26 +67,76 @@ function wrapRequestHandler(
66
67
  // Note: This span will not have a duration unless I/O happens in the handler. This is
67
68
  // because of how the cloudflare workers runtime works.
68
69
  // See: https://developers.cloudflare.com/workers/runtime-apis/performance/
69
- return startSpan(
70
- {
71
- name,
72
- attributes,
73
- },
74
- async span => {
70
+
71
+ // Use startSpanManual to control when span ends (needed for streaming responses)
72
+ return startSpanManual({ name, attributes }, async span => {
73
+ let res;
74
+
75
+ try {
76
+ res = await handler();
77
+ setHttpStatus(span, res.status);
78
+
79
+ // After the handler runs, the span name might have been updated by nested instrumentation
80
+ // (e.g., Remix parameterizing routes). The span should already have the correct name
81
+ // from that instrumentation, so we don't need to do anything here.
82
+ } catch (e) {
83
+ span.end();
84
+ if (captureErrors) {
85
+ captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });
86
+ }
87
+ waitUntil?.(flush(2000));
88
+ throw e;
89
+ }
90
+
91
+ // Classify response to detect actual streaming
92
+ const classification = classifyResponseStreaming(res);
93
+
94
+ if (classification.isStreaming && res.body) {
95
+ // Streaming response detected - monitor consumption to keep span alive
75
96
  try {
76
- const res = await handler();
77
- setHttpStatus(span, res.status);
78
- return res;
97
+ const [clientStream, monitorStream] = res.body.tee();
98
+
99
+ // Monitor stream consumption and end span when complete
100
+ const streamMonitor = (async () => {
101
+ const reader = monitorStream.getReader();
102
+
103
+ try {
104
+ let done = false;
105
+ while (!done) {
106
+ const result = await reader.read();
107
+ done = result.done;
108
+ }
109
+ } catch {
110
+ // Stream error or cancellation - will end span in finally
111
+ } finally {
112
+ reader.releaseLock();
113
+ span.end();
114
+ waitUntil?.(flush(2000));
115
+ }
116
+ })();
117
+
118
+ // Keep worker alive until stream monitoring completes (otherwise span won't end)
119
+ waitUntil?.(streamMonitor);
120
+
121
+ // Return response with client stream
122
+ return new Response(clientStream, {
123
+ status: res.status,
124
+ statusText: res.statusText,
125
+ headers: res.headers,
126
+ });
79
127
  } catch (e) {
80
- if (captureErrors) {
81
- captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });
82
- }
83
- throw e;
84
- } finally {
128
+ // tee() failed (e.g stream already locked) - fall back to non-streaming handling
129
+ span.end();
85
130
  waitUntil?.(flush(2000));
131
+ return res;
86
132
  }
87
- },
88
- );
133
+ }
134
+
135
+ // Non-streaming response - end span immediately and return original
136
+ span.end();
137
+ waitUntil?.(flush(2000));
138
+ return res;
139
+ });
89
140
  },
90
141
  );
91
142
  });
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n flush,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpan,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\n\ninterface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n context: ExecutionContext;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(attributes, httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)));\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n return startSpan(\n {\n name,\n attributes,\n },\n async span => {\n try {\n const res = await handler();\n setHttpStatus(span, res.status);\n return res;\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n },\n );\n },\n );\n });\n}\n"],"names":[],"mappings":";;;;AAmCA;AACA;AACA;AACO,SAAS,kBAAkB;AAClC,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAqB;AACrB,EAAE,OAAO,kBAAkB,CAAC,MAAM,kBAAkB;AACpD,IAAI,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,aAAA,GAAgB,IAAA,EAAK,GAAI,cAAc;;AAErE;AACA;AACA;AACA,IAAI,MAAM,OAAA,GAAU,cAAc,CAAC,OAAA;;AAEnC,IAAI,MAAM,SAAA,GAAY,OAAO,EAAE,SAAS,EAAE,IAAI,GAAG,OAAO,CAAC;;AAEzD,IAAI,MAAM,MAAA,GAAS,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACrD,IAAI,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC;;AAEpC,IAAI,MAAM,YAAY,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC;AACzD,IAAI,MAAM,CAAC,IAAI,EAAE,UAAU,IAAI,+BAA+B,CAAC,SAAS,EAAE,QAAQ,EAAE,sBAAsB,EAAE,OAAO,CAAC;;AAEpH,IAAI,MAAM,aAAA,GAAgB,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;AAC/D,IAAI,IAAI,aAAa,EAAE;AACvB,MAAM,UAAU,CAAC,wBAAwB,CAAA,GAAI,QAAQ,CAAC,aAAa,EAAE,EAAE,CAAC;AAC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AAE,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAA,EAAG;AACzG,MAAM,MAAM;AACZ;AACA;AACA;AACA,QAAQ,OAAO,SAAS;AACxB,UAAU;AACV,YAAY,IAAI;AAChB,YAAY,UAAU;AACtB,WAAW;AACX,UAAU,MAAM,QAAQ;AACxB,YAAY,IAAI;AAChB,cAAc,MAAM,GAAA,GAAM,MAAM,OAAO,EAAE;AACzC,cAAc,aAAa,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC;AAC7C,cAAc,OAAO,GAAG;AACxB,YAAY,CAAA,CAAE,OAAO,CAAC,EAAE;AACxB,cAAc,IAAI,aAAa,EAAE;AACjC,gBAAgB,gBAAgB,CAAC,CAAC,EAAE,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,sBAAA,EAAuB,EAAG,CAAC;AACpG,cAAc;AACd,cAAc,MAAM,CAAC;AACrB,YAAY,UAAU;AACtB,cAAc,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;AACtC,YAAY;AACZ,UAAU,CAAC;AACX,SAAS;AACT,MAAM,CAAC;AACP,KAAK;AACL,EAAE,CAAC,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../src/request.ts"],"sourcesContent":["import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n captureException,\n continueTrace,\n flush,\n getHttpSpanDetailsFromUrlObject,\n httpHeadersToSpanAttributes,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n withIsolationScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { init } from './sdk';\nimport { classifyResponseStreaming } from './utils/streaming';\n\ninterface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown>>;\n context: ExecutionContext;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation\n */\nexport function wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return withIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context = wrapperOptions.context as ExecutionContext | undefined;\n\n const waitUntil = context?.waitUntil?.bind?.(context);\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [name, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, 'server', 'auto.http.cloudflare', request);\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n Object.assign(attributes, httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)));\n\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n throw e;\n } finally {\n waitUntil?.(flush(2000));\n }\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: 'auto.http.cloudflare' } });\n }\n waitUntil?.(flush(2000));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n // Streaming response detected - monitor consumption to keep span alive\n try {\n const [clientStream, monitorStream] = res.body.tee();\n\n // Monitor stream consumption and end span when complete\n const streamMonitor = (async () => {\n const reader = monitorStream.getReader();\n\n try {\n let done = false;\n while (!done) {\n const result = await reader.read();\n done = result.done;\n }\n } catch {\n // Stream error or cancellation - will end span in finally\n } finally {\n reader.releaseLock();\n span.end();\n waitUntil?.(flush(2000));\n }\n })();\n\n // Keep worker alive until stream monitoring completes (otherwise span won't end)\n waitUntil?.(streamMonitor);\n\n // Return response with client stream\n return new Response(clientStream, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch (e) {\n // tee() failed (e.g stream already locked) - fall back to non-streaming handling\n span.end();\n waitUntil?.(flush(2000));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n waitUntil?.(flush(2000));\n return res;\n });\n },\n );\n });\n}\n"],"names":[],"mappings":";;;;;AAoCA;AACA;AACA;AACO,SAAS,kBAAkB;AAClC,EAAE,cAAc;A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AClC,gBAAgB,UAAU,EAAE,GAAG,CAAC,UAAU;AAC1C,gBAAgB,OAAO,EAAE,GAAG,CAAC,OAAO;AACpC,eAAe,CAAC;AAChB,YAAY,CAAA,CAAE,OAAO,CAAC,EAAE;AACxB;AACA,cAAc,IAAI,CAAC,GAAG,EAAE;AACxB,cAAc,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;AACtC,cAAc,OAAO,GAAG;AACxB,YAAY;AACZ,UAAU;;AAEV;AACA,UAAU,IAAI,CAAC,GAAG,EAAE;AACpB,UAAU,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;AAClC,UAAU,OAAO,GAAG;AACpB,QAAQ,CAAC,CAAC;AACV,MAAM,CAAC;AACP,KAAK;AACL,EAAE,CAAC,CAAC;AACJ;;;;"}
@@ -76,7 +76,7 @@ function makeCloudflareTransport(options) {
76
76
  };
77
77
 
78
78
  return suppressTracing(() => {
79
- return fetch(options.url, requestOptions).then(response => {
79
+ return (options.fetch ?? fetch)(options.url, requestOptions).then(response => {
80
80
  return {
81
81
  statusCode: response.status,
82
82
  headers: {
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sources":["../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n oldTaskProducers.map(taskProducer =>\n taskProducer().then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n };\n\n return suppressTracing(() => {\n return fetch(options.url, requestOptions).then(response => {\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));\n}\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;AACT,OAAO,CAAC,IAAI,CAAC,MAAM;AACnB;AACA,QAAQ,YAAY,CAAC,KAAK,CAAC;AAC3B,QAAQ,OAAO,CAAC,IAAI,CAAC;AACrB,MAAM,CAAC,CAAC;AACR,IAAI,CAAC,CAAC;AACN,EAAE;AACF;;AAEA;AACA;AACA;AACO,SAAS,uBAAuB,CAAC,OAAO,EAAyC;AACxF,EAAE,SAAS,WAAW,CAAC,OAAO,EAA+D;AAC7F,IAAI,MAAM,cAAc,GAAgB;AACxC,MAAM,IAAI,EAAE,OAAO,CAAC,IAAI;AACxB,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,OAAO,EAAE,OAAO,CAAC,OAAO;AAC9B,MAAM,GAAG,OAAO,CAAC,YAAY;AAC7B,KAAK;;AAEL,IAAI,OAAO,eAAe,CAAC,MAAM;AACjC,MAAM,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,IAAI,CAAC,YAAY;AACjE,QAAQ,OAAO;AACf,UAAU,UAAU,EAAE,QAAQ,CAAC,MAAM;AACrC,UAAU,OAAO,EAAE;AACnB,YAAY,sBAAsB,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;AAChF,YAAY,aAAa,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAC9D,WAAW;AACX,SAAS;AACT,MAAM,CAAC,CAAC;AACR,IAAI,CAAC,CAAC;AACN,EAAE;;AAEF,EAAE,OAAO,eAAe,CAAC,OAAO,EAAE,WAAW,EAAE,IAAI,qBAAqB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC7F;;;;"}
1
+ {"version":3,"file":"transport.js","sources":["../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n oldTaskProducers.map(taskProducer =>\n taskProducer().then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(response => {\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));\n}\n"],"names":[],"mappings":";;AAUA,MAAM,6BAAA,GAAgC,EAAE;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,qBAAA,CAAsB;AACnC;AACA;;AAOA,GAAS,WAAW,CAAC,WAAA,GAAc,6BAA6B,EAAE;AAClE,IAAI,IAAI,CAAC,CAAA,GAAI,EAAE;AACf,IAAI,IAAI,CAAC,cAAA,GAAiB,EAAE;AAC5B,IAAI,IAAI,CAAC,WAAA,GAAc,WAAW;AAClC,EAAE;;AAEF;AACA;AACA;AACA,GAAS,GAAG,CAAC,YAAY,EAA8F;AACvH,IAAI,IAAI,IAAI,CAAC,cAAc,CAAC,MAAA,IAAU,IAAI,CAAC,WAAW,EAAE;AACxD,MAAM,OAAO,OAAO,CAAC,MAAM,CAAC,wBAAwB,CAAC;AACrD,IAAI;;AAEJ,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;AAC1C,IAAI,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;AAC9B,EAAE;;AAEF;AACA;AACA;AACA,GAAS,KAAK,CAAC,OAAO,EAAiC;AACvD,IAAI,MAAM,mBAAmB,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC;AACrD,IAAI,IAAI,CAAC,cAAA,GAAiB,EAAE;;AAE5B,IAAI,OAAO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CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AAC9D,WAAW;AACX,SAAS;AACT,MAAM,CAAC,CAAC;AACR,IAAI,CAAC,CAAC;AACN,EAAE;;AAEF,EAAE,OAAO,eAAe,CAAC,OAAO,EAAE,WAAW,EAAE,IAAI,qBAAqB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC7F;;;;"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Classifies a Response as streaming or non-streaming.
3
+ *
4
+ * Heuristics:
5
+ * - No body → not streaming
6
+ * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)
7
+ * - text/plain without Content-Length → streaming (some AI APIs)
8
+ * - Otherwise → not streaming (conservative default, including HTML/SSR)
9
+ *
10
+ * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)
11
+ * or SSR streams that may not have data ready immediately.
12
+ */
13
+ function classifyResponseStreaming(res) {
14
+ if (!res.body) {
15
+ return { isStreaming: false };
16
+ }
17
+
18
+ const contentType = res.headers.get('content-type') ?? '';
19
+ const contentLength = res.headers.get('content-length');
20
+
21
+ // Streaming: Known streaming content types
22
+ // - text/event-stream: Server-Sent Events (Vercel AI SDK, real-time APIs)
23
+ // - application/x-ndjson, application/ndjson: Newline-delimited JSON
24
+ // - application/stream+json: JSON streaming
25
+ // - text/plain (without Content-Length): Some AI APIs use this for streaming text
26
+ if (
27
+ /^text\/event-stream\b/i.test(contentType) ||
28
+ /^application\/(x-)?ndjson\b/i.test(contentType) ||
29
+ /^application\/stream\+json\b/i.test(contentType) ||
30
+ (/^text\/plain\b/i.test(contentType) && !contentLength)
31
+ ) {
32
+ return { isStreaming: true };
33
+ }
34
+
35
+ // Default: treat as non-streaming
36
+ return { isStreaming: false };
37
+ }
38
+
39
+ export { classifyResponseStreaming };
40
+ //# sourceMappingURL=streaming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.js","sources":["../../../src/utils/streaming.ts"],"sourcesContent":["export type StreamingGuess = {\n isStreaming: boolean;\n};\n\n/**\n * Classifies a Response as streaming or non-streaming.\n *\n * Heuristics:\n * - No body → not streaming\n * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)\n * - text/plain without Content-Length → streaming (some AI APIs)\n * - Otherwise → not streaming (conservative default, including HTML/SSR)\n *\n * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)\n * or SSR streams that may not have data ready immediately.\n */\nexport function classifyResponseStreaming(res: Response): StreamingGuess {\n if (!res.body) {\n return { isStreaming: false };\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n const contentLength = res.headers.get('content-length');\n\n // Streaming: Known streaming content types\n // - text/event-stream: Server-Sent Events (Vercel AI SDK, real-time APIs)\n // - application/x-ndjson, application/ndjson: Newline-delimited JSON\n // - application/stream+json: JSON streaming\n // - text/plain (without Content-Length): Some AI APIs use this for streaming text\n if (\n /^text\\/event-stream\\b/i.test(contentType) ||\n /^application\\/(x-)?ndjson\\b/i.test(contentType) ||\n /^application\\/stream\\+json\\b/i.test(contentType) ||\n (/^text\\/plain\\b/i.test(contentType) && !contentLength)\n ) {\n return { isStreaming: true };\n }\n\n // Default: treat as non-streaming\n return { isStreaming: false };\n}\n"],"names":[],"mappings":"AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,yBAAyB,CAAC,GAAG,EAA4B;AACzE,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE;AACjB,IAAI,OAAO,EAAE,WAAW,EAAE,OAAO;AACjC,EAAE;;AAEF,EAAE,MAAM,WAAA,GAAc,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAA,IAAK,EAAE;AAC3D,EAAE,MAAM,aAAA,GAAgB,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;;AAEzD;AACA;AACA;AACA;AACA;AACA,EAAE;AACF,IAAI,wBAAwB,CAAC,IAAI,CAAC,WAAW,CAAA;AAC7C,IAAI,8BAA8B,CAAC,IAAI,CAAC,WAAW,CAAA;AACnD,IAAI,+BAA+B,CAAC,IAAI,CAAC,WAAW,CAAA;AACpD,KAAK,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAA,IAAK,CAAC,aAAa;AAC1D,IAAI;AACJ,IAAI,OAAO,EAAE,WAAW,EAAE,MAAM;AAChC,EAAE;;AAEF;AACA,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO;AAC/B;;;;"}
@@ -10,6 +10,9 @@ import type { CloudflareTransportOptions } from './transport';
10
10
  */
11
11
  export declare class CloudflareClient extends ServerRuntimeClient {
12
12
  private readonly _flushLock;
13
+ private _pendingSpans;
14
+ private _spanCompletionPromise;
15
+ private _resolveSpanCompletion;
13
16
  /**
14
17
  * Creates a new Cloudflare SDK instance.
15
18
  * @param options Configuration options for this SDK.
@@ -19,10 +22,16 @@ export declare class CloudflareClient extends ServerRuntimeClient {
19
22
  * Flushes pending operations and ensures all data is processed.
20
23
  * If a timeout is provided, the operation will be completed within the specified time limit.
21
24
  *
25
+ * It will wait for all pending spans to complete before flushing.
26
+ *
22
27
  * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
23
28
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
24
29
  */
25
30
  flush(timeout?: number): Promise<boolean>;
31
+ /**
32
+ * Resets the span completion promise and resolve function.
33
+ */
34
+ private _resetSpanCompletionPromise;
26
35
  }
27
36
  interface BaseCloudflareOptions {
28
37
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAA8B,MAAM,cAAc,CAAC;AACvF,OAAO,EAAoB,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAA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AAc,EAAE,4BAA4B,EAC5C,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,GAC5D,OAAO,CAAC,QAAQ,CAAC,CAiFnB"}
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAc/F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAKlD,UAAU,4BAA4B;IACpC,OAAO,EAAE,iBAAiB,CAAC;IAC3B,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,2BAA2B,CAAC,OAAO,CAAC,CAAC,CAAC;IAChE,OAAO,EAAE,gBAAgB,CAAC;IAC1B;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,cAAc,EAAE,4BAA4B,EAC5C,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,GAC5D,OAAO,CAAC,QAAQ,CAAC,CAmInB"}
@@ -1,5 +1,7 @@
1
1
  import type { BaseTransportOptions, Transport, TransportMakeRequestResponse } from '@sentry/core';
2
2
  export interface CloudflareTransportOptions extends BaseTransportOptions {
3
+ /** Custom fetch function to use. This allows usage of things like Workers VPC */
4
+ fetch?: typeof fetch;
3
5
  /** Fetch API init parameters. */
4
6
  fetchOptions?: RequestInit;
5
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,4BAA4B,EAAoB,MAAM,cAAc,CAAC;AAGpH,MAAM,WAAW,0BAA2B,SAAQ,oBAAoB;IACt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W,CAAC,OAAO,CAAC;CA0BrD;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,0BAA0B,GAAG,SAAS,CAuBtF"}
@@ -0,0 +1,17 @@
1
+ export type StreamingGuess = {
2
+ isStreaming: boolean;
3
+ };
4
+ /**
5
+ * Classifies a Response as streaming or non-streaming.
6
+ *
7
+ * Heuristics:
8
+ * - No body → not streaming
9
+ * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)
10
+ * - text/plain without Content-Length → streaming (some AI APIs)
11
+ * - Otherwise → not streaming (conservative default, including HTML/SSR)
12
+ *
13
+ * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)
14
+ * or SSR streams that may not have data ready immediately.
15
+ */
16
+ export declare function classifyResponseStreaming(res: Response): StreamingGuess;
17
+ //# sourceMappingURL=streaming.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../src/utils/streaming.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GAAG;IAC3B,WAAW,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,QAAQ,GAAG,cAAc,CAwBvE"}
@@ -10,6 +10,9 @@ import { CloudflareTransportOptions } from './transport';
10
10
  */
11
11
  export declare class CloudflareClient extends ServerRuntimeClient {
12
12
  private readonly _flushLock;
13
+ private _pendingSpans;
14
+ private _spanCompletionPromise;
15
+ private _resolveSpanCompletion;
13
16
  /**
14
17
  * Creates a new Cloudflare SDK instance.
15
18
  * @param options Configuration options for this SDK.
@@ -19,10 +22,16 @@ export declare class CloudflareClient extends ServerRuntimeClient {
19
22
  * Flushes pending operations and ensures all data is processed.
20
23
  * If a timeout is provided, the operation will be completed within the specified time limit.
21
24
  *
25
+ * It will wait for all pending spans to complete before flushing.
26
+ *
22
27
  * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
23
28
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
24
29
  */
25
30
  flush(timeout?: number): Promise<boolean>;
31
+ /**
32
+ * Resets the span completion promise and resolve function.
33
+ */
34
+ private _resetSpanCompletionPromise;
26
35
  }
27
36
  interface BaseCloudflareOptions {
28
37
  /**
@@ -1,5 +1,7 @@
1
1
  import { BaseTransportOptions, Transport, TransportMakeRequestResponse } from '@sentry/core';
2
2
  export interface CloudflareTransportOptions extends BaseTransportOptions {
3
+ /** Custom fetch function to use. This allows usage of things like Workers VPC */
4
+ fetch?: typeof fetch;
3
5
  /** Fetch API init parameters. */
4
6
  fetchOptions?: RequestInit;
5
7
  }
@@ -0,0 +1,17 @@
1
+ export type StreamingGuess = {
2
+ isStreaming: boolean;
3
+ };
4
+ /**
5
+ * Classifies a Response as streaming or non-streaming.
6
+ *
7
+ * Heuristics:
8
+ * - No body → not streaming
9
+ * - Known streaming Content-Types → streaming (SSE, NDJSON, JSON streaming)
10
+ * - text/plain without Content-Length → streaming (some AI APIs)
11
+ * - Otherwise → not streaming (conservative default, including HTML/SSR)
12
+ *
13
+ * We avoid probing the stream to prevent blocking on transform streams (like injectTraceMetaTags)
14
+ * or SSR streams that may not have data ready immediately.
15
+ */
16
+ export declare function classifyResponseStreaming(res: Response): StreamingGuess;
17
+ //# sourceMappingURL=streaming.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/cloudflare",
3
- "version": "10.28.0-alpha.0",
3
+ "version": "10.28.0",
4
4
  "description": "Official Sentry SDK for Cloudflare Workers and Pages",
5
5
  "repository": "git://github.com/getsentry/sentry-javascript.git",
6
6
  "homepage": "https://github.com/getsentry/sentry-javascript/tree/master/packages/cloudflare",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@opentelemetry/api": "^1.9.0",
53
- "@sentry/core": "10.28.0-alpha.0"
53
+ "@sentry/core": "10.28.0"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@cloudflare/workers-types": "^4.x"