{"version":3,"file":"addServerConfig.js","sources":["../../../src/vite/addServerConfig.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { createResolver } from '@nuxt/kit';\nimport { debug } from '@sentry/core';\nimport * as fs from 'fs';\nimport type { Nitro } from 'nitropack';\nimport type { InputPluginOption } from 'rollup';\nimport type { SentryNuxtModuleOptions } from '../common/types';\nimport {\n constructFunctionReExport,\n constructWrappedFunctionExportQuery,\n getFilenameFromNodeStartCommand,\n QUERY_END_INDICATOR,\n removeSentryQueryFromPath,\n SENTRY_REEXPORTED_FUNCTIONS,\n SENTRY_WRAPPED_ENTRY,\n SENTRY_WRAPPED_FUNCTIONS,\n} from './utils';\n\nconst SERVER_CONFIG_FILENAME = 'sentry.server.config';\n\n/**\n * 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.\n *\n * By adding a Rollup plugin to the Nitro Rollup options, the Sentry server config is transpiled and emitted to the server build.\n */\nexport function addServerConfigToBuild(\n moduleOptions: SentryNuxtModuleOptions,\n nitro: Nitro,\n serverConfigFile: string,\n): void {\n nitro.hooks.hook('rollup:before', (nitro, rollupConfig) => {\n if (rollupConfig?.plugins === null || rollupConfig?.plugins === undefined) {\n rollupConfig.plugins = [];\n } else if (!Array.isArray(rollupConfig.plugins)) {\n // `rollupConfig.plugins` can be a single plugin, so we want to put it into an array so that we can push our own plugin\n rollupConfig.plugins = [rollupConfig.plugins];\n }\n\n rollupConfig.plugins.push(injectServerConfigPlugin(nitro, serverConfigFile, moduleOptions.debug));\n });\n}\n\n/**\n * Adds the Sentry server config import at the top of the server entry file to load the SDK on the server.\n * This is necessary for environments where modifying the node option `--import` is not possible.\n * However, only limited tracing instrumentation is supported when doing this.\n */\nexport function addSentryTopImport(moduleOptions: SentryNuxtModuleOptions, nitro: Nitro): void {\n nitro.hooks.hook('close', async () => {\n const fileNameFromCommand =\n nitro.options.commands.preview && getFilenameFromNodeStartCommand(nitro.options.commands.preview);\n\n // other presets ('node-server' or 'vercel') have an index.mjs\n const presetsWithServerFile = ['netlify'];\n\n const entryFileName = fileNameFromCommand\n ? fileNameFromCommand\n : typeof nitro.options.rollupConfig?.output.entryFileNames === 'string'\n ? nitro.options.rollupConfig?.output.entryFileNames\n : presetsWithServerFile.includes(nitro.options.preset)\n ? 'server.mjs'\n : 'index.mjs';\n\n const serverDirResolver = createResolver(nitro.options.output.serverDir);\n const entryFilePath = serverDirResolver.resolve(entryFileName);\n\n try {\n fs.readFile(entryFilePath, 'utf8', (err, data) => {\n const updatedContent = `import './${SERVER_CONFIG_FILENAME}.mjs';\\n${data}`;\n\n fs.writeFile(entryFilePath, updatedContent, 'utf8', () => {\n if (moduleOptions.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Sentry] Successfully added the Sentry import to the server entry file \"\\`${entryFilePath}\\`\"`,\n );\n }\n });\n });\n } catch (err) {\n if (moduleOptions.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] An error occurred when trying to add the Sentry import to the server entry file \"\\`${entryFilePath}\\`\":`,\n err,\n );\n }\n }\n });\n}\n\n/**\n * This function modifies the Rollup configuration to include a plugin that wraps the entry file with a dynamic import (`import()`)\n * and adds the Sentry server config with the static `import` declaration.\n *\n * With this, the Sentry server config can be loaded before all other modules of the application (which is needed for import-in-the-middle).\n * See: https://nodejs.org/api/module.html#enabling\n */\nexport function addDynamicImportEntryFileWrapper(\n nitro: Nitro,\n serverConfigFile: string,\n moduleOptions: Omit &\n Required>,\n): void {\n if (!nitro.options.rollupConfig) {\n nitro.options.rollupConfig = { output: {} };\n }\n\n if (nitro.options.rollupConfig?.plugins === null || nitro.options.rollupConfig?.plugins === undefined) {\n nitro.options.rollupConfig.plugins = [];\n } else if (!Array.isArray(nitro.options.rollupConfig.plugins)) {\n // `rollupConfig.plugins` can be a single plugin, so we want to put it into an array so that we can push our own plugin\n nitro.options.rollupConfig.plugins = [nitro.options.rollupConfig.plugins];\n }\n\n nitro.options.rollupConfig.plugins.push(\n wrapEntryWithDynamicImport({\n resolvedSentryConfigPath: createResolver(nitro.options.rootDir).resolve(`/${serverConfigFile}`),\n experimental_entrypointWrappedFunctions: moduleOptions.experimental_entrypointWrappedFunctions,\n }),\n );\n}\n\n/**\n * Rollup plugin to include the Sentry server configuration file to the server build output.\n */\nfunction injectServerConfigPlugin(nitro: Nitro, serverConfigFile: string, isDebug?: boolean): InputPluginOption {\n const filePrefix = '\\0virtual:sentry-server-config:';\n\n return {\n name: 'rollup-plugin-inject-sentry-server-config',\n\n buildStart() {\n const configPath = createResolver(nitro.options.rootDir).resolve(`/${serverConfigFile}`);\n\n if (!existsSync(configPath)) {\n if (isDebug) {\n debug.log(`[Sentry] Sentry server config file not found: ${configPath}`);\n }\n return;\n }\n\n // Emitting a file adds it to the build output (Rollup is aware of the file, and we can later return the code in resolveId)\n this.emitFile({\n type: 'chunk',\n id: `${filePrefix}${serverConfigFile}`,\n fileName: `${SERVER_CONFIG_FILENAME}.mjs`,\n });\n },\n\n resolveId(source) {\n if (source.startsWith(filePrefix)) {\n const originalFilePath = source.replace(filePrefix, '');\n const configPath = createResolver(nitro.options.rootDir).resolve(`/${originalFilePath}`);\n\n return { id: configPath };\n }\n return null;\n },\n };\n}\n\n/**\n * A Rollup plugin which wraps the server entry with a dynamic `import()`. This makes it possible to initialize Sentry first\n * by using a regular `import` and load the server after that.\n * This also works with serverless `handler` functions, as it re-exports the `handler`.\n */\nfunction wrapEntryWithDynamicImport({\n resolvedSentryConfigPath,\n experimental_entrypointWrappedFunctions,\n debug,\n}: {\n resolvedSentryConfigPath: string;\n experimental_entrypointWrappedFunctions: string[];\n debug?: boolean;\n}): InputPluginOption {\n // In order to correctly import the server config file\n // and dynamically import the nitro runtime, we need to\n // mark the resolutionId with '\\0raw' to fall into the\n // raw chunk group, c.f. https://github.com/nitrojs/nitro/commit/8b4a408231bdc222569a32ce109796a41eac4aa6#diff-e58102d2230f95ddeef2662957b48d847a6e891e354cfd0ae6e2e03ce848d1a2R142\n const resolutionIdPrefix = '\\0raw';\n\n return {\n name: 'sentry-wrap-entry-with-dynamic-import',\n async resolveId(source, importer, options) {\n if (source.includes(`/${SERVER_CONFIG_FILENAME}`)) {\n return { id: source, moduleSideEffects: true };\n }\n\n if (source === 'import-in-the-middle/hook.mjs') {\n // We are importing \"import-in-the-middle\" in the returned code of the `load()` function below\n // By setting `moduleSideEffects` to `true`, the import is added to the bundle, although nothing is imported from it\n // By importing \"import-in-the-middle/hook.mjs\", we can make sure this file is included, as not all node builders are including files imported with `module.register()`.\n // Prevents the error \"Failed to register ESM hook Error: Cannot find module 'import-in-the-middle/hook.mjs'\"\n return { id: source, moduleSideEffects: true, external: true };\n }\n\n if (options.isEntry && source.includes('.mjs') && !source.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`)) {\n const resolution = await this.resolve(source, importer, options);\n\n // If it cannot be resolved or is external, just return it so that Rollup can display an error\n if (!resolution || resolution?.external) return resolution;\n\n const moduleInfo = await this.load(resolution);\n\n moduleInfo.moduleSideEffects = true;\n\n // 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\n return resolution.id.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`)\n ? resolution.id\n : `${resolutionIdPrefix}${resolution.id\n // 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)\n .concat(SENTRY_WRAPPED_ENTRY)\n .concat(\n constructWrappedFunctionExportQuery(\n moduleInfo.exportedBindings,\n experimental_entrypointWrappedFunctions,\n debug,\n ),\n )\n .concat(QUERY_END_INDICATOR)}`;\n }\n return null;\n },\n load(id: string) {\n if (id.includes(`.mjs${SENTRY_WRAPPED_ENTRY}`)) {\n const entryId = removeSentryQueryFromPath(id).slice(resolutionIdPrefix.length);\n\n // Mostly useful for serverless `handler` functions\n const reExportedFunctions =\n id.includes(SENTRY_WRAPPED_FUNCTIONS) || id.includes(SENTRY_REEXPORTED_FUNCTIONS)\n ? constructFunctionReExport(id, entryId)\n : '';\n\n return (\n // Regular `import` of the Sentry config\n `import ${JSON.stringify(resolvedSentryConfigPath)};\\n` +\n // Dynamic `import()` for the previous, actual entry point.\n // `import()` can be used for any code that should be run after the hooks are registered (https://nodejs.org/api/module.html#enabling)\n `import(${JSON.stringify(entryId)});\\n` +\n // By importing \"import-in-the-middle/hook.mjs\", we can make sure this file wil be included, as not all node builders are including files imported with `module.register()`.\n \"import 'import-in-the-middle/hook.mjs';\\n\" +\n `${reExportedFunctions}\\n`\n );\n }\n\n return null;\n },\n };\n}\n"],"names":["nitro","getFilenameFromNodeStartCommand","createResolver","existsSync","debug","SENTRY_WRAPPED_ENTRY","constructWrappedFunctionExportQuery","QUERY_END_INDICATOR","removeSentryQueryFromPath","SENTRY_WRAPPED_FUNCTIONS","SENTRY_REEXPORTED_FUNCTIONS","constructFunctionReExport"],"mappings":";;;;;;;;AAkBA,MAAM,sBAAA,GAAyB,sBAAA;AAOxB,SAAS,sBAAA,CACd,aAAA,EACA,KAAA,EACA,gBAAA,EACM;AACN,EAAA,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK,eAAA,EAAiB,CAACA,QAAO,YAAA,KAAiB;AACzD,IAAA,IAAI,YAAA,EAAc,OAAA,KAAY,IAAA,IAAQ,YAAA,EAAc,YAAY,MAAA,EAAW;AACzE,MAAA,YAAA,CAAa,UAAU,EAAC;AAAA,IAC1B,WAAW,CAAC,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,OAAO,CAAA,EAAG;AAE/C,MAAA,YAAA,CAAa,OAAA,GAAU,CAAC,YAAA,CAAa,OAAO,CAAA;AAAA,IAC9C;AAEA,IAAA,YAAA,CAAa,QAAQ,IAAA,CAAK,wBAAA,CAAyBA,QAAO,gBAAA,EAAkB,aAAA,CAAc,KAAK,CAAC,CAAA;AAAA,EAClG,CAAC,CAAA;AACH;AAOO,SAAS,kBAAA,CAAmB,eAAwC,KAAA,EAAoB;AAC7F,EAAA,KAAA,CAAM,KAAA,CAAM,IAAA,CAAK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