@sentry/bundler-plugins 10.74.0 → 10.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/core/debug-id-upload.js +80 -2
- package/build/cjs/core/debug-id-upload.js.map +1 -1
- package/build/cjs/core/index.js +2 -0
- package/build/cjs/core/index.js.map +1 -1
- package/build/cjs/core/version.js +1 -1
- package/build/cjs/core/version.js.map +1 -1
- package/build/cjs/esbuild/index.js +17 -2
- package/build/cjs/esbuild/index.js.map +1 -1
- package/build/cjs/rollup/index.js +23 -13
- package/build/cjs/rollup/index.js.map +1 -1
- package/build/cjs/webpack/webpack4and5.js +34 -0
- package/build/cjs/webpack/webpack4and5.js.map +1 -1
- package/build/esm/core/debug-id-upload.js +79 -3
- package/build/esm/core/debug-id-upload.js.map +1 -1
- package/build/esm/core/index.js +1 -1
- package/build/esm/core/index.js.map +1 -1
- package/build/esm/core/version.js +1 -1
- package/build/esm/core/version.js.map +1 -1
- package/build/esm/esbuild/index.js +19 -4
- package/build/esm/esbuild/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/rollup/index.js +24 -14
- package/build/esm/rollup/index.js.map +1 -1
- package/build/esm/webpack/webpack4and5.js +36 -2
- package/build/esm/webpack/webpack4and5.js.map +1 -1
- package/build/types/core/debug-id-upload.d.ts +28 -0
- package/build/types/core/debug-id-upload.d.ts.map +1 -1
- package/build/types/core/index.d.ts +1 -1
- package/build/types/core/index.d.ts.map +1 -1
- package/build/types/core/types.d.ts +7 -2
- package/build/types/core/types.d.ts.map +1 -1
- package/build/types/core/version.d.ts +1 -1
- package/build/types/esbuild/index.d.ts.map +1 -1
- package/build/types/rollup/index.d.ts +22 -31
- package/build/types/rollup/index.d.ts.map +1 -1
- package/build/types/webpack/webpack4and5.d.ts +20 -21
- package/build/types/webpack/webpack4and5.d.ts.map +1 -1
- package/build/types-ts3.8/core/debug-id-upload.d.ts +28 -0
- package/build/types-ts3.8/core/index.d.ts +1 -1
- package/build/types-ts3.8/core/types.d.ts +7 -2
- package/build/types-ts3.8/core/version.d.ts +1 -1
- package/build/types-ts3.8/rollup/index.d.ts +22 -31
- package/build/types-ts3.8/webpack/webpack4and5.d.ts +20 -21
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack4and5.js","sources":["../../../src/webpack/webpack4and5.ts"],"sourcesContent":["import type { Options } from '../core/index';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n stringToUUID,\n createComponentNameAnnotateHooks,\n CodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n} from '../core/index';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\nconst _req = createRequire(import.meta.url);\n\n// Resolve the loader path via the package's own exports.\n// webpack4and5.ts may end up in a shared chunk (_chunks/) whose import.meta.url\n// does not point to the webpack/ directory where the transform file lives, so\n// a path-relative lookup would fail. Using require.resolve on the package export\n// always finds the correct installed file regardless of chunk placement.\nlet COMPONENT_ANNOTATION_LOADER: string;\ntry {\n COMPONENT_ANNOTATION_LOADER = _req.resolve('@sentry/bundler-plugins/webpack-loader');\n} catch {\n // Fallback for non-packaged environments (e.g., monorepo source runs without dist)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Rollup transpiles import.meta for us for CJS\n const dirname = path.dirname(fileURLToPath(import.meta.url));\n // The Rollup build emits `.js` for both CJS and ESM, so the extension is the same in both.\n COMPONENT_ANNOTATION_LOADER = path.resolve(dirname, 'component-annotation-transform.js');\n}\n\n// since webpack 5.1 compiler contains webpack module so plugins always use correct webpack version\n// https://github.com/webpack/webpack/commit/65eca2e529ce1d79b79200d4bdb1ce1b81141459\n\ninterface BannerPluginCallbackArg {\n chunk?: {\n hash?: string;\n contentHash?: {\n javascript?: string;\n };\n };\n}\n\ntype UnsafeBannerPlugin = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype UnsafeDefinePlugin = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype WebpackModule = {\n resource?: string;\n};\n\ntype WebpackLoaderCallback = (err: Error | null, content?: string, sourceMap?: unknown) => void;\n\ntype WebpackLoaderContext = {\n callback: WebpackLoaderCallback;\n};\n\ntype WebpackCompilationContext = {\n compiler: {\n webpack?: {\n NormalModule?: {\n getCompilationHooks: (compilation: WebpackCompilationContext) => {\n loader: {\n tap: (name: string, callback: (loaderContext: WebpackLoaderContext, module: WebpackModule) => void) => void;\n };\n };\n };\n };\n };\n hooks: {\n normalModuleLoader?: {\n tap: (name: string, callback: (loaderContext: WebpackLoaderContext, module: WebpackModule) => void) => void;\n };\n };\n};\n\ntype WebpackCompiler = {\n options: {\n plugins?: unknown[];\n mode?: string;\n module?: {\n rules?: unknown[];\n };\n };\n hooks: {\n thisCompilation: {\n tap: (name: string, callback: (compilation: WebpackCompilationContext) => void) => void;\n };\n afterEmit: {\n tapAsync: (name: string, callback: (compilation: WebpackCompilation, cb: () => void) => void) => void;\n };\n done: {\n tap: (name: string, callback: () => void) => void;\n };\n };\n webpack?: {\n BannerPlugin?: UnsafeBannerPlugin;\n DefinePlugin?: UnsafeDefinePlugin;\n };\n};\n\ntype WebpackCompilation = {\n outputOptions: {\n path?: string;\n };\n assets: Record<string, unknown>;\n hooks: {\n processAssets: {\n tap: (options: { name: string; stage: number }, callback: () => void) => void;\n };\n };\n};\n\n// Detect webpack major version for telemetry (helps differentiate webpack 4 vs 5 usage)\nfunction getWebpackMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const webpack = req('webpack') as { version?: string; default?: { version?: string } };\n const version = webpack?.version ?? webpack?.default?.version;\n const webpackMajorVersion = version?.split('.')[0]; // \"4\" or \"5\"\n return webpackMajorVersion;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The factory function accepts BannerPlugin and DefinePlugin classes in\n * order to avoid direct dependencies on webpack.\n *\n * This allow us to export version of the plugin for webpack 5.1+ and compatible environments.\n *\n * Since webpack 5.1 compiler contains webpack module so plugins always use correct webpack version.\n */\nexport function sentryWebpackPluginFactory({\n BannerPlugin: UnsafeBannerPlugin,\n DefinePlugin: UnsafeDefinePlugin,\n}: {\n BannerPlugin?: UnsafeBannerPlugin;\n DefinePlugin?: UnsafeDefinePlugin;\n} = {}) {\n return function sentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? '[sentry-webpack-plugin]',\n buildTool: 'webpack',\n buildToolMajorVersion: getWebpackMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n apply() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n return {\n apply(compiler: WebpackCompiler) {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n // Get the correct plugin classes (webpack 5.1+ vs older versions)\n const BannerPlugin = compiler?.webpack?.BannerPlugin || UnsafeBannerPlugin;\n const DefinePlugin = compiler?.webpack?.DefinePlugin || UnsafeDefinePlugin;\n\n // Add BannerPlugin for code injection (release, metadata, debug IDs)\n if (!staticInjectionCode.isEmpty() || sourcemapsEnabled) {\n if (!BannerPlugin) {\n logger.warn(\n 'BannerPlugin is not available. Skipping code injection. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(\n new BannerPlugin({\n raw: true,\n include: /\\.(js|ts|jsx|tsx|mjs|cjs)(\\?[^?]*)?(#[^#]*)?$/,\n banner: (arg?: BannerPluginCallbackArg) => {\n const codeToInject = staticInjectionCode.clone();\n if (sourcemapsEnabled) {\n const hash = arg?.chunk?.contentHash?.javascript ?? arg?.chunk?.hash;\n const debugId = hash ? stringToUUID(hash) : randomUUID();\n codeToInject.append(getDebugIdSnippet(debugId));\n }\n return codeToInject.code();\n },\n }),\n );\n }\n }\n\n // Add DefinePlugin for bundle size optimizations\n if (transformReplace && DefinePlugin) {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(new DefinePlugin(replacementValues));\n }\n\n // Add component name annotation transform\n if (transformAnnotations?.transform) {\n compiler.options.module = compiler.options.module || {};\n compiler.options.module.rules = compiler.options.module.rules || [];\n compiler.options.module.rules.unshift({\n test: /\\.[jt]sx$/,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [\n {\n loader: COMPONENT_ANNOTATION_LOADER,\n options: {\n transform: transformAnnotations.transform,\n },\n },\n ],\n });\n }\n\n compiler.hooks.afterEmit.tapAsync(\n 'sentry-webpack-plugin',\n (compilation: WebpackCompilation, callback: (err?: Error) => void) => {\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n const run = async (): Promise<void> => {\n try {\n await sentryBuildPluginManager.createRelease();\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const outputPath = compilation.outputOptions.path ?? path.resolve();\n const buildArtifacts = Object.keys(compilation.assets).map(asset => path.join(outputPath, asset));\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n };\n\n run().then(\n () => callback(),\n (err: Error) => callback(err),\n );\n },\n );\n\n if (userOptions._experiments?.forceExitOnBuildCompletion && compiler.options.mode === 'production') {\n compiler.hooks.done.tap('sentry-webpack-plugin', () => {\n setTimeout(() => {\n logger.debug('Exiting process after debug file upload');\n process.exit(0);\n });\n });\n }\n },\n };\n };\n}\n\nexport type SentryWebpackPluginOptions = Options & {\n _experiments?: Options['_experiments'] & {\n /**\n * If enabled, the webpack plugin will exit the build process after the build completes.\n * Use this with caution, as it will terminate the process.\n *\n * More information: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/345\n *\n * @default false\n */\n forceExitOnBuildCompletion?: boolean;\n };\n};\n"],"names":["createRequire","path","fileURLToPath","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","stringToUUID","randomUUID","getDebugIdSnippet","createDebugIdUploadFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,IAAA,GAAOA,yBAAA,CAAc,yQAAe,CAAA;AAO1C,IAAI,2BAAA;AACJ,IAAI;AACF,EAAA,2BAAA,GAA8B,IAAA,CAAK,QAAQ,wCAAwC,CAAA;AACrF,CAAA,CAAA,MAAQ;AAIN,EAA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MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAM,CAAA,CAAE,GAAA,CAAI,CAAA,KAAA,KAASA,eAAA,CAAK,IAAA,CAAK,UAAA,EAAY,KAAK,CAAC,CAAA;AAChG,kBAAA,MAAM,OAAO,cAAc,CAAA;AAAA,gBAC7B;AAAA,cACF,CAAA,SAAE;AACA,gBAAA,oCAAA,EAAqC;AACrC,gBAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,cACjD;AAAA,YACF,CAAA;AAEA,YAAA,GAAA,EAAI,CAAE,IAAA;AAAA,cACJ,MAAM,QAAA,EAAS;AAAA,cACf,CAAC,GAAA,KAAe,QAAA,CAAS,GAAG;AAAA,aAC9B;AAAA,UACF;AAAA,SACF;AAEA,QAAA,IAAI,YAAY,YAAA,EAAc,0BAAA,IAA8B,QAAA,CAAS,OAAA,CAAQ,SAAS,YAAA,EAAc;AAClG,UAAA,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,uBAAA,EAAyB,MAAM;AACrD,YAAA,UAAA,CAAW,MAAM;AACf,cAAA,MAAA,CAAO,MAAM,yCAAyC,CAAA;AACtD,cAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,YAChB,CAAC,CAAA;AAAA,UACH,CAAC,CAAA;AAAA,QACH;AAAA,MACF;AAAA,KACF;AAAA,EACF,CAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"webpack4and5.js","sources":["../../../src/webpack/webpack4and5.ts"],"sourcesContent":["import type { Options } from '../core/index';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n stringToUUID,\n createComponentNameAnnotateHooks,\n CodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n isJsFile,\n stampDebugId,\n} from '../core/index';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\nconst _req = createRequire(import.meta.url);\n\n// Resolve the loader path via the package's own exports.\n// webpack4and5.ts may end up in a shared chunk (_chunks/) whose import.meta.url\n// does not point to the webpack/ directory where the transform file lives, so\n// a path-relative lookup would fail. Using require.resolve on the package export\n// always finds the correct installed file regardless of chunk placement.\nlet COMPONENT_ANNOTATION_LOADER: string;\ntry {\n COMPONENT_ANNOTATION_LOADER = _req.resolve('@sentry/bundler-plugins/webpack-loader');\n} catch {\n // Fallback for non-packaged environments (e.g., monorepo source runs without dist)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Rollup transpiles import.meta for us for CJS\n const dirname = path.dirname(fileURLToPath(import.meta.url));\n // The Rollup build emits `.js` for both CJS and ESM, so the extension is the same in both.\n COMPONENT_ANNOTATION_LOADER = path.resolve(dirname, 'component-annotation-transform.js');\n}\n\n// since webpack 5.1 compiler contains webpack module so plugins always use correct webpack version\n// https://github.com/webpack/webpack/commit/65eca2e529ce1d79b79200d4bdb1ce1b81141459\n\ninterface BannerPluginCallbackArg {\n chunk?: {\n hash?: string;\n contentHash?: {\n javascript?: string;\n };\n };\n}\n\ntype UnsafeBannerPlugin = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype UnsafeDefinePlugin = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype WebpackSource = {\n source: () => string | Buffer;\n};\n\ntype WebpackRawSource = {\n new (source: string): WebpackSource;\n};\n\ntype WebpackAsset = {\n name: string;\n source: WebpackSource;\n info: {\n related?: {\n sourceMap?: string | string[];\n };\n };\n};\n\ntype WebpackCompiler = {\n options: {\n plugins?: unknown[];\n mode?: string;\n module?: {\n rules?: unknown[];\n };\n };\n hooks: {\n thisCompilation: {\n tap: (name: string, callback: (compilation: WebpackCompilation) => void) => void;\n };\n afterEmit: {\n tapAsync: (name: string, callback: (compilation: WebpackCompilation, cb: () => void) => void) => void;\n };\n done: {\n tap: (name: string, callback: () => void) => void;\n };\n };\n webpack?: {\n BannerPlugin?: UnsafeBannerPlugin;\n DefinePlugin?: UnsafeDefinePlugin;\n Compilation?: {\n PROCESS_ASSETS_STAGE_DEV_TOOLING?: number;\n };\n sources?: {\n RawSource?: WebpackRawSource;\n };\n };\n};\n\ntype WebpackCompilation = {\n outputOptions: {\n path?: string;\n };\n assets: Record<string, unknown>;\n getAssets: () => WebpackAsset[];\n getAsset: (name: string) => WebpackAsset | undefined;\n updateAsset: (name: string, source: WebpackSource) => void;\n hooks: {\n processAssets: {\n tap: (options: { name: string; stage: number }, callback: () => void) => void;\n };\n };\n};\n\n// Detect webpack major version for telemetry (helps differentiate webpack 4 vs 5 usage)\nfunction getWebpackMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const webpack = req('webpack') as { version?: string; default?: { version?: string } };\n const version = webpack?.version ?? webpack?.default?.version;\n const webpackMajorVersion = version?.split('.')[0]; // \"4\" or \"5\"\n return webpackMajorVersion;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Stamps each JS asset's debug ID into the asset itself and its source map asset.\n *\n * Runs after source maps have been generated, so the JS asset no longer needs to carry\n * source map information and can be replaced with a plain `RawSource`.\n */\nfunction addDebugIdsToAssets(compilation: WebpackCompilation, RawSource: WebpackRawSource): void {\n for (const asset of compilation.getAssets()) {\n if (!isJsFile(asset.name)) {\n continue;\n }\n\n const bundleSource = asset.source.source().toString();\n const relatedSourceMap = asset.info.related?.sourceMap;\n const sourceMapName = typeof relatedSourceMap === 'string' ? relatedSourceMap : `${asset.name}.map`;\n const sourceMapAsset = compilation.getAsset(sourceMapName);\n\n const stamped = stampDebugId(bundleSource, sourceMapAsset?.source.source().toString());\n if (!stamped) {\n continue;\n }\n\n compilation.updateAsset(asset.name, new RawSource(stamped.bundleSource));\n if (stamped.sourceMapSource !== undefined) {\n compilation.updateAsset(sourceMapName, new RawSource(stamped.sourceMapSource));\n }\n }\n}\n\n/**\n * The factory function accepts BannerPlugin and DefinePlugin classes in\n * order to avoid direct dependencies on webpack.\n *\n * This allow us to export version of the plugin for webpack 5.1+ and compatible environments.\n *\n * Since webpack 5.1 compiler contains webpack module so plugins always use correct webpack version.\n */\nexport function sentryWebpackPluginFactory({\n BannerPlugin: UnsafeBannerPlugin,\n DefinePlugin: UnsafeDefinePlugin,\n}: {\n BannerPlugin?: UnsafeBannerPlugin;\n DefinePlugin?: UnsafeDefinePlugin;\n} = {}) {\n return function sentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? '[sentry-webpack-plugin]',\n buildTool: 'webpack',\n buildToolMajorVersion: getWebpackMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n apply() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n return {\n apply(compiler: WebpackCompiler) {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n // Get the correct plugin classes (webpack 5.1+ vs older versions)\n const BannerPlugin = compiler?.webpack?.BannerPlugin || UnsafeBannerPlugin;\n const DefinePlugin = compiler?.webpack?.DefinePlugin || UnsafeDefinePlugin;\n\n // Add BannerPlugin for code injection (release, metadata, debug IDs)\n if (!staticInjectionCode.isEmpty() || sourcemapsEnabled) {\n if (!BannerPlugin) {\n logger.warn(\n 'BannerPlugin is not available. Skipping code injection. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(\n new BannerPlugin({\n raw: true,\n include: /\\.(js|ts|jsx|tsx|mjs|cjs)(\\?[^?]*)?(#[^#]*)?$/,\n banner: (arg?: BannerPluginCallbackArg) => {\n const codeToInject = staticInjectionCode.clone();\n if (sourcemapsEnabled) {\n const hash = arg?.chunk?.contentHash?.javascript ?? arg?.chunk?.hash;\n const debugId = hash ? stringToUUID(hash) : randomUUID();\n codeToInject.append(getDebugIdSnippet(debugId));\n }\n return codeToInject.code();\n },\n }),\n );\n }\n }\n\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is skipped\n // with `disable-upload`, so the emitted artifacts get stamped in the asset pipeline instead.\n if (sourcemapsEnabled && options.sourcemaps?.disable === 'disable-upload') {\n const RawSource = compiler.webpack?.sources?.RawSource;\n // Right after source map generation (and thus after minification, which would strip the comment),\n // so later stages (real content hashing, subresource integrity) see the final assets.\n const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING ?? 500) + 1;\n\n if (!RawSource) {\n logger.warn(\n 'Webpack sources are not available. Skipping debug ID injection into emitted source maps. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => {\n compilation.hooks.processAssets.tap({ name: 'sentry-webpack-plugin', stage }, () => {\n addDebugIdsToAssets(compilation, RawSource);\n });\n });\n }\n }\n\n // Add DefinePlugin for bundle size optimizations\n if (transformReplace && DefinePlugin) {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(new DefinePlugin(replacementValues));\n }\n\n // Add component name annotation transform\n if (transformAnnotations?.transform) {\n compiler.options.module = compiler.options.module || {};\n compiler.options.module.rules = compiler.options.module.rules || [];\n compiler.options.module.rules.unshift({\n test: /\\.[jt]sx$/,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [\n {\n loader: COMPONENT_ANNOTATION_LOADER,\n options: {\n transform: transformAnnotations.transform,\n },\n },\n ],\n });\n }\n\n compiler.hooks.afterEmit.tapAsync(\n 'sentry-webpack-plugin',\n (compilation: WebpackCompilation, callback: (err?: Error) => void) => {\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n const run = async (): Promise<void> => {\n try {\n await sentryBuildPluginManager.createRelease();\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const outputPath = compilation.outputOptions.path ?? path.resolve();\n const buildArtifacts = Object.keys(compilation.assets).map(asset => path.join(outputPath, asset));\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n };\n\n run().then(\n () => callback(),\n (err: Error) => callback(err),\n );\n },\n );\n\n if (userOptions._experiments?.forceExitOnBuildCompletion && compiler.options.mode === 'production') {\n compiler.hooks.done.tap('sentry-webpack-plugin', () => {\n setTimeout(() => {\n logger.debug('Exiting process after debug file upload');\n process.exit(0);\n });\n });\n }\n },\n };\n };\n}\n\nexport type SentryWebpackPluginOptions = Options & {\n _experiments?: Options['_experiments'] & {\n /**\n * If enabled, the webpack plugin will exit the build process after the build completes.\n * Use this with caution, as it will terminate the process.\n *\n * More information: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/345\n *\n * @default false\n */\n forceExitOnBuildCompletion?: boolean;\n };\n};\n"],"names":["createRequire","path","fileURLToPath","isJsFile","stampDebugId","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","stringToUUID","randomUUID","getDebugIdSnippet","createDebugIdUploadFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAM,IAAA,GAAOA,yBAAA,CAAc,yQAAe,CAAA;AAO1C,IAAI,2BAAA;AACJ,IAAI;AACF,EAAA,2BAAA,GAA8B,IAAA,CAAK,QAAQ,wCAAwC,CAAA;AACrF,CAAA,CAAA,MAAQ;AAIN,EAAA,MAAM,UAAUC,eAAA,CAAK,OAAA,CAAQC,sBAAA,CAAc,yQAAe,CAAC,CAAA;AAE3D,EAAA,2BAAA,GAA8BD,eAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,mCAAmC,CAAA;AACzF;AAyFA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAMD,yBAAA,CAAc,yQAAe,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAC7B,IAAA,MAAM,OAAA,GAAU,OAAA,EAAS,OAAA,IAAW,OAAA,EAAS,OAAA,EAAS,OAAA;AACtD,IAAA,MAAM,mBAAA,GAAsB,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AACjD,IAAA,OAAO,mBAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAQA,SAAS,mBAAA,CAAoB,aAAiC,SAAA,EAAmC;AAC/F,EAAA,KAAA,MAAW,KAAA,IAAS,WAAA,CAAY,SAAA,EAAU,EAAG;AAC3C,IAAA,IAAI,CAACG,cAAA,CAAS,KAAA,CAAM,I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GAAA,EAAI,CAAE,IAAA;AAAA,cACJ,MAAM,QAAA,EAAS;AAAA,cACf,CAAC,GAAA,KAAe,QAAA,CAAS,GAAG;AAAA,aAC9B;AAAA,UACF;AAAA,SACF;AAEA,QAAA,IAAI,YAAY,YAAA,EAAc,0BAAA,IAA8B,QAAA,CAAS,OAAA,CAAQ,SAAS,YAAA,EAAc;AAClG,UAAA,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,uBAAA,EAAyB,MAAM;AACrD,YAAA,UAAA,CAAW,MAAM;AACf,cAAA,MAAA,CAAO,MAAM,yCAAyC,CAAA;AACtD,cAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,YAChB,CAAC,CAAA;AAAA,UACH,CAAC,CAAA;AAAA,QACH;AAAA,MACF;AAAA,KACF;AAAA,EACF,CAAA;AACF;;;;"}
|
|
@@ -74,6 +74,83 @@ function addDebugIdToBundleSource(bundleSource, debugId) {
|
|
|
74
74
|
//# debugId=${debugId}`;
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
|
+
function bundleHasInlineSourceMap(bundleSource) {
|
|
78
|
+
return /^\s*\/\/# sourceMappingURL=data:/m.test(bundleSource);
|
|
79
|
+
}
|
|
80
|
+
function setDebugIdOnSourceMap(map, debugId) {
|
|
81
|
+
map["debug_id"] = debugId;
|
|
82
|
+
map["debugId"] = debugId;
|
|
83
|
+
}
|
|
84
|
+
function parseSourceMap(sourceMapSource) {
|
|
85
|
+
let map;
|
|
86
|
+
try {
|
|
87
|
+
map = JSON.parse(sourceMapSource);
|
|
88
|
+
} catch {
|
|
89
|
+
return void 0;
|
|
90
|
+
}
|
|
91
|
+
return map && typeof map === "object" ? map : void 0;
|
|
92
|
+
}
|
|
93
|
+
function stampDebugId(bundleSource, sourceMapSource) {
|
|
94
|
+
const debugId = determineDebugIdFromBundleSource(bundleSource);
|
|
95
|
+
if (debugId === void 0) {
|
|
96
|
+
return void 0;
|
|
97
|
+
}
|
|
98
|
+
if (sourceMapSource === void 0) {
|
|
99
|
+
if (!bundleHasInlineSourceMap(bundleSource)) {
|
|
100
|
+
return void 0;
|
|
101
|
+
}
|
|
102
|
+
return { bundleSource: addDebugIdToBundleSource(bundleSource, debugId), sourceMapSource: void 0 };
|
|
103
|
+
}
|
|
104
|
+
const map = parseSourceMap(sourceMapSource);
|
|
105
|
+
if (!map) {
|
|
106
|
+
return void 0;
|
|
107
|
+
}
|
|
108
|
+
setDebugIdOnSourceMap(map, debugId);
|
|
109
|
+
return {
|
|
110
|
+
bundleSource: addDebugIdToBundleSource(bundleSource, debugId),
|
|
111
|
+
sourceMapSource: JSON.stringify(map)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async function addDebugIdToEmittedArtifacts(bundleFilePath, logger, resolveSourceMapHook) {
|
|
115
|
+
let bundleSource;
|
|
116
|
+
try {
|
|
117
|
+
bundleSource = await fs__default.promises.readFile(bundleFilePath, "utf8");
|
|
118
|
+
} catch (e) {
|
|
119
|
+
logger.error(`Could not read bundle to stamp debug ID: ${bundleFilePath}`, e);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const sourceMapPath = await determineSourceMapPathFromBundle(
|
|
123
|
+
bundleFilePath,
|
|
124
|
+
bundleSource,
|
|
125
|
+
logger,
|
|
126
|
+
resolveSourceMapHook
|
|
127
|
+
);
|
|
128
|
+
let sourceMapSource;
|
|
129
|
+
if (sourceMapPath) {
|
|
130
|
+
try {
|
|
131
|
+
sourceMapSource = await fs__default.promises.readFile(sourceMapPath, "utf8");
|
|
132
|
+
} catch (e) {
|
|
133
|
+
logger.error(`Could not read source map to stamp debug ID: ${sourceMapPath}`, e);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const stamped = stampDebugId(bundleSource, sourceMapSource);
|
|
138
|
+
if (!stamped) {
|
|
139
|
+
logger.debug(
|
|
140
|
+
`Could not stamp debug ID (no debug ID in bundle, no source map, or invalid source map): ${bundleFilePath}`
|
|
141
|
+
);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const writes = [fs__default.promises.writeFile(bundleFilePath, stamped.bundleSource, "utf8")];
|
|
145
|
+
if (sourceMapPath && stamped.sourceMapSource !== void 0) {
|
|
146
|
+
writes.push(fs__default.promises.writeFile(sourceMapPath, stamped.sourceMapSource, "utf8"));
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
await Promise.all(writes);
|
|
150
|
+
} catch (e) {
|
|
151
|
+
logger.error(`Could not write debug ID into build artifacts: ${bundleFilePath}`, e);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
77
154
|
async function determineSourceMapPathFromBundle(bundlePath, bundleSource, logger, resolveSourceMapHook) {
|
|
78
155
|
const sourceMappingUrlMatch = bundleSource.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);
|
|
79
156
|
const sourceMappingUrl = sourceMappingUrlMatch ? sourceMappingUrlMatch[1] : void 0;
|
|
@@ -129,8 +206,7 @@ async function prepareSourceMapForDebugIdUpload(sourceMapPath, targetPath, debug
|
|
|
129
206
|
let map;
|
|
130
207
|
try {
|
|
131
208
|
map = JSON.parse(sourceMapFileContent);
|
|
132
|
-
map
|
|
133
|
-
map["debugId"] = debugId;
|
|
209
|
+
setDebugIdOnSourceMap(map, debugId);
|
|
134
210
|
} catch {
|
|
135
211
|
logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);
|
|
136
212
|
return;
|
|
@@ -157,5 +233,5 @@ function defaultRewriteSourcesHook(source) {
|
|
|
157
233
|
}
|
|
158
234
|
}
|
|
159
235
|
|
|
160
|
-
export { createDebugIdUploadFunction, defaultRewriteSourcesHook, determineSourceMapPathFromBundle, prepareBundleForDebugIdUpload };
|
|
236
|
+
export { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction, defaultRewriteSourcesHook, determineSourceMapPathFromBundle, prepareBundleForDebugIdUpload, stampDebugId };
|
|
161
237
|
//# sourceMappingURL=debug-id-upload.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debug-id-upload.js","sources":["../../../src/core/debug-id-upload.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport * as url from 'url';\nimport * as util from 'util';\nimport { promisify } from 'util';\nimport type { SentryBuildPluginManager } from './build-plugin-manager';\nimport type { Logger } from './logger';\nimport type { ResolveSourceMapHook, RewriteSourcesHook } from './types';\nimport { stripQueryAndHashFromPath } from './utils';\n\ninterface DebugIdUploadPluginOptions {\n sentryBuildPluginManager: SentryBuildPluginManager;\n}\n\nexport function createDebugIdUploadFunction({ sentryBuildPluginManager }: DebugIdUploadPluginOptions) {\n return async (buildArtifactPaths: string[]) => {\n // Webpack and perhaps other bundlers allow you to append query strings to\n // filenames for cache busting purposes. We should strip these before upload.\n const cleanedPaths = buildArtifactPaths.map(stripQueryAndHashFromPath);\n await sentryBuildPluginManager.uploadSourcemaps(cleanedPaths);\n };\n}\n\nexport async function prepareBundleForDebugIdUpload(\n bundleFilePath: string,\n uploadFolder: string,\n chunkIndex: number,\n logger: Logger,\n rewriteSourcesHook: RewriteSourcesHook,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleContent;\n try {\n bundleContent = await promisify(fs.readFile)(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to determine debug ID and source map: ${bundleFilePath}`, e);\n return;\n }\n\n const debugId = determineDebugIdFromBundleSource(bundleContent);\n if (debugId === undefined) {\n logger.debug(\n `Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ${bundleFilePath}`,\n );\n return;\n }\n\n const uniqueUploadName = `${debugId}-${chunkIndex}`;\n\n bundleContent = addDebugIdToBundleSource(bundleContent, debugId);\n const writeSourceFilePromise = fs.promises.writeFile(\n path.join(uploadFolder, `${uniqueUploadName}.js`),\n bundleContent,\n 'utf-8',\n );\n\n const writeSourceMapFilePromise = determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\n logger,\n resolveSourceMapHook,\n ).then(async sourceMapPath => {\n if (sourceMapPath) {\n await prepareSourceMapForDebugIdUpload(\n sourceMapPath,\n path.join(uploadFolder, `${uniqueUploadName}.js.map`),\n debugId,\n rewriteSourcesHook,\n logger,\n );\n }\n });\n\n await writeSourceFilePromise;\n await writeSourceMapFilePromise;\n}\n\n/**\n * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle\n * source and extracts the bundle's debug ID from it.\n *\n * The string pattern is injected via the debug ID injection snipped.\n */\nfunction determineDebugIdFromBundleSource(code: string): string | undefined {\n const match = code.match(\n /sentry-dbid-([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})/,\n );\n\n if (match) {\n return match[1];\n } else {\n return undefined;\n }\n}\n\nconst SPEC_LAST_DEBUG_ID_REGEX = /\\/\\/# debugId=([a-fA-F0-9-]+)(?![\\s\\S]*\\/\\/# debugId=)/m;\n\nfunction hasSpecCompliantDebugId(bundleSource: string): boolean {\n return SPEC_LAST_DEBUG_ID_REGEX.test(bundleSource);\n}\n\nfunction addDebugIdToBundleSource(bundleSource: string, debugId: string): string {\n if (hasSpecCompliantDebugId(bundleSource)) {\n return bundleSource.replace(SPEC_LAST_DEBUG_ID_REGEX, `//# debugId=${debugId}`);\n } else {\n return `${bundleSource}\\n//# debugId=${debugId}`;\n }\n}\n\n/**\n * Applies a set of heuristics to find the source map for a particular bundle.\n *\n * @returns the path to the bundle's source map or `undefined` if none could be found.\n */\nexport async function determineSourceMapPathFromBundle(\n bundlePath: string,\n bundleSource: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<string | undefined> {\n const sourceMappingUrlMatch = bundleSource.match(/^\\s*\\/\\/# sourceMappingURL=(.*)$/m);\n const sourceMappingUrl = sourceMappingUrlMatch ? (sourceMappingUrlMatch[1] as string) : undefined;\n\n const searchLocations: string[] = [];\n\n if (resolveSourceMapHook) {\n logger.debug(\n `Calling sourcemaps.resolveSourceMap(${JSON.stringify(bundlePath)}, ${JSON.stringify(sourceMappingUrl)})`,\n );\n const customPath = await resolveSourceMapHook(bundlePath, sourceMappingUrl);\n logger.debug(`resolveSourceMap hook returned: ${JSON.stringify(customPath)}`);\n\n if (customPath) {\n searchLocations.push(customPath);\n }\n }\n\n // 1. try to find source map at `sourceMappingURL` location\n if (sourceMappingUrl) {\n let parsedUrl: URL | undefined;\n try {\n parsedUrl = new URL(sourceMappingUrl);\n } catch {\n // noop\n }\n\n if (parsedUrl?.protocol === 'file:') {\n searchLocations.push(url.fileURLToPath(sourceMappingUrl));\n } else if (parsedUrl) {\n // noop, non-file urls don't translate to a local sourcemap file\n } else if (path.isAbsolute(sourceMappingUrl)) {\n searchLocations.push(path.normalize(sourceMappingUrl));\n } else {\n searchLocations.push(path.normalize(path.join(path.dirname(bundlePath), sourceMappingUrl)));\n }\n }\n\n // 2. try to find source map at path adjacent to chunk source, but with `.map` appended\n searchLocations.push(`${bundlePath}.map`);\n\n for (const searchLocation of searchLocations) {\n try {\n await util.promisify(fs.access)(searchLocation);\n logger.debug(`Source map found for bundle \\`${bundlePath}\\`: \\`${searchLocation}\\``);\n return searchLocation;\n } catch {\n // noop\n }\n }\n\n // This is just a debug message because it can be quite spammy for some frameworks\n logger.debug(\n `Could not determine source map path for bundle \\`${bundlePath}\\`` +\n ` with sourceMappingURL=${sourceMappingUrl === undefined ? 'undefined' : `\\`${sourceMappingUrl}\\``}` +\n ` - Did you turn on source map generation in your bundler?` +\n ` (Attempted paths: ${searchLocations.map(e => `\\`${e}\\``).join(', ')})`,\n );\n return undefined;\n}\n\n/**\n * Reads a source map, injects debug ID fields, and writes the source map to the target path.\n */\nasync function prepareSourceMapForDebugIdUpload(\n sourceMapPath: string,\n targetPath: string,\n debugId: string,\n rewriteSourcesHook: RewriteSourcesHook,\n logger: Logger,\n): Promise<void> {\n let sourceMapFileContent: string;\n try {\n sourceMapFileContent = await util.promisify(fs.readFile)(sourceMapPath, {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n\n let map: Record<string, unknown>;\n try {\n map = JSON.parse(sourceMapFileContent) as { sources: unknown; [key: string]: unknown };\n // For now we write both fields until we know what will become the standard - if ever.\n map['debug_id'] = debugId;\n map['debugId'] = debugId;\n } catch {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n return;\n }\n\n if (map['sources'] && Array.isArray(map['sources'])) {\n const mapDir = path.dirname(sourceMapPath);\n map['sources'] = map['sources'].map((source: string) => rewriteSourcesHook(source, map, { mapDir }));\n }\n\n try {\n await util.promisify(fs.writeFile)(targetPath, JSON.stringify(map), {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to prepare source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n}\n\nconst PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\\-.]*:\\/\\//;\nexport function defaultRewriteSourcesHook(source: string): string {\n if (source.match(PROTOCOL_REGEX)) {\n return source.replace(PROTOCOL_REGEX, '');\n } else {\n return path.relative(process.cwd(), path.normalize(source));\n }\n}\n"],"names":["fs","path"],"mappings":";;;;;;;AAcO,SAAS,2BAAA,CAA4B,EAAE,wBAAA,EAAyB,EAA+B;AACpG,EAAA,OAAO,OAAO,kBAAA,KAAiC;AAG7C,IAAA,MAAM,YAAA,GAAe,kBAAA,CAAmB,GAAA,CAAI,yBAAyB,CAAA;AACrE,IAAA,MAAM,wBAAA,CAAyB,iBAAiB,YAAY,CAAA;AAAA,EAC9D,CAAA;AACF;AAEA,eAAsB,8BACpB,cAAA,EACA,YAAA,EACA,UAAA,EACA,MAAA,EACA,oBACA,oBAAA,EACe;AACf,EAAA,IAAI,aAAA;AACJ,EAAA,IAAI;AACF,IAAA,aAAA,GAAgB,MAAM,SAAA,CAAUA,WAAA,CAAG,QAAQ,CAAA,CAAE,gBAA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AmB,kBAAA,CAAmB,MAAA,EAAQ,GAAA,EAAK,EAAE,MAAA,EAAQ,CAAC,CAAA;AAAA,EACrG;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,CAAK,UAAUD,WAAA,CAAG,SAAS,EAAE,UAAA,EAAY,IAAA,CAAK,SAAA,CAAU,GAAG,CAAA,EAAG;AAAA,MAClE,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,EACH,SAAS,CAAA,EAAG;AACV,IAAA,MAAA,CAAO,KAAA,CAAM,CAAA,kDAAA,EAAqD,aAAa,CAAA,CAAA,EAAI,CAAC,CAAA;AACpF,IAAA;AAAA,EACF;AACF;AAEA,MAAM,cAAA,GAAiB,gCAAA;AAChB,SAAS,0BAA0B,MAAA,EAAwB;AAChE,EAAA,IAAI,MAAA,CAAO,KAAA,CAAM,cAAc,CAAA,EAAG;AAChC,IAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,cAAA,EAAgB,EAAE,CAAA;AAAA,EAC1C,CAAA,MAAO;AACL,IAAA,OAAOC,aAAA,CAAK,SAAS,OAAA,CAAQ,GAAA,IAAOA,aAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA,EAC5D;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"debug-id-upload.js","sources":["../../../src/core/debug-id-upload.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport * as url from 'url';\nimport * as util from 'util';\nimport { promisify } from 'util';\nimport type { SentryBuildPluginManager } from './build-plugin-manager';\nimport type { Logger } from './logger';\nimport type { ResolveSourceMapHook, RewriteSourcesHook } from './types';\nimport { stripQueryAndHashFromPath } from './utils';\n\ninterface DebugIdUploadPluginOptions {\n sentryBuildPluginManager: SentryBuildPluginManager;\n}\n\nexport function createDebugIdUploadFunction({ sentryBuildPluginManager }: DebugIdUploadPluginOptions) {\n return async (buildArtifactPaths: string[]) => {\n // Webpack and perhaps other bundlers allow you to append query strings to\n // filenames for cache busting purposes. We should strip these before upload.\n const cleanedPaths = buildArtifactPaths.map(stripQueryAndHashFromPath);\n await sentryBuildPluginManager.uploadSourcemaps(cleanedPaths);\n };\n}\n\nexport async function prepareBundleForDebugIdUpload(\n bundleFilePath: string,\n uploadFolder: string,\n chunkIndex: number,\n logger: Logger,\n rewriteSourcesHook: RewriteSourcesHook,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleContent;\n try {\n bundleContent = await promisify(fs.readFile)(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to determine debug ID and source map: ${bundleFilePath}`, e);\n return;\n }\n\n const debugId = determineDebugIdFromBundleSource(bundleContent);\n if (debugId === undefined) {\n logger.debug(\n `Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ${bundleFilePath}`,\n );\n return;\n }\n\n const uniqueUploadName = `${debugId}-${chunkIndex}`;\n\n bundleContent = addDebugIdToBundleSource(bundleContent, debugId);\n const writeSourceFilePromise = fs.promises.writeFile(\n path.join(uploadFolder, `${uniqueUploadName}.js`),\n bundleContent,\n 'utf-8',\n );\n\n const writeSourceMapFilePromise = determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\n logger,\n resolveSourceMapHook,\n ).then(async sourceMapPath => {\n if (sourceMapPath) {\n await prepareSourceMapForDebugIdUpload(\n sourceMapPath,\n path.join(uploadFolder, `${uniqueUploadName}.js.map`),\n debugId,\n rewriteSourcesHook,\n logger,\n );\n }\n });\n\n await writeSourceFilePromise;\n await writeSourceMapFilePromise;\n}\n\n/**\n * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle\n * source and extracts the bundle's debug ID from it.\n *\n * The string pattern is injected via the debug ID injection snipped.\n */\nfunction determineDebugIdFromBundleSource(code: string): string | undefined {\n const match = code.match(\n /sentry-dbid-([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})/,\n );\n\n if (match) {\n return match[1];\n } else {\n return undefined;\n }\n}\n\nconst SPEC_LAST_DEBUG_ID_REGEX = /\\/\\/# debugId=([a-fA-F0-9-]+)(?![\\s\\S]*\\/\\/# debugId=)/m;\n\nfunction hasSpecCompliantDebugId(bundleSource: string): boolean {\n return SPEC_LAST_DEBUG_ID_REGEX.test(bundleSource);\n}\n\nfunction addDebugIdToBundleSource(bundleSource: string, debugId: string): string {\n if (hasSpecCompliantDebugId(bundleSource)) {\n return bundleSource.replace(SPEC_LAST_DEBUG_ID_REGEX, `//# debugId=${debugId}`);\n } else {\n return `${bundleSource}\\n//# debugId=${debugId}`;\n }\n}\n\nfunction bundleHasInlineSourceMap(bundleSource: string): boolean {\n return /^\\s*\\/\\/# sourceMappingURL=data:/m.test(bundleSource);\n}\n\nfunction setDebugIdOnSourceMap(map: Record<string, unknown>, debugId: string): void {\n // For now we write both fields until we know what will become the standard - if ever.\n map['debug_id'] = debugId;\n map['debugId'] = debugId;\n}\n\nexport type StampedArtifacts = {\n bundleSource: string;\n /** `undefined` when the bundle has no separate source map (i.e. the map is inlined). */\n sourceMapSource: string | undefined;\n};\n\nfunction parseSourceMap(sourceMapSource: string): Record<string, unknown> | undefined {\n let map: unknown;\n try {\n map = JSON.parse(sourceMapSource);\n } catch {\n return undefined;\n }\n\n return map && typeof map === 'object' ? (map as Record<string, unknown>) : undefined;\n}\n\n/**\n * Stamps the debug ID injected into `bundleSource` into the bundle (as `//# debugId=` comment) and its\n * source map (as `debug_id`/`debugId` fields).\n *\n * This exists for `sourcemaps.disable: \"disable-upload\"`: the regular upload path only stamps\n * temporary copies of the artifacts (see `prepareBundleForDebugIdUpload`), so without this the\n * emitted artifacts would carry no debug ID and a later manual upload could not match them.\n * Callers must apply the result inside the bundler's asset pipeline (or, for bundlers without one,\n * before the build resolves) so that integrity hashes computed by later build steps include it.\n *\n * Pass `sourceMapSource: undefined` when the bundle has no separate source map. A bundle with an\n * inlined map still gets the comment, which is all the CLI and Symbolicator read the debug ID from.\n *\n * @returns the stamped artifacts, or `undefined` for bundles without a debug ID, without any source\n * map, or with an unparseable map.\n */\nexport function stampDebugId(bundleSource: string, sourceMapSource: string | undefined): StampedArtifacts | undefined {\n const debugId = determineDebugIdFromBundleSource(bundleSource);\n if (debugId === undefined) {\n return undefined;\n }\n\n if (sourceMapSource === undefined) {\n if (!bundleHasInlineSourceMap(bundleSource)) {\n return undefined;\n }\n\n return { bundleSource: addDebugIdToBundleSource(bundleSource, debugId), sourceMapSource: undefined };\n }\n\n const map = parseSourceMap(sourceMapSource);\n if (!map) {\n return undefined;\n }\n\n setDebugIdOnSourceMap(map, debugId);\n\n return {\n bundleSource: addDebugIdToBundleSource(bundleSource, debugId),\n sourceMapSource: JSON.stringify(map),\n };\n}\n\n/**\n * Stamps the debug ID of an emitted bundle into the bundle and its source map on disk.\n *\n * Used by bundlers that offer no hook to modify assets before they are written (esbuild).\n */\nexport async function addDebugIdToEmittedArtifacts(\n bundleFilePath: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleSource: string;\n try {\n bundleSource = await fs.promises.readFile(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to stamp debug ID: ${bundleFilePath}`, e);\n return;\n }\n\n const sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleSource,\n logger,\n resolveSourceMapHook,\n );\n\n let sourceMapSource: string | undefined;\n if (sourceMapPath) {\n try {\n sourceMapSource = await fs.promises.readFile(sourceMapPath, 'utf8');\n } catch (e) {\n logger.error(`Could not read source map to stamp debug ID: ${sourceMapPath}`, e);\n return;\n }\n }\n\n const stamped = stampDebugId(bundleSource, sourceMapSource);\n if (!stamped) {\n logger.debug(\n `Could not stamp debug ID (no debug ID in bundle, no source map, or invalid source map): ${bundleFilePath}`,\n );\n return;\n }\n\n const writes = [fs.promises.writeFile(bundleFilePath, stamped.bundleSource, 'utf8')];\n if (sourceMapPath && stamped.sourceMapSource !== undefined) {\n writes.push(fs.promises.writeFile(sourceMapPath, stamped.sourceMapSource, 'utf8'));\n }\n\n try {\n await Promise.all(writes);\n } catch (e) {\n logger.error(`Could not write debug ID into build artifacts: ${bundleFilePath}`, e);\n }\n}\n\n/**\n * Applies a set of heuristics to find the source map for a particular bundle.\n *\n * @returns the path to the bundle's source map or `undefined` if none could be found.\n */\nexport async function determineSourceMapPathFromBundle(\n bundlePath: string,\n bundleSource: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<string | undefined> {\n const sourceMappingUrlMatch = bundleSource.match(/^\\s*\\/\\/# sourceMappingURL=(.*)$/m);\n const sourceMappingUrl = sourceMappingUrlMatch ? (sourceMappingUrlMatch[1] as string) : undefined;\n\n const searchLocations: string[] = [];\n\n if (resolveSourceMapHook) {\n logger.debug(\n `Calling sourcemaps.resolveSourceMap(${JSON.stringify(bundlePath)}, ${JSON.stringify(sourceMappingUrl)})`,\n );\n const customPath = await resolveSourceMapHook(bundlePath, sourceMappingUrl);\n logger.debug(`resolveSourceMap hook returned: ${JSON.stringify(customPath)}`);\n\n if (customPath) {\n searchLocations.push(customPath);\n }\n }\n\n // 1. try to find source map at `sourceMappingURL` location\n if (sourceMappingUrl) {\n let parsedUrl: URL | undefined;\n try {\n parsedUrl = new URL(sourceMappingUrl);\n } catch {\n // noop\n }\n\n if (parsedUrl?.protocol === 'file:') {\n searchLocations.push(url.fileURLToPath(sourceMappingUrl));\n } else if (parsedUrl) {\n // noop, non-file urls don't translate to a local sourcemap file\n } else if (path.isAbsolute(sourceMappingUrl)) {\n searchLocations.push(path.normalize(sourceMappingUrl));\n } else {\n searchLocations.push(path.normalize(path.join(path.dirname(bundlePath), sourceMappingUrl)));\n }\n }\n\n // 2. try to find source map at path adjacent to chunk source, but with `.map` appended\n searchLocations.push(`${bundlePath}.map`);\n\n for (const searchLocation of searchLocations) {\n try {\n await util.promisify(fs.access)(searchLocation);\n logger.debug(`Source map found for bundle \\`${bundlePath}\\`: \\`${searchLocation}\\``);\n return searchLocation;\n } catch {\n // noop\n }\n }\n\n // This is just a debug message because it can be quite spammy for some frameworks\n logger.debug(\n `Could not determine source map path for bundle \\`${bundlePath}\\`` +\n ` with sourceMappingURL=${sourceMappingUrl === undefined ? 'undefined' : `\\`${sourceMappingUrl}\\``}` +\n ` - Did you turn on source map generation in your bundler?` +\n ` (Attempted paths: ${searchLocations.map(e => `\\`${e}\\``).join(', ')})`,\n );\n return undefined;\n}\n\n/**\n * Reads a source map, injects debug ID fields, and writes the source map to the target path.\n */\nasync function prepareSourceMapForDebugIdUpload(\n sourceMapPath: string,\n targetPath: string,\n debugId: string,\n rewriteSourcesHook: RewriteSourcesHook,\n logger: Logger,\n): Promise<void> {\n let sourceMapFileContent: string;\n try {\n sourceMapFileContent = await util.promisify(fs.readFile)(sourceMapPath, {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n\n let map: Record<string, unknown>;\n try {\n map = JSON.parse(sourceMapFileContent) as { sources: unknown; [key: string]: unknown };\n setDebugIdOnSourceMap(map, debugId);\n } catch {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n return;\n }\n\n if (map['sources'] && Array.isArray(map['sources'])) {\n const mapDir = path.dirname(sourceMapPath);\n map['sources'] = map['sources'].map((source: string) => rewriteSourcesHook(source, map, { mapDir }));\n }\n\n try {\n await util.promisify(fs.writeFile)(targetPath, JSON.stringify(map), {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to prepare source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n}\n\nconst PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\\-.]*:\\/\\//;\nexport function defaultRewriteSourcesHook(source: string): string {\n if (source.match(PROTOCOL_REGEX)) {\n return source.replace(PROTOCOL_REGEX, '');\n } else {\n return path.relative(process.cwd(), path.normalize(source));\n }\n}\n"],"names":["fs","path"],"m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A,CAAO,OAAA,CAAQ,cAAA,EAAgB,EAAE,CAAA;AAAA,EAC1C,CAAA,MAAO;AACL,IAAA,OAAOC,aAAA,CAAK,SAAS,OAAA,CAAQ,GAAA,IAAOA,aAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA,EAC5D;AACF;;;;"}
|
package/build/esm/core/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { stripQueryAndHashFromPath, CodeInjection, containsOnlyImports } from '.
|
|
|
5
5
|
export { generateModuleMetadataInjectorCode, generateReleaseInjectorCode, replaceBooleanFlagsInCode, stringToUUID } from './utils.js';
|
|
6
6
|
export { globFiles } from './glob.js';
|
|
7
7
|
export { createSentryBuildPluginManager } from './build-plugin-manager.js';
|
|
8
|
-
export { createDebugIdUploadFunction } from './debug-id-upload.js';
|
|
8
|
+
export { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction, stampDebugId } from './debug-id-upload.js';
|
|
9
9
|
|
|
10
10
|
let babelAnnotationRuntimePromise;
|
|
11
11
|
function loadBabelAnnotationRuntime() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import SentryCli from '@sentry/cli';\nimport { debug } from '@sentry/core';\nimport * as fs from 'fs';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n/**\n * Determines whether the Sentry CLI binary is in its expected location.\n * This function is useful since `@sentry/cli` installs the binary via a post-install\n * script and post-install scripts may not always run. E.g. with `npm i --ignore-scripts`.\n */\nexport function sentryCliBinaryExists(): boolean {\n return fs.existsSync(SentryCli.getPath());\n}\n\n// We need to be careful not to inject the snippet before any `\"use strict\";`s.\n// As an additional complication `\"use strict\";`s may come after any number of comments.\nexport const COMMENT_USE_STRICT_REGEX =\n // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.\n /^(?:\\s*|\\/\\*(?:.|\\r|\\n)*?\\*\\/|\\/\\/.*[\\n\\r])*(?:\"[^\"]*\";|'[^']*';)?/;\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction } from './debug-id-upload';\n"],"names":[],"mappings":";;;;;;;;;AAgBA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GAAA,CAAI,CAAC,OAAO,aAAa,GAAG,OAAO,0BAAiB,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,MAC9F,CAAC,CAAC,KAAA,EAAO,WAAW,CAAA,KAAM;AACxB,QAAA,OAAO;AAAA,UACL,gBAAgB,KAAA,CAAM,cAAA;AAAA,UACtB,6BAA6B,WAAA,CAAY,OAAA;AAAA,UACzC,yCAAyC,WAAA,CAAY;AAAA,SACvD;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,6BAAA;AACT;AAOO,SAAS,qBAAA,GAAiC;AAC/C,EAAA,OAAO,EAAA,CAAG,UAAA,CAAW,SAAA,CAAU,OAAA,EAAS,CAAA;AAC1C;AAIO,MAAM,wBAAA;AAAA;AAAA,EAEX;AAAA;AAMK,SAAS,SAAS,QAAA,EAA2B;AAClD,EAAA,MAAM,aAAA,GAAgB,0BAA0B,QAAQ,CAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA,CAAE,KAAK,CAAA,GAAA,KAAO,aAAA,CAAc,QAAA,CAAS,GAAG,CAAC,CAAA;AACxE;AAgBO,SAAS,uBAAA,CAAwB,MAAc,c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cAAA,CAAe,IAAA,EAAM;AAAA,UACxC,SAAS,CAAC,CAAC,QAAQ,EAAE,iBAAA,EAAmB,CAAC,CAAA;AAAA,UACzC,QAAA,EAAU,EAAA;AAAA,UACV,cAAA,EAAgB,qBAAA;AAAA,UAChB,UAAA,EAAY;AAAA,YACV,UAAA,EAAY,QAAA;AAAA,YACZ,yBAAA,EAA2B,IAAA;AAAA,YAC3B,OAAA,EAAS;AAAA,WACX;AAAA,UACA,aAAA,EAAe;AAAA,YACb,sBAAA,EAAwB;AAAA,WAC1B;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,QAAQ,IAAA,IAAQ,IAAA;AAAA,UACtB,KAAK,MAAA,EAAQ;AAAA,SACf;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAA,KAAA,CAAM,KAAA,CAAM,yCAAyC,CAAC,CAAA;AAAA,MACxD;AAEA,MAAA,OAAO,EAAE,IAAA,EAAK;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAI,aAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import SentryCli from '@sentry/cli';\nimport { debug } from '@sentry/core';\nimport * as fs from 'fs';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n/**\n * Determines whether the Sentry CLI binary is in its expected location.\n * This function is useful since `@sentry/cli` installs the binary via a post-install\n * script and post-install scripts may not always run. E.g. with `npm i --ignore-scripts`.\n */\nexport function sentryCliBinaryExists(): boolean {\n return fs.existsSync(SentryCli.getPath());\n}\n\n// We need to be careful not to inject the snippet before any `\"use strict\";`s.\n// As an additional complication `\"use strict\";`s may come after any number of comments.\nexport const COMMENT_USE_STRICT_REGEX =\n // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.\n /^(?:\\s*|\\/\\*(?:.|\\r|\\n)*?\\*\\/|\\/\\/.*[\\n\\r])*(?:\"[^\"]*\";|'[^']*';)?/;\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\n"],"names":[],"mappings":";;;;;;;;;AAgBA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GAAA,CAAI,CAAC,OAAO,aAAa,GAAG,OAAO,0BAAiB,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,MAC9F,CAAC,CAAC,KAAA,EAAO,WAAW,CAAA,KAAM;AACxB,QAAA,OAAO;AAAA,UACL,gBAAgB,KAAA,CAAM,cAAA;AAAA,UACtB,6BAA6B,WAAA,CAAY,OAAA;AAAA,UACzC,yCAAyC,WAAA,CAAY;AAAA,SACvD;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,6BAAA;AACT;AAOO,SAAS,qBAAA,GAAiC;AAC/C,EAAA,OAAO,EAAA,CAAG,UAAA,CAAW,SAAA,CAAU,OAAA,EAAS,CAAA;AAC1C;AAIO,MAAM,wBAAA;AAAA;AAAA,EAEX;AAAA;AAMK,SAAS,SAAS,QAAA,EAA2B;AAClD,EAAA,MAAM,aAAA,GAAgB,0BAA0B,QAAQ,CAAA;AACxD,EAAA,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AA6B,uCAAA,EAAwC,GAC3F,MAAM,0BAAA,EAA2B;AACnC,MAAA,MAAM,MAAA,GAAS,iBAAiB,uCAAA,GAA0C,2BAAA;AAE1E,MAAA,IAAI;AACF,QAAA,MAAM,MAAA,GAAS,MAAM,cAAA,CAAe,IAAA,EAAM;AAAA,UACxC,SAAS,CAAC,CAAC,QAAQ,EAAE,iBAAA,EAAmB,CAAC,CAAA;AAAA,UACzC,QAAA,EAAU,EAAA;AAAA,UACV,cAAA,EAAgB,qBAAA;AAAA,UAChB,UAAA,EAAY;AAAA,YACV,UAAA,EAAY,QAAA;AAAA,YACZ,yBAAA,EAA2B,IAAA;AAAA,YAC3B,OAAA,EAAS;AAAA,WACX;AAAA,UACA,aAAA,EAAe;AAAA,YACb,sBAAA,EAAwB;AAAA,WAC1B;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,QAAQ,IAAA,IAAQ,IAAA;AAAA,UACtB,KAAK,MAAA,EAAQ;AAAA,SACf;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAA,KAAA,CAAM,KAAA,CAAM,yCAAyC,CAAC,CAAA;AAAA,MACxD;AAEA,MAAA,OAAO,EAAE,IAAA,EAAK;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAI,aAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"10.
|
|
1
|
+
{"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"10.75.0\";\n"],"names":[],"mappings":"AAAO,MAAM,WAAA,GAAc;;;;"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { getDebugIdSnippet } from '../core/index.js';
|
|
1
|
+
import { getDebugIdSnippet, isJsFile } from '../core/index.js';
|
|
2
2
|
export { sentryCliBinaryExists } from '../core/index.js';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { createSentryBuildPluginManager } from '../core/build-plugin-manager.js';
|
|
7
7
|
import { CodeInjection, generateReleaseInjectorCode, generateModuleMetadataInjectorCode } from '../core/utils.js';
|
|
8
|
-
import { createDebugIdUploadFunction } from '../core/debug-id-upload.js';
|
|
8
|
+
import { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction } from '../core/debug-id-upload.js';
|
|
9
9
|
|
|
10
10
|
function getEsbuildMajorVersion() {
|
|
11
11
|
try {
|
|
@@ -173,9 +173,24 @@ function sentryEsbuildPlugin(userOptions = {}) {
|
|
|
173
173
|
onEnd(async (result) => {
|
|
174
174
|
try {
|
|
175
175
|
await sentryBuildPluginManager.createRelease();
|
|
176
|
-
if (sourcemapsEnabled
|
|
176
|
+
if (sourcemapsEnabled) {
|
|
177
177
|
const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];
|
|
178
|
-
|
|
178
|
+
if (options.sourcemaps?.disable !== "disable-upload") {
|
|
179
|
+
await upload(buildArtifacts);
|
|
180
|
+
} else if (initialOptions.write === false) {
|
|
181
|
+
logger.debug("Build output is not written to disk. Skipping debug ID injection into build artifacts.");
|
|
182
|
+
} else {
|
|
183
|
+
const outputDir = initialOptions.absWorkingDir ?? process.cwd();
|
|
184
|
+
await Promise.all(
|
|
185
|
+
buildArtifacts.filter(isJsFile).map(
|
|
186
|
+
(bundle) => addDebugIdToEmittedArtifacts(
|
|
187
|
+
path.resolve(outputDir, bundle),
|
|
188
|
+
logger,
|
|
189
|
+
options.sourcemaps?.resolveSourceMap
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
);
|
|
193
|
+
}
|
|
179
194
|
}
|
|
180
195
|
} finally {
|
|
181
196
|
freeGlobalDependencyOnBuildArtifacts();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\nexport { sentryCliBinaryExists } from '../core';\n"],"names":[],"mappings":";;;;;;;;;AAoEA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAE7B,IAAA,OAAO,OAAA,CAAQ,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAAA,EACtC,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,MAAM,UAAA,GAAa,uBAAA;AAGZ,SAAS,mBAAA,CAAoB,WAAA,GAAuB,EAAC,EAAQ;AAClE,EAAA,MAAM,wBAAA,GAA2B,+BAA+B,WAAA,EAAa;AAAA,IAC3E,YAAA,EAAc,WAAA,CAAY,YAAA,EAAc,oBAAA,IAAwB,IAAI,UAAU,CAAA,CAAA,CAAA;AAAA,IAC9E,SAAA,EAAW,SAAA;AAAA,IACX,uBAAuB,sBAAA;AAAuB,GAC/C,CAAA;AAED,EAAA,MAAM;AAAA,IACJ,MAAA;AAAA,IACA,iBAAA,EAAmB,OAAA;AAAA,IACnB,uCAAA,EAAyC,iBAAA;AAAA,IACzC,cAAA;AAAA,IACA;AAAA,GACF,GAAI,wBAAA;AAEJ,EAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,4BAAA;AAAA,MACN,KAAA,GAAQ;AAAA,MAER;AAAA,KACF;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,CAAQ,GAAA,EAAI,CAAE,KAAA,CAAM,mCAAmC,CAAA,EAAG;AAC5D,IAAA,MAAA,CAAO,KAAK,wFAAwF,CAAA;AAAA,E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QAAA,CAAS,OAAO,CAAA,GAAI,EAAC;AACjF,YAAA,MAAM,OAAO,cAAc,CAAA;AAAA,UAC7B;AAAA,QACF,CAAA,SAAE;AACA,UAAA,oCAAA,EAAqC;AACrC,UAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n addDebugIdToEmittedArtifacts,\n isJsFile,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n write?: boolean;\n absWorkingDir?: string;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled) {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n\n if (options.sourcemaps?.disable !== 'disable-upload') {\n await upload(buildArtifacts);\n } else if (initialOptions.write === false) {\n logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.');\n } else {\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is\n // skipped with `disable-upload`. esbuild has no hook to modify outputs before they are\n // written, so the emitted artifacts get stamped on disk instead.\n const outputDir = initialOptions.absWorkingDir ?? process.cwd();\n await Promise.all(\n buildArtifacts\n .filter(isJsFile)\n .map(bundle =>\n addDebugIdToEmittedArtifacts(\n path.resolve(outputDir, bundle),\n logger,\n options.sourcemaps?.resolveSourceMap,\n ),\n ),\n );\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\nexport { sentryCliBinaryExists } from '../core';\n"],"names":[],"mappings":";;;;;;;;;AAwEA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAE7B,IAAA,OAAO,OAAA,CAAQ,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAAA,EACtC,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,MAAM,UAAA,GAAa,uBAAA;AAGZ,SAAS,mBAAA,CAAoB,WAAA,GAAuB,EAAC,EAAQ;AAClE,EAAA,MAAM,wBAAA,GAA2B,+BAA+B,WAAA,EAAa;AAAA,IAC3E,YAAA,EAAc,WAAA,CAAY,YA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BAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
|
package/build/esm/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"10.
|
|
1
|
+
{"type":"module","version":"10.75.0","sideEffects":["./sentry-release-injection-file.js","./sentry-esbuild-debugid-injection-file.js"]}
|
|
@@ -6,7 +6,7 @@ import { createRequire } from 'node:module';
|
|
|
6
6
|
import { createSentryBuildPluginManager } from '../core/build-plugin-manager.js';
|
|
7
7
|
import { CodeInjection, generateReleaseInjectorCode, generateModuleMetadataInjectorCode, stringToUUID, replaceBooleanFlagsInCode } from '../core/utils.js';
|
|
8
8
|
import { globFiles } from '../core/glob.js';
|
|
9
|
-
import { createDebugIdUploadFunction } from '../core/debug-id-upload.js';
|
|
9
|
+
import { stampDebugId, createDebugIdUploadFunction } from '../core/debug-id-upload.js';
|
|
10
10
|
|
|
11
11
|
let viteParseAstAsyncPromise;
|
|
12
12
|
const JS_MODULE_ID_FILTER = /\.[cm]?[jt]sx?(?:[?#].*)?$/;
|
|
@@ -164,6 +164,23 @@ function _rollupPluginInternal(userOptions = {}, buildTool, buildToolMajorVersio
|
|
|
164
164
|
map: ms.generateMap({ file: chunk.fileName, hires: "boundary" })
|
|
165
165
|
};
|
|
166
166
|
}
|
|
167
|
+
function generateBundle(_outputOptions, bundle) {
|
|
168
|
+
for (const output of Object.values(bundle)) {
|
|
169
|
+
if (output.type !== "chunk" || !isJsFile(output.fileName)) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const sourceMapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];
|
|
173
|
+
const sourceMapSource = sourceMapAsset?.type === "asset" && typeof sourceMapAsset.source === "string" ? sourceMapAsset.source : void 0;
|
|
174
|
+
const stamped = stampDebugId(output.code, sourceMapSource);
|
|
175
|
+
if (!stamped) {
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
output.code = stamped.bundleSource;
|
|
179
|
+
if (stamped.sourceMapSource !== void 0 && sourceMapAsset?.type === "asset") {
|
|
180
|
+
sourceMapAsset.source = stamped.sourceMapSource;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
167
184
|
async function writeBundle(outputOptions, bundle) {
|
|
168
185
|
try {
|
|
169
186
|
await sentryBuildPluginManager.createRelease();
|
|
@@ -193,23 +210,16 @@ function _rollupPluginInternal(userOptions = {}, buildTool, buildToolMajorVersio
|
|
|
193
210
|
}
|
|
194
211
|
}
|
|
195
212
|
const name = `sentry-${buildTool}-plugin`;
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
} : transform;
|
|
201
|
-
return {
|
|
202
|
-
name,
|
|
203
|
-
buildStart,
|
|
204
|
-
transform: transformHook,
|
|
205
|
-
renderChunk,
|
|
206
|
-
writeBundle
|
|
207
|
-
};
|
|
208
|
-
}
|
|
213
|
+
const transformHook = buildTool === "vite" ? {
|
|
214
|
+
filter: { id: JS_MODULE_ID_FILTER },
|
|
215
|
+
handler: transform
|
|
216
|
+
} : transform;
|
|
209
217
|
return {
|
|
210
218
|
name,
|
|
211
219
|
buildStart,
|
|
220
|
+
...shouldTransform ? { transform: transformHook } : {},
|
|
212
221
|
renderChunk,
|
|
222
|
+
...options.sourcemaps?.disable === "disable-upload" ? { generateBundle: { order: "pre", handler: generateBundle } } : {},
|
|
213
223
|
writeBundle
|
|
214
224
|
};
|
|
215
225
|
}
|