Skip to content

Commit 3915885

Browse files
chargomeclaude
andauthored
fix(cloudflare): Wrap a wrangler main that is a virtual module of another Vite plugin (#26694)
## What `sentryCloudflareVitePlugin` now auto-instruments a wrangler `main` that is a virtual module provided by another Vite plugin, such as `virtual:solid-ssr-handler` from Solid's Vite plugin. Before, it warned "Could not resolve the wrangler `main`" and skipped instrumentation. ## Why A non-path `main` is resolved with Vite's own resolver, which does not see modules other plugins provide. When that fails, the plugin now resolves `main` through the plugin pipeline (`this.resolve()`) in `buildStart`, per environment, and wraps the module it resolves to. `instrument.server.*` is imported by absolute path there, since a virtual module has no directory. `this.resolve()` stays out of `transform`, where it can hang the build. The warning still shows at startup, in `vite dev` too, when nothing resolves `main`. Refs JS-4120 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6eddc50 commit 3915885

3 files changed

Lines changed: 120 additions & 17 deletions

File tree

‎packages/cloudflare/src/vite/autoInstrument.ts‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
5959
let resolveId: ReturnType<typeof createIdResolver> | undefined;
6060
// Each environment resolves with its own conditions, so the entry may differ between them.
6161
const resolvedEntries = new Map<string, Promise<string | undefined>>();
62+
// Per environment, the ID of a virtual module another plugin serves as `main`.
63+
const virtualEntries = new Map<string, string>();
6264

6365
let instrumentFilePath: string | undefined;
6466
let isVinext = false;
@@ -73,22 +75,16 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
7375
// tries the specifier as a path below the root first.
7476
entry = resolveId(environment, specifier, wranglerConfigPath)
7577
.catch(() => undefined)
76-
.then(id => {
77-
if (!id) {
78-
ctx.warn?.(
79-
`[sentry] Could not resolve the wrangler \`main\` "${specifier}". Auto-instrumentation disabled.`,
80-
);
81-
return undefined;
82-
}
83-
return normalizePath(id.replace(/[?#].*$/, ''));
84-
});
78+
.then(id => (id ? normalizePath(id.replace(/[?#].*$/, '')) : undefined));
8579
resolvedEntries.set(environment.name, entry);
8680
}
8781
return entry;
8882
}
8983

9084
return {
9185
name: 'sentry-cloudflare-auto-instrument',
86+
// Without it, `vite dev` calls `buildStart` only for the client environment, which this plugin skips.
87+
perEnvironmentStartEndDuringDev: true,
9288

9389
configResolved(config: {
9490
root: string;
@@ -129,6 +125,26 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
129125
}
130126
},
131127

128+
async buildStart(this: Omit<TransformContext, 'parse'>): Promise<void> {
129+
const environment = this.environment;
130+
if (!entrySpecifier || !environment || environment.name === 'client') return;
131+
132+
if (await resolveEntrySpecifier(this as TransformContext, entrySpecifier)) return;
133+
134+
// Vite's own resolver does not see virtual modules other plugins serve, such as Solid's
135+
// `virtual:solid-ssr-handler`. The plugin pipeline does, and here, unlike in `transform`, it can't wait
136+
// on the entry's own transform.
137+
const resolved = await this.resolve?.(entrySpecifier, wranglerConfigPath ?? '').catch(() => undefined);
138+
if (resolved) {
139+
virtualEntries.set(environment.name, normalizePath(resolved.id.replace(/[?#].*$/, '')));
140+
return;
141+
}
142+
143+
this.warn?.(
144+
`[sentry] Could not resolve the wrangler \`main\` "${entrySpecifier}". Auto-instrumentation disabled.`,
145+
);
146+
},
147+
132148
async transform(
133149
this: TransformContext,
134150
code: string,
@@ -141,11 +157,14 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
141157
// client entry next to a `src/index.ts` worker) out of the browser bundle.
142158
if (this.environment?.name === 'client') return undefined;
143159

144-
const entryPath = entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath;
160+
const virtualEntry = this.environment && virtualEntries.get(this.environment.name);
161+
const entryPath =
162+
virtualEntry ?? (entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath);
145163
if (!entryPath) return undefined;
146164

147165
// Vite may append query/hash params to the module ID.
148166
const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));
167+
149168
if (normalizedId !== entryPath) {
150169
// Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).
151170
if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryPath)) return undefined;
@@ -198,7 +217,8 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
198217
isVinext && (await resolvesNextjsCloudflare(this, normalizedId)) ? NEXTJS_CLOUDFLARE_MODULE : undefined;
199218

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

204224
// No registration import is injected here: the orchestrion plugin's

‎packages/cloudflare/src/vite/instrumentFile.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,21 @@ export function resolveInstrumentFile(dir: string): string | undefined {
3434
* `(env) => CloudflareOptions`.
3535
*
3636
* The import is emitted relative to `entryFilePath` because it is injected into
37-
* the entry file's source. The file extension is kept: extensionless specifiers
37+
* the entry file's source, or as an absolute path with `absolute` when the entry is
38+
* a virtual module without a directory of its own. The file extension is kept: extensionless specifiers
3839
* only resolve for extensions in Vite's default `resolve.extensions` (which
3940
* excludes `.cjs`), and keeping it makes our probe order authoritative when
4041
* several `instrument.server.*` files coexist.
4142
*/
4243
export function buildOptionsImport(
4344
entryFilePath: string,
4445
instrumentFilePath: string,
46+
{ absolute = false }: { absolute?: boolean } = {},
4547
): { optionsFn: string; importStmt: string } {
46-
let relativePath = relative(dirname(entryFilePath), instrumentFilePath).replace(/\\/g, '/');
47-
if (!relativePath.startsWith('.')) relativePath = `./${relativePath}`;
48+
let relativePath = absolute
49+
? instrumentFilePath.replace(/\\/g, '/')
50+
: relative(dirname(entryFilePath), instrumentFilePath).replace(/\\/g, '/');
51+
if (!absolute && !relativePath.startsWith('.')) relativePath = `./${relativePath}`;
4852

4953
return {
5054
optionsFn: OPTIONS_IMPORT_IDENTIFIER,

‎packages/cloudflare/test/vite/autoInstrument.test.ts‎

Lines changed: 82 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -656,8 +656,10 @@ describe('package specifier as wrangler `main`', () => {
656656
const warn = vi.fn();
657657
const tx = (id: string, environment = ssr) =>
658658
plugin.transform.call({ parse: (c: string) => parseJS(c), warn, environment }, code, id);
659+
const buildStart = (resolve = vi.fn().mockResolvedValue(null)) =>
660+
plugin.buildStart.call({ warn, environment: ssr, resolve });
659661

660-
return { tx, entryPath, dir, warn };
662+
return { tx, buildStart, entryPath, dir, warn };
661663
}
662664

663665
it('wraps the module the specifier resolves to', async () => {
@@ -702,10 +704,11 @@ describe('package specifier as wrangler `main`', () => {
702704
expect(result.code).toContain('__SENTRY__.withSentry(__SENTRY_OPTIONS_CALLBACK__,');
703705
});
704706

705-
it('warns once when the specifier does not resolve', async () => {
706-
const { tx, dir, warn } = createPlugin();
707+
it('warns at build start when the specifier does not resolve', async () => {
708+
const { tx, dir, warn, buildStart } = createPlugin();
707709
idResolver.mockResolvedValue(undefined);
708710

711+
await buildStart();
709712
expect(await tx(join(dir, 'a.js'))).toBeUndefined();
710713
expect(await tx(join(dir, 'b.js'))).toBeUndefined();
711714
expect(warn).toHaveBeenCalledTimes(1);
@@ -715,6 +718,82 @@ describe('package specifier as wrangler `main`', () => {
715718
});
716719
});
717720

721+
describe('virtual module as wrangler `main`', () => {
722+
const MAIN = 'virtual:solid-ssr-handler';
723+
const RESOLVED_ID = `\0${MAIN}`;
724+
const code = 'export default { fetch() { return new Response("ok"); } };';
725+
const ssr = { name: 'ssr' };
726+
727+
beforeEach(() => {
728+
idResolver.mockReset();
729+
// Vite's resolver does not see virtual modules other plugins provide.
730+
idResolver.mockResolvedValue(undefined);
731+
});
732+
733+
function createPlugin(files: Record<string, string> = {}) {
734+
const dir = writeTempDir({ 'wrangler.jsonc': JSON.stringify({ main: MAIN }), ...files });
735+
const plugin = sentryCloudflareAutoInstrumentPlugin();
736+
plugin.configResolved({ root: dir });
737+
738+
const warn = vi.fn();
739+
// The plugin pipeline, where the plugin that serves the virtual module resolves it.
740+
const resolve = vi.fn(async (source: string) => (source === MAIN ? { id: RESOLVED_ID } : null));
741+
const context = { parse: (c: string) => parseJS(c), warn, environment: ssr, resolve };
742+
const buildStart = () => plugin.buildStart.call(context);
743+
const tx = (id: string) => plugin.transform.call(context, code, id);
744+
745+
return { plugin, tx, buildStart, resolve, dir, warn };
746+
}
747+
748+
it('wraps the module the plugin pipeline resolves `main` to', async () => {
749+
const { tx, buildStart, resolve, dir, warn } = createPlugin();
750+
751+
await buildStart();
752+
const result = await tx(RESOLVED_ID);
753+
expect(resolve).toHaveBeenCalledWith(MAIN, join(dir, 'wrangler.jsonc'));
754+
expect(result.code).toContain('__SENTRY__.withSentry(');
755+
expect(warn).not.toHaveBeenCalled();
756+
});
757+
758+
it('does not wrap other modules', async () => {
759+
const { tx, buildStart, dir } = createPlugin();
760+
761+
await buildStart();
762+
expect(await tx(join(dir, 'src/app.js'))).toBeUndefined();
763+
expect(await tx(`${RESOLVED_ID}-impl`)).toBeUndefined();
764+
});
765+
766+
it('imports instrument.server.* by its absolute path', async () => {
767+
const { tx, buildStart, dir } = createPlugin({
768+
'instrument.server.ts': 'export default (env) => ({ dsn: env.SENTRY_DSN });',
769+
});
770+
771+
await buildStart();
772+
const result = await tx(RESOLVED_ID);
773+
expect(result.code).toContain(
774+
`import __SENTRY_OPTIONS_CALLBACK__ from '${join(dir, 'instrument.server.ts').replace(/\\/g, '/')}';`,
775+
);
776+
});
777+
778+
it('warns at build start when no plugin resolves `main`', async () => {
779+
const { buildStart, resolve, warn } = createPlugin();
780+
resolve.mockResolvedValue(null);
781+
782+
await buildStart();
783+
expect(warn).toHaveBeenCalledWith(
784+
'[sentry] Could not resolve the wrangler `main` "virtual:solid-ssr-handler". Auto-instrumentation disabled.',
785+
);
786+
});
787+
788+
it('does not resolve `main` in the client environment', async () => {
789+
const { plugin, resolve, warn } = createPlugin();
790+
791+
await plugin.buildStart.call({ warn, environment: { name: 'client' }, resolve });
792+
expect(resolve).not.toHaveBeenCalled();
793+
expect(warn).not.toHaveBeenCalled();
794+
});
795+
});
796+
718797
// ---------------------------------------------------------------------------
719798
// instrument.server.* auto-detection (config from a conventional module)
720799
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)