Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
dist
.void
.void-wrangler.jsonc
.cloudflare
.wrangler
test-results
pnpm-lock.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineCloudflareOptions } from '@sentry/cloudflare';

// The Sentry plugin looks for this file in the Vite root of a Void app, because the directory of the
// generated entry (`.void/`) is not in version control.
export default defineCloudflareOptions((env: { E2E_TEST_DSN: string }) => ({
dsn: env.E2E_TEST_DSN,
environment: 'qa',
tunnel: 'http://localhost:3031/',
tracesSampleRate: 1.0,
transportOptions: {
bufferSize: 1000,
},
}));
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineMiddleware } from 'void';

export default defineMiddleware(async (_c, next) => {
await next();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "void-cloudflare",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"preview": "vite preview --port 8787 --strictPort",
"test": "playwright test",
"test:build": "pnpm install && pnpm build",
"test:assert": "pnpm test"
},
"dependencies": {
"@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz",
"void": "^1.12.2"
},
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@sentry/conventions": "0.36.0",
"vite": "^8.4.0",
"wrangler": "^4.156.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { getPlaywrightConfig } from '@sentry-internal/test-utils';

export default getPlaywrightConfig({
startCommand: 'pnpm preview',
port: 8787,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
allowBuilds:
esbuild: true
workerd: true
minimumReleaseAge: 0
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineHandler } from 'void';

export const GET = defineHandler(() => {
throw new Error('Void route error');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineHandler } from 'void';

export const GET = defineHandler(c => ({ id: c.req.param('id') }));
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { startEventProxyServer } from '@sentry-internal/test-utils';

startEventProxyServer({
port: 3031,
proxyServerName: 'void-cloudflare',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import { SENTRY_ENVIRONMENT, SENTRY_ORIGIN, SENTRY_SEGMENT_ID } from '@sentry/conventions/attributes';
import { HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';

const APP_NAME = 'void-cloudflare';

test('names the request span after the Void route and adds middleware spans', async ({ baseURL }) => {
const spansPromise = collectStreamedSpansUntilSegment(
APP_NAME,
segment => getSpanOp(segment) === HTTP_SERVER && !!segment.name?.includes('/api/users'),
);

const response = await fetch(`${baseURL}/api/users/42`);
expect(response.status).toBe(200);

const spans = await spansPromise;
const segment = spans.find(span => span.is_segment && getSpanOp(span) === HTTP_SERVER)!;

expect(segment.name).toBe('GET /api/users/:id');
expect(segment.attributes[SENTRY_ORIGIN]?.value).toBe('auto.http.cloudflare');
// Only `instrument.server.ts` sets this environment.
expect(segment.attributes[SENTRY_ENVIRONMENT]?.value).toBe('qa');

expect(
spans.filter(
span =>
getSpanOp(span) === MIDDLEWARE &&
span.attributes[SENTRY_ORIGIN]?.value === 'auto.middleware.hono' &&
span.attributes[SENTRY_SEGMENT_ID]?.value === segment.span_id,
),
).not.toHaveLength(0);
});

test('captures an error that a Void route throws', async ({ baseURL }) => {
const errorPromise = waitForError(APP_NAME, event => event.exception?.values?.[0]?.value === 'Void route error');

const response = await fetch(`${baseURL}/api/error`);
expect(response.status).toBe(500);

const errorEvent = await errorPromise;

expect(errorEvent.exception?.values?.[0]?.mechanism).toEqual({
handled: false,
type: 'auto.http.hono.context_error',
});
expect(errorEvent.transaction).toBe('GET /api/error');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';
import { defineConfig } from 'vite';
import { voidPlugin } from 'void';

// The app has no wrangler config and no Sentry calls. Void generates the Worker entry (`.void/entry.ts`),
// and the Sentry plugin wraps it at build time.
// Void does not install `wrangler`. It is a dev dependency because `@sentry/cloudflare/vite` imports it.
export default defineConfig({
plugins: [voidPlugin(), sentryCloudflareVitePlugin()],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from 'void/config';

export default defineConfig({
worker: {
compatibility_date: '2026-11-01',
compatibility_flags: ['nodejs_compat'],
vars: {
E2E_TEST_DSN: process.env.E2E_TEST_DSN,
},
},
});
18 changes: 17 additions & 1 deletion packages/cloudflare/src/vite/autoInstrument.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { basename, dirname, isAbsolute } from 'node:path';
import { basename, dirname, isAbsolute, resolve } from 'node:path';
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 @@ -166,6 +166,22 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
isVinext = config.plugins?.some(plugin => plugin.name?.startsWith('vinext:')) ?? false;

const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);

// A native Void app. `void:routing` writes the Worker entry, and Void gives it to
// `@cloudflare/vite-plugin` in code, so a wrangler config is optional and its `main` is not used.
if (config.plugins?.some(plugin => plugin.name === 'void:routing')) {
wranglerConfig = result?.config ?? {
durableObjects: [],
workflows: [],
workerEntrypoints: [],
sameWorkerBindings: [],
};
entryFilePath = normalizePath(resolve(config.root, '.void/entry.ts'));
// `.void` is a generated directory that is not in version control.
instrumentFilePath = resolveInstrumentFile(config.root);
return;
}

if (!result) {
// An explicit path that fails is a misconfiguration worth naming;
// without one, hint at the option so custom-named configs (e.g. a
Expand Down
3 changes: 3 additions & 0 deletions packages/cloudflare/src/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export interface SentryCloudflareVitePluginOptions {
* left alone, so this is safe alongside manual instrumentation. Set to
* `false` to opt out.
*
* A native Void app needs no wrangler config. The plugin wraps the Worker entry that Void generates and
* reads the options from an `instrument.server.*` file in the Vite root.
*
* The plugin also adds the bindings that resolve to the wrapped classes (this worker's own
* Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to
* other workers stay opt-in, their receivers may not run Sentry.
Expand Down
42 changes: 42 additions & 0 deletions packages/cloudflare/test/vite/autoInstrument.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,48 @@ describe('wranglerConfigPath option', () => {
});
});

describe('native Void app', () => {
const entryCode = 'export default class extends WorkerEntrypoint { fetch(request) { return handle(request); } }';

it('wraps the generated entry with the options file from the Vite root, without a wrangler config', async () => {
const dir = writeTempDir({ 'instrument.server.ts': 'export default env => ({ dsn: env.SENTRY_DSN });' });
const warnings: string[] = [];
const plugin = sentryCloudflareAutoInstrumentPlugin();
plugin.configResolved({
root: dir,
plugins: [{ name: 'void:routing' }],
logger: { warn: msg => warnings.push(msg) },
});

const result = await plugin.transform.call(
{ parse: (c: string) => parseJS(c) },
entryCode,
join(dir, '.void/entry.ts'),
);

expect(warnings).toEqual([]);
expect(result.code).toBe(
[
"import * as __SENTRY__ from '@sentry/cloudflare';",
"import __SENTRY_OPTIONS_CALLBACK__ from '../instrument.server.ts';",
`var __SENTRY_DEFAULT_EXPORT__ = { default: ${entryCode.replace('export default ', '')} }.default;`,
'export { __SENTRY_DEFAULT_EXPORT__ as default };',
'__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(__SENTRY_OPTIONS_CALLBACK__, __SENTRY_DEFAULT_EXPORT__);',
].join('\n'),
);
});

it('uses the generated entry and the settings of a wrangler config that names another `main`', async () => {
const dir = writeTempDir({ 'wrangler.toml': 'name = "void-app"\nmain = "src/index.ts"' });
const plugin = sentryCloudflareAutoInstrumentPlugin();
plugin.configResolved({ root: dir, plugins: [{ name: 'void:routing' }] });
const tx = (id: string) => plugin.transform.call({ parse: (c: string) => parseJS(c) }, entryCode, id);

expect(await tx(join(dir, 'src/index.ts'))).toBeUndefined();
expect((await tx(join(dir, '.void/entry.ts'))).code).toContain('"name":"void-app"');
});
});

describe('package specifier as wrangler `main`', () => {
const MAIN = 'vinext/server/fetch-handler';
const code = 'export default { fetch() { return new Response("ok"); } };';
Expand Down
Loading