import { basename } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import type { InputPluginOption } from 'rollup'; /** THIS FILE IS AN UTILITY FOR NITRO-BASED PACKAGES AND SHOULD BE KEPT IN SYNC IN NUXT, SOLIDSTART, ETC. */ export const SENTRY_WRAPPED_ENTRY = '?sentry-query-wrapped-entry'; export const SENTRY_WRAPPED_FUNCTIONS = '?sentry-query-wrapped-functions='; export const SENTRY_REEXPORTED_FUNCTIONS = '?sentry-query-reexported-functions='; export const QUERY_END_INDICATOR = 'SENTRY-QUERY-END'; /** * `load()` emits `file://` specifiers because Node's ESM loader rejects bare Windows * paths (`ERR_UNSUPPORTED_ESM_URL_SCHEME`), but Rollup's resolver only understands * filesystem paths. Returns `undefined` for a malformed `file://` URL. * * **Only exported for testing** */ export function toResolvablePath(source: string): { path: string; wasFileUrl: boolean } | undefined { if (!source.startsWith('file://')) { return { path: source, wasFileUrl: false }; } if (source === 'file://' || source === 'file:///') { return undefined; } try { const filePath = fileURLToPath(source); if (!filePath || filePath === '/' || filePath === '\\') { return undefined; } return { path: filePath, wasFileUrl: true }; } catch { return undefined; } } const CONFIG_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs', '.mts', '.cts']; function isServerConfigFile(sourcePath: string, resolvedPath: string, configFileName: string): boolean { if (sourcePath === resolvedPath) { return true; } const name = basename(sourcePath); return name === configFileName || CONFIG_EXTENSIONS.some(ext => name === `${configFileName}${ext}`); } export type WrapServerEntryPluginOptions = { serverEntrypointFileName: string; serverConfigFileName: string; resolvedServerConfigPath: string; entrypointWrappedFunctions: string[]; debug?: boolean; }; /** * A Rollup plugin which wraps the server entry with a dynamic `import()`. This makes it possible to initialize Sentry first * by using a regular `import` and load the server after that. * This also works with serverless `handler` functions, as it re-exports the `handler`. * * @param config Configuration options for the Rollup Plugin * @param config.serverConfigFileName Name of the Sentry server config (without file extension). E.g. 'sentry.server.config' * @param config.serverEntrypointFileName The server entrypoint (with file extension). Usually, this is defined by the Nitro preset and is something like 'node-server.mjs' * @param config.resolvedServerConfigPath Resolved path of the Sentry server config (based on `src` directory) * @param config.entryPointWrappedFunctions Exported bindings of the server entry file, which are wrapped as async function. E.g. ['default', 'handler', 'server'] * @param config.debug Whether debug logs are enabled in the build time environment */ export function wrapServerEntryWithDynamicImport(config: WrapServerEntryPluginOptions): InputPluginOption { const { serverConfigFileName, serverEntrypointFileName, resolvedServerConfigPath, entrypointWrappedFunctions, debug, } = config; // In order to correctly import the server config file // and dynamically import the nitro runtime, we need to // mark the resolutionId with '\0raw' to fall into the // raw chunk group, c.f. https://github.com/nitrojs/nitro/commit/8b4a408231bdc222569a32ce109796a41eac4aa6#diff-e58102d2230f95ddeef2662957b48d847a6e891e354cfd0ae6e2e03ce848d1a2R142 const resolutionIdPrefix = '\0raw'; return { name: 'sentry-wrap-server-entry-with-dynamic-import', async resolveId(source, importer, options) { // `load()` emits `file://` specifiers because Node's ESM loader rejects bare Windows paths, // but Rollup's resolver only understands filesystem paths. const resolvable = toResolvablePath(source); if (!resolvable) { return null; } const { path: normalizedSource, wasFileUrl } = resolvable; if (isServerConfigFile(normalizedSource, resolvedServerConfigPath, serverConfigFileName)) { return { id: normalizedSource, moduleSideEffects: true }; } if ( options.isEntry && normalizedSource.includes(serverEntrypointFileName) && normalizedSource.includes('.mjs') && !normalizedSource.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`) ) { const resolution = await this.resolve(normalizedSource, importer, options); // If it cannot be resolved or is external, just return it so that Rollup can display an error if (!resolution || resolution?.external) return resolution; const moduleInfo = await this.load(resolution); moduleInfo.moduleSideEffects = true; // The enclosing `if` already checks for the suffix in `source`, but a check in `resolution.id` is needed as well to prevent multiple attachment of the suffix return resolution.id.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`) ? resolution.id : `${resolutionIdPrefix}${resolution.id // Concatenates the query params to mark the file (also attaches names of re-exports - this is needed for serverless functions to re-export the handler) .concat(SENTRY_WRAPPED_ENTRY) .concat( constructWrappedFunctionExportQuery(moduleInfo.exportedBindings, entrypointWrappedFunctions, debug), ) .concat(QUERY_END_INDICATOR)}`; } // Pass isEntry:false to avoid double-wrapping (normalizedSource lacks query suffix). if (wasFileUrl) { const resolved = await this.resolve(normalizedSource, importer, { ...options, isEntry: false }); if (resolved) return resolved; return { id: normalizedSource }; } return null; }, load(id: string) { if (id.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`)) { const entryId = removeSentryQueryFromPath(id).slice(resolutionIdPrefix.length); const entryIdUrl = pathToFileURL(entryId).href; const configUrl = pathToFileURL(resolvedServerConfigPath).href; // Use entryIdUrl so Node's runtime ESM loader receives file:// on Windows; Rollup normalizes it in resolveId. // Mostly useful for serverless `handler` functions const reExportedFunctions = id.includes(SENTRY_WRAPPED_FUNCTIONS) || id.includes(SENTRY_REEXPORTED_FUNCTIONS) ? constructFunctionReExport(id, entryIdUrl) : ''; return ( // Regular `import` of the Sentry config `import ${stringifyForCodeInjection(configUrl)};\n` + // Dynamic `import()` for the previous, actual entry point. // `import()` can be used for any code that should be run after the hooks are registered (https://nodejs.org/api/module.html#enabling) `import(${stringifyForCodeInjection(entryIdUrl)});\n` + `${reExportedFunctions}\n` ); } return null; }, }; } /** * Strips the Sentry query part from a path. * Example: example/path?sentry-query-wrapped-entry?sentry-query-functions-reexport=foo,SENTRY-QUERY-END -> /example/path * * **Only exported for testing** */ export function removeSentryQueryFromPath(url: string): string { // oxlint-disable-next-line sdk/no-regexp-constructor const regex = new RegExp(`\\${SENTRY_WRAPPED_ENTRY}.*?\\${QUERY_END_INDICATOR}`); return url.replace(regex, ''); } /** * Extracts and sanitizes function re-export and function wrap query parameters from a query string. * If it is a default export, it is not considered for re-exporting. * * **Only exported for testing** */ export function extractFunctionReexportQueryParameters(query: string): { wrap: string[]; reexport: string[] } { // Regex matches the comma-separated params between the functions query // oxlint-disable-next-line sdk/no-regexp-constructor const wrapRegex = new RegExp( `\\${SENTRY_WRAPPED_FUNCTIONS}(.*?)(\\${QUERY_END_INDICATOR}|\\${SENTRY_REEXPORTED_FUNCTIONS})`, ); // oxlint-disable-next-line sdk/no-regexp-constructor const reexportRegex = new RegExp(`\\${SENTRY_REEXPORTED_FUNCTIONS}(.*?)(\\${QUERY_END_INDICATOR})`); const wrapMatch = query.match(wrapRegex); const reexportMatch = query.match(reexportRegex); const wrap = wrapMatch?.[1] ? wrapMatch[1] .split(',') .filter(param => param !== '') // Sanitize, as code could be injected with another rollup plugin .map((str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) : []; const reexport = reexportMatch?.[1] ? reexportMatch[1] .split(',') .filter(param => param !== '' && param !== 'default') // Sanitize, as code could be injected with another rollup plugin .map((str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) : []; return { wrap, reexport }; } /** * Constructs a comma-separated string with all functions that need to be re-exported later from the server entry. * It uses Rollup's `exportedBindings` to determine the functions to re-export. Functions which should be wrapped * (e.g. serverless handlers) are wrapped by Sentry. * * **Only exported for testing** */ export function constructWrappedFunctionExportQuery( exportedBindings: Record | null, entrypointWrappedFunctions: string[], debug?: boolean, ): string { const functionsToExport: { wrap: string[]; reexport: string[] } = { wrap: [], reexport: [], }; // `exportedBindings` can look like this: `{ '.': [ 'handler' ] }` or `{ '.': [], './firebase-gen-1.mjs': [ 'server' ] }` // The key `.` refers to exports within the current file, while other keys show from where exports were imported first. Object.values(exportedBindings || {}).forEach(functions => functions.forEach(fn => { if (entrypointWrappedFunctions.includes(fn)) { functionsToExport.wrap.push(fn); } else { functionsToExport.reexport.push(fn); } }), ); if (debug && functionsToExport.wrap.length === 0) { consoleSandbox(() => // eslint-disable-next-line no-console console.warn( '[Sentry] No functions found to wrap. In case the server needs to export async functions other than `handler` or `server`, consider adding the name(s) to `entrypointWrappedFunctions`.', ), ); } const wrapQuery = functionsToExport.wrap.length ? `${SENTRY_WRAPPED_FUNCTIONS}${functionsToExport.wrap.join(',')}` : ''; const reexportQuery = functionsToExport.reexport.length ? `${SENTRY_REEXPORTED_FUNCTIONS}${functionsToExport.reexport.join(',')}` : ''; return [wrapQuery, reexportQuery].join(''); } /** * Constructs a code snippet with function reexports (can be used in Rollup plugins as a return value for `load()`) * * **Only exported for testing** */ export function constructFunctionReExport(pathWithQuery: string, entryId: string): string { const { wrap: wrapFunctions, reexport: reexportFunctions } = extractFunctionReexportQueryParameters(pathWithQuery); return wrapFunctions .reduce( (functionsCode, currFunctionName) => functionsCode.concat( `async function ${currFunctionName}_sentryWrapped(...args) {\n` + ` const res = await import(${stringifyForCodeInjection(entryId)});\n` + ` return res.${currFunctionName}.call(this, ...args);\n` + '}\n' + `export { ${currFunctionName}_sentryWrapped as ${currFunctionName} };\n`, ), '', ) .concat( reexportFunctions.reduce( (functionsCode, currFunctionName) => functionsCode.concat(`export { ${currFunctionName} } from ${stringifyForCodeInjection(entryId)};`), '', ), ); }