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
Expand Up @@ -14,7 +14,7 @@ test.describe('server-side errors', () => {

expect(errorEventFrames?.[errorEventFrames?.length - 1]).toEqual(
expect.objectContaining({
function: 'load$1',
function: 'load',
in_app: true,
}),
);
Expand Down Expand Up @@ -42,7 +42,7 @@ test.describe('server-side errors', () => {

expect(errorEventFrames?.[errorEventFrames?.length - 1]).toEqual(
expect.objectContaining({
function: 'load$1',
function: 'load',
in_app: true,
}),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ if (process.env.E2E_VARIANT === 'manual-upload') {
}
} else {
// Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed.
const { requests, sourcemaps } = assertSourceMapUpload({
const { requests } = assertSourceMapUpload({
outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT],
// The server output keeps `sourceMappingURL` comments that point at the deleted maps. Nothing serves
// it, so only the client output must be free of them.
Expand All @@ -72,13 +72,6 @@ if (process.env.E2E_VARIANT === 'manual-upload') {
requests.some(r => r.url?.includes('/releases') && r.method === 'POST'),
'Expected a POST to create the release',
);

// The auto-instrument plugin loads wrapped modules under this suffix. It must be stripped before
// upload, or the uploaded sources don't match the frames Sentry receives.
const wrappedSources = sourcemaps
.flatMap(map => map.sourcemap.sources ?? [])
.filter(source => source.includes('?sentry-auto-wrap'));
assert.deepEqual(wrappedSources, [], 'Expected no uploaded source to carry the auto-wrap query suffix');
}

console.log('All sourcemap assertions passed!');
Expand Down
2 changes: 0 additions & 2 deletions packages/sveltekit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,6 @@
"@sentry/server-utils": "11.16.0",
"@sentry/svelte": "11.16.0",
"@sentry/bundler-plugins": "11.16.0",
"@sveltejs/acorn-typescript": "^1.0.13",
"acorn": "^8.14.0",
"magic-string": "~0.30.0",
"sorcery": "1.0.0"
},
Expand Down
2 changes: 0 additions & 2 deletions packages/sveltekit/src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { HttpError, Redirect } from '@sveltejs/kit';
import { isObjectLike } from '@sentry/core';

export const WRAPPED_MODULE_SUFFIX = '?sentry-auto-wrap';

export type SentryWrappedFlag = {
/**
* If this flag is set, we know that the load event was already wrapped once
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
join,
rewriteFramesIntegration as originalRewriteFramesIntegration,
} from '@sentry/core';
import { WRAPPED_MODULE_SUFFIX } from '../../common/utils';
import type { GlobalWithSentryValues } from '../../vite/injectGlobalValues';

type StackFrameIteratee = (frame: StackFrame) => StackFrame;
Expand Down Expand Up @@ -79,12 +78,6 @@ export function rewriteFramesIteratee(frame: StackFrame): StackFrame {

delete frame.module;

// In dev-mode, the WRAPPED_MODULE_SUFFIX is still present in the frame's file name.
// We need to remove it to make sure that the frame's filename matches the actual file
if (frame.filename.endsWith(WRAPPED_MODULE_SUFFIX)) {
frame.filename = frame.filename.slice(0, -WRAPPED_MODULE_SUFFIX.length);
}

return frame;
}

Expand Down
198 changes: 80 additions & 118 deletions packages/sveltekit/src/vite/autoInstrument.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { tsPlugin } from '@sveltejs/acorn-typescript';
import * as acorn from 'acorn';
import * as fs from 'fs';
import * as path from 'path';
import {
addImport,
collectDeclaringStatements,
collectManuallyWrappedLocals,
createCallSiteRewriter,
exportedName,
findNamedExports,
hasImport,
type RewriteRule,
type RuleContext,
wrapForeignExport,
wrapInlineExport,
wrapLocalBinding,
wrapSpecifierExports,
} from '@sentry/bundler-plugins/rewriter';
import type { Plugin } from 'vite';
import { WRAPPED_MODULE_SUFFIX } from '../common/utils';
import type { ResolvedKitConfig } from './kitConfig';
import { isNativeServerTracingEnabled } from './kitConfig';
import { stringifyForCodeInjection } from '@sentry/core';

const AcornParser = acorn.Parser.extend(tsPlugin());

export type AutoInstrumentSelection = {
/**
Expand All @@ -34,6 +41,10 @@ type AutoInstrumentPluginOptions = AutoInstrumentSelection & {
getKitConfig: () => Promise<ResolvedKitConfig>;
};

type LoadWrapper = 'wrapLoadWithSentry' | 'wrapServerLoadWithSentry';

const LOAD_WRAPPERS: readonly LoadWrapper[] = ['wrapLoadWithSentry', 'wrapServerLoadWithSentry'];

/**
* Creates a Vite plugin that automatically instruments the parts of the app
* specified in @param options. This includes
Expand All @@ -54,6 +65,15 @@ export function makeAutoInstrumentationPlugin(options: AutoInstrumentPluginOptio
const shouldOnlyInstrumentClient = (): Promise<boolean> =>
(onlyInstrumentClientPromise ??= getKitConfig().then(isNativeServerTracingEnabled));

const universalRules = wrapLoadEnabled
? [loadRule(/^\+(page|layout)\.(js|ts|mjs|mts)$/, 'wrapLoadWithSentry', debug)]
: [];
const serverRules = wrapServerLoadEnabled
? [loadRule(/^\+(page|layout)\.server\.(js|ts|mjs|mts)$/, 'wrapServerLoadWithSentry', debug)]
: [];
const universalRewriter = createCallSiteRewriter(universalRules);
const rewriter = createCallSiteRewriter([...universalRules, ...serverRules]);

return {
name: 'sentry-auto-instrumentation',
// This plugin needs to run as early as possible, before the SvelteKit plugin virtualizes all paths and ids
Expand All @@ -67,142 +87,84 @@ export function makeAutoInstrumentationPlugin(options: AutoInstrumentPluginOptio
isServerBuild = !!config.build.ssr;
},

async load(id) {
async transform(code, id) {
// On Vite 6+ `config.build.ssr` captured in `configResolved` no longer reliably reflects the per-environment build.
// Prefer the environment of the current build (`this.environment.name === 'ssr'`) and fall back to
// `isServerBuild` for older Vite versions that don't expose environments.
const environmentName = (this as { environment?: { name?: string } }).environment?.name;
const isServerEnvironment = environmentName != null ? environmentName === 'ssr' : !!isServerBuild;

if (isServerEnvironment && (await shouldOnlyInstrumentClient())) {
return null;
}

const applyUniversalLoadWrapper =
wrapLoadEnabled &&
/^\+(page|layout)\.(js|ts|mjs|mts)$/.test(path.basename(id)) &&
(await canWrapLoad(id, debug));

if (applyUniversalLoadWrapper) {
// eslint-disable-next-line no-console
debug && console.log(`Wrapping ${id} with Sentry load wrapper`);
return getWrapperCode('wrapLoadWithSentry', `${id}${WRAPPED_MODULE_SUFFIX}`);
}

if (await shouldOnlyInstrumentClient()) {
// Now that we've checked universal files, we can early return and avoid further
// regexp checks below for server-only files.
const onlyInstrumentClient = await shouldOnlyInstrumentClient();
if (isServerEnvironment && onlyInstrumentClient) {
return null;
}

const applyServerLoadWrapper =
wrapServerLoadEnabled &&
/^\+(page|layout)\.server\.(js|ts|mjs|mts)$/.test(path.basename(id)) &&
(await canWrapLoad(id, debug));
return (onlyInstrumentClient ? universalRewriter : rewriter).transform(code, id, this);
},
};
}

if (applyServerLoadWrapper) {
function loadRule(basename: RegExp, wrapper: LoadWrapper, debug: boolean): RewriteRule {
return {
name: wrapper,
include: { basename, contains: ['load'] },
apply: ctx => {
if (wrapLoadExport(ctx, wrapper)) {
// eslint-disable-next-line no-console
debug && console.log(`Wrapping ${id} with Sentry load wrapper`);
return getWrapperCode('wrapServerLoadWithSentry', `${id}${WRAPPED_MODULE_SUFFIX}`);
debug && console.log(`Wrapping ${ctx.id} with Sentry load wrapper`);
}

return null;
},
};
}

/**
* We only want to apply our wrapper to files that
* Wraps the module's `load` export in place, in any export form, unless the
* user already wrapped it.
*
* - Have no Sentry code yet in them. This is to avoid double-wrapping or interfering with custom
* Sentry calls.
* - Actually declare a `load` function. The second check of course is not 100% accurate, but it's good enough.
* Injecting our wrapper into files that don't declare a `load` function would result in a build-time warning
* because vite/rollup warns if we reference an export from the user's file in our wrapping code that
* doesn't exist.
*
* Exported for testing
*
* @returns `true` if we can wrap the given file, `false` otherwise
* @returns whether the export was wrapped
*/
export async function canWrapLoad(id: string, debug: boolean): Promise<boolean> {
// Some 3rd party plugins add ids to the build that actually don't exist.
// We need to check for that here, otherwise users get get a build errors.
if (!fs.existsSync(id)) {
debug &&
// eslint-disable-next-line no-console
console.log(
`Skipping wrapping ${id} because it doesn't exist. A 3rd party plugin might have added this as a virtual file to the build`,
);
return false;
}

const code = (await fs.promises.readFile(id, 'utf8')).toString();

let program: acorn.Program;
try {
program = AcornParser.parse(code, {
sourceType: 'module',
ecmaVersion: 'latest',
locations: true,
});
} catch {
// eslint-disable-next-line no-console
debug && console.log(`Skipping wrapping ${id} because it doesn't contain valid JavaScript or TypeScript`);
return false;
}

const hasLoadDeclaration = program.body
.filter((statement): statement is acorn.ExportNamedDeclaration => statement.type === 'ExportNamedDeclaration')
.find(exportDecl => {
// find `export const load = ...`
if (exportDecl.declaration?.type === 'VariableDeclaration') {
const variableDeclarations = exportDecl.declaration.declarations;
return variableDeclarations.find(
decl => decl.type === 'VariableDeclarator' && decl.id.type === 'Identifier' && decl.id.name === 'load',
);
function wrapLoadExport({ ast, state }: RuleContext, wrapper: LoadWrapper): boolean {
const handWrapped = collectManuallyWrappedLocals(ast, LOAD_WRAPPERS);
const declaringStatements = collectDeclaringStatements(ast);
const wrap = (target: string): string => `${wrapper}(${target})`;
let wrapped = false;

for (const node of findNamedExports(ast, 'load')) {
if (node.declaration) {
if (handWrapped.has('load')) {
state.report.alreadyWrapped.push('load');
} else if (wrapInlineExport(state, node, 'load', wrap)) {
wrapped = true;
}
continue;
}

// find `export function load = ...`
if (exportDecl.declaration?.type === 'FunctionDeclaration') {
const functionId = exportDecl.declaration.id;
return functionId?.name === 'load';
wrapSpecifierExports(state, node, (specifier, sourceLiteral, prelude) => {
const local = specifier.local?.type === 'Identifier' ? specifier.local.name : undefined;
if (exportedName(specifier.exported) !== 'load' || !local) return undefined;

if (sourceLiteral) {
wrapped = true;
return wrapForeignExport(state, local, 'load', sourceLiteral, prelude, wrap);
}

// find `export { load, somethingElse as load, somethingElse as "load" }`
if (exportDecl.specifiers) {
return exportDecl.specifiers.find(specifier => {
return (
(specifier.exported.type === 'Identifier' && specifier.exported.name === 'load') ||
// ESTree/acorn represents `export { x as "load" }` with a Literal node (not Babel's StringLiteral)
(specifier.exported.type === 'Literal' && specifier.exported.value === 'load')
);
});
const declaringStatement = declaringStatements.get(local);
if (handWrapped.has(local)) {
state.report.alreadyWrapped.push('load');
return undefined;
}
if (!declaringStatement) return undefined;

return false;
wrapped = true;
return `${wrapLocalBinding(state, local, declaringStatement, wrap)} as load`;
});

if (!hasLoadDeclaration) {
// eslint-disable-next-line no-console
debug && console.log(`Skipping wrapping ${id} because it doesn't declare a \`load\` function`);
return false;
}

return true;
}

/**
* Return wrapper code fo the given module id and wrapping function
*/
function getWrapperCode(
wrapperFunction: 'wrapLoadWithSentry' | 'wrapServerLoadWithSentry',
idWithSuffix: string,
): string {
return (
`import { ${wrapperFunction} } from "@sentry/sveltekit";` +
`import * as userModule from ${stringifyForCodeInjection(idWithSuffix)};` +
`export const load = userModule.load ? ${wrapperFunction}(userModule.load) : undefined;` +
`export * from ${stringifyForCodeInjection(idWithSuffix)};`
);
if (wrapped) {
state.report.wrapped.push('load');
if (!hasImport(ast, '@sentry/sveltekit', wrapper)) {
addImport(state, ast, `import { ${wrapper} } from '@sentry/sveltekit';`);
}
}
return wrapped;
}
18 changes: 1 addition & 17 deletions packages/sveltekit/src/vite/sourceMaps.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeStringForRegex, resolveSourceMapsFeatures, uuid4 } from '@sentry/core';
import { resolveSourceMapsFeatures, uuid4 } from '@sentry/core';
import { getSentryRelease } from '@sentry/node';
import { addDebugIdToEmittedArtifacts } from '@sentry/bundler-plugins/core';
import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite';
Expand All @@ -7,7 +7,6 @@ import * as child_process from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import type { Plugin, UserConfig } from 'vite';
import { WRAPPED_MODULE_SUFFIX } from '../common/utils';
import { makeReleaseInjectionPlugin } from './injectRelease';
import type { ResolvedKitConfig } from './kitConfig';
import type { CustomSentryVitePluginOptions } from './types';
Expand Down Expand Up @@ -243,21 +242,6 @@ export async function makeCustomSentryVitePlugins(
console.error('[Source Maps Plugin] error while flattening', file, e);
}
}

// We need to remove the query string from the source map files that our auto-instrument plugin added
// to proxy the load functions during building.
const mapFile = `${file}.map`;
try {
const mapContent = (await fs.promises.readFile(mapFile, 'utf-8')).toString();
const cleanedMapContent = mapContent.replace(
// oxlint-disable-next-line sdk/no-regexp-constructor -- no user input + escaped anyway
new RegExp(escapeStringForRegex(WRAPPED_MODULE_SUFFIX), 'gm'),
'',
);
await fs.promises.writeFile(mapFile, cleanedMapContent);
} catch {
// Map file doesn't exist, nothing to clean
}
}

if (sourceMapsFeatures.injectDebugIds && !sourceMapsFeatures.upload) {
Expand Down
Loading
Loading