@sentry/cloudflare 11.0.0-alpha.1 → 11.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/dev/baseSdk.js +20 -8
- package/build/cjs/dev/baseSdk.js.map +1 -1
- package/build/cjs/dev/client.js +116 -24
- package/build/cjs/dev/client.js.map +1 -1
- package/build/cjs/dev/clientCache.js +15 -0
- package/build/cjs/dev/clientCache.js.map +1 -0
- package/build/cjs/dev/defineCloudflareOptions.js.map +1 -1
- package/build/cjs/dev/durableobject.js +24 -8
- package/build/cjs/dev/durableobject.js.map +1 -1
- package/build/cjs/dev/flush.js +6 -4
- package/build/cjs/dev/flush.js.map +1 -1
- package/build/cjs/dev/index.js +3 -3
- package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js +4 -4
- package/build/cjs/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
- package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js +8 -16
- package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js +5 -1
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentEmail.js +4 -2
- package/build/cjs/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentEnv.js +5 -5
- package/build/cjs/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentFetch.js +8 -8
- package/build/cjs/dev/instrumentations/worker/instrumentFetch.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentQueue.js +4 -2
- package/build/cjs/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentR2.js +21 -18
- package/build/cjs/dev/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentRateLimit.js +6 -1
- package/build/cjs/dev/instrumentations/worker/instrumentRateLimit.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js +4 -2
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentTail.js +2 -0
- package/build/cjs/dev/instrumentations/worker/instrumentTail.js.map +1 -1
- package/build/cjs/dev/integrations/fetch.js +1 -11
- package/build/cjs/dev/integrations/fetch.js.map +1 -1
- package/build/cjs/dev/opentelemetry/tracer.js +2 -40
- package/build/cjs/dev/opentelemetry/tracer.js.map +1 -1
- package/build/cjs/dev/pages-plugin.js +2 -2
- package/build/cjs/dev/pages-plugin.js.map +1 -1
- package/build/cjs/dev/request.js +2 -123
- package/build/cjs/dev/request.js.map +1 -1
- package/build/cjs/dev/sdk.js +12 -6
- package/build/cjs/dev/sdk.js.map +1 -1
- package/build/cjs/dev/transport.js +1 -1
- package/build/cjs/dev/transport.js.map +1 -1
- package/build/cjs/dev/utils/invocationContext.js +41 -0
- package/build/cjs/dev/utils/invocationContext.js.map +1 -0
- package/build/cjs/dev/utils/invocationScope.js +7 -2
- package/build/cjs/dev/utils/invocationScope.js.map +1 -1
- package/build/cjs/dev/utils/rpcPropagation.js +15 -0
- package/build/cjs/dev/utils/rpcPropagation.js.map +1 -0
- package/build/cjs/dev/vite/autoInstrument.js +2 -1
- package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
- package/build/cjs/dev/vite/index.js.map +1 -1
- package/build/cjs/dev/vite/transform.js +30 -5
- package/build/cjs/dev/vite/transform.js.map +1 -1
- package/build/cjs/dev/vite/wranglerConfig.js +21 -1
- package/build/cjs/dev/vite/wranglerConfig.js.map +1 -1
- package/build/cjs/dev/withSentry.js.map +1 -1
- package/build/cjs/dev/workflows.js +45 -33
- package/build/cjs/dev/workflows.js.map +1 -1
- package/build/cjs/dev/wrapMethodWithSentry.js +51 -15
- package/build/cjs/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/dev/wrapRequestHandlerWithInit.js +133 -0
- package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -0
- package/build/cjs/prod/baseSdk.js +20 -8
- package/build/cjs/prod/baseSdk.js.map +1 -1
- package/build/cjs/prod/client.js +116 -24
- package/build/cjs/prod/client.js.map +1 -1
- package/build/cjs/prod/clientCache.js +15 -0
- package/build/cjs/prod/clientCache.js.map +1 -0
- package/build/cjs/prod/defineCloudflareOptions.js.map +1 -1
- package/build/cjs/prod/durableobject.js +24 -8
- package/build/cjs/prod/durableobject.js.map +1 -1
- package/build/cjs/prod/flush.js +6 -4
- package/build/cjs/prod/flush.js.map +1 -1
- package/build/cjs/prod/index.js +3 -3
- package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js +4 -4
- package/build/cjs/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
- package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js +8 -16
- package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js +5 -1
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentEmail.js +4 -2
- package/build/cjs/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentEnv.js +5 -5
- package/build/cjs/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentFetch.js +8 -8
- package/build/cjs/prod/instrumentations/worker/instrumentFetch.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentQueue.js +4 -2
- package/build/cjs/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentR2.js +21 -18
- package/build/cjs/prod/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentRateLimit.js +6 -1
- package/build/cjs/prod/instrumentations/worker/instrumentRateLimit.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js +4 -2
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentTail.js +2 -0
- package/build/cjs/prod/instrumentations/worker/instrumentTail.js.map +1 -1
- package/build/cjs/prod/integrations/fetch.js +1 -11
- package/build/cjs/prod/integrations/fetch.js.map +1 -1
- package/build/cjs/prod/opentelemetry/tracer.js +2 -40
- package/build/cjs/prod/opentelemetry/tracer.js.map +1 -1
- package/build/cjs/prod/pages-plugin.js +2 -2
- package/build/cjs/prod/pages-plugin.js.map +1 -1
- package/build/cjs/prod/request.js +2 -123
- package/build/cjs/prod/request.js.map +1 -1
- package/build/cjs/prod/sdk.js +12 -6
- package/build/cjs/prod/sdk.js.map +1 -1
- package/build/cjs/prod/transport.js +1 -1
- package/build/cjs/prod/transport.js.map +1 -1
- package/build/cjs/prod/utils/invocationContext.js +41 -0
- package/build/cjs/prod/utils/invocationContext.js.map +1 -0
- package/build/cjs/prod/utils/invocationScope.js +7 -2
- package/build/cjs/prod/utils/invocationScope.js.map +1 -1
- package/build/cjs/prod/utils/rpcPropagation.js +15 -0
- package/build/cjs/prod/utils/rpcPropagation.js.map +1 -0
- package/build/cjs/prod/vite/autoInstrument.js +2 -1
- package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
- package/build/cjs/prod/vite/index.js.map +1 -1
- package/build/cjs/prod/vite/transform.js +30 -5
- package/build/cjs/prod/vite/transform.js.map +1 -1
- package/build/cjs/prod/vite/wranglerConfig.js +21 -1
- package/build/cjs/prod/vite/wranglerConfig.js.map +1 -1
- package/build/cjs/prod/withSentry.js.map +1 -1
- package/build/cjs/prod/workflows.js +45 -33
- package/build/cjs/prod/workflows.js.map +1 -1
- package/build/cjs/prod/wrapMethodWithSentry.js +51 -15
- package/build/cjs/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/prod/wrapRequestHandlerWithInit.js +133 -0
- package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -0
- package/build/esm/dev/baseSdk.js +21 -9
- package/build/esm/dev/baseSdk.js.map +1 -1
- package/build/esm/dev/client.js +117 -25
- package/build/esm/dev/client.js.map +1 -1
- package/build/esm/dev/clientCache.js +12 -0
- package/build/esm/dev/clientCache.js.map +1 -0
- package/build/esm/dev/defineCloudflareOptions.js.map +1 -1
- package/build/esm/dev/durableobject.js +23 -7
- package/build/esm/dev/durableobject.js.map +1 -1
- package/build/esm/dev/flush.js +6 -4
- package/build/esm/dev/flush.js.map +1 -1
- package/build/esm/dev/index.js +3 -4
- package/build/esm/dev/index.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js +4 -4
- package/build/esm/dev/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js +8 -16
- package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentD1.js +6 -2
- package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentEmail.js +7 -5
- package/build/esm/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentEnv.js +5 -5
- package/build/esm/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentFetch.js +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentFetch.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentQueue.js +7 -5
- package/build/esm/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentR2.js +22 -19
- package/build/esm/dev/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentRateLimit.js +6 -1
- package/build/esm/dev/instrumentations/worker/instrumentRateLimit.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js +7 -5
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentTail.js +2 -0
- package/build/esm/dev/instrumentations/worker/instrumentTail.js.map +1 -1
- package/build/esm/dev/integrations/fetch.js +2 -12
- package/build/esm/dev/integrations/fetch.js.map +1 -1
- package/build/esm/dev/opentelemetry/tracer.js +2 -40
- package/build/esm/dev/opentelemetry/tracer.js.map +1 -1
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/pages-plugin.js +1 -1
- package/build/esm/dev/pages-plugin.js.map +1 -1
- package/build/esm/dev/request.js +2 -122
- package/build/esm/dev/request.js.map +1 -1
- package/build/esm/dev/sdk.js +12 -7
- package/build/esm/dev/sdk.js.map +1 -1
- package/build/esm/dev/transport.js +1 -1
- package/build/esm/dev/transport.js.map +1 -1
- package/build/esm/dev/utils/invocationContext.js +37 -0
- package/build/esm/dev/utils/invocationContext.js.map +1 -0
- package/build/esm/dev/utils/invocationScope.js +7 -2
- package/build/esm/dev/utils/invocationScope.js.map +1 -1
- package/build/esm/dev/utils/rpcPropagation.js +13 -0
- package/build/esm/dev/utils/rpcPropagation.js.map +1 -0
- package/build/esm/dev/utils/traceLinks.js +1 -1
- package/build/esm/dev/vite/autoInstrument.js +2 -1
- package/build/esm/dev/vite/autoInstrument.js.map +1 -1
- package/build/esm/dev/vite/index.js.map +1 -1
- package/build/esm/dev/vite/transform.js +30 -5
- package/build/esm/dev/vite/transform.js.map +1 -1
- package/build/esm/dev/vite/wranglerConfig.js +21 -2
- package/build/esm/dev/vite/wranglerConfig.js.map +1 -1
- package/build/esm/dev/withSentry.js.map +1 -1
- package/build/esm/dev/workflows.js +48 -36
- package/build/esm/dev/workflows.js.map +1 -1
- package/build/esm/dev/wrapMethodWithSentry.js +53 -17
- package/build/esm/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/dev/wrapRequestHandlerWithInit.js +131 -0
- package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -0
- package/build/esm/prod/baseSdk.js +21 -9
- package/build/esm/prod/baseSdk.js.map +1 -1
- package/build/esm/prod/client.js +117 -25
- package/build/esm/prod/client.js.map +1 -1
- package/build/esm/prod/clientCache.js +12 -0
- package/build/esm/prod/clientCache.js.map +1 -0
- package/build/esm/prod/defineCloudflareOptions.js.map +1 -1
- package/build/esm/prod/durableobject.js +23 -7
- package/build/esm/prod/durableobject.js.map +1 -1
- package/build/esm/prod/flush.js +6 -4
- package/build/esm/prod/flush.js.map +1 -1
- package/build/esm/prod/index.js +3 -4
- package/build/esm/prod/index.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js +4 -4
- package/build/esm/prod/instrumentations/instrumentDurableObjectNamespace.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js +8 -16
- package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentD1.js +6 -2
- package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentEmail.js +7 -5
- package/build/esm/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentEnv.js +5 -5
- package/build/esm/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentFetch.js +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentFetch.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentQueue.js +7 -5
- package/build/esm/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentR2.js +22 -19
- package/build/esm/prod/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentRateLimit.js +6 -1
- package/build/esm/prod/instrumentations/worker/instrumentRateLimit.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js +7 -5
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentTail.js +2 -0
- package/build/esm/prod/instrumentations/worker/instrumentTail.js.map +1 -1
- package/build/esm/prod/integrations/fetch.js +2 -12
- package/build/esm/prod/integrations/fetch.js.map +1 -1
- package/build/esm/prod/opentelemetry/tracer.js +2 -40
- package/build/esm/prod/opentelemetry/tracer.js.map +1 -1
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/pages-plugin.js +1 -1
- package/build/esm/prod/pages-plugin.js.map +1 -1
- package/build/esm/prod/request.js +2 -122
- package/build/esm/prod/request.js.map +1 -1
- package/build/esm/prod/sdk.js +12 -7
- package/build/esm/prod/sdk.js.map +1 -1
- package/build/esm/prod/transport.js +1 -1
- package/build/esm/prod/transport.js.map +1 -1
- package/build/esm/prod/utils/invocationContext.js +37 -0
- package/build/esm/prod/utils/invocationContext.js.map +1 -0
- package/build/esm/prod/utils/invocationScope.js +7 -2
- package/build/esm/prod/utils/invocationScope.js.map +1 -1
- package/build/esm/prod/utils/rpcPropagation.js +13 -0
- package/build/esm/prod/utils/rpcPropagation.js.map +1 -0
- package/build/esm/prod/utils/traceLinks.js +1 -1
- package/build/esm/prod/vite/autoInstrument.js +2 -1
- package/build/esm/prod/vite/autoInstrument.js.map +1 -1
- package/build/esm/prod/vite/index.js.map +1 -1
- package/build/esm/prod/vite/transform.js +30 -5
- package/build/esm/prod/vite/transform.js.map +1 -1
- package/build/esm/prod/vite/wranglerConfig.js +21 -2
- package/build/esm/prod/vite/wranglerConfig.js.map +1 -1
- package/build/esm/prod/withSentry.js.map +1 -1
- package/build/esm/prod/workflows.js +48 -36
- package/build/esm/prod/workflows.js.map +1 -1
- package/build/esm/prod/wrapMethodWithSentry.js +53 -17
- package/build/esm/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/prod/wrapRequestHandlerWithInit.js +131 -0
- package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -0
- package/build/types/baseSdk.d.ts +8 -0
- package/build/types/baseSdk.d.ts.map +1 -1
- package/build/types/client.d.ts +90 -17
- package/build/types/client.d.ts.map +1 -1
- package/build/types/clientCache.d.ts +8 -0
- package/build/types/clientCache.d.ts.map +1 -0
- package/build/types/defineCloudflareOptions.d.ts +3 -2
- package/build/types/defineCloudflareOptions.d.ts.map +1 -1
- package/build/types/durableobject.d.ts +5 -7
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/flush.d.ts +2 -0
- package/build/types/flush.d.ts.map +1 -1
- package/build/types/index.d.ts +3 -4
- package/build/types/index.d.ts.map +1 -1
- package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts +2 -1
- package/build/types/instrumentations/instrumentDurableObjectNamespace.d.ts.map +1 -1
- package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts +2 -3
- package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentEmail.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentR2.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentRateLimit.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentTail.d.ts.map +1 -1
- package/build/types/integrations/fetch.d.ts.map +1 -1
- package/build/types/opentelemetry/tracer.d.ts.map +1 -1
- package/build/types/pages-plugin.d.ts +3 -1
- package/build/types/pages-plugin.d.ts.map +1 -1
- package/build/types/request.d.ts +5 -31
- package/build/types/request.d.ts.map +1 -1
- package/build/types/sdk.d.ts +13 -4
- package/build/types/sdk.d.ts.map +1 -1
- package/build/types/transport.d.ts.map +1 -1
- package/build/types/types.d.ts +28 -0
- package/build/types/types.d.ts.map +1 -1
- package/build/types/utils/invocationContext.d.ts +58 -0
- package/build/types/utils/invocationContext.d.ts.map +1 -0
- package/build/types/utils/invocationScope.d.ts +2 -1
- package/build/types/utils/invocationScope.d.ts.map +1 -1
- package/build/types/utils/rpcPropagation.d.ts +10 -0
- package/build/types/utils/rpcPropagation.d.ts.map +1 -0
- package/build/types/vite/autoInstrument.d.ts.map +1 -1
- package/build/types/vite/index.d.ts +4 -0
- package/build/types/vite/index.d.ts.map +1 -1
- package/build/types/vite/transform.d.ts +3 -0
- package/build/types/vite/transform.d.ts.map +1 -1
- package/build/types/vite/wranglerConfig.d.ts +13 -0
- package/build/types/vite/wranglerConfig.d.ts.map +1 -1
- package/build/types/withSentry.d.ts +2 -3
- package/build/types/withSentry.d.ts.map +1 -1
- package/build/types/workflows.d.ts +3 -3
- package/build/types/workflows.d.ts.map +1 -1
- package/build/types/wrapMethodWithSentry.d.ts +6 -1
- package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
- package/build/types/wrapRequestHandlerWithInit.d.ts +31 -0
- package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -0
- package/package.json +6 -4
- package/build/cjs/dev/integrations/tracing/vercelai.js +0 -18
- package/build/cjs/dev/integrations/tracing/vercelai.js.map +0 -1
- package/build/cjs/prod/integrations/tracing/vercelai.js +0 -18
- package/build/cjs/prod/integrations/tracing/vercelai.js.map +0 -1
- package/build/esm/dev/integrations/tracing/vercelai.js +0 -16
- package/build/esm/dev/integrations/tracing/vercelai.js.map +0 -1
- package/build/esm/prod/integrations/tracing/vercelai.js +0 -16
- package/build/esm/prod/integrations/tracing/vercelai.js.map +0 -1
- package/build/types/integrations/tracing/vercelai.d.ts +0 -39
- package/build/types/integrations/tracing/vercelai.d.ts.map +0 -1
package/build/esm/prod/sdk.js
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
|
-
import { vercelAIIntegration } from './integrations/tracing/vercelai.js';
|
|
2
1
|
import { getBaseDefaultIntegrations, initWithDefaultIntegrations } from './baseSdk.js';
|
|
2
|
+
import { setupOpenTelemetryTracer } from './opentelemetry/tracer.js';
|
|
3
|
+
import { wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit.js';
|
|
4
|
+
import '@sentry/core';
|
|
3
5
|
|
|
4
6
|
function getDefaultIntegrations(options) {
|
|
5
|
-
return
|
|
6
|
-
...getBaseDefaultIntegrations(options),
|
|
7
|
-
// Subscribes to the `ai` SDK's native `node:diagnostics_channel` telemetry channel.
|
|
8
|
-
vercelAIIntegration()
|
|
9
|
-
];
|
|
7
|
+
return getBaseDefaultIntegrations(options);
|
|
10
8
|
}
|
|
11
9
|
function init(options) {
|
|
10
|
+
options.enableOpenTelemetrySetup ?? (options.enableOpenTelemetrySetup = false);
|
|
11
|
+
if (options.enableOpenTelemetrySetup) {
|
|
12
|
+
setupOpenTelemetryTracer();
|
|
13
|
+
}
|
|
12
14
|
return initWithDefaultIntegrations(options, getDefaultIntegrations);
|
|
13
15
|
}
|
|
16
|
+
function _INTERNAL_wrapRequestHandler(wrapperOptions, handler) {
|
|
17
|
+
return wrapRequestHandlerWithInit(wrapperOptions, handler, init);
|
|
18
|
+
}
|
|
14
19
|
|
|
15
|
-
export { getDefaultIntegrations, init };
|
|
20
|
+
export { _INTERNAL_wrapRequestHandler, getDefaultIntegrations, init };
|
|
16
21
|
//# sourceMappingURL=sdk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport {
|
|
1
|
+
{"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import type { Integration } from '@sentry/core';\nimport { getBaseDefaultIntegrations, initWithDefaultIntegrations } from './baseSdk';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n// Test-only helper, re-exported here so tests can reset the global client cache.\nexport { _clearGlobalClientCache } from './clientCache';\n\n/**\n * Get the default integrations for the Cloudflare SDK.\n */\nexport function getDefaultIntegrations(options: CloudflareOptions): Integration[] {\n return getBaseDefaultIntegrations(options);\n}\n\n/**\n * Initializes the cloudflare SDK.\n */\nexport function init(options: CloudflareOptions): CloudflareClient | undefined {\n // Like most Node-based SDKs, Cloudflare defaults to running without a Sentry OpenTelemetry tracer\n // provider. Scope isolation is handled by the entrypoint wrappers' AsyncLocalStorage strategy.\n options.enableOpenTelemetrySetup ??= false;\n\n // Opt-in only: when `enableOpenTelemetrySetup` is `true`, set up a custom trace provider so spans\n // emitted via `@opentelemetry/api` are captured by Sentry. See the option's docs for the caveats.\n if (options.enableOpenTelemetrySetup) {\n setupOpenTelemetryTracer();\n }\n\n return initWithDefaultIntegrations(options, getDefaultIntegrations);\n}\n\n/**\n * `wrapRequestHandler` backed by `init`, so the request gets the full default integrations and\n * honors `enableOpenTelemetrySetup`. The `@sentry/cloudflare/request` variant deliberately skips\n * both to stay usable without `nodejs_compat`.\n *\n * For framework SDKs building on the main entry point, e.g. SvelteKit, whose OpenTelemetry spans\n * need the tracer provider.\n *\n * @internal\n */\nexport function _INTERNAL_wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, init);\n}\n"],"names":[],"mappings":";;;;;AAYO,SAAS,uBAAuB,OAAA,EAA2C;AAChF,EAAA,OAAO,2BAA2B,OAAO,CAAA;AAC3C;AAKO,SAAS,KAAK,OAAA,EAA0D;AAG7E,EAAA,OAAA,CAAQ,wBAAA,KAAR,QAAQ,wBAAA,GAA6B,KAAA,CAAA;AAIrC,EAAA,IAAI,QAAQ,wBAAA,EAA0B;AACpC,IAAA,wBAAA,EAAyB;AAAA,EAC3B;AAEA,EAAA,OAAO,2BAAA,CAA4B,SAAS,sBAAsB,CAAA;AACpE;AAYO,SAAS,4BAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAO,0BAAA,CAA2B,cAAA,EAAgB,OAAA,EAAS,IAAI,CAAA;AACjE;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createTransport, suppressTracing, SENTRY_BUFFER_FULL_ERROR } from '@sentry/core';
|
|
2
2
|
|
|
3
|
-
const DEFAULT_TRANSPORT_BUFFER_SIZE =
|
|
3
|
+
const DEFAULT_TRANSPORT_BUFFER_SIZE = 256;
|
|
4
4
|
class IsolatedPromiseBuffer {
|
|
5
5
|
constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {
|
|
6
6
|
this.$ = [];
|
|
@@ -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 /** 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 =
|
|
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\n/**\n * How many payloads the buffer holds before it starts rejecting new ones.\n *\n * With `cacheClient` a single client is reused across an isolate's invocations, so one buffer now has to absorb\n * the payloads of many invocations rather than one. 256 is the size that held up under load testing that scenario.\n */\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 256;\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 as BodyInit,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(async response => {\n // Consume the response body to satisfy Cloudflare Workers' fetch requirements.\n // The runtime requires all fetch response bodies to be read or explicitly canceled\n // to prevent connection stalls and potential deadlocks. We read the body as text\n // even though we don't use the content, as Sentry's response information is in the headers.\n // See: https://github.com/getsentry/sentry-javascript/issues/18534\n try {\n await response.text();\n } catch {\n // no-op\n }\n\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":";;AAgBA,MAAM,6BAAA,GAAgC,GAAA;AAU/B,MAAM,qBAAA,CAAsB;AAAA,EAS1B,WAAA,CAAY,cAAc,6BAAA,EAA+B;AAC9D,IAAA,IAAA,CAAK,IAAI,EAAC;AACV,IAAA,IAAA,CAAK,iBAAiB,EAAC;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKO,IAAI,YAAA,EAA0G;AACnH,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,IAAU,IAAA,CAAK,WAAA,EAAa;AAClD,MAAA,OAAO,OAAA,CAAQ,OAAO,wBAAwB,CAAA;AAAA,IAChD;AAEA,IAAA,IAAA,CAAK,cAAA,CAAe,KAAK,YAAY,CAAA;AACrC,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,EAAE,CAAA;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKO,MAAM,OAAA,EAAwC;AACnD,IAAA,MAAM,gBAAA,GAAmB,CAAC,GAAG,IAAA,CAAK,cAAc,CAAA;AAChD,IAAA,IAAA,CAAK,iBAAiB,EAAC;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AAS,OAAA,CAAQ,GAAA,CAAI,aAAa;AAAA;AACnD,SACF;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,gBAAgB,OAAA,EAAS,WAAA,EAAa,IAAI,qBAAA,CAAsB,OAAA,CAAQ,UAAU,CAAC,CAAA;AAC5F;;;;"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getIsolationScope, getDefaultIsolationScope, debug } from '@sentry/core';
|
|
2
|
+
import { DEBUG_BUILD } from '../debug-build.js';
|
|
3
|
+
import { getOriginalWaitUntil } from '../flush.js';
|
|
4
|
+
|
|
5
|
+
const INVOCATION_STATE = /* @__PURE__ */ Symbol("sentryInvocationState");
|
|
6
|
+
function getInvocationWaitUntil(state) {
|
|
7
|
+
if (state.waitUntil === void 0) {
|
|
8
|
+
const ctx = state.ctx;
|
|
9
|
+
let resolved = null;
|
|
10
|
+
try {
|
|
11
|
+
const original = ctx && getOriginalWaitUntil(ctx);
|
|
12
|
+
resolved = original ? original.bind(ctx) : null;
|
|
13
|
+
} catch {
|
|
14
|
+
}
|
|
15
|
+
state.waitUntil = resolved;
|
|
16
|
+
}
|
|
17
|
+
return state.waitUntil ?? void 0;
|
|
18
|
+
}
|
|
19
|
+
function setInvocationState(scope, state) {
|
|
20
|
+
if (scope === getDefaultIsolationScope()) {
|
|
21
|
+
DEBUG_BUILD && debug.warn(
|
|
22
|
+
"[Sentry] Cannot track this invocation. Telemetry captured after the invocation ends may not be delivered."
|
|
23
|
+
);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
scope[INVOCATION_STATE] = state;
|
|
27
|
+
}
|
|
28
|
+
function getInvocationState() {
|
|
29
|
+
const isolationScope = getIsolationScope();
|
|
30
|
+
if (isolationScope === getDefaultIsolationScope()) {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
return isolationScope[INVOCATION_STATE];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { getInvocationState, getInvocationWaitUntil, setInvocationState };
|
|
37
|
+
//# sourceMappingURL=invocationContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invocationContext.js","sources":["../../../../src/utils/invocationContext.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { debug, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { getOriginalWaitUntil } from '../flush';\n\n/**\n * State owned by a single invocation (request, RPC call, cron, ...).\n *\n * A cached client (`cacheClient`) is shared by all invocations running in the same\n * isolate, so anything invocation-owned must not live on the client: two overlapping\n * requests would otherwise overwrite each other's state (e.g. the execution context\n * used to register eager flushes) and the earlier invocation's envelopes would be\n * suspended when the later invocation ends.\n *\n * The state rides on the invocation's forked isolation scope, which the async\n * context strategy (AsyncLocalStorage) hands back for exactly the async context that\n * owns the invocation — including detached continuations created inside it. A symbol\n * key keeps it off `Scope.clone()` and out of serialized event data.\n */\nexport interface InvocationState {\n /**\n * The execution context of the invocation that owns this scope. Eager envelope\n * sends are registered with this context's `waitUntil`, so they are attributed to\n * the invocation that captured the data even when invocations overlap.\n */\n readonly ctx: ExecutionContextCompat | undefined;\n /**\n * Set on the client's `flush` hook, the invocation's natural flush point.\n * Captures before it are drained by that flush; captures after it (in\n * `waitUntil` work or detached continuations) have no later flush to ride and\n * are delivered eagerly.\n */\n flushPointReached?: boolean;\n /**\n * `ctx.waitUntil` resolved once for this invocation (see `getInvocationWaitUntil`).\n * `null` once resolved to \"no usable waitUntil\".\n */\n waitUntil?: ExecutionContext['waitUntil'] | null;\n}\n\nconst INVOCATION_STATE: unique symbol = Symbol('sentryInvocationState');\n\n/**\n * Returns the invocation's original (un-instrumented) `waitUntil`, bound to its context,\n * resolving it on first use and caching it on the state. Reading `ctx.waitUntil` on a\n * native `ExecutionContext`/`DurableObjectState` goes through the runtime's property\n * getter every time; one read per invocation is enough.\n */\nexport function getInvocationWaitUntil(state: InvocationState): ExecutionContext['waitUntil'] | undefined {\n if (state.waitUntil === undefined) {\n const ctx = state.ctx;\n let resolved: ExecutionContext['waitUntil'] | null = null;\n try {\n const original = ctx && getOriginalWaitUntil(ctx);\n resolved = original ? original.bind(ctx) : null;\n } catch {\n // Accessing `waitUntil` can throw on foreign or already-torn-down contexts.\n }\n state.waitUntil = resolved;\n }\n return state.waitUntil ?? undefined;\n}\n\ntype ScopeWithInvocationState = Scope & {\n [INVOCATION_STATE]?: InvocationState;\n};\n\n/**\n * Attaches invocation state to a forked isolation scope. Only meaningful on a scope\n * that outlives nothing but this invocation — never attach to the default isolation\n * scope, which is shared by every invocation in the isolate.\n */\nexport function setInvocationState(scope: Scope, state: InvocationState): void {\n if (scope === getDefaultIsolationScope()) {\n DEBUG_BUILD &&\n debug.warn(\n '[Sentry] Cannot track this invocation. Telemetry captured after the invocation ends may not be delivered.',\n );\n return;\n }\n\n (scope as ScopeWithInvocationState)[INVOCATION_STATE] = state;\n}\n\n/**\n * Returns the state of the invocation that owns the current async context, or\n * `undefined` outside any instrumented invocation (the default isolation scope is\n * shared, so state read from it could not be attributed to one invocation — and it\n * is never attached there in the first place).\n */\nexport function getInvocationState(): InvocationState | undefined {\n const isolationScope = getIsolationScope() as ScopeWithInvocationState;\n if (isolationScope === getDefaultIsolationScope()) {\n return undefined;\n }\n return isolationScope[INVOCATION_STATE];\n}\n"],"names":[],"mappings":";;;;AA0CA,MAAM,gBAAA,0BAAyC,uBAAuB,CAAA;AAQ/D,SAAS,uBAAuB,KAAA,EAAmE;AACxG,EAAA,IAAI,KAAA,CAAM,cAAc,MAAA,EAAW;AACjC,IAAA,MAAM,MAAM,KAAA,CAAM,GAAA;AAClB,IAAA,IAAI,QAAA,GAAiD,IAAA;AACrD,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,GAAA,IAAO,oBAAA,CAAqB,GAAG,CAAA;AAChD,MAAA,QAAA,GAAW,QAAA,GAAW,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,GAAI,IAAA;AAAA,IAC7C,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,KAAA,CAAM,SAAA,GAAY,QAAA;AAAA,EACpB;AACA,EAAA,OAAO,MAAM,SAAA,IAAa,MAAA;AAC5B;AAWO,SAAS,kBAAA,CAAmB,OAAc,KAAA,EAA8B;AAC7E,EAAA,IAAI,KAAA,KAAU,0BAAyB,EAAG;AACxC,IAAA,WAAA,IACE,KAAA,CAAM,IAAA;AAAA,MACJ;AAAA,KACF;AACF,IAAA;AAAA,EACF;AAEA,EAAC,KAAA,CAAmC,gBAAgB,CAAA,GAAI,KAAA;AAC1D;AAQO,SAAS,kBAAA,GAAkD;AAChE,EAAA,MAAM,iBAAiB,iBAAA,EAAkB;AACzC,EAAA,IAAI,cAAA,KAAmB,0BAAyB,EAAG;AACjD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,eAAe,gBAAgB,CAAA;AACxC;;;;"}
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { getIsolationScope, getDefaultIsolationScope, withIsolationScope } from '@sentry/core';
|
|
2
|
+
import { setInvocationState } from './invocationContext.js';
|
|
2
3
|
|
|
3
|
-
function withInvocationIsolationScope(callback) {
|
|
4
|
+
function withInvocationIsolationScope(callback, context) {
|
|
4
5
|
const isolationScope = getIsolationScope();
|
|
5
|
-
const
|
|
6
|
+
const isEntryPoint = isolationScope === getDefaultIsolationScope();
|
|
7
|
+
const newIsolationScope = isEntryPoint ? isolationScope.clone() : isolationScope;
|
|
8
|
+
if (isEntryPoint) {
|
|
9
|
+
setInvocationState(newIsolationScope, { ctx: context });
|
|
10
|
+
}
|
|
6
11
|
return withIsolationScope(newIsolationScope, () => callback(newIsolationScope));
|
|
7
12
|
}
|
|
8
13
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invocationScope.js","sources":["../../../../src/utils/invocationScope.ts"],"sourcesContent":["import { getDefaultIsolationScope, getIsolationScope, type Scope, withIsolationScope } from '@sentry/core';\n\n/**\n * Runs `callback` on the isolation scope for the current invocation.\n *\n * An instrumented handler is either the entry point of an invocation or reentrant — reached from\n * another instrumented handler already serving the same invocation (a Durable Object method calling\n * its own `fetch`, an RPC method reaching a sibling method). Only the entry point may fork:\n *\n * - Forking at the entry point is mandatory. `setUser`/`setTag` write to the isolation scope, and a\n * Durable Object's isolation scope outlives the invocation that touched it, so without a fork one\n * invocation's user and tags reappear on the next invocation's events in the same isolate.\n * Forking clones, so request data set by an enclosing wrapper is still inherited.\n * - Forking again when reentrant would be wrong. Everything below the entry point is one logical\n * unit of work: a nested call must see what the caller set and be able to add to it, the way it\n * would if the SDK were not wrapping it at all.\n *\n * The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in\n * flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default\n * is therefore enough to tell the two cases apart. The stack fallback does not fork, so it reports the\n * default scope even inside an invocation; there the fork degrades to a no-op, which the stack strategy\n * tolerates. This matches the approach used by `patchEventHandler` in Nuxt.\n */\nexport function withInvocationIsolationScope<T>(callback: (scope: Scope) => T): T {\n const isolationScope = getIsolationScope();\n\n const
|
|
1
|
+
{"version":3,"file":"invocationScope.js","sources":["../../../../src/utils/invocationScope.ts"],"sourcesContent":["import { getDefaultIsolationScope, getIsolationScope, type Scope, withIsolationScope } from '@sentry/core';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { setInvocationState } from './invocationContext';\n\n/**\n * Runs `callback` on the isolation scope for the current invocation.\n *\n * An instrumented handler is either the entry point of an invocation or reentrant — reached from\n * another instrumented handler already serving the same invocation (a Durable Object method calling\n * its own `fetch`, an RPC method reaching a sibling method). Only the entry point may fork:\n *\n * - Forking at the entry point is mandatory. `setUser`/`setTag` write to the isolation scope, and a\n * Durable Object's isolation scope outlives the invocation that touched it, so without a fork one\n * invocation's user and tags reappear on the next invocation's events in the same isolate.\n * Forking clones, so request data set by an enclosing wrapper is still inherited.\n * - Forking again when reentrant would be wrong. Everything below the entry point is one logical\n * unit of work: a nested call must see what the caller set and be able to add to it, the way it\n * would if the SDK were not wrapping it at all.\n *\n * The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in\n * flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default\n * is therefore enough to tell the two cases apart. The stack fallback does not fork, so it reports the\n * default scope even inside an invocation; there the fork degrades to a no-op, which the stack strategy\n * tolerates. This matches the approach used by `patchEventHandler` in Nuxt.\n */\nexport function withInvocationIsolationScope<T>(callback: (scope: Scope) => T, context?: ExecutionContextCompat): T {\n const isolationScope = getIsolationScope();\n\n const isEntryPoint = isolationScope === getDefaultIsolationScope();\n const newIsolationScope = isEntryPoint ? isolationScope.clone() : isolationScope;\n\n if (isEntryPoint) {\n setInvocationState(newIsolationScope, { ctx: context });\n }\n\n return withIsolationScope(newIsolationScope, () => callback(newIsolationScope));\n}\n"],"names":[],"mappings":";;;AAyBO,SAAS,4BAAA,CAAgC,UAA+B,OAAA,EAAqC;AAClH,EAAA,MAAM,iBAAiB,iBAAA,EAAkB;AAEzC,EAAA,MAAM,YAAA,GAAe,mBAAmB,wBAAA,EAAyB;AACjE,EAAA,MAAM,iBAAA,GAAoB,YAAA,GAAe,cAAA,CAAe,KAAA,EAAM,GAAI,cAAA;AAElE,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,kBAAA,CAAmB,iBAAA,EAAmB,EAAE,GAAA,EAAK,OAAA,EAAS,CAAA;AAAA,EACxD;AAEA,EAAA,OAAO,kBAAA,CAAmB,iBAAA,EAAmB,MAAM,QAAA,CAAS,iBAAiB,CAAC,CAAA;AAChF;;;;"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { matchesTracePropagationTargets } from '@sentry/core';
|
|
2
|
+
|
|
3
|
+
const PROPAGATE_TO_NONE = () => false;
|
|
4
|
+
function createRpcPropagationResolver(options) {
|
|
5
|
+
const bindings = options?.rpcTracePropagationBindings;
|
|
6
|
+
if (!bindings?.length) {
|
|
7
|
+
return PROPAGATE_TO_NONE;
|
|
8
|
+
}
|
|
9
|
+
return (bindingName) => matchesTracePropagationTargets(bindingName, bindings, true);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export { createRpcPropagationResolver };
|
|
13
|
+
//# sourceMappingURL=rpcPropagation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpcPropagation.js","sources":["../../../../src/utils/rpcPropagation.ts"],"sourcesContent":["import { matchesTracePropagationTargets } from '@sentry/core';\nimport type { CloudflareOptions } from '../client';\n\nconst PROPAGATE_TO_NONE = () => false;\n\n/**\n * Builds the per-binding predicate that decides whether a binding takes part in RPC trace\n * propagation.\n *\n * Callers only. Receivers continue an incoming trace whenever one arrives, so they have nothing to\n * match against.\n */\nexport function createRpcPropagationResolver(options: CloudflareOptions | undefined): (bindingName: string) => boolean {\n const bindings = options?.rpcTracePropagationBindings;\n\n if (!bindings?.length) {\n return PROPAGATE_TO_NONE;\n }\n\n // Strings must match a binding name exactly, without this, an entry of `DB` would also enable\n // propagation for a binding named `MY_DB`. Regular expressions still give pattern matching.\n return (bindingName: string) => matchesTracePropagationTargets(bindingName, bindings, true);\n}\n"],"names":[],"mappings":";;AAGA,MAAM,oBAAoB,MAAM,KAAA;AASzB,SAAS,6BAA6B,OAAA,EAA0E;AACrH,EAAA,MAAM,WAAW,OAAA,EAAS,2BAAA;AAE1B,EAAA,IAAI,CAAC,UAAU,MAAA,EAAQ;AACrB,IAAA,OAAO,iBAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,WAAA,KAAwB,8BAAA,CAA+B,WAAA,EAAa,UAAU,IAAI,CAAA;AAC5F;;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TraceFlags } from '@opentelemetry/api';
|
|
2
|
-
import {
|
|
2
|
+
import { getActiveSpan, spanIsSampled, debug, SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE } from '@sentry/core';
|
|
3
3
|
import { DEBUG_BUILD } from '../debug-build.js';
|
|
4
4
|
|
|
5
5
|
const SENTRY_TRACE_LINK_KEY_PREFIX = "__SENTRY_TRACE_LINK__";
|
|
@@ -74,7 +74,8 @@ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
|
|
|
74
74
|
classWrappers,
|
|
75
75
|
agentClasses,
|
|
76
76
|
optionsFn,
|
|
77
|
-
optionsImport
|
|
77
|
+
optionsImport,
|
|
78
|
+
sameWorkerBindings: wranglerConfig.sameWorkerBindings
|
|
78
79
|
});
|
|
79
80
|
const wrappedClasses = result?.wrappedClasses ?? /* @__PURE__ */ new Set();
|
|
80
81
|
const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoInstrument.js","sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument class(es) ${missing.join(', ')}: no matching exported class ` +\n 'declaration found in the worker entry (re-exports from other modules cannot be wrapped ' +\n 'automatically). Wrap them manually with the matching `instrument*WithSentry` helper.',\n );\n }\n\n return result ??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../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument class(es) ${missing.join(', ')}: no matching exported class ` +\n 'declaration found in the worker entry (re-exports from other modules cannot be wrapped ' +\n 'automatically). Wrap them manually with the matching `instrument*WithSentry` helper.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"names":["code"],"mappings":";;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAEpB,SAAS,oCAAA,CAAqC,OAAA,GAA2C,EAAC,EAAG;AAClG,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI,aAAA;AAEJ,EAAA,IAAI,SAAA,GAAY,uBAAA;AAChB,EAAA,IAAI,aAAA;AAEJ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,mCAAA;AAAA,IAEN,eAAe,MAAA,EAAsE;AACnF,MAAA,MAAM,MAAA,GAAS,qBAAA,CAAsB,MAAA,CAAO,IAAA,EAAM,QAAQ,kBAAkB,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CAAA,GAAI;AAAA,OACjF,CAAA,GACD,MAAA;AAMN,MAAA,MAAM,MAAA,GAAS,6BAAA,CAA8B,IAAA,EAAM,GAAA,EAAK;AAAA,QACtD,aAAA;AAAA,QACA,YAAA;AAAA,QACA,SAAA;AAAA,QACA,aAAA;AAAA,QACA,oBAAoB,cAAA,CAAe;AAAA,OACpC,CAAA;AAED,MAAA,MAAM,cAAA,GAAiB,MAAA,EAAQ,cAAA,oBAAkB,IAAI,GAAA,EAAY;AACjE,MAAA,MAAM,OAAA,GAAU,CAAC,GAAG,aAAA,CAAc,IAAA,EAAM,CAAA,CAAE,MAAA,CAAO,CAAA,IAAA,KAAQ,CAAC,cAAA,CAAe,GAAA,CAAI,IAAI,CAAC,CAAA;AAClF,MAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,QAAA,IAAA,CAAK,IAAA;AAAA,UACH,CAAA,6CAAA,EAAgD,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,0MAAA;AAAA,SAGpE;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n }),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n }),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;AAmFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACL,uBAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ;AAAA,KACnC,CAAA;AAAA,IACD,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAAC,oCAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import MagicString from 'magic-string';
|
|
2
|
+
import { DEFAULT_EXPORT } from './wranglerConfig.js';
|
|
2
3
|
import { detectWorkerEntrypointClasses } from './workerEntrypoint.js';
|
|
3
4
|
|
|
5
|
+
const MERGED_OPTIONS_IDENTIFIER = "__SENTRY_OPTIONS__";
|
|
4
6
|
function isCallToMethod(node, methodName) {
|
|
5
7
|
if (node.type !== "CallExpression") return false;
|
|
6
8
|
const callee = node.callee;
|
|
@@ -17,6 +19,7 @@ const WRAPPER_METHODS = {
|
|
|
17
19
|
function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
18
20
|
const ms = new MagicString(code);
|
|
19
21
|
const topLevelClasses = collectTopLevelClasses(ast);
|
|
22
|
+
const sameWorkerBindings = ctx.sameWorkerBindings ?? [];
|
|
20
23
|
const state = {
|
|
21
24
|
ms,
|
|
22
25
|
needsImport: false,
|
|
@@ -25,7 +28,10 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
|
25
28
|
renamedLocals: /* @__PURE__ */ new Set(),
|
|
26
29
|
classWrappers: ctx.classWrappers,
|
|
27
30
|
agentClasses: ctx.agentClasses ?? /* @__PURE__ */ new Set(),
|
|
28
|
-
workerEntrypointClasses: detectWorkerEntrypointClasses(ast)
|
|
31
|
+
workerEntrypointClasses: detectWorkerEntrypointClasses(ast),
|
|
32
|
+
// The identifier must be chosen before wrapping, which bindings survive is only known after.
|
|
33
|
+
optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,
|
|
34
|
+
autoWrapped: /* @__PURE__ */ new Set()
|
|
29
35
|
};
|
|
30
36
|
const { wrappedClasses } = state;
|
|
31
37
|
for (const node of ast.body) {
|
|
@@ -42,6 +48,9 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
|
42
48
|
if (wrappedClasses.size === 0) return void 0;
|
|
43
49
|
return { code, map: ms.generateMap({ hires: true }), wrappedClasses };
|
|
44
50
|
}
|
|
51
|
+
if (sameWorkerBindings.length > 0) {
|
|
52
|
+
ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
|
|
53
|
+
}
|
|
45
54
|
if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
|
|
46
55
|
ms.prepend("import * as __SENTRY__ from '@sentry/cloudflare';\n");
|
|
47
56
|
return {
|
|
@@ -50,6 +59,16 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
|
|
|
50
59
|
wrappedClasses
|
|
51
60
|
};
|
|
52
61
|
}
|
|
62
|
+
function buildMergedOptionsDeclaration(sameWorkerBindings, optionsFn, state) {
|
|
63
|
+
const bindingNames = sameWorkerBindings.filter(({ className }) => state.autoWrapped.has(className)).map(({ bindingName }) => bindingName);
|
|
64
|
+
if (!bindingNames.length) {
|
|
65
|
+
return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
const names = bindingNames.map((name) => JSON.stringify(name)).join(", ");
|
|
69
|
+
return `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { const opts = (${optionsFn})(env); return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
53
72
|
function resolveWrapperKind(exportedName, localName, state) {
|
|
54
73
|
const configured = state.classWrappers.get(exportedName);
|
|
55
74
|
if (configured === "durableObject" && localName && state.agentClasses.has(localName)) return "agent";
|
|
@@ -69,12 +88,16 @@ function collectTopLevelClasses(ast) {
|
|
|
69
88
|
function wrapDefaultExport(node, ctx, state) {
|
|
70
89
|
const decl = node.declaration;
|
|
71
90
|
if (isCallToMethod(decl, "withSentry")) return;
|
|
72
|
-
if (decl.type === "Identifier" && state.renamedLocals.has(decl.name))
|
|
91
|
+
if (decl.type === "Identifier" && state.renamedLocals.has(decl.name)) {
|
|
92
|
+
state.autoWrapped.add(DEFAULT_EXPORT);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
73
95
|
state.ms.overwrite(node.start, decl.start, "const __SENTRY_DEFAULT_EXPORT__ = ");
|
|
74
96
|
state.ms.append(`
|
|
75
|
-
export default __SENTRY__.withSentry(${
|
|
97
|
+
export default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);
|
|
76
98
|
`);
|
|
77
99
|
state.needsImport = true;
|
|
100
|
+
state.autoWrapped.add(DEFAULT_EXPORT);
|
|
78
101
|
}
|
|
79
102
|
function handleNamedExport(node, ctx, state) {
|
|
80
103
|
const decl = node.declaration;
|
|
@@ -113,10 +136,11 @@ function wrapInlineClassExport(exportNode, classDecl, ctx, state) {
|
|
|
113
136
|
state.ms.appendLeft(
|
|
114
137
|
exportNode.end,
|
|
115
138
|
`
|
|
116
|
-
export const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${
|
|
139
|
+
export const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${renamedClass});
|
|
117
140
|
`
|
|
118
141
|
);
|
|
119
142
|
state.wrappedClasses.add(className);
|
|
143
|
+
state.autoWrapped.add(className);
|
|
120
144
|
state.renamedLocals.add(className);
|
|
121
145
|
state.needsImport = true;
|
|
122
146
|
}
|
|
@@ -130,6 +154,7 @@ function wrapSpecifierExport(specifier, ctx, state) {
|
|
|
130
154
|
const localClass = localName ? state.topLevelClasses.get(localName) : void 0;
|
|
131
155
|
if (!localName || !localClass?.id) return;
|
|
132
156
|
state.wrappedClasses.add(exportedName);
|
|
157
|
+
state.autoWrapped.add(exportedName);
|
|
133
158
|
state.needsImport = true;
|
|
134
159
|
if (state.renamedLocals.has(localName)) return;
|
|
135
160
|
state.renamedLocals.add(localName);
|
|
@@ -138,7 +163,7 @@ function wrapSpecifierExport(specifier, ctx, state) {
|
|
|
138
163
|
state.ms.appendLeft(
|
|
139
164
|
localClass.end,
|
|
140
165
|
`
|
|
141
|
-
const ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${
|
|
166
|
+
const ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${renamedClass});
|
|
142
167
|
`
|
|
143
168
|
);
|
|
144
169
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform.js","sources":["../../../../src/vite/transform.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode {\n type: string;\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: unknown;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles both `export class MyDO {}` and the specifier form\n * (`class MyDO {}` … `export { MyDO }` / `export { Foo as MyDO }`).\n * Re-exports from other modules (`export { MyDO } from './do'`) cannot be\n * wrapped here and are left alone — the plugin warns about them via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n renamedLocals: new Set<string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(\"import * as __SENTRY__ from '@sentry/cloudflare';\\n\");\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level (non-exported) class declarations, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class names already renamed + wrapped, so two specifiers pointing at\n * the same class don't produce duplicate bindings.\n */\n renamedLocals: Set<string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n if (configured === 'durableObject' && localName && state.agentClasses.has(localName)) return 'agent';\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`.\n if (decl.type === 'Identifier' && state.renamedLocals.has((decl as IdentifierNode).name)) return;\n\n // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${ctx.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export of a local class (`export { Foo as MyDO }`) ----\n // Re-exports from another module carry a `source` — nothing local to wrap.\n if (node.source) return;\n for (const specifier of node.specifiers ?? []) {\n wrapSpecifierExport(specifier, ctx, state);\n }\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n const renamedClass = `__SENTRY_ORIGINAL_${className}__`;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n // Rename the class to avoid a duplicate binding\n state.ms.overwrite(classId.start, classId.end, renamedClass);\n\n // Insert the wrapped re-export after the class body\n state.ms.appendLeft(\n exportNode.end,\n `\\nexport const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n\n state.wrappedClasses.add(className);\n state.renamedLocals.add(className);\n state.needsImport = true;\n}\n\nfunction wrapSpecifierExport(specifier: ExportSpecifierNode, ctx: TransformContext, state: TransformState): void {\n if (specifier.type !== 'ExportSpecifier' || specifier.exported?.type !== 'Identifier') return;\n const exportedName = specifier.exported.name;\n if (!exportedName) return;\n\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n const kind = resolveWrapperKind(exportedName, localName, state);\n if (!kind) return;\n\n const localClass = localName ? state.topLevelClasses.get(localName) : undefined;\n if (!localName || !localClass?.id) return;\n\n state.wrappedClasses.add(exportedName);\n state.needsImport = true;\n if (state.renamedLocals.has(localName)) return;\n state.renamedLocals.add(localName);\n\n const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;\n state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);\n // The existing `export { ... }` statement keeps exporting the (now\n // wrapped) `localName` binding, so the wrapper is NOT exported here.\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});\\n`,\n );\n}\n"],"names":[],"mappings":";;;AA4DA,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;AAC5C,EAAA,IAAI,CAAC,QAAQ,OAAO,KAAA;AACpB,EAAA,IAAI,OAAO,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,IAAA,KAAS,YAAY,OAAO,IAAA;AACvE,EAAA,OACE,MAAA,CAAO,SAAS,kBAAA,IAAsB,MAAA,CAAO,UAAU,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,QAAA,CAAS,IAAA,KAAS,UAAA;AAE7G;AAoBA,MAAM,eAAA,GAAoD;AAAA,EACxD,aAAA,EAAe,mCAAA;AAAA,EACf,KAAA,EAAO,2BAAA;AAAA,EACP,QAAA,EAAU,8BAAA;AAAA,EACV,gBAAA,EAAkB;AACpB,CAAA;AA8CO,SAAS,6BAAA,CACd,IAAA,EACA,GAAA,EACA,GAAA,EAC6B;AAC7B,EAAA,MAAM,EAAA,GAAK,IAAI,WAAA,CAAY,IAAI,CAAA;AAC/B,EAAA,MAAM,eAAA,GAAkB,uBAAuB,GAAG,CAAA;AAClD,EAAA,MAAM,KAAA,GAAwB;AAAA,IAC5B,EAAA;AAAA,IACA,WAAA,EAAa,KAAA;AAAA,IACb,cAAA,sBAAoB,GAAA,EAAY;AAAA,IAChC,eAAA;AAAA,IACA,aAAA,sBAAmB,GAAA,EAAY;AAAA,IAC/B,eAAe,GAAA,CAAI,aAAA;AAAA,IACnB,YAAA,EAAc,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,YAAY,SAAA,CAAU,KAAA,EAAO,SAAS,YAAA,GAAe,SAAA,CAAU,MAAM,IAAA,GAAO,MAAA;AAClF,EAAA,MAAM,IAAA,GAAO,kBAAA,CAAmB,YAAA,EAAc,SAAA,EAAW,KAAK,CAAA;AAC9D,EAAA,IAAI,CAAC,IAAA,EAAM;AAEX,EAAA,MAAM,aAAa,SAAA,GAAY,KAAA,CAAM,eAAA,CAAgB,GAAA,CAAI,SAAS,CAAA,GAAI,MAAA;AACtE,EAAA,IAAI,CAAC,SAAA,IAAa,CAAC,UAAA,EAAY,EAAA,EAAI;AAEnC,EAAA,KAAA,CAAM,cAAA,CAAe,IAAI,YAAY,CAAA;AACrC,EAAA,KAAA,CAAM,WAAA,GAAc,IAAA;AACpB,EAAA,IAAI,KAAA,CAAM,aAAA,CAAc,GAAA,CAAI,SAAS,CAAA,EAAG;AACxC,EAAA,KAAA,CAAM,aAAA,CAAc,IAAI,SAAS,CAAA;AAEjC,EAAA,MAAM,YAAA,GAAe,qBAAqB,SAAS,CAAA,EAAA,CAAA;AACnD,EAAA,KAAA,CAAM,EAAA,CAAG,UAAU,UAAA,CAAW,EAAA,CAAG,OAAO,UAAA,CAAW,EAAA,CAAG,KAAK,YAAY,CAAA;AAGvE,EAAA,KAAA,CAAM,EAAA,CAAG,UAAA;AAAA,IACP,UAAA,CAAW,GAAA;AAAA,IACX;AAAA,MAAA,EAAW,SAAS,iBAAiB,eAAA,CAAgB,IAAI,CAAC,CAAA,CAAA,EAAI,GAAA,CAAI,SAAS,CAAA,EAAA,EAAK,YAAY,CAAA;AAAA;AAAA,GAC9F;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"transform.js","sources":["../../../../src/vite/transform.ts"],"sourcesContent":["import MagicString from 'magic-string';\nimport { DEFAULT_EXPORT, type ExportName, type SameWorkerBinding } from './wranglerConfig';\nimport { detectWorkerEntrypointClasses } from './workerEntrypoint';\n\nconst MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node types for the AST nodes we inspect.\n// ---------------------------------------------------------------------------\n\nexport interface BaseNode {\n type: string;\n start: number;\n end: number;\n}\n\nexport interface ProgramBody {\n body: BaseNode[];\n}\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface CalleeNode {\n type: string;\n name?: string;\n property?: { type: string; name?: string };\n}\n\ninterface CallExpressionNode extends BaseNode {\n callee?: CalleeNode;\n}\n\ninterface ClassDeclarationNode extends BaseNode {\n id?: IdentifierNode | null;\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportSpecifierNode {\n type: string;\n local?: { type: string; name?: string };\n exported?: { type: string; name?: string };\n}\n\ninterface ExportNamedNode extends BaseNode {\n declaration?: BaseNode | null;\n source?: unknown;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface VariableDeclaratorNode {\n id?: { type: string; name?: string };\n init?: BaseNode | null;\n}\n\ninterface VariableDeclarationNode extends BaseNode {\n declarations?: VariableDeclaratorNode[];\n}\n\nfunction isCallToMethod(node: BaseNode, methodName: string): boolean {\n if (node.type !== 'CallExpression') return false;\n const callee = (node as CallExpressionNode).callee;\n if (!callee) return false;\n if (callee.type === 'Identifier' && callee.name === methodName) return true;\n return (\n callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName\n );\n}\n\n/**\n * The kind of Sentry wrapper to apply to an exported class.\n *\n * `durableObject` and `workflow` are keyed by name from the wrangler config\n * (`durable_objects.bindings`, `workflows`), since those class names are\n * authoritative there. `workerEntrypoint` is different: a worker's own\n * entrypoints aren't enumerated in its config, so they're detected structurally\n * (a class extending `WorkerEntrypoint` from `cloudflare:workers`), with the\n * config providing only a fallback for self-bound entrypoints whose base class\n * lives in another module.\n */\nexport type ClassWrapperKind = 'durableObject' | 'agent' | 'workflow' | 'workerEntrypoint';\n\n/**\n * The `@sentry/cloudflare` helper each wrapper kind emits. All share the same\n * `(optionsCallback, Class)` signature. `WorkerEntrypoint` classes use\n * `withSentry`, which runtime-detects the class type and routes accordingly.\n */\nconst WRAPPER_METHODS: Record<ClassWrapperKind, string> = {\n durableObject: 'instrumentDurableObjectWithSentry',\n agent: 'instrumentAgentWithSentry',\n workflow: 'instrumentWorkflowWithSentry',\n workerEntrypoint: 'withSentry',\n};\n\nexport interface TransformContext {\n /**\n * Exported class name → the kind of Sentry wrapper to apply. Populated from\n * the wrangler config, so the transform can wrap by name without resolving\n * each class's base type.\n */\n classWrappers: Map<string, ClassWrapperKind>;\n /**\n * Local class names detected as `agents` Agents. An Agent is configured as a Durable Object in\n * wrangler, so this upgrades those entries from `durableObject` to `agent`.\n */\n agentClasses?: ReadonlySet<string>;\n optionsFn: string;\n /** Import statement prepended when `optionsFn` references a separate module. */\n optionsImport?: string;\n /** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */\n sameWorkerBindings?: readonly SameWorkerBinding[];\n}\n\nexport interface TransformResult {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n /**\n * The configured class names that were actually wrapped. Lets the plugin warn\n * about configured classes it could not find, instead of silently leaving\n * them uninstrumented.\n */\n wrappedClasses: Set<string>;\n}\n\n/**\n * Rewrite the worker entry source to wrap its default export with `withSentry`\n * and any configured class export with its matching Sentry wrapper (see\n * {@link TransformContext.classWrappers}, e.g. Durable Object classes with\n * `instrumentDurableObjectWithSentry`).\n *\n * Handles both `export class MyDO {}` and the specifier form\n * (`class MyDO {}` … `export { MyDO }` / `export { Foo as MyDO }`).\n * Re-exports from other modules (`export { MyDO } from './do'`) cannot be\n * wrapped here and are left alone — the plugin warns about them via\n * {@link TransformResult.wrappedClasses}.\n *\n * Exported (rather than inlined into the plugin) so it can be unit-tested with a\n * plain AST and no Vite context. Returns `undefined` when nothing was wrapped and\n * there are no already-manually-wrapped classes to report.\n */\nexport function applyAutoInstrumentTransforms(\n code: string,\n ast: ProgramBody,\n ctx: TransformContext,\n): TransformResult | undefined {\n const ms = new MagicString(code);\n const topLevelClasses = collectTopLevelClasses(ast);\n const sameWorkerBindings = ctx.sameWorkerBindings ?? [];\n const state: TransformState = {\n ms,\n needsImport: false,\n wrappedClasses: new Set<string>(),\n topLevelClasses,\n renamedLocals: new Set<string>(),\n classWrappers: ctx.classWrappers,\n agentClasses: ctx.agentClasses ?? new Set<string>(),\n workerEntrypointClasses: detectWorkerEntrypointClasses(ast),\n // The identifier must be chosen before wrapping, which bindings survive is only known after.\n optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,\n autoWrapped: new Set<ExportName>(),\n };\n const { wrappedClasses } = state;\n\n // Named exports first, regardless of source order: the default-export handler\n // needs to know which local bindings a named export already wrapped, so it can\n // skip a class that is both exported by name and re-exported as default (which\n // would otherwise wrap it twice).\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n handleNamedExport(node, ctx, state);\n }\n }\n for (const node of ast.body) {\n if (node.type === 'ExportDefaultDeclaration') {\n wrapDefaultExport(node as ExportDefaultNode, ctx, state);\n }\n }\n\n if (!state.needsImport) {\n // Nothing was rewritten. Still surface any classes found already wrapped\n // manually (via `wrappedClasses`) so the caller doesn't warn about them;\n // return undefined only when there was nothing to report either.\n if (wrappedClasses.size === 0) return undefined;\n return { code, map: ms.generateMap({ hires: true }), wrappedClasses };\n }\n\n // `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.\n if (sameWorkerBindings.length > 0) {\n ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));\n }\n if (ctx.optionsImport) ms.prepend(ctx.optionsImport);\n ms.prepend(\"import * as __SENTRY__ from '@sentry/cloudflare';\\n\");\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n wrappedClasses,\n };\n}\n\ninterface TransformState {\n ms: MagicString;\n needsImport: boolean;\n wrappedClasses: Set<string>;\n /**\n * Top-level (non-exported) class declarations, so specifier exports like\n * `export { MyDO }` can locate the class they refer to.\n */\n topLevelClasses: Map<string, ClassDeclarationNode>;\n /**\n * Local class names already renamed + wrapped, so two specifiers pointing at\n * the same class don't produce duplicate bindings.\n */\n renamedLocals: Set<string>;\n /** Class name → wrapper kind, keyed by the *exported* name (from config). */\n classWrappers: Map<string, ClassWrapperKind>;\n /** Local class names detected as `agents` Agents (see {@link TransformContext.agentClasses}). */\n agentClasses: ReadonlySet<string>;\n /**\n * Local class names detected as `WorkerEntrypoint` subclasses in this module,\n * so they can be wrapped without a config entry.\n */\n workerEntrypointClasses: Set<string>;\n optionsFn: string;\n /**\n * Export names wrapped by this transform, so their options can be extended with\n * `rpcTracePropagationBindings`. Hand-wrapped exports stay out, they keep the options they were\n * wrapped with. `wrappedClasses` counts both.\n */\n autoWrapped: Set<ExportName>;\n}\n\n/**\n * Builds the callback that merges same-worker binding names into `rpcTracePropagationBindings` at\n * runtime, the options object only exists once the callback runs with `env`. Only bindings whose\n * class this transform wrapped survive, a hand-wrapped class runs on its own options.\n */\nfunction buildMergedOptionsDeclaration(\n sameWorkerBindings: readonly SameWorkerBinding[],\n optionsFn: string,\n state: TransformState,\n): string {\n const bindingNames = sameWorkerBindings\n .filter(({ className }) => state.autoWrapped.has(className))\n .map(({ bindingName }) => bindingName);\n\n if (!bindingNames.length) {\n return `const ${MERGED_OPTIONS_IDENTIFIER} = ${optionsFn};\\n`;\n }\n\n const names = bindingNames.map(name => JSON.stringify(name)).join(', ');\n return (\n `const ${MERGED_OPTIONS_IDENTIFIER} = (env) => { ` +\n `const opts = (${optionsFn})(env); ` +\n `return { ...opts, rpcTracePropagationBindings: [${names}, ...(opts?.rpcTracePropagationBindings ?? [])] }; };\\n`\n );\n}\n\n/**\n * Resolve the wrapper kind for a class export.\n *\n * Config (`classWrappers`) wins — it's authoritative for Durable Objects and\n * Workflows, and provides the self-binding fallback for WorkerEntrypoints whose\n * base class this module can't see. Otherwise a structurally-detected\n * `WorkerEntrypoint` subclass (matched by its *local* name) gets wrapped with\n * `withSentry`.\n *\n * The one case where config is refined rather than obeyed is an `agents` Agent:\n * it *is* a Durable Object, so wrangler can only ever describe it as one, and\n * only the detected base chain distinguishes the two.\n */\nfunction resolveWrapperKind(\n exportedName: string,\n localName: string | undefined,\n state: TransformState,\n): ClassWrapperKind | undefined {\n const configured = state.classWrappers.get(exportedName);\n if (configured === 'durableObject' && localName && state.agentClasses.has(localName)) return 'agent';\n if (configured) return configured;\n if (localName && state.workerEntrypointClasses.has(localName)) return 'workerEntrypoint';\n return undefined;\n}\n\nfunction collectTopLevelClasses(ast: ProgramBody): Map<string, ClassDeclarationNode> {\n const classes = new Map<string, ClassDeclarationNode>();\n for (const node of ast.body) {\n if (node.type !== 'ClassDeclaration') continue;\n const classNode = node as ClassDeclarationNode;\n if (classNode.id?.name) classes.set(classNode.id.name, classNode);\n }\n return classes;\n}\n\nfunction wrapDefaultExport(node: ExportDefaultNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // Already wrapped — leave it alone\n if (isCallToMethod(decl, 'withSentry')) return;\n\n // `export default Foo` where `Foo` is a local class already wrapped by a named\n // export (e.g. a self-bound WorkerEntrypoint also used as the default handler).\n // Wrapping again would produce `withSentry(withSentry(...))`. The binding still\n // points at the wrapped class, so the default export counts as auto-wrapped.\n if (decl.type === 'Identifier' && state.renamedLocals.has((decl as IdentifierNode).name)) {\n state.autoWrapped.add(DEFAULT_EXPORT);\n return;\n }\n\n // `export default <expr>` → `const __SENTRY_DEFAULT_EXPORT__ = <expr>`\n // MagicString positions are always relative to the original source.\n state.ms.overwrite(node.start, decl.start, 'const __SENTRY_DEFAULT_EXPORT__ = ');\n state.ms.append(`\\nexport default __SENTRY__.withSentry(${state.optionsFn}, __SENTRY_DEFAULT_EXPORT__);\\n`);\n state.needsImport = true;\n state.autoWrapped.add(DEFAULT_EXPORT);\n}\n\nfunction handleNamedExport(node: ExportNamedNode, ctx: TransformContext, state: TransformState): void {\n const decl = node.declaration;\n\n // ---- Manually wrapped class export ----\n // `export const MyDO = instrumentDurableObjectWithSentry(...)` — count it\n // as wrapped so the plugin doesn't warn about it, but leave it alone.\n if (decl?.type === 'VariableDeclaration') {\n collectManuallyWrappedClassExports(decl, ctx, state);\n return;\n }\n\n // ---- Named class export matching a configured binding ----\n if (decl?.type === 'ClassDeclaration') {\n wrapInlineClassExport(node, decl, ctx, state);\n return;\n }\n\n // ---- Specifier export of a local class (`export { Foo as MyDO }`) ----\n // Re-exports from another module carry a `source` — nothing local to wrap.\n if (node.source) return;\n for (const specifier of node.specifiers ?? []) {\n wrapSpecifierExport(specifier, ctx, state);\n }\n}\n\nfunction collectManuallyWrappedClassExports(\n varDecl: VariableDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n for (const declarator of varDecl.declarations ?? []) {\n const name = declarator.id?.type === 'Identifier' ? declarator.id.name : undefined;\n const kind = name ? ctx.classWrappers.get(name) : undefined;\n if (!name || !kind || !declarator.init) continue;\n\n // A hand-wrapped Agent is configured as a Durable Object, so accept either helper there —\n // otherwise an already-instrumented Agent would be reported as unwrapped.\n const accepted =\n kind === 'durableObject' ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];\n\n if (accepted.some(method => isCallToMethod(declarator.init as BaseNode, method))) {\n state.wrappedClasses.add(name);\n }\n }\n}\n\nfunction wrapInlineClassExport(\n exportNode: ExportNamedNode,\n classDecl: ClassDeclarationNode,\n ctx: TransformContext,\n state: TransformState,\n): void {\n const classId = classDecl.id;\n // Inline export: the exported name and the local class name are the same.\n const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : undefined;\n if (!classId || !kind) return;\n\n const className = classId.name;\n const renamedClass = `__SENTRY_ORIGINAL_${className}__`;\n\n // Strip the `export ` keyword\n state.ms.overwrite(exportNode.start, classDecl.start, '');\n\n // Rename the class to avoid a duplicate binding\n state.ms.overwrite(classId.start, classId.end, renamedClass);\n\n // Insert the wrapped re-export after the class body\n state.ms.appendLeft(\n exportNode.end,\n `\\nexport const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${renamedClass});\\n`,\n );\n\n state.wrappedClasses.add(className);\n state.autoWrapped.add(className);\n state.renamedLocals.add(className);\n state.needsImport = true;\n}\n\nfunction wrapSpecifierExport(specifier: ExportSpecifierNode, ctx: TransformContext, state: TransformState): void {\n if (specifier.type !== 'ExportSpecifier' || specifier.exported?.type !== 'Identifier') return;\n const exportedName = specifier.exported.name;\n if (!exportedName) return;\n\n const localName = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;\n const kind = resolveWrapperKind(exportedName, localName, state);\n if (!kind) return;\n\n const localClass = localName ? state.topLevelClasses.get(localName) : undefined;\n if (!localName || !localClass?.id) return;\n\n state.wrappedClasses.add(exportedName);\n state.autoWrapped.add(exportedName);\n state.needsImport = true;\n if (state.renamedLocals.has(localName)) return;\n state.renamedLocals.add(localName);\n\n const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;\n state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);\n // The existing `export { ... }` statement keeps exporting the (now\n // wrapped) `localName` binding, so the wrapper is NOT exported here.\n state.ms.appendLeft(\n localClass.end,\n `\\nconst ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsFn}, ${renamedClass});\\n`,\n );\n}\n"],"names":[],"mappings":";;;;AAIA,MAAM,yBAAA,GAA4B,oBAAA;AA2DlC,SAAS,cAAA,CAAe,MAAgB,UAAA,EAA6B;AACnE,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,gBAAA,EAAkB,OAAO,KAAA;AAC3C,EAAA,MAAM,SAAU,IAAA,CAA4B,MAAA;AAC5C,EAAA,IAAI,CAAC,QAAQ,OAAO,KAAA;AACpB,EAAA,IAAI,OAAO,IAAA,KAAS,YAAA,IAAgB,MAAA,CAAO,IAAA,KAAS,YAAY,OAAO,IAAA;AACvE,EAAA,OACE,MAAA,CAAO,SAAS,kBAAA,IAAsB,MAAA,CAAO,UAAU,IAAA,KAAS,YAAA,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MAAM,YAAA,GAAe,qBAAqB,SAAS,CAAA,EAAA,CAAA;AACnD,EAAA,KAAA,CAAM,EAAA,CAAG,UAAU,UAAA,CAAW,EAAA,CAAG,OAAO,UAAA,CAAW,EAAA,CAAG,KAAK,YAAY,CAAA;AAGvE,EAAA,KAAA,CAAM,EAAA,CAAG,UAAA;AAAA,IACP,UAAA,CAAW,GAAA;AAAA,IACX;AAAA,MAAA,EAAW,SAAS,iBAAiB,eAAA,CAAgB,IAAI,CAAC,CAAA,CAAA,EAAI,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,YAAY,CAAA;AAAA;AAAA,GAChG;AACF;;;;"}
|
|
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
|
|
|
2
2
|
import { resolve, dirname } from 'node:path';
|
|
3
3
|
import { unstable_readConfig } from 'wrangler';
|
|
4
4
|
|
|
5
|
+
const DEFAULT_EXPORT = /* @__PURE__ */ Symbol("defaultExport");
|
|
5
6
|
function resolveWranglerConfig(root, explicitPath) {
|
|
6
7
|
const configPath = explicitPath ? resolve(root, explicitPath) : ["wrangler.json", "wrangler.jsonc", "wrangler.toml"].map((name) => resolve(root, name)).find(existsSync);
|
|
7
8
|
if (!configPath || !existsSync(configPath)) {
|
|
@@ -18,7 +19,8 @@ function resolveWranglerConfig(root, explicitPath) {
|
|
|
18
19
|
main: raw.main,
|
|
19
20
|
durableObjects: collectClassBindings(raw.durable_objects?.bindings),
|
|
20
21
|
workflows: collectClassBindings(raw.workflows),
|
|
21
|
-
workerEntrypoints: collectSelfBoundEntrypoints(raw)
|
|
22
|
+
workerEntrypoints: collectSelfBoundEntrypoints(raw),
|
|
23
|
+
sameWorkerBindings: collectSameWorkerBindings(raw)
|
|
22
24
|
},
|
|
23
25
|
configDir: dirname(raw.configPath ?? configPath)
|
|
24
26
|
};
|
|
@@ -35,6 +37,23 @@ function collectSelfBoundEntrypoints(raw) {
|
|
|
35
37
|
}
|
|
36
38
|
return [...entrypoints];
|
|
37
39
|
}
|
|
40
|
+
function collectSameWorkerBindings(raw) {
|
|
41
|
+
const bindings = [];
|
|
42
|
+
for (const binding of raw.durable_objects?.bindings ?? []) {
|
|
43
|
+
if (typeof binding?.name === "string" && typeof binding.class_name === "string" && !binding.script_name) {
|
|
44
|
+
bindings.push({ bindingName: binding.name, className: binding.class_name });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
for (const binding of raw.services ?? []) {
|
|
48
|
+
if (raw.name && binding?.service === raw.name && typeof binding.binding === "string") {
|
|
49
|
+
bindings.push({
|
|
50
|
+
bindingName: binding.binding,
|
|
51
|
+
className: typeof binding.entrypoint === "string" ? binding.entrypoint : DEFAULT_EXPORT
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return bindings;
|
|
56
|
+
}
|
|
38
57
|
function collectClassBindings(bindings) {
|
|
39
58
|
const result = [];
|
|
40
59
|
const seenClassNames = /* @__PURE__ */ new Set();
|
|
@@ -48,5 +67,5 @@ function collectClassBindings(bindings) {
|
|
|
48
67
|
return result;
|
|
49
68
|
}
|
|
50
69
|
|
|
51
|
-
export { resolveWranglerConfig };
|
|
70
|
+
export { DEFAULT_EXPORT, resolveWranglerConfig };
|
|
52
71
|
//# sourceMappingURL=wranglerConfig.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wranglerConfig.js","sources":["../../../../src/vite/wranglerConfig.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { type Unstable_Config, unstable_readConfig } from 'wrangler';\n\n/**\n * The slice of the wrangler configuration the auto-instrument plugin cares\n * about. `main` is an absolute path (wrangler resolves it against the config\n * file's directory).\n */\nexport interface WranglerConfig {\n main?: string;\n durableObjects: Array<{ name: string; className: string }>;\n workflows: Array<{ name: string; className: string }>;\n /**\n * Named `WorkerEntrypoint` exports this worker binds to itself via a service\n * binding (`services[]` whose `service` is this worker's own `name`). Only\n * self-bindings appear here: a service binding's `entrypoint` otherwise names\n * an export on a *different* worker, which this build can't wrap.\n */\n workerEntrypoints: string[];\n}\n\n/**\n * Locate and resolve the wrangler configuration via wrangler's own\n * `unstable_readConfig` — the API `@cloudflare/vite-plugin` uses.\n *\n * We only locate the file (probing `wrangler.json`, `.jsonc`, `.toml` inside\n * `root` with wrangler's own precedence, since it discovers from `cwd` rather\n * than an arbitrary root); wrangler then parses it, flattens the active\n * environment (honoring `CLOUDFLARE_ENV`), and resolves `main` to an absolute\n * path. Durable Object and Workflow bindings are the active environment's,\n * matching what the deployed Worker actually binds.\n *\n * Returns `undefined` when no config file is found or it can't be read/parsed\n * (the caller warns and disables auto-instrumentation rather than failing the\n * whole build).\n */\nexport function resolveWranglerConfig(\n root: string,\n explicitPath?: string,\n): { config: WranglerConfig; configDir: string } | undefined {\n const configPath = explicitPath\n ? resolve(root, explicitPath)\n : ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'].map(name => resolve(root, name)).find(existsSync);\n\n if (!configPath || !existsSync(configPath)) {\n return undefined;\n }\n\n let raw: Unstable_Config;\n try {\n // `hideWarnings` keeps wrangler's config diagnostics (e.g. missing DO\n // migrations) out of the Vite build output.\n raw = unstable_readConfig({ config: configPath }, { hideWarnings: true });\n } catch {\n return undefined;\n }\n\n return {\n config: {\n main: raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n },\n configDir: dirname(raw.configPath ?? configPath),\n };\n}\n\n/**\n * Collect named `WorkerEntrypoint` exports the worker binds to itself. A service\n * binding's `entrypoint` normally names an export on the *target* worker, so it\n * is only ours when `service` equals this worker's own `name`. Without a `name`\n * there is nothing to match against, so no entrypoints are derivable.\n */\nfunction collectSelfBoundEntrypoints(raw: Unstable_Config): string[] {\n if (!raw.name) {\n return [];\n }\n const entrypoints = new Set<string>();\n for (const binding of raw.services ?? []) {\n if (binding?.service === raw.name && typeof binding.entrypoint === 'string') {\n entrypoints.add(binding.entrypoint);\n }\n }\n return [...entrypoints];\n}\n\n/**\n * Map wrangler class bindings (Durable Objects, Workflows — same shape) to the\n * `{ name, className }` the transform needs, skipping duplicates and bindings\n * with a `script_name` (those reference a class exported by a *different*\n * worker, so there is nothing to wrap in this worker's entry file).\n */\nfunction collectClassBindings(\n bindings: ReadonlyArray<{ name: string; class_name?: string; script_name?: string }> | undefined,\n): Array<{ name: string; className: string }> {\n const result: Array<{ name: string; className: string }> = [];\n const seenClassNames = new Set<string>();\n for (const binding of bindings ?? []) {\n if (typeof binding?.class_name !== 'string' || binding.script_name || seenClassNames.has(binding.class_name)) {\n continue;\n }\n seenClassNames.add(binding.class_name);\n result.push({ name: binding.name, className: binding.class_name });\n }\n return result;\n}\n"],"names":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"wranglerConfig.js","sources":["../../../../src/vite/wranglerConfig.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { type Unstable_Config, unstable_readConfig } from 'wrangler';\n\n/**\n * The slice of the wrangler configuration the auto-instrument plugin cares\n * about. `main` is an absolute path (wrangler resolves it against the config\n * file's directory).\n */\nexport interface WranglerConfig {\n main?: string;\n durableObjects: Array<{ name: string; className: string }>;\n workflows: Array<{ name: string; className: string }>;\n /**\n * Named `WorkerEntrypoint` exports this worker binds to itself via a service\n * binding (`services[]` whose `service` is this worker's own `name`). Only\n * self-bindings appear here: a service binding's `entrypoint` otherwise names\n * an export on a *different* worker, which this build can't wrap.\n */\n workerEntrypoints: string[];\n /**\n * Bindings whose RPC receiver lives in this worker, so this build instruments it. Not deduped by\n * class, two bindings may point at the same class and both names have to be listed.\n */\n sameWorkerBindings: SameWorkerBinding[];\n}\n\n/** Stands in for a class name where a binding targets the module's default export. */\nexport const DEFAULT_EXPORT = Symbol('defaultExport');\n\n/** The name a binding or an export is known by, either an exported class name or the default export. */\nexport type ExportName = string | typeof DEFAULT_EXPORT;\n\nexport interface SameWorkerBinding {\n bindingName: string;\n className: ExportName;\n}\n\n/**\n * Locate and resolve the wrangler configuration via wrangler's own\n * `unstable_readConfig` — the API `@cloudflare/vite-plugin` uses.\n *\n * We only locate the file (probing `wrangler.json`, `.jsonc`, `.toml` inside\n * `root` with wrangler's own precedence, since it discovers from `cwd` rather\n * than an arbitrary root); wrangler then parses it, flattens the active\n * environment (honoring `CLOUDFLARE_ENV`), and resolves `main` to an absolute\n * path. Durable Object and Workflow bindings are the active environment's,\n * matching what the deployed Worker actually binds.\n *\n * Returns `undefined` when no config file is found or it can't be read/parsed\n * (the caller warns and disables auto-instrumentation rather than failing the\n * whole build).\n */\nexport function resolveWranglerConfig(\n root: string,\n explicitPath?: string,\n): { config: WranglerConfig; configDir: string } | undefined {\n const configPath = explicitPath\n ? resolve(root, explicitPath)\n : ['wrangler.json', 'wrangler.jsonc', 'wrangler.toml'].map(name => resolve(root, name)).find(existsSync);\n\n if (!configPath || !existsSync(configPath)) {\n return undefined;\n }\n\n let raw: Unstable_Config;\n try {\n // `hideWarnings` keeps wrangler's config diagnostics (e.g. missing DO\n // migrations) out of the Vite build output.\n raw = unstable_readConfig({ config: configPath }, { hideWarnings: true });\n } catch {\n return undefined;\n }\n\n return {\n config: {\n main: raw.main,\n durableObjects: collectClassBindings(raw.durable_objects?.bindings),\n workflows: collectClassBindings(raw.workflows),\n workerEntrypoints: collectSelfBoundEntrypoints(raw),\n sameWorkerBindings: collectSameWorkerBindings(raw),\n },\n configDir: dirname(raw.configPath ?? configPath),\n };\n}\n\n/**\n * Collect named `WorkerEntrypoint` exports the worker binds to itself. A service\n * binding's `entrypoint` normally names an export on the *target* worker, so it\n * is only ours when `service` equals this worker's own `name`. Without a `name`\n * there is nothing to match against, so no entrypoints are derivable.\n */\nfunction collectSelfBoundEntrypoints(raw: Unstable_Config): string[] {\n if (!raw.name) {\n return [];\n }\n const entrypoints = new Set<string>();\n for (const binding of raw.services ?? []) {\n if (binding?.service === raw.name && typeof binding.entrypoint === 'string') {\n entrypoints.add(binding.entrypoint);\n }\n }\n return [...entrypoints];\n}\n\n/**\n * Bindings with a `script_name` or naming another worker target a class this build does not wrap,\n * so they are excluded and stay opt-in.\n */\nfunction collectSameWorkerBindings(raw: Unstable_Config): SameWorkerBinding[] {\n const bindings: SameWorkerBinding[] = [];\n\n for (const binding of raw.durable_objects?.bindings ?? []) {\n if (typeof binding?.name === 'string' && typeof binding.class_name === 'string' && !binding.script_name) {\n bindings.push({ bindingName: binding.name, className: binding.class_name });\n }\n }\n\n for (const binding of raw.services ?? []) {\n // A service binding is only ours when `service` names this worker; without a `name` none can be.\n if (raw.name && binding?.service === raw.name && typeof binding.binding === 'string') {\n bindings.push({\n bindingName: binding.binding,\n className: typeof binding.entrypoint === 'string' ? binding.entrypoint : DEFAULT_EXPORT,\n });\n }\n }\n\n return bindings;\n}\n\n/**\n * Map wrangler class bindings (Durable Objects, Workflows — same shape) to the\n * `{ name, className }` the transform needs, skipping duplicates and bindings\n * with a `script_name` (those reference a class exported by a *different*\n * worker, so there is nothing to wrap in this worker's entry file).\n */\nfunction collectClassBindings(\n bindings: ReadonlyArray<{ name: string; class_name?: string; script_name?: string }> | undefined,\n): Array<{ name: string; className: string }> {\n const result: Array<{ name: string; className: string }> = [];\n const seenClassNames = new Set<string>();\n for (const binding of bindings ?? []) {\n if (typeof binding?.class_name !== 'string' || binding.script_name || seenClassNames.has(binding.class_name)) {\n continue;\n }\n seenClassNames.add(binding.class_name);\n result.push({ name: binding.name, className: binding.class_name });\n }\n return result;\n}\n"],"names":[],"mappings":";;;;AA4BO,MAAM,cAAA,0BAAwB,eAAe;AAyB7C,SAAS,qBAAA,CACd,MACA,YAAA,EAC2D;AAC3D,EAAA,MAAM,aAAa,YAAA,GACf,OAAA,CAAQ,MAAM,YAAY,CAAA,GAC1B,CAAC,eAAA,EAAiB,gBAAA,EAAkB,eAAe,CAAA,CAAE,GAAA,CAAI,UAAQ,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAC,CAAA,CAAE,KAA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