Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@sentry/bundler-plugins": "11.19.0",
"@sentry/conventions": "^0.36.0",
"@sentry/core": "11.19.0",
"@sentry/opentelemetry": "11.19.0",
Expand All @@ -79,7 +80,6 @@
"@cloudflare/workers-types": "5.20260710.1",
"@sentry-internal/rollup-utils": "11.19.0",
"@types/node": "^20.19.0",
"acorn": "^8.14.0",
"vite": "^8.3.6",
"wrangler": "4.156.0"
},
Expand Down
6 changes: 3 additions & 3 deletions packages/cloudflare/src/vite/agentClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export async function detectAgentClasses(
candidates: Iterable<string>,
resolver: ModuleResolver,
): Promise<Set<string>> {
// The entry's shape comes from the AST Vite already handed us (TypeScript stripped, full
// fidelity); only sibling modules fall back to source scanning.
// The entry's shape comes from the AST the plugin already parsed; sibling modules are parsed
// from their source on disk.
const ctx: DetectContext = { resolver, modules: new Map([[entryId, shapeFromAst(ast)]]) };

const detected = new Set<string>();
Expand Down Expand Up @@ -225,7 +225,7 @@ async function getModuleShape(ctx: DetectContext, moduleId: string): Promise<Mod
? ctx.resolver.readFile(moduleId)
: readFileSync(moduleId.replace(/[?#].*$/, ''), 'utf8');
if (typeof code === 'string') {
shape = shapeFromSource(code);
shape = shapeFromSource(code, moduleId);
}
} catch {
// Unreadable or not a source file — treat as "not an Agent" rather than failing the build.
Expand Down
180 changes: 99 additions & 81 deletions packages/cloudflare/src/vite/autoInstrument.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { basename, dirname, isAbsolute } from 'node:path';
import { createCallSiteRewriter, type ModuleParser, parseModule } from '@sentry/bundler-plugins/rewriter';
import { createIdResolver, type ResolvedConfig } from 'vite';
import { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';
import { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';
Expand Down Expand Up @@ -222,7 +223,8 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
code: string,
id: string,
): Promise<{ code: string; map: unknown } | undefined> {
if (!wranglerConfig || (!entryFilePath && !entrySpecifier)) return undefined;
const config = wranglerConfig;
if (!config || (!entryFilePath && !entrySpecifier)) return undefined;

// The worker entry never belongs to the client (browser) environment.
// Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`
Expand Down Expand Up @@ -251,86 +253,102 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
}
}

let ast: ProgramBody;
try {
ast = this.parse(code);
} catch {
// Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)
// or the file is genuinely broken. Either way, skip silently.
return undefined;
}

const classWrappers = new Map<string, ClassWrapperKind>();
for (const { className } of wranglerConfig.durableObjects) {
classWrappers.set(className, 'durableObject');
}
for (const { className } of wranglerConfig.workflows) {
classWrappers.set(className, 'workflow');
}
for (const className of wranglerConfig.workerEntrypoints) {
classWrappers.set(className, 'workerEntrypoint');
}

// An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only
// its base-class chain tells the two apart. Detection walks the module graph (base classes
// usually live in their own file), so it is limited to the configured DO classes.
//
// Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform
// hook deadlocks the build, since the module can't finish loading while this transform is
// still pending. `agentClass` reads sibling modules off disk instead.
const agentCandidates = collectAgentCandidates(
ast,
[...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),
);
const agentClasses =
agentCandidates.size > 0
? await detectAgentClasses(ast, normalizedId, agentCandidates, {
parse: code => this.parse(code),
resolve: this.resolve?.bind(this),
})
: undefined;

// A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.
const sentryModule =
isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;

const { optionsFn, importStmt: optionsImport } = instrumentFilePath
? // A virtual module has no directory to import from relatively.
buildOptionsImport(entryPath, instrumentFilePath, { absolute: !!virtualEntry })
: { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };

// The TanStack Start server entry shim with a release wraps the default export of the entry it re-exports
// (`export default addReleaseMetaTag(serverEntry, release)`). That entry is wrapped already, and a second
// `withSentry` would start a second trace for each request.
const reexportsEntry = reexportsAllFromSameFile(ast, normalizedId);

// No registration import is injected here: the orchestrion plugin's
// subscribe-injection makes each bundled package self-register its channel
// subscriber on the global marker, so wrapping the entry with `withSentry`
// is all this plugin needs to do.
const result = applyAutoInstrumentTransforms(code, ast, {
classWrappers,
agentClasses,
optionsFn,
optionsImport,
sameWorkerBindings: wranglerConfig.sameWorkerBindings,
sentryModule,
workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate },
wrapDefault: !reexportsEntry,
});

const wrappedClasses = result?.wrappedClasses ?? new Set<string>();
const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));
if (missing.length > 0 && !reexportsEntry) {
this.warn?.(
`[sentry] Could not auto-instrument ${missing.join(', ')}. ` +
'The worker entry has no export matching them. ' +
'Star re-exports (`export * from "./do"`) are not matched. ' +
'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',
);
}

return result ?? undefined;
// `this.parse` fails on raw TypeScript, which oxc parses.
const parse: ModuleParser = (source, moduleId) => {
try {
return this.parse(source);
} catch {
return parseModule(source, moduleId);
}
};

const output = await createCallSiteRewriter(
[
{
name: 'cloudflare-worker-entry',
include: {},
apply: async ({ ast, state }) => {
const classWrappers = new Map<string, ClassWrapperKind>();
for (const { className } of config.durableObjects) {
classWrappers.set(className, 'durableObject');
}
for (const { className } of config.workflows) {
classWrappers.set(className, 'workflow');
}
for (const className of config.workerEntrypoints) {
classWrappers.set(className, 'workerEntrypoint');
}

// An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only
// its base-class chain tells the two apart. Detection walks the module graph (base classes
// usually live in their own file), so it is limited to the configured DO classes.
//
// Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform
// hook deadlocks the build, since the module can't finish loading while this transform is
// still pending. `agentClass` reads sibling modules off disk instead.
const agentCandidates = collectAgentCandidates(
ast,
[...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),
);
const agentClasses =
agentCandidates.size > 0
? await detectAgentClasses(ast, normalizedId, agentCandidates, {
parse: code => this.parse(code),
resolve: this.resolve?.bind(this),
})
: undefined;

// A vinext app with `@sentry/nextjs` installed gets `withSentry` of `@sentry/nextjs/cloudflare`.
const sentryModule =
isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;

const { optionsFn, importStmt: optionsImport } = instrumentFilePath
? // A virtual module has no directory to import from relatively.
buildOptionsImport(entryPath, instrumentFilePath, { absolute: !!virtualEntry })
: { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined };

// The TanStack Start server entry shim with a release wraps the default export of the entry it re-exports
// (`export default addReleaseMetaTag(serverEntry, release)`). That entry is wrapped already, and a second
// `withSentry` would start a second trace for each request.
const reexportsEntry = reexportsAllFromSameFile(ast, normalizedId);

// No registration import is injected here: the orchestrion plugin's
// subscribe-injection makes each bundled package self-register its channel
// subscriber on the global marker, so wrapping the entry with `withSentry`
// is all this plugin needs to do.
const result = applyAutoInstrumentTransforms(
code,
ast,
{
classWrappers,
agentClasses,
optionsFn,
optionsImport,
sameWorkerBindings: config.sameWorkerBindings,
sentryModule,
workerInfo: { name: config.name, compatibilityDate: config.compatibilityDate },
wrapDefault: !reexportsEntry,
},
state,
);

const wrappedClasses = result?.wrappedClasses ?? new Set<string>();
const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));
if (missing.length > 0 && !reexportsEntry) {
this.warn?.(
`[sentry] Could not auto-instrument ${missing.join(', ')}. ` +
'The worker entry has no export matching them. ' +
'Star re-exports (`export * from "./do"`) are not matched. ' +
'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',
);
}
},
},
],
{ parse },
).transform(code, normalizedId);

return output ?? undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parse fallback can emit TypeScript

Medium Severity

When this.parse fails, the plugin now parses the entry with oxc and returns the rewriter output. oxc can read TypeScript, but the rewriter only splices wrappers and does not strip types. This plugin runs with enforce: 'post', so that output can become the final module source. Previously the hook returned undefined and left the file to the rest of the pipeline.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c3dab93. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rewriter only adds plain JavaScript, so if TypeScript reached this point the output would contain the same TypeScript that the input already had.

},
};
}
Loading
Loading