Skip to content

Commit d15f512

Browse files
committed
feat(nuxt): Add Rollup plugin to wrap server entry with import()
1 parent 86c626e commit d15f512

File tree

3 files changed

+224
-5
lines changed

3 files changed

+224
-5
lines changed

packages/nuxt/src/vite/addServerConfig.ts

+105-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,17 @@ import { createResolver } from '@nuxt/kit';
33
import type { Nuxt } from '@nuxt/schema';
44
import { consoleSandbox } from '@sentry/utils';
55
import type { Nitro } from 'nitropack';
6+
import type { InputPluginOption } from 'rollup';
67
import type { SentryNuxtModuleOptions } from '../common/types';
8+
import {
9+
QUERY_END_INDICATOR,
10+
SENTRY_FUNCTIONS_REEXPORT,
11+
SENTRY_WRAPPED_ENTRY,
12+
constructFunctionReExport,
13+
stripQueryPart,
14+
} from './utils';
15+
16+
const SERVER_CONFIG_FILENAME = 'sentry.server.config';
717

818
/**
919
* Adds the `sentry.server.config.ts` file as `sentry.server.config.mjs` to the `.output` directory to be able to reference this file in the node --import option.
@@ -23,7 +33,7 @@ export function addServerConfigToBuild(
2333
'server' in viteInlineConfig.build.rollupOptions.input
2434
) {
2535
// Create a rollup entry for the server config to add it as `sentry.server.config.mjs` to the build
26-
(viteInlineConfig.build.rollupOptions.input as { [entryName: string]: string })['sentry.server.config'] =
36+
(viteInlineConfig.build.rollupOptions.input as { [entryName: string]: string })[SERVER_CONFIG_FILENAME] =
2737
createResolver(nuxt.options.srcDir).resolve(`/${serverConfigFile}`);
2838
}
2939

@@ -34,8 +44,8 @@ export function addServerConfigToBuild(
3444
nitro.hooks.hook('close', async () => {
3545
const buildDirResolver = createResolver(nitro.options.buildDir);
3646
const serverDirResolver = createResolver(nitro.options.output.serverDir);
37-
const source = buildDirResolver.resolve('dist/server/sentry.server.config.mjs');
38-
const destination = serverDirResolver.resolve('sentry.server.config.mjs');
47+
const source = buildDirResolver.resolve(`dist/server/${SERVER_CONFIG_FILENAME}.mjs`);
48+
const destination = serverDirResolver.resolve(`${SERVER_CONFIG_FILENAME}.mjs`);
3949

4050
try {
4151
await fs.promises.access(source, fs.constants.F_OK);
@@ -85,7 +95,7 @@ export function addSentryTopImport(moduleOptions: SentryNuxtModuleOptions, nitro
8595

8696
try {
8797
fs.readFile(entryFilePath, 'utf8', (err, data) => {
88-
const updatedContent = `import './sentry.server.config.mjs';\n${data}`;
98+
const updatedContent = `import './${SERVER_CONFIG_FILENAME}.mjs';\n${data}`;
8999

90100
fs.writeFile(entryFilePath, updatedContent, 'utf8', () => {
91101
if (moduleOptions.debug) {
@@ -111,3 +121,94 @@ export function addSentryTopImport(moduleOptions: SentryNuxtModuleOptions, nitro
111121
}
112122
});
113123
}
124+
125+
/**
126+
* This function modifies the Rollup configuration to include a plugin that wraps the entry file with a dynamic import (`import()`)
127+
* and adds the Sentry server config with the static `import` declaration.
128+
*
129+
* With this, the Sentry server config can be loaded before all other modules of the application (which is needed for import-in-the-middle).
130+
* See: https://nodejs.org/api/module.html#enabling
131+
*/
132+
export function addDynamicImportEntryFileWrapper(nitro: Nitro, serverConfigFile: string): void {
133+
if (!nitro.options.rollupConfig) {
134+
nitro.options.rollupConfig = { output: {} };
135+
}
136+
137+
if (nitro.options.rollupConfig?.plugins === null || nitro.options.rollupConfig?.plugins === undefined) {
138+
nitro.options.rollupConfig.plugins = [];
139+
} else if (!Array.isArray(nitro.options.rollupConfig.plugins)) {
140+
// `rollupConfig.plugins` can be a single plugin, so we want to put it into an array so that we can push our own plugin
141+
nitro.options.rollupConfig.plugins = [nitro.options.rollupConfig.plugins];
142+
}
143+
144+
nitro.options.rollupConfig.plugins.push(
145+
// @ts-expect-error - This is the correct type, but it shows an error because of two different definitions
146+
wrapEntryWithDynamicImport(createResolver(nitro.options.srcDir).resolve(`/${serverConfigFile}`)),
147+
);
148+
}
149+
150+
function wrapEntryWithDynamicImport(resolvedSentryConfigPath: string): InputPluginOption {
151+
const containsSuffix = (sourcePath: string): boolean => {
152+
return sourcePath.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`) || sourcePath.includes(SENTRY_FUNCTIONS_REEXPORT);
153+
};
154+
155+
return {
156+
name: 'sentry-wrap-entry-with-dynamic-import',
157+
async resolveId(source, importer, options) {
158+
if (source.includes(`/${SERVER_CONFIG_FILENAME}`)) {
159+
return { id: source, moduleSideEffects: true };
160+
}
161+
162+
if (source === 'import-in-the-middle/hook.mjs') {
163+
return { id: source, moduleSideEffects: true, external: true };
164+
}
165+
166+
if (options.isEntry && !source.includes(SENTRY_WRAPPED_ENTRY)) {
167+
const resolution = await this.resolve(source, importer, options);
168+
169+
// If it cannot be resolved or is external, just return it
170+
// so that Rollup can display an error
171+
if (!resolution || resolution?.external) return resolution;
172+
173+
const moduleInfo = await this.load(resolution);
174+
175+
moduleInfo.moduleSideEffects = true;
176+
177+
const exportedFunctions = moduleInfo.exportedBindings?.['.'];
178+
179+
// checks are needed to prevent multiple attachment of the suffix
180+
return containsSuffix(source) || containsSuffix(resolution.id)
181+
? resolution.id
182+
: resolution.id
183+
// concat the query params to mark the file (also attaches names of exports - this is needed for serverless functions to re-export the handler)
184+
.concat(SENTRY_WRAPPED_ENTRY)
185+
.concat(
186+
exportedFunctions?.length
187+
? SENTRY_FUNCTIONS_REEXPORT.concat(exportedFunctions.join(',')).concat(QUERY_END_INDICATOR)
188+
: '',
189+
);
190+
}
191+
return null;
192+
},
193+
load(id: string) {
194+
if (id.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`)) {
195+
const entryId = stripQueryPart(id);
196+
197+
const reExportedFunctions = id.includes(SENTRY_FUNCTIONS_REEXPORT)
198+
? constructFunctionReExport(id, entryId)
199+
: '';
200+
201+
return (
202+
// Import the Sentry server config
203+
`import ${JSON.stringify(resolvedSentryConfigPath)};\n` +
204+
// Dynamic import for the previous, actual entry point.
205+
// import() can be used for any code that should be run after the hooks are registered (https://nodejs.org/api/module.html#enabling)
206+
`import(${JSON.stringify(entryId)});\n` +
207+
`${reExportedFunctions}\n`
208+
);
209+
}
210+
211+
return null;
212+
},
213+
};
214+
}

packages/nuxt/src/vite/utils.ts

+52
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,55 @@ export function findDefaultSdkInitFile(type: 'server' | 'client'): string | unde
2424

2525
return filePaths.find(filename => fs.existsSync(filename));
2626
}
27+
28+
export const SENTRY_WRAPPED_ENTRY = '?sentry-query-wrapped-entry';
29+
export const SENTRY_FUNCTIONS_REEXPORT = '?sentry-query-functions-reexport=';
30+
export const QUERY_END_INDICATOR = 'SENTRY-QUERY-END';
31+
32+
/**
33+
* Strips a specific query part from a URL.
34+
*
35+
* Only exported for testing.
36+
*/
37+
export function stripQueryPart(url: string): string {
38+
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
39+
const regex = new RegExp(`\\${SENTRY_WRAPPED_ENTRY}.*?\\${QUERY_END_INDICATOR}`);
40+
return url.replace(regex, '');
41+
}
42+
43+
/**
44+
* Extracts and sanitizes function reexport query parameters from a query string.
45+
*
46+
* Only exported for testing.
47+
*/
48+
export function extractFunctionReexportQueryParameters(query: string): string[] {
49+
// Regex matches the comma-separated params between the functions query
50+
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
51+
const regex = new RegExp(`\\${SENTRY_FUNCTIONS_REEXPORT}(.*?)\\${QUERY_END_INDICATOR}`);
52+
const match = query.match(regex);
53+
54+
return match && match[1]
55+
? match[1]
56+
.split(',')
57+
.filter(param => param !== '' && param !== 'default')
58+
// sanitize
59+
.map((str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
60+
: [];
61+
}
62+
63+
/**
64+
* Constructs a code snippet with function reexports (can be used in Rollup plugins)
65+
*/
66+
export function constructFunctionReExport(pathWithQuery: string, entryId: string): string {
67+
const functionNames = extractFunctionReexportQueryParameters(pathWithQuery);
68+
69+
return functionNames.reduce(
70+
(functionsCode, currFunctionName) =>
71+
functionsCode.concat(
72+
`export function ${currFunctionName}(...args) {\n` +
73+
` return import(${JSON.stringify(entryId)}).then((res) => res.${currFunctionName}(...args));\n` +
74+
'}\n',
75+
),
76+
'',
77+
);
78+
}

packages/nuxt/test/vite/utils.test.ts

+67-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import * as fs from 'fs';
22
import { afterEach, describe, expect, it, vi } from 'vitest';
3-
import { findDefaultSdkInitFile } from '../../src/vite/utils';
3+
import {
4+
QUERY_END_INDICATOR,
5+
SENTRY_FUNCTIONS_REEXPORT,
6+
SENTRY_WRAPPED_ENTRY,
7+
constructFunctionReExport,
8+
extractFunctionReexportQueryParameters,
9+
findDefaultSdkInitFile,
10+
stripQueryPart,
11+
} from '../../src/vite/utils';
412

513
vi.mock('fs');
614

@@ -59,3 +67,61 @@ describe('findDefaultSdkInitFile', () => {
5967
expect(result).toMatch('packages/nuxt/sentry.server.config.js');
6068
});
6169
});
70+
71+
describe('stripQueryPart', () => {
72+
it('strips the specific query part from the URL', () => {
73+
const url = `/example/path${SENTRY_WRAPPED_ENTRY}${SENTRY_FUNCTIONS_REEXPORT}foo,${QUERY_END_INDICATOR}`;
74+
const result = stripQueryPart(url);
75+
expect(result).toBe('/example/path');
76+
});
77+
78+
it('returns the same URL if the specific query part is not present', () => {
79+
const url = '/example/path?other-query=param';
80+
const result = stripQueryPart(url);
81+
expect(result).toBe(url);
82+
});
83+
});
84+
85+
describe('extractFunctionReexportQueryParameters', () => {
86+
it.each([
87+
[`${SENTRY_FUNCTIONS_REEXPORT}foo,bar,${QUERY_END_INDICATOR}`, ['foo', 'bar']],
88+
[`${SENTRY_FUNCTIONS_REEXPORT}foo,bar,default${QUERY_END_INDICATOR}`, ['foo', 'bar']],
89+
[
90+
`${SENTRY_FUNCTIONS_REEXPORT}foo,a.b*c?d[e]f(g)h|i\\\\j(){hello},${QUERY_END_INDICATOR}`,
91+
['foo', 'a\\.b\\*c\\?d\\[e\\]f\\(g\\)h\\|i\\\\\\\\j\\(\\)\\{hello\\}'],
92+
],
93+
[`/example/path/${SENTRY_FUNCTIONS_REEXPORT}foo,bar${QUERY_END_INDICATOR}`, ['foo', 'bar']],
94+
[`${SENTRY_FUNCTIONS_REEXPORT}${QUERY_END_INDICATOR}`, []],
95+
['?other-query=param', []],
96+
])('extracts parameters from the query string: %s', (query, expected) => {
97+
const result = extractFunctionReexportQueryParameters(query);
98+
expect(result).toEqual(expected);
99+
});
100+
});
101+
102+
describe('constructFunctionReExport', () => {
103+
it('constructs re-export code for given query parameters and entry ID', () => {
104+
const query = `${SENTRY_FUNCTIONS_REEXPORT}foo,bar,${QUERY_END_INDICATOR}}`;
105+
const query2 = `${SENTRY_FUNCTIONS_REEXPORT}foo,bar${QUERY_END_INDICATOR}}`;
106+
const entryId = './module';
107+
const result = constructFunctionReExport(query, entryId);
108+
const result2 = constructFunctionReExport(query2, entryId);
109+
110+
const expected = `
111+
export function foo(...args) {
112+
return import("./module").then((res) => res.foo(...args));
113+
}
114+
export function bar(...args) {
115+
return import("./module").then((res) => res.bar(...args));
116+
}`;
117+
expect(result.trim()).toBe(expected.trim());
118+
expect(result2.trim()).toBe(expected.trim());
119+
});
120+
121+
it('returns an empty string if the query string is empty', () => {
122+
const query = '';
123+
const entryId = './module';
124+
const result = constructFunctionReExport(query, entryId);
125+
expect(result).toBe('');
126+
});
127+
});

0 commit comments

Comments
 (0)