Skip to content

Commit 58c3718

Browse files
committed
move to virtual injection file
1 parent 6d03f84 commit 58c3718

File tree

5 files changed

+104
-21
lines changed

5 files changed

+104
-21
lines changed

packages/sveltekit/src/server/utils.ts

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type { DynamicSamplingContext, StackFrame, TraceparentData } from '@sentry/types';
2-
import type { InternalGlobal } from '@sentry/utils';
32
import {
43
baggageHeaderToDynamicSamplingContext,
54
basename,
@@ -11,17 +10,7 @@ import {
1110
import type { RequestEvent } from '@sveltejs/kit';
1211

1312
import { WRAPPED_MODULE_SUFFIX } from '../vite/autoInstrument';
14-
15-
export type GlobalSentryValues = {
16-
__sentry_sveltekit_output_dir?: string;
17-
};
18-
19-
/**
20-
* Extend the `global` type with custom properties that are
21-
* injected by the SvelteKit SDK at build time.
22-
* @see packages/sveltekit/src/vite/sourcemaps.ts
23-
*/
24-
export type GlobalWithSentryValues = InternalGlobal & GlobalSentryValues;
13+
import type { GlobalWithSentryValues } from '../vite/injectGLobalValues';
2514

2615
/**
2716
* Takes a request event and extracts traceparent and DSC data
@@ -71,7 +60,7 @@ export function rewriteFramesIteratee(frame: StackFrame): StackFrame {
7160
let strippedFilename;
7261
if (svelteKitBuildOutDir) {
7362
strippedFilename = filename.replace(
74-
new RegExp(`^.*${escapeStringForRegex(join(svelteKitBuildOutDir, 'server'))}`),
63+
new RegExp(`^.*${escapeStringForRegex(join(svelteKitBuildOutDir, 'server'))}/`),
7564
'',
7665
);
7766
} else {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import type { InternalGlobal } from '@sentry/utils';
2+
3+
export type GlobalSentryValues = {
4+
__sentry_sveltekit_output_dir?: string;
5+
};
6+
7+
/**
8+
* Extend the `global` type with custom properties that are
9+
* injected by the SvelteKit SDK at build time.
10+
* @see packages/sveltekit/src/vite/sourcemaps.ts
11+
*/
12+
export type GlobalWithSentryValues = InternalGlobal & GlobalSentryValues;
13+
14+
export const VIRTUAL_GLOBAL_VALUES_FILE = '\0sentry-inject-global-values-file';
15+
16+
/**
17+
* @returns code that injects @param globalSentryValues into the global scope.
18+
*/
19+
export function getGlobalValueInjectionCode(globalSentryValues: GlobalSentryValues): string {
20+
if (Object.keys(globalSentryValues).length === 0) {
21+
return '';
22+
}
23+
24+
const sentryGlobal = '_global';
25+
26+
const globalCode = `var ${sentryGlobal} =
27+
typeof window !== 'undefined' ?
28+
window :
29+
typeof globalThis !== 'undefined' ?
30+
globalThis :
31+
typeof global !== 'undefined' ?
32+
global :
33+
typeof self !== 'undefined' ?
34+
self :
35+
{};`;
36+
const injectedValuesCode = Object.entries(globalSentryValues)
37+
.map(([key, value]) => `${sentryGlobal}["${key}"] = ${JSON.stringify(value)};`)
38+
.join('\n');
39+
40+
return `${globalCode}\n${injectedValuesCode}\n`;
41+
}

packages/sveltekit/src/vite/sourceMaps.ts

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ import * as path from 'path';
1010
import * as sorcery from 'sorcery';
1111
import type { Plugin } from 'vite';
1212

13-
import type { GlobalSentryValues } from '../server/utils';
1413
import { WRAPPED_MODULE_SUFFIX } from './autoInstrument';
1514
import type { SupportedSvelteKitAdapters } from './detectAdapter';
15+
import type { GlobalSentryValues } from './injectGLobalValues';
16+
import { getGlobalValueInjectionCode, VIRTUAL_GLOBAL_VALUES_FILE } from './injectGLobalValues';
1617
import { getAdapterOutputDir, getHooksFileName, loadSvelteConfig } from './svelteConfig';
1718

1819
// sorcery has no types, so these are some basic type definitions:
@@ -73,7 +74,7 @@ export async function makeCustomSentryVitePlugin(options?: CustomSentryVitePlugi
7374
const sentryPlugin: Plugin = sentryVitePlugin(mergedOptions);
7475

7576
const { debug } = mergedOptions;
76-
const { buildStart, resolveId, renderChunk } = sentryPlugin;
77+
const { buildStart, renderChunk } = sentryPlugin;
7778

7879
let isSSRBuild = true;
7980

@@ -91,7 +92,6 @@ export async function makeCustomSentryVitePlugin(options?: CustomSentryVitePlugi
9192
// These hooks are copied from the original Sentry Vite plugin.
9293
// They're mostly responsible for options parsing and release injection.
9394
buildStart,
94-
resolveId,
9595
renderChunk,
9696

9797
// Modify the config to generate source maps
@@ -107,6 +107,27 @@ export async function makeCustomSentryVitePlugin(options?: CustomSentryVitePlugi
107107
};
108108
},
109109

110+
resolveId: (id, _importer, _ref) => {
111+
if (id === VIRTUAL_GLOBAL_VALUES_FILE) {
112+
return {
113+
id: VIRTUAL_GLOBAL_VALUES_FILE,
114+
external: false,
115+
moduleSideEffects: true,
116+
};
117+
}
118+
// @ts-ignore - this hook exists on the plugin!
119+
return sentryPlugin.resolveId(id, _importer, _ref);
120+
},
121+
122+
load: id => {
123+
if (id === VIRTUAL_GLOBAL_VALUES_FILE) {
124+
return {
125+
code: getGlobalValueInjectionCode(globalSentryValues),
126+
};
127+
}
128+
return null;
129+
},
130+
110131
configResolved: config => {
111132
// The SvelteKit plugins trigger additional builds within the main (SSR) build.
112133
// We just need a mechanism to upload source maps only once.
@@ -122,10 +143,8 @@ export async function makeCustomSentryVitePlugin(options?: CustomSentryVitePlugi
122143
const isServerHooksFile = new RegExp(`/${escapeStringForRegex(serverHooksFile)}(.(js|ts|mjs|mts))?`).test(id);
123144

124145
if (isServerHooksFile) {
125-
const injectedCode = Object.entries(globalSentryValues)
126-
.map(([key, value]) => `globalThis["${key}"] = ${JSON.stringify(value)};`)
127-
.join('\n');
128-
modifiedCode = `${code}\n${injectedCode}\n`;
146+
const globalValuesImport = `; import "${VIRTUAL_GLOBAL_VALUES_FILE}";`;
147+
modifiedCode = `${code}\n${globalValuesImport}\n`;
129148
}
130149
// @ts-ignore - this hook exists on the plugin!
131150
return sentryPlugin.transform(modifiedCode, id);
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { getGlobalValueInjectionCode } from '../../src/vite/injectGlobalValues';
2+
3+
describe('getGlobalValueInjectionCode', () => {
4+
it('returns code that injects values into the global object', () => {
5+
const injectionCode = getGlobalValueInjectionCode({
6+
// @ts-ignore - just want to test this with multiple values
7+
something: 'else',
8+
__sentry_sveltekit_output_dir: '.svelte-kit/output',
9+
});
10+
expect(injectionCode).toEqual(`var _global =
11+
typeof window !== 'undefined' ?
12+
window :
13+
typeof globalThis !== 'undefined' ?
14+
globalThis :
15+
typeof global !== 'undefined' ?
16+
global :
17+
typeof self !== 'undefined' ?
18+
self :
19+
{};
20+
_global["something"] = "else";
21+
_global["__sentry_sveltekit_output_dir"] = ".svelte-kit/output";
22+
`);
23+
24+
// Check that the code above is in fact valid and works as expected
25+
// The return value of eval here is the value of the last expression in the code
26+
expect(eval(`${injectionCode}`)).toEqual('.svelte-kit/output');
27+
28+
delete globalThis.__sentry_sveltekit_output_dir;
29+
});
30+
31+
it('returns empty string if no values are passed', () => {
32+
expect(getGlobalValueInjectionCode({})).toEqual('');
33+
});
34+
});

packages/sveltekit/test/vite/sourceMaps.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ describe('makeCustomSentryVitePlugin()', () => {
5858
const plugin = await makeCustomSentryVitePlugin();
5959
// @ts-ignore this function exists!
6060
const transformedCode = await plugin.transform('foo', '/src/hooks.server.ts');
61-
const expectedtransformedCode = 'foo\nglobalThis["__sentry_sveltekit_output_dir"] = ".svelte-kit/output";\n';
61+
const expectedtransformedCode = 'foo\n; import "\0sentry-inject-global-values-file";\n';
6262
expect(mockedSentryVitePlugin.transform).toHaveBeenCalledWith(expectedtransformedCode, '/src/hooks.server.ts');
6363
expect(transformedCode).toEqual(expectedtransformedCode);
6464
});

0 commit comments

Comments
 (0)