@sentry/cloudflare 10.67.0 → 10.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/build/cjs/client.js +5 -0
  2. package/build/cjs/client.js.map +1 -1
  3. package/build/cjs/defineCloudflareOptions.js +11 -0
  4. package/build/cjs/defineCloudflareOptions.js.map +1 -0
  5. package/build/cjs/durableobject.js +131 -96
  6. package/build/cjs/durableobject.js.map +1 -1
  7. package/build/cjs/index.js +6 -0
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/instrumentations/agents/index.js +14 -0
  10. package/build/cjs/instrumentations/agents/index.js.map +1 -0
  11. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js +52 -0
  12. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
  13. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js +31 -0
  14. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
  15. package/build/cjs/instrumentations/agents/types.js +32 -0
  16. package/build/cjs/instrumentations/agents/types.js.map +1 -0
  17. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +6 -0
  18. package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  19. package/build/cjs/instrumentations/instrumentSqlStorage.js +1 -1
  20. package/build/cjs/instrumentations/instrumentSqlStorage.js.map +1 -1
  21. package/build/cjs/integrations/spotlight.js +64 -0
  22. package/build/cjs/integrations/spotlight.js.map +1 -0
  23. package/build/cjs/integrations/tracing/vercelai.js.map +1 -1
  24. package/build/cjs/nodejs_compat/index.js +10 -4
  25. package/build/cjs/nodejs_compat/index.js.map +1 -1
  26. package/build/cjs/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
  27. package/build/cjs/options.js +14 -1
  28. package/build/cjs/options.js.map +1 -1
  29. package/build/cjs/sdk.js +20 -1
  30. package/build/cjs/sdk.js.map +1 -1
  31. package/build/cjs/utils/internalSqlQuery.js +13 -7
  32. package/build/cjs/utils/internalSqlQuery.js.map +1 -1
  33. package/build/cjs/utils/internalStorageKey.js +44 -0
  34. package/build/cjs/utils/internalStorageKey.js.map +1 -0
  35. package/build/cjs/vite/agentClass.js +114 -0
  36. package/build/cjs/vite/agentClass.js.map +1 -0
  37. package/build/cjs/vite/autoInstrument.js +94 -0
  38. package/build/cjs/vite/autoInstrument.js.map +1 -0
  39. package/build/cjs/vite/index.js +14 -0
  40. package/build/cjs/vite/index.js.map +1 -0
  41. package/build/cjs/vite/instrumentFile.js +31 -0
  42. package/build/cjs/vite/instrumentFile.js.map +1 -0
  43. package/build/cjs/vite/moduleShape.js +231 -0
  44. package/build/cjs/vite/moduleShape.js.map +1 -0
  45. package/build/cjs/vite/transform.js +149 -0
  46. package/build/cjs/vite/transform.js.map +1 -0
  47. package/build/cjs/vite/workerEntrypoint.js +66 -0
  48. package/build/cjs/vite/workerEntrypoint.js.map +1 -0
  49. package/build/cjs/vite/wranglerConfig.js +54 -0
  50. package/build/cjs/vite/wranglerConfig.js.map +1 -0
  51. package/build/esm/client.js +6 -1
  52. package/build/esm/client.js.map +1 -1
  53. package/build/esm/defineCloudflareOptions.js +9 -0
  54. package/build/esm/defineCloudflareOptions.js.map +1 -0
  55. package/build/esm/durableobject.js +129 -97
  56. package/build/esm/durableobject.js.map +1 -1
  57. package/build/esm/index.js +4 -2
  58. package/build/esm/index.js.map +1 -1
  59. package/build/esm/instrumentations/agents/index.js +12 -0
  60. package/build/esm/instrumentations/agents/index.js.map +1 -0
  61. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js +50 -0
  62. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
  63. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js +29 -0
  64. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
  65. package/build/esm/instrumentations/agents/types.js +26 -0
  66. package/build/esm/instrumentations/agents/types.js.map +1 -0
  67. package/build/esm/instrumentations/instrumentDurableObjectStorage.js +7 -1
  68. package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
  69. package/build/esm/instrumentations/instrumentSqlStorage.js +1 -1
  70. package/build/esm/instrumentations/instrumentSqlStorage.js.map +1 -1
  71. package/build/esm/integrations/spotlight.js +61 -0
  72. package/build/esm/integrations/spotlight.js.map +1 -0
  73. package/build/esm/integrations/tracing/vercelai.js.map +1 -1
  74. package/build/esm/nodejs_compat/index.js +5 -3
  75. package/build/esm/nodejs_compat/index.js.map +1 -1
  76. package/build/esm/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
  77. package/build/esm/options.js +14 -1
  78. package/build/esm/options.js.map +1 -1
  79. package/build/esm/package.json +1 -1
  80. package/build/esm/sdk.js +21 -2
  81. package/build/esm/sdk.js.map +1 -1
  82. package/build/esm/utils/internalSqlQuery.js +13 -7
  83. package/build/esm/utils/internalSqlQuery.js.map +1 -1
  84. package/build/esm/utils/internalStorageKey.js +41 -0
  85. package/build/esm/utils/internalStorageKey.js.map +1 -0
  86. package/build/esm/utils/traceLinks.js +1 -1
  87. package/build/esm/vite/agentClass.js +111 -0
  88. package/build/esm/vite/agentClass.js.map +1 -0
  89. package/build/esm/vite/autoInstrument.js +92 -0
  90. package/build/esm/vite/autoInstrument.js.map +1 -0
  91. package/build/esm/vite/index.js +12 -0
  92. package/build/esm/vite/index.js.map +1 -0
  93. package/build/esm/vite/instrumentFile.js +27 -0
  94. package/build/esm/vite/instrumentFile.js.map +1 -0
  95. package/build/esm/vite/moduleShape.js +227 -0
  96. package/build/esm/vite/moduleShape.js.map +1 -0
  97. package/build/esm/vite/transform.js +147 -0
  98. package/build/esm/vite/transform.js.map +1 -0
  99. package/build/esm/vite/workerEntrypoint.js +64 -0
  100. package/build/esm/vite/workerEntrypoint.js.map +1 -0
  101. package/build/esm/vite/wranglerConfig.js +52 -0
  102. package/build/esm/vite/wranglerConfig.js.map +1 -0
  103. package/build/types/client.d.ts +37 -0
  104. package/build/types/client.d.ts.map +1 -1
  105. package/build/types/defineCloudflareOptions.d.ts +38 -0
  106. package/build/types/defineCloudflareOptions.d.ts.map +1 -0
  107. package/build/types/durableobject.d.ts +81 -0
  108. package/build/types/durableobject.d.ts.map +1 -1
  109. package/build/types/index.d.ts +4 -2
  110. package/build/types/index.d.ts.map +1 -1
  111. package/build/types/instrumentations/agents/index.d.ts +24 -0
  112. package/build/types/instrumentations/agents/index.d.ts.map +1 -0
  113. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
  114. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts.map +1 -0
  115. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
  116. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts.map +1 -0
  117. package/build/types/instrumentations/agents/types.d.ts +49 -0
  118. package/build/types/instrumentations/agents/types.d.ts.map +1 -0
  119. package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts.map +1 -1
  120. package/build/types/integrations/spotlight.d.ts +22 -0
  121. package/build/types/integrations/spotlight.d.ts.map +1 -0
  122. package/build/types/integrations/tracing/vercelai.d.ts.map +1 -1
  123. package/build/types/nodejs_compat/index.d.ts +1 -1
  124. package/build/types/nodejs_compat/index.d.ts.map +1 -1
  125. package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts +1 -8
  126. package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts.map +1 -1
  127. package/build/types/options.d.ts.map +1 -1
  128. package/build/types/sdk.d.ts.map +1 -1
  129. package/build/types/utils/internalSqlQuery.d.ts +4 -2
  130. package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
  131. package/build/types/utils/internalStorageKey.d.ts +22 -0
  132. package/build/types/utils/internalStorageKey.d.ts.map +1 -0
  133. package/build/types/vite/agentClass.d.ts +41 -0
  134. package/build/types/vite/agentClass.d.ts.map +1 -0
  135. package/build/types/vite/autoInstrument.d.ts +22 -0
  136. package/build/types/vite/autoInstrument.d.ts.map +1 -0
  137. package/build/types/vite/index.d.ts +98 -0
  138. package/build/types/vite/index.d.ts.map +1 -0
  139. package/build/types/vite/instrumentFile.d.ts +22 -0
  140. package/build/types/vite/instrumentFile.d.ts.map +1 -0
  141. package/build/types/vite/moduleShape.d.ts +52 -0
  142. package/build/types/vite/moduleShape.d.ts.map +1 -0
  143. package/build/types/vite/transform.d.ts +65 -0
  144. package/build/types/vite/transform.d.ts.map +1 -0
  145. package/build/types/vite/workerEntrypoint.d.ts +12 -0
  146. package/build/types/vite/workerEntrypoint.d.ts.map +1 -0
  147. package/build/types/vite/wranglerConfig.d.ts +43 -0
  148. package/build/types/vite/wranglerConfig.d.ts.map +1 -0
  149. package/build/types-ts3.8/client.d.ts +37 -0
  150. package/build/types-ts3.8/defineCloudflareOptions.d.ts +38 -0
  151. package/build/types-ts3.8/durableobject.d.ts +81 -0
  152. package/build/types-ts3.8/index.d.ts +4 -2
  153. package/build/types-ts3.8/instrumentations/agents/index.d.ts +24 -0
  154. package/build/types-ts3.8/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
  155. package/build/types-ts3.8/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
  156. package/build/types-ts3.8/instrumentations/agents/types.d.ts +49 -0
  157. package/build/types-ts3.8/integrations/spotlight.d.ts +22 -0
  158. package/build/types-ts3.8/nodejs_compat/index.d.ts +1 -1
  159. package/build/types-ts3.8/nodejs_compat/integrations/tracing/vercelai.d.ts +7 -14
  160. package/build/types-ts3.8/utils/internalSqlQuery.d.ts +4 -2
  161. package/build/types-ts3.8/utils/internalStorageKey.d.ts +22 -0
  162. package/build/types-ts3.8/vite/agentClass.d.ts +41 -0
  163. package/build/types-ts3.8/vite/autoInstrument.d.ts +22 -0
  164. package/build/types-ts3.8/vite/index.d.ts +98 -0
  165. package/build/types-ts3.8/vite/instrumentFile.d.ts +22 -0
  166. package/build/types-ts3.8/vite/moduleShape.d.ts +52 -0
  167. package/build/types-ts3.8/vite/transform.d.ts +65 -0
  168. package/build/types-ts3.8/vite/workerEntrypoint.d.ts +12 -0
  169. package/build/types-ts3.8/vite/wranglerConfig.d.ts +43 -0
  170. package/package.json +19 -5
@@ -0,0 +1,92 @@
1
+ import { basename } from 'node:path';
2
+ import { collectAgentCandidates, detectAgentClasses } from './agentClass.js';
3
+ import { resolveInstrumentFile, buildOptionsImport, ENV_FALLBACK_OPTIONS_FN } from './instrumentFile.js';
4
+ import { applyAutoInstrumentTransforms } from './transform.js';
5
+ import { resolveWranglerConfig } from './wranglerConfig.js';
6
+
7
+ function normalizePath(path) {
8
+ return path.replace(/\\/g, "/");
9
+ }
10
+ const JS_EXTENSION_REGEX = /\.[cm]?[jt]sx?$/;
11
+ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
12
+ let wranglerConfig;
13
+ let entryFilePath;
14
+ let optionsFn = ENV_FALLBACK_OPTIONS_FN;
15
+ let optionsImport;
16
+ return {
17
+ name: "sentry-cloudflare-auto-instrument",
18
+ configResolved(config) {
19
+ const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);
20
+ if (!result) {
21
+ config.logger?.warn(
22
+ options.wranglerConfigPath ? `[sentry] Could not find or parse the wrangler config "${basename(options.wranglerConfigPath)}" (resolved against the Vite root) \u2014 auto-instrumentation disabled.` : "[sentry] No parseable wrangler config found \u2014 auto-instrumentation disabled. Set `wranglerConfigPath` if your config uses a custom name."
23
+ );
24
+ return;
25
+ }
26
+ wranglerConfig = result.config;
27
+ if (wranglerConfig.main) {
28
+ entryFilePath = normalizePath(wranglerConfig.main);
29
+ }
30
+ if (entryFilePath) {
31
+ const instrumentFilePath = resolveInstrumentFile(entryFilePath);
32
+ if (instrumentFilePath) {
33
+ const built = buildOptionsImport(entryFilePath, instrumentFilePath);
34
+ optionsFn = built.optionsFn;
35
+ optionsImport = built.importStmt;
36
+ }
37
+ }
38
+ },
39
+ async transform(code, id) {
40
+ if (!wranglerConfig || !entryFilePath) return void 0;
41
+ if (this.environment?.name === "client") return void 0;
42
+ const normalizedId = normalizePath(id.replace(/[?#].*$/, ""));
43
+ if (normalizedId !== entryFilePath) {
44
+ if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return void 0;
45
+ if (normalizedId.replace(JS_EXTENSION_REGEX, "") !== entryFilePath.replace(JS_EXTENSION_REGEX, "")) {
46
+ return void 0;
47
+ }
48
+ }
49
+ let ast;
50
+ try {
51
+ ast = this.parse(code);
52
+ } catch {
53
+ return void 0;
54
+ }
55
+ const classWrappers = /* @__PURE__ */ new Map();
56
+ for (const { className } of wranglerConfig.durableObjects) {
57
+ classWrappers.set(className, "durableObject");
58
+ }
59
+ for (const { className } of wranglerConfig.workflows) {
60
+ classWrappers.set(className, "workflow");
61
+ }
62
+ for (const className of wranglerConfig.workerEntrypoints) {
63
+ classWrappers.set(className, "workerEntrypoint");
64
+ }
65
+ const agentCandidates = collectAgentCandidates(
66
+ ast,
67
+ [...classWrappers].filter(([, kind]) => kind === "durableObject").map(([name]) => name)
68
+ );
69
+ const agentClasses = agentCandidates.size > 0 ? await detectAgentClasses(ast, normalizedId, agentCandidates, {
70
+ parse: (code2) => this.parse(code2),
71
+ resolve: this.resolve ? (source, importer) => this.resolve(source, importer) : void 0
72
+ }) : void 0;
73
+ const result = applyAutoInstrumentTransforms(code, ast, {
74
+ classWrappers,
75
+ agentClasses,
76
+ optionsFn,
77
+ optionsImport
78
+ });
79
+ const wrappedClasses = result?.wrappedClasses ?? /* @__PURE__ */ new Set();
80
+ const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
81
+ if (missing.length > 0) {
82
+ this.warn?.(
83
+ `[sentry] Could not auto-instrument class(es) ${missing.join(", ")}: no matching exported class declaration found in the worker entry (re-exports from other modules cannot be wrapped automatically). Wrap them manually with the matching \`instrument*WithSentry\` helper.`
84
+ );
85
+ }
86
+ return result ?? void 0;
87
+ }
88
+ };
89
+ }
90
+
91
+ export { sentryCloudflareAutoInstrumentPlugin };
92
+ //# sourceMappingURL=autoInstrument.js.map
@@ -0,0 +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 ?? 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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K,OAAA,CAAS,MAAA,EAAQ,QAAQ,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,OACD,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;;;;"}
@@ -0,0 +1,12 @@
1
+ import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
2
+ import { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument.js';
3
+
4
+ function sentryCloudflareVitePlugin(options = {}) {
5
+ return [
6
+ ...options._experimental?.useDiagnosticsChannelInjection ? [sentryOrchestrionPlugin({ injectChannelSubscribers: true })] : [],
7
+ ...options._experimental?.autoInstrumentation ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })] : []
8
+ ];
9
+ }
10
+
11
+ export { sentryCloudflareVitePlugin };
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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 * Experimental options that may change or be removed without notice.\n */\n _experimental?: {\n /**\n * Enables build-time automatic instrumentation of supported dependencies\n * (e.g. database clients like `mysql`) so the Sentry Cloudflare SDK can\n * trace them without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel`\n * calls into the bundled packages and, next to each, a snippet that\n * registers the matching Sentry channel-subscriber factory on the global\n * marker, which the SDK picks up in `Sentry.withSentry()`. Both `vite build`\n * and `vite dev` are instrumented.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n useDiagnosticsChannelInjection?: 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.\n *\n * @default false\n * @experimental May change or be removed in any release.\n */\n autoInstrumentation?: boolean;\n };\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. Configure the Sentry\n * SDK in your Worker as usual with `Sentry.withSentry()`.\n *\n * Currently, the only functionality is the experimental\n * `_experimental.useDiagnosticsChannelInjection` option, which traces supported\n * dependencies (such as database clients) without changing your application\n * code. Without it, the plugin is a no-op.\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: [\n * cloudflare(),\n * sentryCloudflareVitePlugin({\n * _experimental: {\n * useDiagnosticsChannelInjection: true,\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}) {\n return [\n ...(options._experimental?.useDiagnosticsChannelInjection\n ? [sentryOrchestrionPlugin({ injectChannelSubscribers: true })]\n : []),\n ...(options._experimental?.autoInstrumentation\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;AAwFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAAG;AAC1F,EAAA,OAAO;AAAA,IACL,GAAI,OAAA,CAAQ,aAAA,EAAe,8BAAA,GACvB,CAAC,uBAAA,CAAwB,EAAE,wBAAA,EAA0B,IAAA,EAAM,CAAC,CAAA,GAC5D,EAAC;AAAA,IACL,GAAI,OAAA,CAAQ,aAAA,EAAe,mBAAA,GACvB,CAAC,oCAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
@@ -0,0 +1,27 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, resolve, relative } from 'node:path';
3
+
4
+ const ENV_FALLBACK_OPTIONS_FN = "() => undefined";
5
+ const OPTIONS_IMPORT_IDENTIFIER = "__SENTRY_OPTIONS_CALLBACK__";
6
+ const INSTRUMENT_FILE_BASENAME = "instrument.server";
7
+ const INSTRUMENT_FILE_EXTENSIONS = ["ts", "mts", "js", "mjs", "cjs"];
8
+ function resolveInstrumentFile(entryFilePath) {
9
+ const dir = dirname(entryFilePath);
10
+ for (const ext of INSTRUMENT_FILE_EXTENSIONS) {
11
+ const candidate = resolve(dir, `${INSTRUMENT_FILE_BASENAME}.${ext}`);
12
+ if (existsSync(candidate)) return candidate;
13
+ }
14
+ return void 0;
15
+ }
16
+ function buildOptionsImport(entryFilePath, instrumentFilePath) {
17
+ let relativePath = relative(dirname(entryFilePath), instrumentFilePath).replace(/\\/g, "/");
18
+ if (!relativePath.startsWith(".")) relativePath = `./${relativePath}`;
19
+ return {
20
+ optionsFn: OPTIONS_IMPORT_IDENTIFIER,
21
+ importStmt: `import ${OPTIONS_IMPORT_IDENTIFIER} from '${relativePath}';
22
+ `
23
+ };
24
+ }
25
+
26
+ export { ENV_FALLBACK_OPTIONS_FN, buildOptionsImport, resolveInstrumentFile };
27
+ //# sourceMappingURL=instrumentFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentFile.js","sources":["../../../src/vite/instrumentFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, relative, resolve } from 'node:path';\n\n// Fallback options callback used when no instrument file is present. Returning\n// `undefined` makes the SDK read all configuration (DSN, release, environment,\n// sample rate, …) from the worker's `env` at runtime.\nexport const ENV_FALLBACK_OPTIONS_FN = '() => undefined';\n\n// Identifier the generated import binds the user's options module to.\nconst OPTIONS_IMPORT_IDENTIFIER = '__SENTRY_OPTIONS_CALLBACK__';\n\n// Conventional, non-configurable name of the Sentry options module. It is\n// looked up next to the worker entry file; its default export is the options\n// callback `(env) => CloudflareOptions`.\nconst INSTRUMENT_FILE_BASENAME = 'instrument.server';\nconst INSTRUMENT_FILE_EXTENSIONS = ['ts', 'mts', 'js', 'mjs', 'cjs'];\n\n/**\n * Locate the conventional `instrument.server.*` module sitting next to the\n * worker entry file. Returns its absolute path, or `undefined` when absent.\n */\nexport function resolveInstrumentFile(entryFilePath: string): string | undefined {\n const dir = dirname(entryFilePath);\n for (const ext of INSTRUMENT_FILE_EXTENSIONS) {\n const candidate = resolve(dir, `${INSTRUMENT_FILE_BASENAME}.${ext}`);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\n/**\n * Build the `optionsFn` reference and `import` statement for the instrument\n * module whose **default export** is the options callback\n * `(env) => CloudflareOptions`.\n *\n * The import is emitted relative to `entryFilePath` because it is injected into\n * the entry file's source. The file extension is kept: extensionless specifiers\n * only resolve for extensions in Vite's default `resolve.extensions` (which\n * excludes `.cjs`), and keeping it makes our probe order authoritative when\n * several `instrument.server.*` files coexist.\n */\nexport function buildOptionsImport(\n entryFilePath: string,\n instrumentFilePath: string,\n): { optionsFn: string; importStmt: string } {\n let relativePath = relative(dirname(entryFilePath), instrumentFilePath).replace(/\\\\/g, '/');\n if (!relativePath.startsWith('.')) relativePath = `./${relativePath}`;\n\n return {\n optionsFn: OPTIONS_IMPORT_IDENTIFIER,\n importStmt: `import ${OPTIONS_IMPORT_IDENTIFIER} from '${relativePath}';\\n`,\n };\n}\n"],"names":[],"mappings":";;;AAMO,MAAM,uBAAA,GAA0B;AAGvC,MAAM,yBAAA,GAA4B,6BAAA;AAKlC,MAAM,wBAAA,GAA2B,mBAAA;AACjC,MAAM,6BAA6B,CAAC,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,OAAO,KAAK,CAAA;AAM5D,SAAS,sBAAsB,aAAA,EAA2C;AAC/E,EAAA,MAAM,GAAA,GAAM,QAAQ,aAAa,CAAA;AACjC,EAAA,KAAA,MAAW,OAAO,0BAAA,EAA4B;AAC5C,IAAA,MAAM,YAAY,OAAA,CAAQ,GAAA,EAAK,GAAG,wBAAwB,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AACnE,IAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG,OAAO,SAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA;AACT;AAaO,SAAS,kBAAA,CACd,eACA,kBAAA,EAC2C;AAC3C,EAAA,IAAI,YAAA,GAAe,SAAS,OAAA,CAAQ,aAAa,GAAG,kBAAkB,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAC1F,EAAA,IAAI,CAAC,YAAA,CAAa,UAAA,CAAW,GAAG,CAAA,EAAG,YAAA,GAAe,KAAK,YAAY,CAAA,CAAA;AAEnE,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,yBAAA;AAAA,IACX,UAAA,EAAY,CAAA,OAAA,EAAU,yBAAyB,CAAA,OAAA,EAAU,YAAY,CAAA;AAAA;AAAA,GACvE;AACF;;;;"}
@@ -0,0 +1,227 @@
1
+ const DEFAULT_EXPORT = "default";
2
+ function emptyShape() {
3
+ return {
4
+ classes: /* @__PURE__ */ new Map(),
5
+ imports: /* @__PURE__ */ new Map(),
6
+ namespaces: /* @__PURE__ */ new Map(),
7
+ reexports: /* @__PURE__ */ new Map(),
8
+ localExports: /* @__PURE__ */ new Map(),
9
+ starExports: []
10
+ };
11
+ }
12
+ function shapeFromAst(ast) {
13
+ const shape = emptyShape();
14
+ for (const node of ast.body) {
15
+ switch (node.type) {
16
+ case "ClassDeclaration":
17
+ addAstClass(shape, node);
18
+ break;
19
+ case "ImportDeclaration":
20
+ addAstImports(shape, node);
21
+ break;
22
+ case "ExportNamedDeclaration":
23
+ addAstNamedExport(shape, node);
24
+ break;
25
+ case "ExportDefaultDeclaration": {
26
+ const decl = node.declaration;
27
+ if (decl.type === "ClassDeclaration" || decl.type === "ClassExpression") {
28
+ shape.defaultExportIsClass = true;
29
+ shape.defaultExportSuper = superRefFromNode(decl.superClass);
30
+ addAstClass(shape, decl);
31
+ } else if (decl.type === "Identifier") {
32
+ shape.defaultExportName = decl.name;
33
+ }
34
+ break;
35
+ }
36
+ case "ExportAllDeclaration": {
37
+ const starNode = node;
38
+ const source = starNode.exported ? void 0 : asString(starNode.source?.value);
39
+ if (source) shape.starExports.push(source);
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ return shape;
45
+ }
46
+ function superRefFromNode(superClass) {
47
+ if (!superClass) return void 0;
48
+ if (superClass.type === "Identifier") {
49
+ return { kind: "identifier", name: superClass.name };
50
+ }
51
+ if (superClass.type === "MemberExpression") {
52
+ const member = superClass;
53
+ const object = member.object?.type === "Identifier" ? member.object.name : void 0;
54
+ const property = member.property?.name;
55
+ if (object && property) return { kind: "member", object, property };
56
+ }
57
+ return void 0;
58
+ }
59
+ function addAstClass(shape, classNode) {
60
+ if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));
61
+ }
62
+ function addAstImports(shape, node) {
63
+ const source = asString(node.source?.value);
64
+ if (!source) return;
65
+ for (const specifier of node.specifiers ?? []) {
66
+ const local = specifier.local?.name;
67
+ if (!local) continue;
68
+ if (specifier.type === "ImportSpecifier" && specifier.imported?.name) {
69
+ shape.imports.set(local, { source, imported: specifier.imported.name });
70
+ } else if (specifier.type === "ImportDefaultSpecifier") {
71
+ shape.imports.set(local, { source, imported: DEFAULT_EXPORT });
72
+ } else if (specifier.type === "ImportNamespaceSpecifier") {
73
+ shape.namespaces.set(local, source);
74
+ }
75
+ }
76
+ }
77
+ function addAstNamedExport(shape, node) {
78
+ if (node.declaration?.type === "ClassDeclaration") {
79
+ addAstClass(shape, node.declaration);
80
+ return;
81
+ }
82
+ const source = asString(node.source?.value);
83
+ for (const specifier of node.specifiers ?? []) {
84
+ const exported = specifier.exported?.name;
85
+ const local = specifier.local?.name;
86
+ if (!exported || !local) continue;
87
+ if (source) {
88
+ shape.reexports.set(exported, { source, imported: local });
89
+ } else {
90
+ shape.localExports.set(exported, local);
91
+ }
92
+ }
93
+ }
94
+ function shapeFromSource(rawCode) {
95
+ const code = stripComments(rawCode);
96
+ const shape = emptyShape();
97
+ const CLASS_RE = /\b(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)([^{]*)\{/g;
98
+ for (const match of code.matchAll(CLASS_RE)) {
99
+ const className = match[1];
100
+ const isDefault = /\bexport\s+default\b/.test(match[0]);
101
+ const superRef = superRefFromHeader(match[2] ?? "");
102
+ shape.classes.set(className, superRef);
103
+ if (isDefault) {
104
+ shape.defaultExportIsClass = true;
105
+ shape.defaultExportSuper = superRef;
106
+ }
107
+ }
108
+ const defaultExprMatch = /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/.exec(code);
109
+ if (defaultExprMatch && !shape.defaultExportIsClass) {
110
+ shape.defaultExportName = defaultExprMatch[1];
111
+ }
112
+ for (const match of code.matchAll(/\bexport\s*\*\s*from\s*['"]([^'"]+)['"]/g)) {
113
+ if (match[1]) shape.starExports.push(match[1]);
114
+ }
115
+ for (const match of code.matchAll(/\bexport\s*\{([^}]*)\}\s*(?:from\s*['"]([^'"]+)['"])?/g)) {
116
+ const source = match[2];
117
+ for (const { imported, local } of parseSpecifierList(match[1] ?? "")) {
118
+ if (source) {
119
+ shape.reexports.set(local, { source, imported });
120
+ } else {
121
+ shape.localExports.set(local, imported);
122
+ }
123
+ }
124
+ }
125
+ for (const match of code.matchAll(/\bimport\s+([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g)) {
126
+ addSourceImports(shape, match[1] ?? "", match[2]);
127
+ }
128
+ return shape;
129
+ }
130
+ function superRefFromHeader(header) {
131
+ const withoutParams = stripLeadingGenerics(header);
132
+ const match = /\bextends\s+([A-Za-z_$][\w$]*)\s*(?:\.\s*([A-Za-z_$][\w$]*))?/.exec(withoutParams);
133
+ if (!match) return void 0;
134
+ return match[2] ? { kind: "member", object: match[1], property: match[2] } : { kind: "identifier", name: match[1] };
135
+ }
136
+ function stripLeadingGenerics(header) {
137
+ const start = header.indexOf("<");
138
+ if (start === -1 || header.slice(0, start).trim() !== "") return header;
139
+ let depth = 0;
140
+ for (let i = start; i < header.length; i++) {
141
+ const char = header[i];
142
+ if (char === "<") depth++;
143
+ else if (char === ">") {
144
+ depth--;
145
+ if (depth === 0) return header.slice(i + 1);
146
+ }
147
+ }
148
+ return header;
149
+ }
150
+ function parseSpecifierList(clause) {
151
+ const specifiers = [];
152
+ for (const rawPart of clause.split(",")) {
153
+ const part = rawPart.trim().replace(/^type\s+/, "");
154
+ if (!part) continue;
155
+ const aliased = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(part);
156
+ if (aliased) {
157
+ specifiers.push({ imported: aliased[1], local: aliased[2] });
158
+ } else if (/^[A-Za-z_$][\w$]*$/.test(part)) {
159
+ specifiers.push({ imported: part, local: part });
160
+ }
161
+ }
162
+ return specifiers;
163
+ }
164
+ function addSourceImports(shape, clause, source) {
165
+ if (/^type\s/.test(clause.trim())) return;
166
+ const namespaceMatch = /\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(clause);
167
+ if (namespaceMatch) {
168
+ shape.namespaces.set(namespaceMatch[1], source);
169
+ }
170
+ const bracesMatch = /\{([^}]*)\}/.exec(clause);
171
+ if (bracesMatch) {
172
+ for (const { imported, local } of parseSpecifierList(bracesMatch[1] ?? "")) {
173
+ shape.imports.set(local, { source, imported });
174
+ }
175
+ }
176
+ const defaultMatch = /^\s*([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(clause);
177
+ if (defaultMatch) {
178
+ shape.imports.set(defaultMatch[1], { source, imported: DEFAULT_EXPORT });
179
+ }
180
+ }
181
+ function stripComments(code) {
182
+ let result = "";
183
+ let index = 0;
184
+ while (index < code.length) {
185
+ const char = code[index];
186
+ const next = code[index + 1];
187
+ if (char === "/" && next === "/") {
188
+ while (index < code.length && code[index] !== "\n") index++;
189
+ continue;
190
+ }
191
+ if (char === "/" && next === "*") {
192
+ index += 2;
193
+ while (index < code.length && !(code[index] === "*" && code[index + 1] === "/")) index++;
194
+ index += 2;
195
+ result += " ";
196
+ continue;
197
+ }
198
+ if (char === '"' || char === "'" || char === "`") {
199
+ const quote = char;
200
+ result += char;
201
+ index++;
202
+ while (index < code.length) {
203
+ const inner = code[index];
204
+ result += inner;
205
+ index++;
206
+ if (inner === "\\") {
207
+ if (index < code.length) {
208
+ result += code[index];
209
+ index++;
210
+ }
211
+ continue;
212
+ }
213
+ if (inner === quote) break;
214
+ }
215
+ continue;
216
+ }
217
+ result += char;
218
+ index++;
219
+ }
220
+ return result;
221
+ }
222
+ function asString(value) {
223
+ return typeof value === "string" && value ? value : void 0;
224
+ }
225
+
226
+ export { DEFAULT_EXPORT, shapeFromAst, shapeFromSource };
227
+ //# sourceMappingURL=moduleShape.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"moduleShape.js","sources":["../../../src/vite/moduleShape.ts"],"sourcesContent":["import type { BaseNode, ProgramBody } from './transform';\n\n// ---------------------------------------------------------------------------\n// Minimal ESTree node shapes for structural Agent detection.\n// ---------------------------------------------------------------------------\n\ninterface IdentifierNode extends BaseNode {\n name: string;\n}\n\ninterface ClassNode extends BaseNode {\n id?: IdentifierNode | null;\n superClass?: BaseNode | null;\n}\n\ninterface MemberExpressionNode extends BaseNode {\n object?: { type: string; name?: string };\n property?: { type: string; name?: string };\n}\n\ninterface ImportSpecifierNode {\n type: string;\n imported?: { type: string; name?: string };\n local?: { type: string; name?: string };\n}\n\ninterface ImportDeclarationNode extends BaseNode {\n source?: { value?: unknown };\n specifiers?: ImportSpecifierNode[];\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?: { value?: unknown } | null;\n specifiers?: ExportSpecifierNode[];\n}\n\ninterface ExportDefaultNode extends BaseNode {\n declaration: BaseNode;\n}\n\ninterface ExportAllNode extends BaseNode {\n source?: { value?: unknown };\n exported?: { type: string; name?: string } | null;\n}\n\n/** Binding name used for a module's default export. */\nexport const DEFAULT_EXPORT = 'default';\n\n/** A resolved superclass reference: a bare identifier or a `ns.Member` expression. */\nexport type SuperRef = { kind: 'identifier'; name: string } | { kind: 'member'; object: string; property: string };\n\n/** The declarations of a single module that binding resolution needs. */\nexport interface ModuleShape {\n /** Top-level class names → their superclass reference (absent when the class has no `extends`). */\n classes: Map<string, SuperRef | undefined>;\n /** Local binding name → the import it came from (`imported` is `default` for a default import). */\n imports: Map<string, { source: string; imported: string }>;\n /** Local binding name → module specifier, for `import * as ns from '...'`. */\n namespaces: Map<string, string>;\n /** Exported name → the re-export it came from, for `export { x as y } from '...'`. */\n reexports: Map<string, { source: string; imported: string }>;\n /** Exported name → local binding name, for `export { x as y }` without a source. */\n localExports: Map<string, string>;\n /** Module specifiers of bare `export * from '...'` declarations. */\n starExports: string[];\n /** `export default <Identifier>` — the local name it refers to. */\n defaultExportName?: string;\n /** True when the module's default export is a class declaration/expression. */\n defaultExportIsClass?: boolean;\n /** Superclass of an anonymous `export default class extends X`. */\n defaultExportSuper?: SuperRef;\n}\n\nfunction emptyShape(): ModuleShape {\n return {\n classes: new Map(),\n imports: new Map(),\n namespaces: new Map(),\n reexports: new Map(),\n localExports: new Map(),\n starExports: [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shape from a parsed AST (used for the entry module)\n// ---------------------------------------------------------------------------\n\n/** Collect the shape of a module from its parsed AST — used for the already-parsed entry module. */\nexport function shapeFromAst(ast: ProgramBody): ModuleShape {\n const shape = emptyShape();\n\n for (const node of ast.body) {\n switch (node.type) {\n case 'ClassDeclaration':\n addAstClass(shape, node as ClassNode);\n break;\n case 'ImportDeclaration':\n addAstImports(shape, node as ImportDeclarationNode);\n break;\n case 'ExportNamedDeclaration':\n addAstNamedExport(shape, node as ExportNamedNode);\n break;\n case 'ExportDefaultDeclaration': {\n const decl = (node as ExportDefaultNode).declaration;\n if (decl.type === 'ClassDeclaration' || decl.type === 'ClassExpression') {\n shape.defaultExportIsClass = true;\n shape.defaultExportSuper = superRefFromNode((decl as ClassNode).superClass);\n // `export default class Foo {}` also binds `Foo` locally.\n addAstClass(shape, decl as ClassNode);\n } else if (decl.type === 'Identifier') {\n shape.defaultExportName = (decl as IdentifierNode).name;\n }\n break;\n }\n case 'ExportAllDeclaration': {\n const starNode = node as ExportAllNode;\n // `export * as ns from '...'` binds a namespace object, not the individual exports.\n const source = starNode.exported ? undefined : asString(starNode.source?.value);\n if (source) shape.starExports.push(source);\n break;\n }\n }\n }\n\n return shape;\n}\n\nfunction superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined {\n if (!superClass) return undefined;\n\n if (superClass.type === 'Identifier') {\n return { kind: 'identifier', name: (superClass as IdentifierNode).name };\n }\n\n if (superClass.type === 'MemberExpression') {\n const member = superClass as MemberExpressionNode;\n const object = member.object?.type === 'Identifier' ? member.object.name : undefined;\n const property = member.property?.name;\n if (object && property) return { kind: 'member', object, property };\n }\n\n return undefined;\n}\n\nfunction addAstClass(shape: ModuleShape, classNode: ClassNode): void {\n if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass));\n}\n\nfunction addAstImports(shape: ModuleShape, node: ImportDeclarationNode): void {\n const source = asString(node.source?.value);\n if (!source) return;\n\n for (const specifier of node.specifiers ?? []) {\n const local = specifier.local?.name;\n if (!local) continue;\n\n if (specifier.type === 'ImportSpecifier' && specifier.imported?.name) {\n shape.imports.set(local, { source, imported: specifier.imported.name });\n } else if (specifier.type === 'ImportDefaultSpecifier') {\n shape.imports.set(local, { source, imported: DEFAULT_EXPORT });\n } else if (specifier.type === 'ImportNamespaceSpecifier') {\n shape.namespaces.set(local, source);\n }\n }\n}\n\nfunction addAstNamedExport(shape: ModuleShape, node: ExportNamedNode): void {\n if (node.declaration?.type === 'ClassDeclaration') {\n addAstClass(shape, node.declaration as ClassNode);\n return;\n }\n\n const source = asString(node.source?.value);\n for (const specifier of node.specifiers ?? []) {\n const exported = specifier.exported?.name;\n const local = specifier.local?.name;\n if (!exported || !local) continue;\n\n if (source) {\n shape.reexports.set(exported, { source, imported: local });\n } else {\n shape.localExports.set(exported, local);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shape from raw source (used for sibling modules read off disk)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the module shape from **unprocessed source**.\n *\n * Sibling modules are read straight from disk (the plugin context's `load()` would deadlock inside a\n * transform hook), so they may still be TypeScript — which no JS parser will accept. Only\n * import/export statements and `class X extends Y` headers matter here, and those are\n * declaration-level syntax a scan can pick out reliably; class bodies, type annotations and generics\n * are irrelevant and simply skipped.\n */\nexport function shapeFromSource(rawCode: string): ModuleShape {\n const code = stripComments(rawCode);\n const shape = emptyShape();\n\n // `class X extends Y {` / `class X<T> extends Y<T> {`, optionally exported and/or abstract.\n const CLASS_RE = /\\b(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+([A-Za-z_$][\\w$]*)([^{]*)\\{/g;\n for (const match of code.matchAll(CLASS_RE)) {\n const className = match[1]!;\n const isDefault = /\\bexport\\s+default\\b/.test(match[0]);\n const superRef = superRefFromHeader(match[2] ?? '');\n\n shape.classes.set(className, superRef);\n if (isDefault) {\n shape.defaultExportIsClass = true;\n shape.defaultExportSuper = superRef;\n }\n }\n\n // `export default Identifier;`\n const defaultExprMatch = /\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\s*;/.exec(code);\n if (defaultExprMatch && !shape.defaultExportIsClass) {\n shape.defaultExportName = defaultExprMatch[1];\n }\n\n // `export * from '...'` (but not `export * as ns from '...'`).\n for (const match of code.matchAll(/\\bexport\\s*\\*\\s*from\\s*['\"]([^'\"]+)['\"]/g)) {\n if (match[1]) shape.starExports.push(match[1]);\n }\n\n // `export { a, b as c } from '...'` and `export { a, b as c }`.\n for (const match of code.matchAll(/\\bexport\\s*\\{([^}]*)\\}\\s*(?:from\\s*['\"]([^'\"]+)['\"])?/g)) {\n const source = match[2];\n for (const { imported, local } of parseSpecifierList(match[1] ?? '')) {\n // In an export clause the first name is local and the alias is the exported name.\n if (source) {\n shape.reexports.set(local, { source, imported });\n } else {\n shape.localExports.set(local, imported);\n }\n }\n }\n\n // `import Default, { a as b }, * as ns from '...'` in its various shapes.\n for (const match of code.matchAll(/\\bimport\\s+([^'\";]+?)\\s+from\\s*['\"]([^'\"]+)['\"]/g)) {\n addSourceImports(shape, match[1] ?? '', match[2]!);\n }\n\n return shape;\n}\n\n/** Pull the superclass out of the text between a class name and its body. */\nfunction superRefFromHeader(header: string): SuperRef | undefined {\n // The header still carries the class's own generic parameter list (`<T extends S>`), whose\n // constraint `extends` would otherwise be mistaken for the superclass clause. Strip a leading\n // balanced `<...>` first, then read the (possibly dotted) base name. Trailing generic args on the\n // base (`extends Agent<Env>`) stop the match naturally.\n const withoutParams = stripLeadingGenerics(header);\n const match = /\\bextends\\s+([A-Za-z_$][\\w$]*)\\s*(?:\\.\\s*([A-Za-z_$][\\w$]*))?/.exec(withoutParams);\n if (!match) return undefined;\n\n return match[2] ? { kind: 'member', object: match[1]!, property: match[2] } : { kind: 'identifier', name: match[1]! };\n}\n\n/**\n * Remove a leading `<...>` generic parameter list, honoring nesting (`<T extends Map<K, V>>`).\n * Anything after the balanced close — the superclass clause — is returned unchanged. When the\n * header doesn't start with `<` (no generics), it is returned as-is.\n */\nfunction stripLeadingGenerics(header: string): string {\n const start = header.indexOf('<');\n // Only treat it as a parameter list when `<` is the first meaningful token — a `<` appearing\n // later is part of the superclass's own generic args and must be left alone.\n if (start === -1 || header.slice(0, start).trim() !== '') return header;\n\n let depth = 0;\n for (let i = start; i < header.length; i++) {\n const char = header[i];\n if (char === '<') depth++;\n else if (char === '>') {\n depth--;\n if (depth === 0) return header.slice(i + 1);\n }\n }\n // Unbalanced `<` — fall back to the untouched header rather than dropping the superclass.\n return header;\n}\n\n/** Parse `a, b as c` into `{ imported: 'b', local: 'c' }` pairs (type-only specifiers dropped). */\nfunction parseSpecifierList(clause: string): Array<{ imported: string; local: string }> {\n const specifiers: Array<{ imported: string; local: string }> = [];\n\n for (const rawPart of clause.split(',')) {\n const part = rawPart.trim().replace(/^type\\s+/, '');\n if (!part) continue;\n\n const aliased = /^([A-Za-z_$][\\w$]*)\\s+as\\s+([A-Za-z_$][\\w$]*)$/.exec(part);\n if (aliased) {\n specifiers.push({ imported: aliased[1]!, local: aliased[2]! });\n } else if (/^[A-Za-z_$][\\w$]*$/.test(part)) {\n specifiers.push({ imported: part, local: part });\n }\n }\n\n return specifiers;\n}\n\nfunction addSourceImports(shape: ModuleShape, clause: string, source: string): void {\n // Type-only imports never contribute a runtime base class.\n if (/^type\\s/.test(clause.trim())) return;\n\n const namespaceMatch = /\\*\\s*as\\s+([A-Za-z_$][\\w$]*)/.exec(clause);\n if (namespaceMatch) {\n shape.namespaces.set(namespaceMatch[1]!, source);\n }\n\n const bracesMatch = /\\{([^}]*)\\}/.exec(clause);\n if (bracesMatch) {\n for (const { imported, local } of parseSpecifierList(bracesMatch[1] ?? '')) {\n shape.imports.set(local, { source, imported });\n }\n }\n\n // A leading bare identifier (before any brace/star) is the default import.\n const defaultMatch = /^\\s*([A-Za-z_$][\\w$]*)\\s*(?:,|$)/.exec(clause);\n if (defaultMatch) {\n shape.imports.set(defaultMatch[1]!, { source, imported: DEFAULT_EXPORT });\n }\n}\n\n/** Remove line and block comments, leaving string literals (module specifiers) intact. */\nfunction stripComments(code: string): string {\n let result = '';\n let index = 0;\n\n while (index < code.length) {\n const char = code[index]!;\n const next = code[index + 1];\n\n if (char === '/' && next === '/') {\n while (index < code.length && code[index] !== '\\n') index++;\n continue;\n }\n\n if (char === '/' && next === '*') {\n index += 2;\n while (index < code.length && !(code[index] === '*' && code[index + 1] === '/')) index++;\n index += 2;\n // Keep a separator so `*/class` doesn't fuse into one token.\n result += ' ';\n continue;\n }\n\n if (char === '\"' || char === \"'\" || char === '`') {\n const quote = char;\n result += char;\n index++;\n while (index < code.length) {\n const inner = code[index]!;\n result += inner;\n index++;\n if (inner === '\\\\') {\n if (index < code.length) {\n result += code[index]!;\n index++;\n }\n continue;\n }\n if (inner === quote) break;\n }\n continue;\n }\n\n result += char;\n index++;\n }\n\n return result;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined;\n}\n"],"names":[],"mappings":"AAqDO,MAAM,cAAA,GAAiB;AA2B9B,SAAS,UAAA,GAA0B;AACjC,EAAA,OAAO;AAAA,IACL,OAAA,sBAAa,GAAA,EAAI;AAAA,IACjB,OAAA,sBAAa,GAAA,EAAI;AAAA,IACjB,UAAA,sBAAgB,GAAA,EAAI;AAAA,IACpB,SAAA,sBAAe,GAAA,EAAI;AAAA,IACnB,YAAA,sBAAkB,GAAA,EAAI;AAAA,IACtB,aAAa;AAAC,GAChB;AACF;AAOO,SAAS,aAAa,GAAA,EAA+B;AAC1D,EAAA,MAAM,QAAQ,UAAA,EAAW;AAEzB,EAAA,KAAA,MAAW,IAAA,IAAQ,IAAI,IAAA,EAAM;AAC3B,IAAA,QAAQ,KAAK,IAAA;AAAM,MACjB,KAAK,kBAAA;AACH,QAAA,WAAA,CAAY,OAAO,IAAiB,CAAA;AACpC,QAAA;AAAA,MACF,KAAK,mBAAA;AACH,QAAA,aAAA,CAAc,OAAO,IAA6B,CAAA;AAClD,QAAA;AAAA,MACF,KAAK,wBAAA;AACH,QAAA,iBAAA,CAAkB,OAAO,IAAuB,CAAA;AAChD,QAAA;AAAA,MACF,KAAK,0BAAA,EAA4B;AAC/B,QAAA,MAAM,OAAQ,IAAA,CAA2B,WAAA;AACzC,QAAA,IAAI,IAAA,CAAK,IAAA,KAAS,kBAAA,IAAsB,IAAA,CAAK,SAAS,iBAAA,EAAmB;AACvE,UAAA,KAAA,CAAM,oBAAA,GAAuB,IAAA;AAC7B,UAAA,KAAA,CAAM,kBAAA,GAAqB,gBAAA,CAAkB,IAAA,CAAmB,UAAU,CAAA;AAE1E,UAAA,WAAA,CAAY,OAAO,IAAiB,CAAA;AAAA,QACtC,CAAA,MAAA,IAAW,IAAA,CAAK,IAAA,KAAS,YAAA,EAAc;AACrC,UAAA,KAAA,CAAM,oBAAqB,IAAA,CAAwB,I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A,QAAA,IAAI,UAAU,KAAA,EAAO;AAAA,MACvB;AACA,MAAA;AAAA,IACF;AAEA,IAAA,MAAA,IAAU,IAAA;AACV,IAAA,KAAA,EAAA;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,SAAS,KAAA,EAAoC;AACpD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,GAAQ,KAAA,GAAQ,MAAA;AACtD;;;;"}
@@ -0,0 +1,147 @@
1
+ import MagicString from 'magic-string';
2
+ import { detectWorkerEntrypointClasses } from './workerEntrypoint.js';
3
+
4
+ function isCallToMethod(node, methodName) {
5
+ if (node.type !== "CallExpression") return false;
6
+ const callee = node.callee;
7
+ if (!callee) return false;
8
+ if (callee.type === "Identifier" && callee.name === methodName) return true;
9
+ return callee.type === "MemberExpression" && callee.property?.type === "Identifier" && callee.property.name === methodName;
10
+ }
11
+ const WRAPPER_METHODS = {
12
+ durableObject: "instrumentDurableObjectWithSentry",
13
+ agent: "instrumentAgentWithSentry",
14
+ workflow: "instrumentWorkflowWithSentry",
15
+ workerEntrypoint: "withSentry"
16
+ };
17
+ function applyAutoInstrumentTransforms(code, ast, ctx) {
18
+ const ms = new MagicString(code);
19
+ const topLevelClasses = collectTopLevelClasses(ast);
20
+ const state = {
21
+ ms,
22
+ needsImport: false,
23
+ wrappedClasses: /* @__PURE__ */ new Set(),
24
+ topLevelClasses,
25
+ renamedLocals: /* @__PURE__ */ new Set(),
26
+ classWrappers: ctx.classWrappers,
27
+ agentClasses: ctx.agentClasses ?? /* @__PURE__ */ new Set(),
28
+ workerEntrypointClasses: detectWorkerEntrypointClasses(ast)
29
+ };
30
+ const { wrappedClasses } = state;
31
+ for (const node of ast.body) {
32
+ if (node.type === "ExportNamedDeclaration") {
33
+ handleNamedExport(node, ctx, state);
34
+ }
35
+ }
36
+ for (const node of ast.body) {
37
+ if (node.type === "ExportDefaultDeclaration") {
38
+ wrapDefaultExport(node, ctx, state);
39
+ }
40
+ }
41
+ if (!state.needsImport) {
42
+ if (wrappedClasses.size === 0) return void 0;
43
+ return { code, map: ms.generateMap({ hires: true }), wrappedClasses };
44
+ }
45
+ if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
46
+ ms.prepend("import * as __SENTRY__ from '@sentry/cloudflare';\n");
47
+ return {
48
+ code: ms.toString(),
49
+ map: ms.generateMap({ hires: true }),
50
+ wrappedClasses
51
+ };
52
+ }
53
+ function resolveWrapperKind(exportedName, localName, state) {
54
+ const configured = state.classWrappers.get(exportedName);
55
+ if (configured === "durableObject" && localName && state.agentClasses.has(localName)) return "agent";
56
+ if (configured) return configured;
57
+ if (localName && state.workerEntrypointClasses.has(localName)) return "workerEntrypoint";
58
+ return void 0;
59
+ }
60
+ function collectTopLevelClasses(ast) {
61
+ const classes = /* @__PURE__ */ new Map();
62
+ for (const node of ast.body) {
63
+ if (node.type !== "ClassDeclaration") continue;
64
+ const classNode = node;
65
+ if (classNode.id?.name) classes.set(classNode.id.name, classNode);
66
+ }
67
+ return classes;
68
+ }
69
+ function wrapDefaultExport(node, ctx, state) {
70
+ const decl = node.declaration;
71
+ if (isCallToMethod(decl, "withSentry")) return;
72
+ if (decl.type === "Identifier" && state.renamedLocals.has(decl.name)) return;
73
+ state.ms.overwrite(node.start, decl.start, "const __SENTRY_DEFAULT_EXPORT__ = ");
74
+ state.ms.append(`
75
+ export default __SENTRY__.withSentry(${ctx.optionsFn}, __SENTRY_DEFAULT_EXPORT__);
76
+ `);
77
+ state.needsImport = true;
78
+ }
79
+ function handleNamedExport(node, ctx, state) {
80
+ const decl = node.declaration;
81
+ if (decl?.type === "VariableDeclaration") {
82
+ collectManuallyWrappedClassExports(decl, ctx, state);
83
+ return;
84
+ }
85
+ if (decl?.type === "ClassDeclaration") {
86
+ wrapInlineClassExport(node, decl, ctx, state);
87
+ return;
88
+ }
89
+ if (node.source) return;
90
+ for (const specifier of node.specifiers ?? []) {
91
+ wrapSpecifierExport(specifier, ctx, state);
92
+ }
93
+ }
94
+ function collectManuallyWrappedClassExports(varDecl, ctx, state) {
95
+ for (const declarator of varDecl.declarations ?? []) {
96
+ const name = declarator.id?.type === "Identifier" ? declarator.id.name : void 0;
97
+ const kind = name ? ctx.classWrappers.get(name) : void 0;
98
+ if (!name || !kind || !declarator.init) continue;
99
+ const accepted = kind === "durableObject" ? [WRAPPER_METHODS.durableObject, WRAPPER_METHODS.agent] : [WRAPPER_METHODS[kind]];
100
+ if (accepted.some((method) => isCallToMethod(declarator.init, method))) {
101
+ state.wrappedClasses.add(name);
102
+ }
103
+ }
104
+ }
105
+ function wrapInlineClassExport(exportNode, classDecl, ctx, state) {
106
+ const classId = classDecl.id;
107
+ const kind = classId ? resolveWrapperKind(classId.name, classId.name, state) : void 0;
108
+ if (!classId || !kind) return;
109
+ const className = classId.name;
110
+ const renamedClass = `__SENTRY_ORIGINAL_${className}__`;
111
+ state.ms.overwrite(exportNode.start, classDecl.start, "");
112
+ state.ms.overwrite(classId.start, classId.end, renamedClass);
113
+ state.ms.appendLeft(
114
+ exportNode.end,
115
+ `
116
+ export const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});
117
+ `
118
+ );
119
+ state.wrappedClasses.add(className);
120
+ state.renamedLocals.add(className);
121
+ state.needsImport = true;
122
+ }
123
+ function wrapSpecifierExport(specifier, ctx, state) {
124
+ if (specifier.type !== "ExportSpecifier" || specifier.exported?.type !== "Identifier") return;
125
+ const exportedName = specifier.exported.name;
126
+ if (!exportedName) return;
127
+ const localName = specifier.local?.type === "Identifier" ? specifier.local.name : void 0;
128
+ const kind = resolveWrapperKind(exportedName, localName, state);
129
+ if (!kind) return;
130
+ const localClass = localName ? state.topLevelClasses.get(localName) : void 0;
131
+ if (!localName || !localClass?.id) return;
132
+ state.wrappedClasses.add(exportedName);
133
+ state.needsImport = true;
134
+ if (state.renamedLocals.has(localName)) return;
135
+ state.renamedLocals.add(localName);
136
+ const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;
137
+ state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);
138
+ state.ms.appendLeft(
139
+ localClass.end,
140
+ `
141
+ const ${localName} = __SENTRY__.${WRAPPER_METHODS[kind]}(${ctx.optionsFn}, ${renamedClass});
142
+ `
143
+ );
144
+ }
145
+
146
+ export { applyAutoInstrumentTransforms };
147
+ //# sourceMappingURL=transform.js.map