@sentry/bundler-plugins 11.17.0 → 11.19.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.
Files changed (53) hide show
  1. package/build/cjs/core/build-plugin-manager.js +4 -10
  2. package/build/cjs/core/build-plugin-manager.js.map +1 -1
  3. package/build/cjs/core/debug-id-upload.js +1 -1
  4. package/build/cjs/core/debug-id-upload.js.map +1 -1
  5. package/build/cjs/core/index.js +3 -2
  6. package/build/cjs/core/index.js.map +1 -1
  7. package/build/cjs/core/options-mapping.js +3 -6
  8. package/build/cjs/core/options-mapping.js.map +1 -1
  9. package/build/cjs/core/sentry/telemetry.js +1 -1
  10. package/build/cjs/core/sentry/telemetry.js.map +1 -1
  11. package/build/cjs/core/sourcemap-settings.js +26 -22
  12. package/build/cjs/core/sourcemap-settings.js.map +1 -1
  13. package/build/cjs/core/upload-credentials.js +49 -0
  14. package/build/cjs/core/upload-credentials.js.map +1 -0
  15. package/build/cjs/core/version.js +1 -1
  16. package/build/cjs/core/version.js.map +1 -1
  17. package/build/cjs/vite/source-map-hooks.js +1 -1
  18. package/build/cjs/vite/source-map-hooks.js.map +1 -1
  19. package/build/esm/core/build-plugin-manager.js +4 -9
  20. package/build/esm/core/build-plugin-manager.js.map +1 -1
  21. package/build/esm/core/debug-id-upload.js +1 -1
  22. package/build/esm/core/debug-id-upload.js.map +1 -1
  23. package/build/esm/core/index.js +3 -2
  24. package/build/esm/core/index.js.map +1 -1
  25. package/build/esm/core/options-mapping.js +4 -7
  26. package/build/esm/core/options-mapping.js.map +1 -1
  27. package/build/esm/core/sentry/telemetry.js +1 -1
  28. package/build/esm/core/sentry/telemetry.js.map +1 -1
  29. package/build/esm/core/sourcemap-settings.js +26 -21
  30. package/build/esm/core/sourcemap-settings.js.map +1 -1
  31. package/build/esm/core/upload-credentials.js +42 -0
  32. package/build/esm/core/upload-credentials.js.map +1 -0
  33. package/build/esm/core/version.js +1 -1
  34. package/build/esm/core/version.js.map +1 -1
  35. package/build/esm/package.json +1 -1
  36. package/build/esm/vite/source-map-hooks.js +2 -2
  37. package/build/esm/vite/source-map-hooks.js.map +1 -1
  38. package/build/types/core/build-plugin-manager.d.ts.map +1 -1
  39. package/build/types/core/debug-id-upload.d.ts.map +1 -1
  40. package/build/types/core/index.d.ts +2 -1
  41. package/build/types/core/index.d.ts.map +1 -1
  42. package/build/types/core/options-mapping.d.ts +2 -2
  43. package/build/types/core/options-mapping.d.ts.map +1 -1
  44. package/build/types/core/sentry/telemetry.d.ts.map +1 -1
  45. package/build/types/core/sourcemap-settings.d.ts +8 -6
  46. package/build/types/core/sourcemap-settings.d.ts.map +1 -1
  47. package/build/types/core/types.d.ts +14 -11
  48. package/build/types/core/types.d.ts.map +1 -1
  49. package/build/types/core/upload-credentials.d.ts +18 -0
  50. package/build/types/core/upload-credentials.d.ts.map +1 -0
  51. package/build/types/core/version.d.ts +1 -1
  52. package/build/types/vite/source-map-hooks.d.ts.map +1 -1
  53. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"build-plugin-manager.js","names":["escapeGlob"],"sources":["../../../src/core/build-plugin-manager.ts"],"sourcesContent":["/* oxlint-disable max-lines */\nimport { closeSession, DEFAULT_ENVIRONMENT, makeSession, setMeasurement, startSpan } from '@sentry/core';\nimport * as dotenv from 'dotenv';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { escape as escapeGlob } from 'glob';\nimport { SentryCliAdapter } from './cli';\nimport type { NormalizedOptions } from './options-mapping';\nimport { normalizeUserOptions, validateOptions } from './options-mapping';\nimport type { Logger } from './logger';\nimport { createLogger } from './logger';\nimport { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry';\nimport type { InternalOptions, SentrySDKBuildFlags } from './types';\nimport { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils';\nimport {\n defaultRewriteSourcesHook,\n prepareArtifactForUpload,\n prepareBundleForDebugIdUpload,\n writePreparedArtifact,\n} from './debug-id-upload';\nimport { globFiles } from './glob';\nimport type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';\nimport { decideSourceMapHandling, getSourceMapFeatures } from './sourcemap-settings';\nimport type { UploadFilter } from './upload-filter';\nimport { createUploadFilter } from './upload-filter';\nimport { LIB_VERSION } from './version';\n\n// Module-level guard to prevent duplicate deploy records when multiple bundler plugin\n// instances run in the same process (e.g. Next.js creates separate webpack compilers\n// for client, server, and edge). Keyed by release name.\nconst _deployedReleases = new Set<string>();\n\n/** @internal Exported for testing only. */\nexport function _resetDeployedReleasesForTesting(): void {\n _deployedReleases.clear();\n}\n\n/**\n * A temporary folder that build artifacts are written into straight from the bundler's output,\n * before the bundler writes them to disk. The upload reads from this folder, so the bundler can\n * drop the source map assets from its own output.\n */\nexport type UploadResult = { uploaded: boolean; uploadedSourceMapPaths: string[] };\n\nexport type UploadStaging = {\n readonly dir: string;\n /** Number of artifacts written so far. */\n readonly count: number;\n /**\n * Absolute paths of the chunks staged so far (`mapDir` joined with the file name). The upload\n * does not prepare these again from disk, where a stale map of an earlier build could sit\n * next to them.\n */\n readonly stagedChunkPaths: ReadonlySet<string>;\n /**\n * Stamps the debug ID into the chunk and its source map and writes both into the folder.\n *\n * `mapSource` is `undefined` when the chunk has no separate source map. `mapDir` is the directory\n * the map would be written to and is passed to the `rewriteSources` hook. `chunkPath` is where\n * the chunk is written; `sourcemaps.assets` and `sourcemaps.ignore` are matched against it.\n */\n stage(input: {\n code: string;\n mapSource: string | undefined;\n mapDir: string;\n chunkPath: string;\n }): Promise<'staged' | 'skipped' | 'excluded' | 'failed'>;\n /** Removes the folder. Call this when no upload will consume it. */\n discard(): Promise<void>;\n /**\n * Keeps the folder and logs how to upload it by hand. Call this when the bundler already\n * dropped the staged source maps from its output but the upload did not run. Removes the\n * folder instead when nothing was staged.\n */\n keep(reason: string): Promise<void>;\n};\n\nexport type SentryBuildPluginManager = {\n /**\n * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)\n */\n logger: Logger;\n\n /**\n * Options after normalization. Includes things like the inferred release name.\n */\n normalizedOptions: NormalizedOptions;\n /**\n * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes\n * into account the options passed to the build plugin manager.\n */\n bundleSizeOptimizationReplacementValues: SentrySDKBuildFlags;\n /**\n * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.\n */\n // See `generateModuleMetadataInjectorCode` for how this should be used exactly\n bundleMetadata: Record<string, unknown>;\n\n /**\n * Contains utility functions for emitting telemetry via the build plugin manager.\n */\n telemetry: {\n /**\n * Emits a `Sentry Bundler Plugin execution` signal.\n */\n emitBundlerPluginExecutionSignal(): Promise<void>;\n };\n\n /**\n * Will potentially create a release based on the build plugin manager options.\n *\n * Also\n * - finalizes the release\n * - sets commits\n * - uploads legacy sourcemaps\n * - adds deploy information\n */\n createRelease(): Promise<void>;\n\n /**\n * Injects debug IDs into the build artifacts.\n *\n * This is a separate function from `uploadSourcemaps` because that needs to run before the sourcemaps are uploaded.\n * Usually the respective bundler-plugin will take care of this before the sourcemaps are uploaded.\n * Only use this if you need to manually inject debug IDs into the build artifacts.\n */\n injectDebugIds(buildArtifactPaths: string[]): Promise<void>;\n\n /**\n * Uploads sourcemaps using the \"Debug ID\" method. This function takes a list of build artifact paths that will be uploaded\n *\n * `uploadedSourceMapPaths` lists the source maps read from disk that were uploaded. It is empty\n * when nothing was uploaded, in direct mode (`prepareArtifacts: false`) and for staged artifacts.\n */\n uploadSourcemaps(\n buildArtifactPaths: string[],\n opts?: { prepareArtifacts?: boolean; staging?: UploadStaging },\n ): Promise<UploadResult>;\n\n /**\n * Creates a staging folder that `uploadSourcemaps` uploads together with the build artifacts\n * found on disk, in both the prepared and the direct (`prepareArtifacts: false`) mode.\n */\n createUploadStaging(): Promise<UploadStaging>;\n\n sourceMaps: {\n /**\n * Whether a source map upload can run with the current options and environment.\n */\n uploadPossible: boolean;\n /**\n * Decides how the plugin treats the user's source map setting (see `decideSourceMapHandling`).\n * Logs the decision's message once per message, unless `log` is `false`.\n */\n decide(kind: SourceMapKind, options?: { log?: boolean; environment?: string }): SourceMapDecision;\n /** Logs the decision's message, once per message. */\n logDecision(decision: SourceMapDecision): void;\n /**\n * Whether a file of the build output is uploaded, for files that are not on disk yet. Mirrors\n * the glob of the upload from disk: it must match `sourcemaps.assets` (all files when unset)\n * and none of `sourcemaps.ignore`.\n */\n shouldUpload: UploadFilter;\n /**\n * Deletes source maps from the build output after their upload. A map that cannot be deleted\n * goes to `errorHandler`, or fails the build when none is set.\n */\n deleteFromOutput(sourceMapPaths: string[]): Promise<void>;\n };\n\n /**\n * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.\n */\n deleteArtifacts(): Promise<void>;\n\n createDependencyOnBuildArtifacts: () => () => void;\n};\n\n/**\n * Creates a build plugin manager that exposes primitives for everything that a Sentry JavaScript SDK or build tooling may do during a build.\n *\n * The build plugin manager's behavior strongly depends on the options that are passed in.\n */\nexport function createSentryBuildPluginManager(\n userOptions: InternalOptions,\n bundlerPluginMetaContext: {\n /**\n * E.g. `webpack` or `nextjs` or `turbopack`\n */\n buildTool: string;\n /**\n * E.g. `5` for webpack v5 or `4` for Rollup v4\n */\n buildToolMajorVersion?: string;\n /**\n * E.g. `[sentry-webpack-plugin]` or `[@sentry/nextjs]`\n */\n loggerPrefix: string;\n },\n): SentryBuildPluginManager {\n const logger = createLogger({\n prefix: bundlerPluginMetaContext.loggerPrefix,\n silent: userOptions.silent ?? false,\n debug: userOptions.debug ?? false,\n });\n\n try {\n const dotenvFile = fs.readFileSync(path.join(process.cwd(), '.env.sentry-build-plugin'), 'utf-8');\n // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want.\n const dotenvResult = dotenv.parse(dotenvFile);\n\n // Vite has a bug/behaviour where spreading into process.env will cause it to crash\n // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251\n Object.assign(process.env, dotenvResult);\n\n logger.info('Using environment variables configured in \".env.sentry-build-plugin\".');\n } catch (e: unknown) {\n // Ignore \"file not found\" errors but throw all others\n if (typeof e === 'object' && e && 'code' in e && e.code !== 'ENOENT') {\n throw e;\n }\n }\n\n const options = normalizeUserOptions(userOptions);\n\n if (options.disable) {\n // Early-return a noop build plugin manager instance so that we\n // don't continue validating options, setting up Sentry, etc.\n // Otherwise we might create side-effects or log messages that\n // users don't expect from a disabled plugin.\n return {\n normalizedOptions: options,\n logger,\n bundleSizeOptimizationReplacementValues: {},\n telemetry: {\n emitBundlerPluginExecutionSignal: async () => {\n /* noop */\n },\n },\n bundleMetadata: {},\n createRelease: async () => {\n /* noop */\n },\n uploadSourcemaps: async () => ({ uploaded: false, uploadedSourceMapPaths: [] }),\n createUploadStaging: async () => ({\n dir: '',\n count: 0,\n stagedChunkPaths: new Set<string>(),\n stage: async () => 'skipped' as const,\n discard: async () => {\n /* noop */\n },\n keep: async () => {\n /* noop */\n },\n }),\n sourceMaps: {\n uploadPossible: false,\n decide: () => ({ enableHidden: false, deleteAfterUpload: false }),\n logDecision: () => undefined,\n shouldUpload: () => false,\n deleteFromOutput: async () => {\n /* noop */\n },\n },\n deleteArtifacts: async () => {\n /* noop */\n },\n createDependencyOnBuildArtifacts: () => () => {\n /* noop */\n },\n injectDebugIds: async () => {\n /* noop */\n },\n };\n }\n\n const shouldSendTelemetry = allowedToSendTelemetry(options);\n const { sentryScope, sentryClient } = createSentryInstance(\n options,\n shouldSendTelemetry,\n bundlerPluginMetaContext.buildTool,\n bundlerPluginMetaContext.buildToolMajorVersion,\n );\n\n const { release, environment = DEFAULT_ENVIRONMENT } = sentryClient.getOptions();\n\n const sentrySession = makeSession({ release, environment });\n sentryScope.setSession(sentrySession);\n // Send the start of the session\n sentryClient.captureSession(sentrySession);\n\n let sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out\n\n function endSession(): void {\n if (sessionHasEnded) {\n return;\n }\n\n closeSession(sentrySession);\n sentryClient.captureSession(sentrySession);\n sessionHasEnded = true;\n }\n\n // We also need to manually end sessions on errors because beforeExit is not called on crashes\n process.on('beforeExit', () => {\n endSession();\n });\n\n // Set the User-Agent that Sentry CLI will use when interacting with Sentry\n process.env['SENTRY_PIPELINE'] = `${bundlerPluginMetaContext.buildTool}-plugin/${LIB_VERSION}`;\n\n // Propagate debug flag to Sentry CLI via environment variable\n // Only set if not already defined to respect user's explicit configuration\n if (options.debug && !process.env['SENTRY_LOG_LEVEL']) {\n process.env['SENTRY_LOG_LEVEL'] = 'debug';\n }\n\n // Not a bulletproof check but should be good enough to at least sometimes determine\n // if the plugin is called in dev/watch mode or for a prod build. The important part\n // here is to avoid a false positive. False negatives are okay.\n const isDevMode = process.env['NODE_ENV'] === 'development';\n\n /**\n * Handles errors caught and emitted in various areas of the plugin.\n *\n * Also sets the sentry session status according to the error handling.\n *\n * If users specify their custom `errorHandler` we'll leave the decision to throw\n * or continue up to them. By default, @param throwByDefault controls if the plugin\n * should throw an error (which causes a build fail in most bundlers) or continue.\n */\n function handleRecoverableError(unknownError: unknown, throwByDefault: boolean): void {\n sentrySession.status = 'abnormal';\n try {\n if (options.errorHandler) {\n try {\n if (unknownError instanceof Error) {\n options.errorHandler(unknownError);\n } else {\n options.errorHandler(new Error('An unknown error occurred'));\n }\n } catch (e) {\n sentrySession.status = 'crashed';\n throw e;\n }\n } else {\n // setting the session to \"crashed\" b/c from a plugin perspective this run failed.\n // However, we're intentionally not rethrowing the error to avoid breaking the user build.\n sentrySession.status = 'crashed';\n if (throwByDefault) {\n throw unknownError;\n }\n logger.error(\"An error occurred. Couldn't finish all operations:\", unknownError);\n }\n } finally {\n endSession();\n }\n }\n\n if (!validateOptions(options, logger)) {\n // Throwing by default to avoid a misconfigured plugin going unnoticed.\n handleRecoverableError(new Error('Options were not set correctly. See output above for more details.'), true);\n }\n\n // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)\n // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.\n // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).\n // Since the plugins among themselves are not aware of when they run and finish, we need a system to\n // track their dependencies on the generated files, so that we can initiate the file deletion only after\n // nothing depends on the files anymore.\n const dependenciesOnBuildArtifacts = new Set<symbol>();\n const buildArtifactsDependencySubscribers: (() => void)[] = [];\n\n function notifyBuildArtifactDependencySubscribers(): void {\n buildArtifactsDependencySubscribers.forEach(subscriber => {\n subscriber();\n });\n }\n\n function createDependencyOnBuildArtifacts(): () => void {\n const dependencyIdentifier = Symbol();\n dependenciesOnBuildArtifacts.add(dependencyIdentifier);\n\n return function freeDependencyOnBuildArtifacts() {\n dependenciesOnBuildArtifacts.delete(dependencyIdentifier);\n notifyBuildArtifactDependencySubscribers();\n };\n }\n\n const sourceMapUploadPossible = getSourceMapUploadBlocker(options, isDevMode) === undefined;\n const loggedSourceMapMessages = new Set<string>();\n const shouldUpload = createUploadFilter(options);\n\n function logDecision(decision: SourceMapDecision): void {\n if (decision.log && !loggedSourceMapMessages.has(decision.log.message)) {\n loggedSourceMapMessages.add(decision.log.message);\n logger[decision.log.level](decision.log.message);\n }\n }\n\n /**\n * Returns a Promise that resolves when all the currently active dependencies are freed again.\n *\n * It is very important that this function is called as late as possible before wanting to await the Promise to give\n * the dependency producers as much time as possible to register themselves.\n */\n function waitUntilBuildArtifactDependenciesAreFreed(): Promise<void> {\n return new Promise<void>(resolve => {\n buildArtifactsDependencySubscribers.push(() => {\n if (dependenciesOnBuildArtifacts.size === 0) {\n resolve();\n }\n });\n\n if (dependenciesOnBuildArtifacts.size === 0) {\n resolve();\n }\n });\n }\n\n const bundleSizeOptimizationReplacementValues: SentrySDKBuildFlags = {};\n if (options.bundleSizeOptimizations) {\n const { bundleSizeOptimizations } = options;\n\n if (bundleSizeOptimizations.excludeDebugStatements) {\n bundleSizeOptimizationReplacementValues['__SENTRY_DEBUG__'] = false;\n }\n if (bundleSizeOptimizations.excludeTracing) {\n bundleSizeOptimizationReplacementValues['__SENTRY_TRACING__'] = false;\n }\n if (bundleSizeOptimizations.excludeChannelInjection) {\n bundleSizeOptimizationReplacementValues['__SENTRY_CHANNEL_INJECTION__'] = false;\n }\n if (bundleSizeOptimizations.excludeReplayCanvas) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_CANVAS__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayIframe) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_IFRAME__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayShadowDom) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_SHADOW_DOM__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayWorker) {\n bundleSizeOptimizationReplacementValues['__SENTRY_EXCLUDE_REPLAY_WORKER__'] = true;\n }\n }\n\n let bundleMetadata: Record<string, unknown> = {};\n if (options.moduleMetadata || options.applicationKey) {\n if (options.applicationKey) {\n // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.\n // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple\n // injections, the first injection will always \"win\" because it comes last in the code. We would generally be\n // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing\n // the app keys in different object keys.\n // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.\n bundleMetadata[`_sentryBundlerPluginAppKey:${options.applicationKey}`] = true;\n }\n\n if (typeof options.moduleMetadata === 'function') {\n const args = {\n org: options.org,\n project: getProjects(options.project)?.[0],\n projects: getProjects(options.project),\n release: options.release.name,\n };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bundleMetadata = { ...bundleMetadata, ...options.moduleMetadata(args) };\n } else {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bundleMetadata = { ...bundleMetadata, ...options.moduleMetadata };\n }\n }\n\n return {\n /**\n * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)\n */\n logger,\n\n /**\n * Options after normalization. Includes things like the inferred release name.\n */\n normalizedOptions: options,\n\n /**\n * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes\n * into account the options passed to the build plugin manager.\n */\n bundleSizeOptimizationReplacementValues,\n\n /**\n * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.\n */\n // See `generateModuleMetadataInjectorCode` for how this should be used exactly\n bundleMetadata,\n\n /**\n * Contains utility functions for emitting telemetry via the build plugin manager.\n */\n telemetry: {\n /**\n * Emits a `Sentry Bundler Plugin execution` signal.\n */\n async emitBundlerPluginExecutionSignal() {\n if (await shouldSendTelemetry) {\n logger.info(\n 'Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.',\n );\n startSpan({ name: 'Sentry Bundler Plugin execution', scope: sentryScope }, () => {\n //\n });\n await safeFlushTelemetry(sentryClient);\n }\n },\n },\n\n /**\n * Will potentially create a release based on the build plugin manager options.\n *\n * Also\n * - finalizes the release\n * - sets commits\n * - uploads legacy sourcemaps\n * - adds deploy information\n */\n async createRelease() {\n if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not create release. Please set the `release.name` option to identify your release.',\n );\n return;\n } else if (isDevMode) {\n logger.debug('Running in development mode. Will not create release.');\n return;\n } else if (!options.authToken) {\n logger.warn(\n `No auth token provided. Will not create release. Please set the \\`authToken\\` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/${getTurborepoEnvPassthroughWarning('SENTRY_AUTH_TOKEN')}`,\n );\n return;\n } else if (!options.org && !options.authToken.startsWith('sntrys_')) {\n logger.warn(\n `No organization slug provided. Will not create release. Please set the \\`org\\` option to your Sentry organization slug.${getTurborepoEnvPassthroughWarning('SENTRY_ORG')}`,\n );\n return;\n } else if (!options.project || (Array.isArray(options.project) && options.project.length === 0)) {\n logger.warn(\n `No project provided. Will not create release. Please set the \\`project\\` option to your Sentry project slug.${getTurborepoEnvPassthroughWarning('SENTRY_PROJECT')}`,\n );\n return;\n }\n\n // It is possible that this writeBundle hook is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)\n // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.\n const freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnBuildArtifacts();\n\n // Guaranteed to be set by the guard clause above.\n const releaseName = options.release.name;\n\n try {\n const cliInstance = new SentryCliAdapter(options);\n\n if (options.release.create) {\n const releaseOutput = await cliInstance.createRelease(releaseName);\n logger.debug('Release created:', releaseOutput);\n }\n\n if (options.release.uploadLegacySourcemaps) {\n const uploadTargets = arrayify(options.release.uploadLegacySourcemaps)\n .map(includeItem => (typeof includeItem === 'string' ? { paths: [includeItem] } : includeItem))\n .flatMap(includeEntry =>\n includeEntry.paths.map(directory => ({\n directory,\n dist: options.release.dist,\n ext: includeEntry.ext\n ? includeEntry.ext.map(extension => `.${extension.replace(/^\\./, '')}`)\n : ['.js', '.map', '.jsbundle', '.bundle'],\n // The old CLI only skipped `node_modules` when neither ignore source was configured.\n ignore: includeEntry.ignore\n ? arrayify(includeEntry.ignore)\n : includeEntry.ignoreFile\n ? undefined\n : ['node_modules'],\n ignoreFile: includeEntry.ignoreFile,\n urlPrefix: includeEntry.urlPrefix,\n })),\n );\n\n warnAboutDirectoriesWithoutSourcemaps(logger, await cliInstance.uploadSourcemaps(releaseName, uploadTargets));\n }\n\n if (options.release.setCommits !== false) {\n try {\n await cliInstance.setCommits(\n releaseName,\n // set commits always exists due to the normalize function\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.release.setCommits!,\n );\n } catch (e) {\n // shouldNotThrowOnFailure being present means that the plugin defaulted to `{ auto: true }` for the setCommitsOptions, meaning that wee should not throw when CLI throws because there is no repo\n if (\n options.release.setCommits &&\n 'shouldNotThrowOnFailure' in options.release.setCommits &&\n options.release.setCommits.shouldNotThrowOnFailure\n ) {\n logger.debug(\n 'An error occurred setting commits on release (this message can be ignored unless you want commits set on the release):',\n e,\n );\n } else {\n throw e;\n }\n }\n }\n\n if (options.release.finalize) {\n await cliInstance.finalizeRelease(releaseName);\n }\n\n if (options.release.deploy && !_deployedReleases.has(releaseName)) {\n await cliInstance.newDeploy(releaseName, options.release.deploy);\n _deployedReleases.add(releaseName);\n }\n } catch (e) {\n sentryScope.captureException('Error in \"releaseManagementPlugin\" writeBundle hook');\n await safeFlushTelemetry(sentryClient);\n handleRecoverableError(e, false);\n } finally {\n freeWriteBundleInvocationDependencyOnSourcemapFiles();\n }\n },\n\n /*\n Injects debug IDs into the build artifacts.\n\n This is a separate function from `uploadSourcemaps` because that needs to run before the sourcemaps are uploaded.\n Usually the respective bundler-plugin will take care of this before the sourcemaps are uploaded.\n Only use this if you need to manually inject debug IDs into the build artifacts.\n */\n async injectDebugIds(buildArtifactPaths: string[]) {\n if (!getSourceMapFeatures(options).injectDebugIds) {\n logger.debug('Debug ID injection was disabled. Will not inject debug IDs.');\n return;\n }\n\n // oxlint-disable-next-line typescript/no-deprecated\n await startSpan({ name: 'inject-debug-ids', scope: sentryScope, forceTransaction: true }, async () => {\n try {\n const cliInstance = new SentryCliAdapter(options);\n await cliInstance.injectDebugIds(buildArtifactPaths, options.sourcemaps?.ignore);\n } catch (e) {\n sentryScope.captureException('Error in \"debugIdInjectionPlugin\" writeBundle hook');\n handleRecoverableError(e, false);\n } finally {\n await safeFlushTelemetry(sentryClient);\n }\n });\n },\n\n /**\n * Uploads sourcemaps using the \"Debug ID\" method.\n *\n * By default, this prepares bundles in a temporary folder before uploading. You can opt into an\n * in-place, direct upload path by setting `prepareArtifacts` to `false`. If `prepareArtifacts` is set to\n * `false`, no preparation (e.g. adding `//# debugId=...` and writing adjusted source maps) is performed and no temp folder is used.\n *\n * @param buildArtifactPaths - The paths of the build artifacts to upload\n * @param opts - Optional flags to control temp folder usage and preparation\n */\n async uploadSourcemaps(\n buildArtifactPaths: string[],\n opts?: { prepareArtifacts?: boolean; staging?: UploadStaging },\n ): Promise<UploadResult> {\n const staging = opts?.staging;\n\n if (!canUploadSourceMaps(options, logger, isDevMode)) {\n await staging?.discard();\n return { uploaded: false, uploadedSourceMapPaths: [] };\n }\n\n const assets = options.sourcemaps?.assets;\n let uploaded = false;\n const preparedSourceMapPaths: string[] = [];\n\n await startSpan(\n // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.\n // oxlint-disable-next-line typescript/no-deprecated\n { name: 'debug-id-sourcemap-upload', scope: sentryScope, forceTransaction: true },\n async () => {\n // If we're not using a temp folder, we must not prepare artifacts in-place (to avoid mutating user files)\n const shouldPrepare = opts?.prepareArtifacts ?? true;\n\n let folderToCleanUp: string | undefined = staging?.dir;\n\n // It is possible that this writeBundle hook (which calls this function) is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)\n // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.\n const freeUploadDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n\n try {\n if (!shouldPrepare) {\n // Direct CLI upload from existing artifact paths (no globbing, no preparation)\n let pathsToUpload: string[];\n\n if (assets) {\n pathsToUpload = Array.isArray(assets) ? assets : [assets];\n logger.debug(\n `Direct upload mode: passing user-provided assets directly to CLI: ${pathsToUpload.join(', ')}`,\n );\n } else {\n // Use original paths e.g. like ['.next/server'] directly –> preferred way when no globbing is done\n pathsToUpload = buildArtifactPaths;\n }\n\n // Staged artifacts are already prepared, so the CLI can take the folder as it is.\n if (staging && staging.count > 0) {\n pathsToUpload = [...pathsToUpload, staging.dir];\n }\n\n if (pathsToUpload.length === 0) {\n logger.warn(\n \"Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.\",\n );\n return;\n }\n\n const emptyDirectories = await startSpan({ name: 'upload', scope: sentryScope }, async () => {\n const cliInstance = new SentryCliAdapter(options);\n return cliInstance.uploadSourcemaps(\n options.release.name ?? 'undefined',\n pathsToUpload.map(directory => ({\n directory,\n dist: options.release.dist,\n ignore: options.sourcemaps?.ignore,\n })),\n );\n });\n\n warnAboutDirectoriesWithoutSourcemaps(logger, emptyDirectories);\n if (emptyDirectories.length < pathsToUpload.length) {\n uploaded = true;\n logger.info('Successfully uploaded source maps to Sentry');\n }\n } else {\n // Prepare artifacts in temp folder before uploading\n let globAssets: string | string[];\n if (assets) {\n globAssets = assets;\n } else {\n logger.debug(\n 'No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.',\n );\n globAssets = buildArtifactPaths.map(asset => escapeGlob(asset.split(path.sep).join('/')));\n }\n\n const globResult = await startSpan({ name: 'glob', scope: sentryScope }, async () =>\n globFiles(globAssets, { ignore: options.sourcemaps?.ignore }),\n );\n\n const debugIdChunkFilePaths = globResult.filter(debugIdChunkFilePath => {\n const filePath = stripQueryAndHashFromPath(debugIdChunkFilePath);\n return !!filePath.match(/\\.(js|mjs|cjs)$/) && !staging?.stagedChunkPaths.has(path.resolve(filePath));\n });\n\n // The order of the files output by glob() is not deterministic\n // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent\n debugIdChunkFilePaths.sort();\n\n const stagedCount = staging?.count ?? 0;\n\n if (debugIdChunkFilePaths.length === 0 && stagedCount === 0) {\n logger.warn(\n \"Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.\",\n );\n } else {\n const tmpUploadFolder =\n staging?.dir ??\n (await startSpan({ name: 'mkdtemp', scope: sentryScope }, () => createTempUploadFolder()));\n folderToCleanUp = tmpUploadFolder;\n\n // Prepare into temp folder, then upload\n await startSpan({ name: 'prepare-bundles', scope: sentryScope }, async prepBundlesSpan => {\n // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so\n // instead we do it with a maximum of 16 concurrent workers\n const preparationTasks = debugIdChunkFilePaths.map((chunkFilePath, chunkIndex) => async () => {\n const prepared = await prepareBundleForDebugIdUpload(\n chunkFilePath,\n tmpUploadFolder,\n stagedCount + chunkIndex,\n logger,\n options.sourcemaps?.rewriteSources ?? defaultRewriteSourcesHook,\n options.sourcemaps?.resolveSourceMap,\n );\n if (prepared?.sourceMapPath !== undefined) {\n preparedSourceMapPaths.push(prepared.sourceMapPath);\n }\n });\n const workers: Promise<void>[] = [];\n const worker = async (): Promise<void> => {\n while (preparationTasks.length > 0) {\n const task = preparationTasks.shift();\n if (task) {\n await task();\n }\n }\n };\n for (let workerIndex = 0; workerIndex < 16; workerIndex++) {\n workers.push(worker());\n }\n\n await Promise.all(workers);\n\n const files = await fs.promises.readdir(tmpUploadFolder);\n const stats = files.map(file => fs.promises.stat(path.join(tmpUploadFolder, file)));\n const uploadSize = (await Promise.all(stats)).reduce(\n (accumulator, { size }) => accumulator + size,\n 0,\n );\n\n setMeasurement('files', files.length, 'none', prepBundlesSpan);\n setMeasurement('upload_size', uploadSize, 'byte', prepBundlesSpan);\n\n // Preparation produced no artifacts, meaning none of the\n // matched bundles had an associated source map. This almost\n // always means source map generation is turned off in the\n // bundler, so warn instead of silently reporting success.\n if (files.length === 0) {\n logger.warn(\n `No source maps found for any of the ${debugIdChunkFilePaths.length + stagedCount} matched build ` +\n 'artifacts, so no source maps were uploaded to Sentry. This usually means source map ' +\n 'generation is not enabled in your bundler. Enable it so Sentry can un-minify your stack traces.',\n );\n return;\n }\n\n await startSpan({ name: 'upload', scope: sentryScope }, async () => {\n const cliInstance = new SentryCliAdapter(options);\n await cliInstance.uploadSourcemaps(options.release.name ?? 'undefined', [\n {\n directory: tmpUploadFolder,\n dist: options.release.dist,\n },\n ]);\n });\n\n // this must be in the method so that the \"no sourcemaps\"\n // early return doesn't also log success.\n uploaded = true;\n logger.info('Successfully uploaded source maps to Sentry');\n });\n }\n }\n } catch (e) {\n if (staging && folderToCleanUp) {\n await staging.keep('Source map upload failed.');\n folderToCleanUp = undefined;\n }\n sentryScope.captureException('Error in \"debugIdUploadPlugin\" writeBundle hook');\n handleRecoverableError(e, false);\n } finally {\n if (folderToCleanUp && !process.env?.['SENTRY_TEST_OVERRIDE_TEMP_DIR']) {\n logger.debug('Cleaning up temporary files...');\n try {\n await startSpan({ name: 'cleanup', scope: sentryScope }, async () => {\n if (folderToCleanUp) {\n await fs.promises.rm(folderToCleanUp, { recursive: true, force: true });\n logger.debug(`Temporary folder deleted: ${folderToCleanUp}`);\n }\n });\n } catch (e) {\n // A failed cleanup must not skip the teardown steps below (freeing upload\n // dependencies, flushing telemetry), so swallow and log instead of rethrowing.\n logger.debug('Failed to clean up temporary folder:', e);\n }\n }\n logger.debug('Freeing upload dependencies...');\n freeUploadDependencyOnBuildArtifacts();\n logger.debug('Flushing telemetry data...');\n await safeFlushTelemetry(sentryClient);\n logger.debug('Telemetry flushed. Plugin upload process complete.');\n }\n },\n );\n\n return { uploaded, uploadedSourceMapPaths: uploaded ? preparedSourceMapPaths.sort() : [] };\n },\n\n async createUploadStaging(): Promise<UploadStaging> {\n const dir = await createTempUploadFolder();\n const rewriteSourcesHook = options.sourcemaps?.rewriteSources ?? defaultRewriteSourcesHook;\n let count = 0;\n let discarded = false;\n const stagedChunkPaths = new Set<string>();\n\n const discard = async (): Promise<void> => {\n if (discarded) {\n return;\n }\n discarded = true;\n\n if (process.env['SENTRY_TEST_OVERRIDE_TEMP_DIR']) {\n return;\n }\n\n try {\n await fs.promises.rm(dir, { recursive: true, force: true });\n } catch (e) {\n logger.debug(`Failed to remove staging folder ${dir}:`, e);\n }\n };\n\n return {\n dir,\n get count() {\n return count;\n },\n stagedChunkPaths,\n async stage(input) {\n const chunkPath = path.resolve(input.chunkPath);\n const chunkName = path.basename(chunkPath);\n if (!shouldUpload(chunkPath)) {\n logger.debug(\n `Not staging ${chunkName} for upload: excluded by \\`sourcemaps.assets\\` or \\`sourcemaps.ignore\\`.`,\n );\n return 'excluded';\n }\n\n const result = prepareArtifactForUpload({\n code: input.code,\n mapSource: input.mapSource,\n mapDir: input.mapDir,\n rewriteSourcesHook,\n });\n\n if (!result.ok) {\n logger.debug(`Not staging ${chunkName} for upload: ${result.reason}`);\n return 'skipped';\n }\n\n const index = count++;\n\n try {\n await writePreparedArtifact(dir, `${result.artifact.debugId}-${index}`, result.artifact);\n stagedChunkPaths.add(chunkPath);\n return 'staged';\n } catch (e) {\n sentryScope.captureException('Error staging build artifact for upload');\n // Throwing by default: the bundler drops the source map from its\n // output once staged, so a lost copy would leave no map at all.\n handleRecoverableError(e, true);\n return 'failed';\n }\n },\n discard,\n async keep(reason) {\n if (count === 0) {\n await discard();\n return;\n }\n if (discarded) {\n return;\n }\n discarded = true;\n\n // The bundler dropped the staged source maps from its output, so\n // this folder is the only copy left.\n logger.error(\n `${reason} The source maps were kept in ${dir}. Upload them with \\`sentry sourcemap upload ${dir}\\`.`,\n );\n },\n };\n },\n\n sourceMaps: {\n uploadPossible: sourceMapUploadPossible,\n decide(kind, { log = true, environment } = {}) {\n // Watch builds in development keep their source maps.\n const decision = isDevMode\n ? { enableHidden: false, deleteAfterUpload: false }\n : decideSourceMapHandling(kind, options, sourceMapUploadPossible, environment);\n if (log) {\n logDecision(decision);\n }\n return decision;\n },\n logDecision,\n shouldUpload,\n async deleteFromOutput(sourceMapPaths) {\n try {\n await Promise.all(\n sourceMapPaths.map(async sourceMapPath => {\n try {\n await fs.promises.rm(sourceMapPath, { force: true });\n } catch (e) {\n logger.error(`Could not delete source map ${sourceMapPath} from the build output.`);\n throw e;\n }\n }),\n );\n } catch (e) {\n sentryScope.captureException('Error deleting source maps after upload');\n await safeFlushTelemetry(sentryClient);\n // Throwing by default: a map left in the output could leak to production.\n handleRecoverableError(e, true);\n }\n },\n },\n\n /**\n * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.\n */\n async deleteArtifacts() {\n try {\n const filesToDelete = await options.sourcemaps?.filesToDeleteAfterUpload;\n if (filesToDelete !== undefined) {\n const filePathsToDelete = await globFiles(filesToDelete);\n\n logger.debug('Waiting for dependencies on generated files to be freed before deleting...');\n\n await waitUntilBuildArtifactDependenciesAreFreed();\n\n filePathsToDelete.forEach(filePathToDelete => {\n logger.debug(`Deleting asset after upload: ${filePathToDelete}`);\n });\n\n await Promise.all(\n filePathsToDelete.map(filePathToDelete =>\n fs.promises.rm(filePathToDelete, { force: true }).catch(e => {\n // This is allowed to fail - we just don't do anything\n logger.debug(`An error occurred while attempting to delete asset: ${filePathToDelete}`, e);\n }),\n ),\n );\n }\n } catch (e) {\n sentryScope.captureException('Error in \"sentry-file-deletion-plugin\" buildEnd hook');\n await safeFlushTelemetry(sentryClient);\n // We throw by default if we get here b/c not being able to delete\n // source maps could leak them to production\n handleRecoverableError(e, true);\n }\n },\n createDependencyOnBuildArtifacts,\n };\n}\n\nasync function createTempUploadFolder(): Promise<string> {\n return (\n process.env['SENTRY_TEST_OVERRIDE_TEMP_DIR'] ||\n (await fs.promises.mkdtemp(path.join(os.tmpdir(), 'sentry-bundler-plugin-upload-')))\n );\n}\n\ntype SourceMapUploadBlocker = 'disabled' | 'no-assets' | 'dev-mode' | 'no-auth-token' | 'no-org' | 'no-project';\n\nfunction getSourceMapUploadBlocker(options: NormalizedOptions, isDevMode: boolean): SourceMapUploadBlocker | undefined {\n if (!getSourceMapFeatures(options).upload) {\n return 'disabled';\n }\n if (Array.isArray(options.sourcemaps?.assets) && options.sourcemaps.assets.length === 0) {\n return 'no-assets';\n }\n if (isDevMode) {\n return 'dev-mode';\n }\n if (!options.authToken) {\n return 'no-auth-token';\n }\n if (!options.org && !options.authToken.startsWith('sntrys_')) {\n return 'no-org';\n }\n if (!getProjects(options.project)?.[0]) {\n return 'no-project';\n }\n return undefined;\n}\n\nfunction canUploadSourceMaps(options: NormalizedOptions, logger: Logger, isDevMode: boolean): boolean {\n switch (getSourceMapUploadBlocker(options, isDevMode)) {\n case 'disabled':\n logger.debug('Source map upload was disabled. Will not upload sourcemaps using debug ID process.');\n return false;\n case 'no-assets':\n logger.debug('Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.');\n return false;\n case 'dev-mode':\n logger.debug('Running in development mode. Will not upload sourcemaps.');\n return false;\n case 'no-auth-token':\n logger.warn(\n `No auth token provided. Will not upload source maps. Please set the \\`authToken\\` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/${getTurborepoEnvPassthroughWarning('SENTRY_AUTH_TOKEN')}`,\n );\n return false;\n case 'no-org':\n logger.warn(\n `No org provided. Will not upload source maps. Please set the \\`org\\` option to your Sentry organization slug.${getTurborepoEnvPassthroughWarning('SENTRY_ORG')}`,\n );\n return false;\n case 'no-project':\n logger.warn(\n `No project provided. Will not upload source maps. Please set the \\`project\\` option to your Sentry project slug.${getTurborepoEnvPassthroughWarning('SENTRY_PROJECT')}`,\n );\n return false;\n default:\n return true;\n }\n}\n\nfunction warnAboutDirectoriesWithoutSourcemaps(logger: Logger, directories: string[]): void {\n if (directories.length === 0) {\n return;\n }\n const list = directories.map(directory => ` - ${directory}`).join('\\n');\n logger.warn(\n `No source maps found in the following directories, so nothing was uploaded from them:\\n${list}\\n` +\n 'This usually means source map generation is not enabled for these build outputs. ' +\n 'Enable it so Sentry can un-minify stack traces from these files.',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA+BA,MAAM,oCAAoB,IAAI,IAAY;;;;;;AAyJ1C,SAAgB,+BACd,aACA,0BAc0B;CAC1B,MAAM,SAAS,aAAa;EAC1B,QAAQ,yBAAyB;EACjC,QAAQ,YAAY,UAAU;EAC9B,OAAO,YAAY,SAAS;CAC9B,CAAC;CAED,IAAI;EACF,MAAM,aAAa,GAAG,aAAa,KAAK,KAAK,QAAQ,IAAI,GAAG,0BAA0B,GAAG,OAAO;EAEhG,MAAM,eAAe,OAAO,MAAM,UAAU;EAI5C,OAAO,OAAO,QAAQ,KAAK,YAAY;EAEvC,OAAO,KAAK,yEAAuE;CACrF,SAAS,GAAY;EAEnB,IAAI,OAAO,MAAM,YAAY,KAAK,UAAU,KAAK,EAAE,SAAS,UAC1D,MAAM;CAEV;CAEA,MAAM,UAAU,qBAAqB,WAAW;CAEhD,IAAI,QAAQ,SAKV,OAAO;EACL,mBAAmB;EACnB;EACA,yCAAyC,CAAC;EAC1C,WAAW,EACT,kCAAkC,YAAY,CAE9C,EACF;EACA,gBAAgB,CAAC;EACjB,eAAe,YAAY,CAE3B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M,QAAQ,QAAQ,YAAY,MAAM,KAAK,QAAQ,WAAW,OAAO,WAAW,GACpF,OAAO;CAET,IAAI,WACF,OAAO;CAET,IAAI,CAAC,QAAQ,WACX,OAAO;CAET,IAAI,CAAC,QAAQ,OAAO,CAAC,QAAQ,UAAU,WAAW,SAAS,GACzD,OAAO;CAET,IAAI,CAAC,YAAY,QAAQ,OAAO,CAAC,GAAG,IAClC,OAAO;AAGX;AAEA,SAAS,oBAAoB,SAA4B,QAAgB,WAA6B;CACpG,QAAQ,0BAA0B,SAAS,SAAS,GAApD;EACE,KAAK;GACH,OAAO,MAAM,oFAAoF;GACjG,OAAO;EACT,KAAK;GACH,OAAO,MAAM,sFAAsF;GACnG,OAAO;EACT,KAAK;GACH,OAAO,MAAM,0DAA0D;GACvE,OAAO;EACT,KAAK;GACH,OAAO,KACL,mMAAmM,kCAAkC,mBAAmB,GAC1P;GACA,OAAO;EACT,KAAK;GACH,OAAO,KACL,gHAAgH,kCAAkC,YAAY,GAChK;GACA,OAAO;EACT,KAAK;GACH,OAAO,KACL,mHAAmH,kCAAkC,gBAAgB,GACvK;GACA,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,SAAS,sCAAsC,QAAgB,aAA6B;CAC1F,IAAI,YAAY,WAAW,GACzB;CAEF,MAAM,OAAO,YAAY,KAAI,cAAa,OAAO,WAAW,CAAC,CAAC,KAAK,IAAI;CACvE,OAAO,KACL,0FAA0F,KAAK,oJAGjG;AACF"}
1
+ {"version":3,"file":"build-plugin-manager.js","names":["escapeGlob"],"sources":["../../../src/core/build-plugin-manager.ts"],"sourcesContent":["/* oxlint-disable max-lines */\nimport { closeSession, DEFAULT_ENVIRONMENT, makeSession, setMeasurement, startSpan } from '@sentry/core';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { escape as escapeGlob } from 'glob';\nimport { SentryCliAdapter } from './cli';\nimport type { NormalizedOptions } from './options-mapping';\nimport { normalizeUserOptions, validateOptions } from './options-mapping';\nimport type { Logger } from './logger';\nimport { createLogger } from './logger';\nimport { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry';\nimport type { InternalOptions, SentrySDKBuildFlags } from './types';\nimport { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils';\nimport {\n defaultRewriteSourcesHook,\n prepareArtifactForUpload,\n prepareBundleForDebugIdUpload,\n writePreparedArtifact,\n} from './debug-id-upload';\nimport { globFiles } from './glob';\nimport type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';\nimport { decideSourceMapHandling, getSourceMapFeatures } from './sourcemap-settings';\nimport type { UploadFilter } from './upload-filter';\nimport { createUploadFilter } from './upload-filter';\nimport { getMissingUploadCredential, readSentryBuildPluginEnvFile } from './upload-credentials';\nimport { LIB_VERSION } from './version';\n\n// Module-level guard to prevent duplicate deploy records when multiple bundler plugin\n// instances run in the same process (e.g. Next.js creates separate webpack compilers\n// for client, server, and edge). Keyed by release name.\nconst _deployedReleases = new Set<string>();\n\n/** @internal Exported for testing only. */\nexport function _resetDeployedReleasesForTesting(): void {\n _deployedReleases.clear();\n}\n\n/**\n * A temporary folder that build artifacts are written into straight from the bundler's output,\n * before the bundler writes them to disk. The upload reads from this folder, so the bundler can\n * drop the source map assets from its own output.\n */\nexport type UploadResult = { uploaded: boolean; uploadedSourceMapPaths: string[] };\n\nexport type UploadStaging = {\n readonly dir: string;\n /** Number of artifacts written so far. */\n readonly count: number;\n /**\n * Absolute paths of the chunks staged so far (`mapDir` joined with the file name). The upload\n * does not prepare these again from disk, where a stale map of an earlier build could sit\n * next to them.\n */\n readonly stagedChunkPaths: ReadonlySet<string>;\n /**\n * Stamps the debug ID into the chunk and its source map and writes both into the folder.\n *\n * `mapSource` is `undefined` when the chunk has no separate source map. `mapDir` is the directory\n * the map would be written to and is passed to the `rewriteSources` hook. `chunkPath` is where\n * the chunk is written; `sourcemaps.assets` and `sourcemaps.ignore` are matched against it.\n */\n stage(input: {\n code: string;\n mapSource: string | undefined;\n mapDir: string;\n chunkPath: string;\n }): Promise<'staged' | 'skipped' | 'excluded' | 'failed'>;\n /** Removes the folder. Call this when no upload will consume it. */\n discard(): Promise<void>;\n /**\n * Keeps the folder and logs how to upload it by hand. Call this when the bundler already\n * dropped the staged source maps from its output but the upload did not run. Removes the\n * folder instead when nothing was staged.\n */\n keep(reason: string): Promise<void>;\n};\n\nexport type SentryBuildPluginManager = {\n /**\n * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)\n */\n logger: Logger;\n\n /**\n * Options after normalization. Includes things like the inferred release name.\n */\n normalizedOptions: NormalizedOptions;\n /**\n * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes\n * into account the options passed to the build plugin manager.\n */\n bundleSizeOptimizationReplacementValues: SentrySDKBuildFlags;\n /**\n * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.\n */\n // See `generateModuleMetadataInjectorCode` for how this should be used exactly\n bundleMetadata: Record<string, unknown>;\n\n /**\n * Contains utility functions for emitting telemetry via the build plugin manager.\n */\n telemetry: {\n /**\n * Emits a `Sentry Bundler Plugin execution` signal.\n */\n emitBundlerPluginExecutionSignal(): Promise<void>;\n };\n\n /**\n * Will potentially create a release based on the build plugin manager options.\n *\n * Also\n * - finalizes the release\n * - sets commits\n * - uploads legacy sourcemaps\n * - adds deploy information\n */\n createRelease(): Promise<void>;\n\n /**\n * Injects debug IDs into the build artifacts.\n *\n * This is a separate function from `uploadSourcemaps` because that needs to run before the sourcemaps are uploaded.\n * Usually the respective bundler-plugin will take care of this before the sourcemaps are uploaded.\n * Only use this if you need to manually inject debug IDs into the build artifacts.\n */\n injectDebugIds(buildArtifactPaths: string[]): Promise<void>;\n\n /**\n * Uploads sourcemaps using the \"Debug ID\" method. This function takes a list of build artifact paths that will be uploaded\n *\n * `uploadedSourceMapPaths` lists the source maps read from disk that were uploaded. It is empty\n * when nothing was uploaded, in direct mode (`prepareArtifacts: false`) and for staged artifacts.\n */\n uploadSourcemaps(\n buildArtifactPaths: string[],\n opts?: { prepareArtifacts?: boolean; staging?: UploadStaging },\n ): Promise<UploadResult>;\n\n /**\n * Creates a staging folder that `uploadSourcemaps` uploads together with the build artifacts\n * found on disk, in both the prepared and the direct (`prepareArtifacts: false`) mode.\n */\n createUploadStaging(): Promise<UploadStaging>;\n\n sourceMaps: {\n /**\n * Whether a source map upload can run with the current options and environment.\n */\n uploadPossible: boolean;\n /**\n * Decides how the plugin treats the user's source map setting (see `decideSourceMapHandling`).\n * Logs the decision's message once per message, unless `log` is `false`.\n */\n decide(kind: SourceMapKind, options?: { log?: boolean; environment?: string }): SourceMapDecision;\n /** Logs the decision's message, once per message. */\n logDecision(decision: SourceMapDecision): void;\n /**\n * Whether a file of the build output is uploaded, for files that are not on disk yet. Mirrors\n * the glob of the upload from disk: it must match `sourcemaps.assets` (all files when unset)\n * and none of `sourcemaps.ignore`.\n */\n shouldUpload: UploadFilter;\n /**\n * Deletes source maps from the build output after their upload. A map that cannot be deleted\n * goes to `errorHandler`, or fails the build when none is set.\n */\n deleteFromOutput(sourceMapPaths: string[]): Promise<void>;\n };\n\n /**\n * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.\n */\n deleteArtifacts(): Promise<void>;\n\n createDependencyOnBuildArtifacts: () => () => void;\n};\n\n/**\n * Creates a build plugin manager that exposes primitives for everything that a Sentry JavaScript SDK or build tooling may do during a build.\n *\n * The build plugin manager's behavior strongly depends on the options that are passed in.\n */\nexport function createSentryBuildPluginManager(\n userOptions: InternalOptions,\n bundlerPluginMetaContext: {\n /**\n * E.g. `webpack` or `nextjs` or `turbopack`\n */\n buildTool: string;\n /**\n * E.g. `5` for webpack v5 or `4` for Rollup v4\n */\n buildToolMajorVersion?: string;\n /**\n * E.g. `[sentry-webpack-plugin]` or `[@sentry/nextjs]`\n */\n loggerPrefix: string;\n },\n): SentryBuildPluginManager {\n const logger = createLogger({\n prefix: bundlerPluginMetaContext.loggerPrefix,\n silent: userOptions.silent ?? false,\n debug: userOptions.debug ?? false,\n });\n\n const dotenvResult = readSentryBuildPluginEnvFile();\n if (dotenvResult) {\n // Vite has a bug/behaviour where spreading into process.env will cause it to crash\n // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251\n Object.assign(process.env, dotenvResult);\n\n logger.info('Using environment variables configured in \".env.sentry-build-plugin\".');\n }\n\n const options = normalizeUserOptions(userOptions);\n\n if (options.disable) {\n // Early-return a noop build plugin manager instance so that we\n // don't continue validating options, setting up Sentry, etc.\n // Otherwise we might create side-effects or log messages that\n // users don't expect from a disabled plugin.\n return {\n normalizedOptions: options,\n logger,\n bundleSizeOptimizationReplacementValues: {},\n telemetry: {\n emitBundlerPluginExecutionSignal: async () => {\n /* noop */\n },\n },\n bundleMetadata: {},\n createRelease: async () => {\n /* noop */\n },\n uploadSourcemaps: async () => ({ uploaded: false, uploadedSourceMapPaths: [] }),\n createUploadStaging: async () => ({\n dir: '',\n count: 0,\n stagedChunkPaths: new Set<string>(),\n stage: async () => 'skipped' as const,\n discard: async () => {\n /* noop */\n },\n keep: async () => {\n /* noop */\n },\n }),\n sourceMaps: {\n uploadPossible: false,\n decide: () => ({ enableHidden: false, deleteAfterUpload: false }),\n logDecision: () => undefined,\n shouldUpload: () => false,\n deleteFromOutput: async () => {\n /* noop */\n },\n },\n deleteArtifacts: async () => {\n /* noop */\n },\n createDependencyOnBuildArtifacts: () => () => {\n /* noop */\n },\n injectDebugIds: async () => {\n /* noop */\n },\n };\n }\n\n const shouldSendTelemetry = allowedToSendTelemetry(options);\n const { sentryScope, sentryClient } = createSentryInstance(\n options,\n shouldSendTelemetry,\n bundlerPluginMetaContext.buildTool,\n bundlerPluginMetaContext.buildToolMajorVersion,\n );\n\n const { release, environment = DEFAULT_ENVIRONMENT } = sentryClient.getOptions();\n\n const sentrySession = makeSession({ release, environment });\n sentryScope.setSession(sentrySession);\n // Send the start of the session\n sentryClient.captureSession(sentrySession);\n\n let sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out\n\n function endSession(): void {\n if (sessionHasEnded) {\n return;\n }\n\n closeSession(sentrySession);\n sentryClient.captureSession(sentrySession);\n sessionHasEnded = true;\n }\n\n // We also need to manually end sessions on errors because beforeExit is not called on crashes\n process.on('beforeExit', () => {\n endSession();\n });\n\n // Set the User-Agent that Sentry CLI will use when interacting with Sentry\n process.env['SENTRY_PIPELINE'] = `${bundlerPluginMetaContext.buildTool}-plugin/${LIB_VERSION}`;\n\n // Propagate debug flag to Sentry CLI via environment variable\n // Only set if not already defined to respect user's explicit configuration\n if (options.debug && !process.env['SENTRY_LOG_LEVEL']) {\n process.env['SENTRY_LOG_LEVEL'] = 'debug';\n }\n\n // Not a bulletproof check but should be good enough to at least sometimes determine\n // if the plugin is called in dev/watch mode or for a prod build. The important part\n // here is to avoid a false positive. False negatives are okay.\n const isDevMode = process.env['NODE_ENV'] === 'development';\n\n /**\n * Handles errors caught and emitted in various areas of the plugin.\n *\n * Also sets the sentry session status according to the error handling.\n *\n * If users specify their custom `errorHandler` we'll leave the decision to throw\n * or continue up to them. By default, @param throwByDefault controls if the plugin\n * should throw an error (which causes a build fail in most bundlers) or continue.\n */\n function handleRecoverableError(unknownError: unknown, throwByDefault: boolean): void {\n sentrySession.status = 'abnormal';\n try {\n if (options.errorHandler) {\n try {\n if (unknownError instanceof Error) {\n options.errorHandler(unknownError);\n } else {\n options.errorHandler(new Error('An unknown error occurred'));\n }\n } catch (e) {\n sentrySession.status = 'crashed';\n throw e;\n }\n } else {\n // setting the session to \"crashed\" b/c from a plugin perspective this run failed.\n // However, we're intentionally not rethrowing the error to avoid breaking the user build.\n sentrySession.status = 'crashed';\n if (throwByDefault) {\n throw unknownError;\n }\n logger.error(\"An error occurred. Couldn't finish all operations:\", unknownError);\n }\n } finally {\n endSession();\n }\n }\n\n if (!validateOptions(options, logger)) {\n // Throwing by default to avoid a misconfigured plugin going unnoticed.\n handleRecoverableError(new Error('Options were not set correctly. See output above for more details.'), true);\n }\n\n // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)\n // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.\n // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).\n // Since the plugins among themselves are not aware of when they run and finish, we need a system to\n // track their dependencies on the generated files, so that we can initiate the file deletion only after\n // nothing depends on the files anymore.\n const dependenciesOnBuildArtifacts = new Set<symbol>();\n const buildArtifactsDependencySubscribers: (() => void)[] = [];\n\n function notifyBuildArtifactDependencySubscribers(): void {\n buildArtifactsDependencySubscribers.forEach(subscriber => {\n subscriber();\n });\n }\n\n function createDependencyOnBuildArtifacts(): () => void {\n const dependencyIdentifier = Symbol();\n dependenciesOnBuildArtifacts.add(dependencyIdentifier);\n\n return function freeDependencyOnBuildArtifacts() {\n dependenciesOnBuildArtifacts.delete(dependencyIdentifier);\n notifyBuildArtifactDependencySubscribers();\n };\n }\n\n const sourceMapUploadPossible = getSourceMapUploadBlocker(options, isDevMode) === undefined;\n const loggedSourceMapMessages = new Set<string>();\n const shouldUpload = createUploadFilter(options);\n\n function logDecision(decision: SourceMapDecision): void {\n if (decision.log && !loggedSourceMapMessages.has(decision.log.message)) {\n loggedSourceMapMessages.add(decision.log.message);\n logger[decision.log.level](decision.log.message);\n }\n }\n\n /**\n * Returns a Promise that resolves when all the currently active dependencies are freed again.\n *\n * It is very important that this function is called as late as possible before wanting to await the Promise to give\n * the dependency producers as much time as possible to register themselves.\n */\n function waitUntilBuildArtifactDependenciesAreFreed(): Promise<void> {\n return new Promise<void>(resolve => {\n buildArtifactsDependencySubscribers.push(() => {\n if (dependenciesOnBuildArtifacts.size === 0) {\n resolve();\n }\n });\n\n if (dependenciesOnBuildArtifacts.size === 0) {\n resolve();\n }\n });\n }\n\n const bundleSizeOptimizationReplacementValues: SentrySDKBuildFlags = {};\n if (options.bundleSizeOptimizations) {\n const { bundleSizeOptimizations } = options;\n\n if (bundleSizeOptimizations.excludeDebugStatements) {\n bundleSizeOptimizationReplacementValues['__SENTRY_DEBUG__'] = false;\n }\n if (bundleSizeOptimizations.excludeTracing) {\n bundleSizeOptimizationReplacementValues['__SENTRY_TRACING__'] = false;\n }\n if (bundleSizeOptimizations.excludeChannelInjection) {\n bundleSizeOptimizationReplacementValues['__SENTRY_CHANNEL_INJECTION__'] = false;\n }\n if (bundleSizeOptimizations.excludeReplayCanvas) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_CANVAS__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayIframe) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_IFRAME__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayShadowDom) {\n bundleSizeOptimizationReplacementValues['__RRWEB_EXCLUDE_SHADOW_DOM__'] = true;\n }\n if (bundleSizeOptimizations.excludeReplayWorker) {\n bundleSizeOptimizationReplacementValues['__SENTRY_EXCLUDE_REPLAY_WORKER__'] = true;\n }\n }\n\n let bundleMetadata: Record<string, unknown> = {};\n if (options.moduleMetadata || options.applicationKey) {\n if (options.applicationKey) {\n // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.\n // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple\n // injections, the first injection will always \"win\" because it comes last in the code. We would generally be\n // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing\n // the app keys in different object keys.\n // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.\n bundleMetadata[`_sentryBundlerPluginAppKey:${options.applicationKey}`] = true;\n }\n\n if (typeof options.moduleMetadata === 'function') {\n const args = {\n org: options.org,\n project: getProjects(options.project)?.[0],\n projects: getProjects(options.project),\n release: options.release.name,\n };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bundleMetadata = { ...bundleMetadata, ...options.moduleMetadata(args) };\n } else {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n bundleMetadata = { ...bundleMetadata, ...options.moduleMetadata };\n }\n }\n\n return {\n /**\n * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)\n */\n logger,\n\n /**\n * Options after normalization. Includes things like the inferred release name.\n */\n normalizedOptions: options,\n\n /**\n * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes\n * into account the options passed to the build plugin manager.\n */\n bundleSizeOptimizationReplacementValues,\n\n /**\n * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.\n */\n // See `generateModuleMetadataInjectorCode` for how this should be used exactly\n bundleMetadata,\n\n /**\n * Contains utility functions for emitting telemetry via the build plugin manager.\n */\n telemetry: {\n /**\n * Emits a `Sentry Bundler Plugin execution` signal.\n */\n async emitBundlerPluginExecutionSignal() {\n if (await shouldSendTelemetry) {\n logger.info(\n 'Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.',\n );\n startSpan({ name: 'Sentry Bundler Plugin execution', scope: sentryScope }, () => {\n //\n });\n await safeFlushTelemetry(sentryClient);\n }\n },\n },\n\n /**\n * Will potentially create a release based on the build plugin manager options.\n *\n * Also\n * - finalizes the release\n * - sets commits\n * - uploads legacy sourcemaps\n * - adds deploy information\n */\n async createRelease() {\n if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not create release. Please set the `release.name` option to identify your release.',\n );\n return;\n } else if (isDevMode) {\n logger.debug('Running in development mode. Will not create release.');\n return;\n } else if (!options.authToken) {\n logger.warn(\n `No auth token provided. Will not create release. Please set the \\`authToken\\` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/${getTurborepoEnvPassthroughWarning('SENTRY_AUTH_TOKEN')}`,\n );\n return;\n } else if (!options.org && !options.authToken.startsWith('sntrys_')) {\n logger.warn(\n `No organization slug provided. Will not create release. Please set the \\`org\\` option to your Sentry organization slug.${getTurborepoEnvPassthroughWarning('SENTRY_ORG')}`,\n );\n return;\n } else if (!options.project || (Array.isArray(options.project) && options.project.length === 0)) {\n logger.warn(\n `No project provided. Will not create release. Please set the \\`project\\` option to your Sentry project slug.${getTurborepoEnvPassthroughWarning('SENTRY_PROJECT')}`,\n );\n return;\n }\n\n // It is possible that this writeBundle hook is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)\n // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.\n const freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnBuildArtifacts();\n\n // Guaranteed to be set by the guard clause above.\n const releaseName = options.release.name;\n\n try {\n const cliInstance = new SentryCliAdapter(options);\n\n if (options.release.create) {\n const releaseOutput = await cliInstance.createRelease(releaseName);\n logger.debug('Release created:', releaseOutput);\n }\n\n if (options.release.uploadLegacySourcemaps) {\n const uploadTargets = arrayify(options.release.uploadLegacySourcemaps)\n .map(includeItem => (typeof includeItem === 'string' ? { paths: [includeItem] } : includeItem))\n .flatMap(includeEntry =>\n includeEntry.paths.map(directory => ({\n directory,\n dist: options.release.dist,\n ext: includeEntry.ext\n ? includeEntry.ext.map(extension => `.${extension.replace(/^\\./, '')}`)\n : ['.js', '.map', '.jsbundle', '.bundle'],\n // The old CLI only skipped `node_modules` when neither ignore source was configured.\n ignore: includeEntry.ignore\n ? arrayify(includeEntry.ignore)\n : includeEntry.ignoreFile\n ? undefined\n : ['node_modules'],\n ignoreFile: includeEntry.ignoreFile,\n urlPrefix: includeEntry.urlPrefix,\n })),\n );\n\n warnAboutDirectoriesWithoutSourcemaps(logger, await cliInstance.uploadSourcemaps(releaseName, uploadTargets));\n }\n\n if (options.release.setCommits !== false) {\n try {\n await cliInstance.setCommits(\n releaseName,\n // set commits always exists due to the normalize function\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n options.release.setCommits!,\n );\n } catch (e) {\n // shouldNotThrowOnFailure being present means that the plugin defaulted to `{ auto: true }` for the setCommitsOptions, meaning that wee should not throw when CLI throws because there is no repo\n if (\n options.release.setCommits &&\n 'shouldNotThrowOnFailure' in options.release.setCommits &&\n options.release.setCommits.shouldNotThrowOnFailure\n ) {\n logger.debug(\n 'An error occurred setting commits on release (this message can be ignored unless you want commits set on the release):',\n e,\n );\n } else {\n throw e;\n }\n }\n }\n\n if (options.release.finalize) {\n await cliInstance.finalizeRelease(releaseName);\n }\n\n if (options.release.deploy && !_deployedReleases.has(releaseName)) {\n await cliInstance.newDeploy(releaseName, options.release.deploy);\n _deployedReleases.add(releaseName);\n }\n } catch (e) {\n sentryScope.captureException('Error in \"releaseManagementPlugin\" writeBundle hook');\n await safeFlushTelemetry(sentryClient);\n handleRecoverableError(e, false);\n } finally {\n freeWriteBundleInvocationDependencyOnSourcemapFiles();\n }\n },\n\n /*\n Injects debug IDs into the build artifacts.\n\n This is a separate function from `uploadSourcemaps` because that needs to run before the sourcemaps are uploaded.\n Usually the respective bundler-plugin will take care of this before the sourcemaps are uploaded.\n Only use this if you need to manually inject debug IDs into the build artifacts.\n */\n async injectDebugIds(buildArtifactPaths: string[]) {\n if (!getSourceMapFeatures(options).injectDebugIds) {\n logger.debug('Debug ID injection was disabled. Will not inject debug IDs.');\n return;\n }\n\n // oxlint-disable-next-line typescript/no-deprecated\n await startSpan({ name: 'inject-debug-ids', scope: sentryScope, forceTransaction: true }, async () => {\n try {\n const cliInstance = new SentryCliAdapter(options);\n await cliInstance.injectDebugIds(buildArtifactPaths, options.sourcemaps?.ignore);\n } catch (e) {\n sentryScope.captureException('Error in \"debugIdInjectionPlugin\" writeBundle hook');\n handleRecoverableError(e, false);\n } finally {\n await safeFlushTelemetry(sentryClient);\n }\n });\n },\n\n /**\n * Uploads sourcemaps using the \"Debug ID\" method.\n *\n * By default, this prepares bundles in a temporary folder before uploading. You can opt into an\n * in-place, direct upload path by setting `prepareArtifacts` to `false`. If `prepareArtifacts` is set to\n * `false`, no preparation (e.g. adding `//# debugId=...` and writing adjusted source maps) is performed and no temp folder is used.\n *\n * @param buildArtifactPaths - The paths of the build artifacts to upload\n * @param opts - Optional flags to control temp folder usage and preparation\n */\n async uploadSourcemaps(\n buildArtifactPaths: string[],\n opts?: { prepareArtifacts?: boolean; staging?: UploadStaging },\n ): Promise<UploadResult> {\n const staging = opts?.staging;\n\n if (!canUploadSourceMaps(options, logger, isDevMode)) {\n await staging?.discard();\n return { uploaded: false, uploadedSourceMapPaths: [] };\n }\n\n const assets = options.sourcemaps?.assets;\n let uploaded = false;\n const preparedSourceMapPaths: string[] = [];\n\n await startSpan(\n // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.\n // oxlint-disable-next-line typescript/no-deprecated\n { name: 'debug-id-sourcemap-upload', scope: sentryScope, forceTransaction: true },\n async () => {\n // If we're not using a temp folder, we must not prepare artifacts in-place (to avoid mutating user files)\n const shouldPrepare = opts?.prepareArtifacts ?? true;\n\n let folderToCleanUp: string | undefined = staging?.dir;\n\n // It is possible that this writeBundle hook (which calls this function) is called multiple times in one build (for example when reusing the plugin, or when using build tooling like `@vitejs/plugin-legacy`)\n // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.\n const freeUploadDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n\n try {\n if (!shouldPrepare) {\n // Direct CLI upload from existing artifact paths (no globbing, no preparation)\n let pathsToUpload: string[];\n\n if (assets) {\n pathsToUpload = Array.isArray(assets) ? assets : [assets];\n logger.debug(\n `Direct upload mode: passing user-provided assets directly to CLI: ${pathsToUpload.join(', ')}`,\n );\n } else {\n // Use original paths e.g. like ['.next/server'] directly –> preferred way when no globbing is done\n pathsToUpload = buildArtifactPaths;\n }\n\n // Staged artifacts are already prepared, so the CLI can take the folder as it is.\n if (staging && staging.count > 0) {\n pathsToUpload = [...pathsToUpload, staging.dir];\n }\n\n if (pathsToUpload.length === 0) {\n logger.warn(\n \"Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.\",\n );\n return;\n }\n\n const emptyDirectories = await startSpan({ name: 'upload', scope: sentryScope }, async () => {\n const cliInstance = new SentryCliAdapter(options);\n return cliInstance.uploadSourcemaps(\n options.release.name ?? 'undefined',\n pathsToUpload.map(directory => ({\n directory,\n dist: options.release.dist,\n ignore: options.sourcemaps?.ignore,\n })),\n );\n });\n\n warnAboutDirectoriesWithoutSourcemaps(logger, emptyDirectories);\n if (emptyDirectories.length < pathsToUpload.length) {\n uploaded = true;\n logger.info('Successfully uploaded source maps to Sentry');\n }\n } else {\n // Prepare artifacts in temp folder before uploading\n let globAssets: string | string[];\n if (assets) {\n globAssets = assets;\n } else {\n logger.debug(\n 'No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.',\n );\n globAssets = buildArtifactPaths.map(asset => escapeGlob(asset.split(path.sep).join('/')));\n }\n\n const globResult = await startSpan({ name: 'glob', scope: sentryScope }, async () =>\n globFiles(globAssets, { ignore: options.sourcemaps?.ignore }),\n );\n\n const debugIdChunkFilePaths = globResult.filter(debugIdChunkFilePath => {\n const filePath = stripQueryAndHashFromPath(debugIdChunkFilePath);\n return !!filePath.match(/\\.(js|mjs|cjs)$/) && !staging?.stagedChunkPaths.has(path.resolve(filePath));\n });\n\n // The order of the files output by glob() is not deterministic\n // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent\n debugIdChunkFilePaths.sort();\n\n const stagedCount = staging?.count ?? 0;\n\n if (debugIdChunkFilePaths.length === 0 && stagedCount === 0) {\n logger.warn(\n \"Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.\",\n );\n } else {\n const tmpUploadFolder =\n staging?.dir ??\n (await startSpan({ name: 'mkdtemp', scope: sentryScope }, () => createTempUploadFolder()));\n folderToCleanUp = tmpUploadFolder;\n\n // Prepare into temp folder, then upload\n await startSpan({ name: 'prepare-bundles', scope: sentryScope }, async prepBundlesSpan => {\n // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so\n // instead we do it with a maximum of 16 concurrent workers\n const preparationTasks = debugIdChunkFilePaths.map((chunkFilePath, chunkIndex) => async () => {\n const prepared = await prepareBundleForDebugIdUpload(\n chunkFilePath,\n tmpUploadFolder,\n stagedCount + chunkIndex,\n logger,\n options.sourcemaps?.rewriteSources ?? defaultRewriteSourcesHook,\n options.sourcemaps?.resolveSourceMap,\n );\n if (prepared?.sourceMapPath !== undefined) {\n preparedSourceMapPaths.push(prepared.sourceMapPath);\n }\n });\n const workers: Promise<void>[] = [];\n const worker = async (): Promise<void> => {\n while (preparationTasks.length > 0) {\n const task = preparationTasks.shift();\n if (task) {\n await task();\n }\n }\n };\n for (let workerIndex = 0; workerIndex < 16; workerIndex++) {\n workers.push(worker());\n }\n\n await Promise.all(workers);\n\n const files = await fs.promises.readdir(tmpUploadFolder);\n const stats = files.map(file => fs.promises.stat(path.join(tmpUploadFolder, file)));\n const uploadSize = (await Promise.all(stats)).reduce(\n (accumulator, { size }) => accumulator + size,\n 0,\n );\n\n setMeasurement('files', files.length, 'none', prepBundlesSpan);\n setMeasurement('upload_size', uploadSize, 'byte', prepBundlesSpan);\n\n // Preparation produced no artifacts, meaning none of the\n // matched bundles had an associated source map. This almost\n // always means source map generation is turned off in the\n // bundler, so warn instead of silently reporting success.\n if (files.length === 0) {\n logger.warn(\n `No source maps found for any of the ${debugIdChunkFilePaths.length + stagedCount} matched build ` +\n 'artifacts, so no source maps were uploaded to Sentry. This usually means source map ' +\n 'generation is not enabled in your bundler. Enable it so Sentry can un-minify your stack traces.',\n );\n return;\n }\n\n await startSpan({ name: 'upload', scope: sentryScope }, async () => {\n const cliInstance = new SentryCliAdapter(options);\n await cliInstance.uploadSourcemaps(options.release.name ?? 'undefined', [\n {\n directory: tmpUploadFolder,\n dist: options.release.dist,\n },\n ]);\n });\n\n // this must be in the method so that the \"no sourcemaps\"\n // early return doesn't also log success.\n uploaded = true;\n logger.info('Successfully uploaded source maps to Sentry');\n });\n }\n }\n } catch (e) {\n if (staging && folderToCleanUp) {\n await staging.keep('Source map upload failed.');\n folderToCleanUp = undefined;\n }\n sentryScope.captureException('Error in \"debugIdUploadPlugin\" writeBundle hook');\n handleRecoverableError(e, false);\n } finally {\n if (folderToCleanUp && !process.env?.['SENTRY_TEST_OVERRIDE_TEMP_DIR']) {\n logger.debug('Cleaning up temporary files...');\n try {\n await startSpan({ name: 'cleanup', scope: sentryScope }, async () => {\n if (folderToCleanUp) {\n await fs.promises.rm(folderToCleanUp, { recursive: true, force: true });\n logger.debug(`Temporary folder deleted: ${folderToCleanUp}`);\n }\n });\n } catch (e) {\n // A failed cleanup must not skip the teardown steps below (freeing upload\n // dependencies, flushing telemetry), so swallow and log instead of rethrowing.\n logger.debug('Failed to clean up temporary folder:', e);\n }\n }\n logger.debug('Freeing upload dependencies...');\n freeUploadDependencyOnBuildArtifacts();\n logger.debug('Flushing telemetry data...');\n await safeFlushTelemetry(sentryClient);\n logger.debug('Telemetry flushed. Plugin upload process complete.');\n }\n },\n );\n\n return { uploaded, uploadedSourceMapPaths: uploaded ? preparedSourceMapPaths.sort() : [] };\n },\n\n async createUploadStaging(): Promise<UploadStaging> {\n const dir = await createTempUploadFolder();\n const rewriteSourcesHook = options.sourcemaps?.rewriteSources ?? defaultRewriteSourcesHook;\n let count = 0;\n let discarded = false;\n const stagedChunkPaths = new Set<string>();\n\n const discard = async (): Promise<void> => {\n if (discarded) {\n return;\n }\n discarded = true;\n\n if (process.env['SENTRY_TEST_OVERRIDE_TEMP_DIR']) {\n return;\n }\n\n try {\n await fs.promises.rm(dir, { recursive: true, force: true });\n } catch (e) {\n logger.debug(`Failed to remove staging folder ${dir}:`, e);\n }\n };\n\n return {\n dir,\n get count() {\n return count;\n },\n stagedChunkPaths,\n async stage(input) {\n const chunkPath = path.resolve(input.chunkPath);\n const chunkName = path.basename(chunkPath);\n if (!shouldUpload(chunkPath)) {\n logger.debug(\n `Not staging ${chunkName} for upload: excluded by \\`sourcemaps.assets\\` or \\`sourcemaps.ignore\\`.`,\n );\n return 'excluded';\n }\n\n const result = prepareArtifactForUpload({\n code: input.code,\n mapSource: input.mapSource,\n mapDir: input.mapDir,\n rewriteSourcesHook,\n });\n\n if (!result.ok) {\n logger.debug(`Not staging ${chunkName} for upload: ${result.reason}`);\n return 'skipped';\n }\n\n const index = count++;\n\n try {\n await writePreparedArtifact(dir, `${result.artifact.debugId}-${index}`, result.artifact);\n stagedChunkPaths.add(chunkPath);\n return 'staged';\n } catch (e) {\n sentryScope.captureException('Error staging build artifact for upload');\n // Throwing by default: the bundler drops the source map from its\n // output once staged, so a lost copy would leave no map at all.\n handleRecoverableError(e, true);\n return 'failed';\n }\n },\n discard,\n async keep(reason) {\n if (count === 0) {\n await discard();\n return;\n }\n if (discarded) {\n return;\n }\n discarded = true;\n\n // The bundler dropped the staged source maps from its output, so\n // this folder is the only copy left.\n logger.error(\n `${reason} The source maps were kept in ${dir}. Upload them with \\`sentry sourcemap upload ${dir}\\`.`,\n );\n },\n };\n },\n\n sourceMaps: {\n uploadPossible: sourceMapUploadPossible,\n decide(kind, { log = true, environment } = {}) {\n // Watch builds in development keep their source maps.\n const decision = isDevMode\n ? { enableHidden: false, deleteAfterUpload: false }\n : decideSourceMapHandling(kind, options, sourceMapUploadPossible, environment);\n if (log) {\n logDecision(decision);\n }\n return decision;\n },\n logDecision,\n shouldUpload,\n async deleteFromOutput(sourceMapPaths) {\n try {\n await Promise.all(\n sourceMapPaths.map(async sourceMapPath => {\n try {\n await fs.promises.rm(sourceMapPath, { force: true });\n } catch (e) {\n logger.error(`Could not delete source map ${sourceMapPath} from the build output.`);\n throw e;\n }\n }),\n );\n } catch (e) {\n sentryScope.captureException('Error deleting source maps after upload');\n await safeFlushTelemetry(sentryClient);\n // Throwing by default: a map left in the output could leak to production.\n handleRecoverableError(e, true);\n }\n },\n },\n\n /**\n * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.\n */\n async deleteArtifacts() {\n try {\n const filesToDelete = await options.sourcemaps?.filesToDeleteAfterUpload;\n if (filesToDelete !== undefined) {\n const filePathsToDelete = await globFiles(filesToDelete);\n\n logger.debug('Waiting for dependencies on generated files to be freed before deleting...');\n\n await waitUntilBuildArtifactDependenciesAreFreed();\n\n filePathsToDelete.forEach(filePathToDelete => {\n logger.debug(`Deleting asset after upload: ${filePathToDelete}`);\n });\n\n await Promise.all(\n filePathsToDelete.map(filePathToDelete =>\n fs.promises.rm(filePathToDelete, { force: true }).catch(e => {\n // This is allowed to fail - we just don't do anything\n logger.debug(`An error occurred while attempting to delete asset: ${filePathToDelete}`, e);\n }),\n ),\n );\n }\n } catch (e) {\n sentryScope.captureException('Error in \"sentry-file-deletion-plugin\" buildEnd hook');\n await safeFlushTelemetry(sentryClient);\n // We throw by default if we get here b/c not being able to delete\n // source maps could leak them to production\n handleRecoverableError(e, true);\n }\n },\n createDependencyOnBuildArtifacts,\n };\n}\n\nasync function createTempUploadFolder(): Promise<string> {\n return (\n process.env['SENTRY_TEST_OVERRIDE_TEMP_DIR'] ||\n (await fs.promises.mkdtemp(path.join(os.tmpdir(), 'sentry-bundler-plugin-upload-')))\n );\n}\n\ntype SourceMapUploadBlocker = 'disabled' | 'no-assets' | 'dev-mode' | 'no-auth-token' | 'no-org' | 'no-project';\n\nfunction getSourceMapUploadBlocker(options: NormalizedOptions, isDevMode: boolean): SourceMapUploadBlocker | undefined {\n if (!getSourceMapFeatures(options).upload) {\n return 'disabled';\n }\n if (Array.isArray(options.sourcemaps?.assets) && options.sourcemaps.assets.length === 0) {\n return 'no-assets';\n }\n if (isDevMode) {\n return 'dev-mode';\n }\n return getMissingUploadCredential(options);\n}\n\nfunction canUploadSourceMaps(options: NormalizedOptions, logger: Logger, isDevMode: boolean): boolean {\n switch (getSourceMapUploadBlocker(options, isDevMode)) {\n case 'disabled':\n logger.debug('Source map upload was disabled. Will not upload sourcemaps using debug ID process.');\n return false;\n case 'no-assets':\n logger.debug('Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.');\n return false;\n case 'dev-mode':\n logger.debug('Running in development mode. Will not upload sourcemaps.');\n return false;\n case 'no-auth-token':\n logger.warn(\n `No auth token provided. Will not upload source maps. Please set the \\`authToken\\` option. You can find information on how to generate a Sentry auth token here: https://docs.sentry.io/api/auth/${getTurborepoEnvPassthroughWarning('SENTRY_AUTH_TOKEN')}`,\n );\n return false;\n case 'no-org':\n logger.warn(\n `No org provided. Will not upload source maps. Please set the \\`org\\` option to your Sentry organization slug.${getTurborepoEnvPassthroughWarning('SENTRY_ORG')}`,\n );\n return false;\n case 'no-project':\n logger.warn(\n `No project provided. Will not upload source maps. Please set the \\`project\\` option to your Sentry project slug.${getTurborepoEnvPassthroughWarning('SENTRY_PROJECT')}`,\n );\n return false;\n default:\n return true;\n }\n}\n\nfunction warnAboutDirectoriesWithoutSourcemaps(logger: Logger, directories: string[]): void {\n if (directories.length === 0) {\n return;\n }\n const list = directories.map(directory => ` - ${directory}`).join('\\n');\n logger.warn(\n `No source maps found in the following directories, so nothing was uploaded from them:\\n${list}\\n` +\n 'This usually means source map generation is not enabled for these build outputs. ' +\n 'Enable it so Sentry can un-minify stack traces from these files.',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA+BA,MAAM,oCAAoB,IAAI,IAAY;;;;;;AAyJ1C,SAAgB,+BACd,aACA,0BAc0B;CAC1B,MAAM,SAAS,aAAa;EAC1B,QAAQ,yBAAyB;EACjC,QAAQ,YAAY,UAAU;EAC9B,OAAO,YAAY,SAAS;CAC9B,CAAC;CAED,MAAM,eAAe,6BAA6B;CAClD,IAAI,cAAc;EAGhB,OAAO,OAAO,QAAQ,KAAK,YAAY;EAEvC,OAAO,KAAK,yEAAuE;CACrF;CAEA,MAAM,UAAU,qBAAqB,WAAW;CAEhD,IAAI,QAAQ,SAKV,OAAO;EACL,mBAAmB;EACnB;EACA,yCAAyC,CAAC;EAC1C,WAAW,EACT,kCAAkC,YAAY,CAE9C,EACF;EACA,gBAAgB,CAAC;EACjB,eAAe,YAAY,CAE3B;EACA,kBAAkB,aAAa;GAAE,UAAU;GAAO,wBAAwB,CAAC;EAAE;EAC7E,qBAAqB,aAAa;GAChC,KAAK;GACL,OAAO;GACP,kCAAkB,IAAI,IAAY;GAClC,OAAO,YAAY;GACnB,SAAS,YAAY,CAErB;GACA,MAAM,YAAY,CAElB;EACF;EACA,YAAY;GACV,gBAAgB;GACh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AO,MAAM,oFAAoF;GACjG,OAAO;EACT,KAAK;GACH,OAAO,MAAM,sFAAsF;GACnG,OAAO;EACT,KAAK;GACH,OAAO,MAAM,0DAA0D;GACvE,OAAO;EACT,KAAK;GACH,OAAO,KACL,mMAAmM,kCAAkC,mBAAmB,GAC1P;GACA,OAAO;EACT,KAAK;GACH,OAAO,KACL,gHAAgH,kCAAkC,YAAY,GAChK;GACA,OAAO;EACT,KAAK;GACH,OAAO,KACL,mHAAmH,kCAAkC,gBAAgB,GACvK;GACA,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,SAAS,sCAAsC,QAAgB,aAA6B;CAC1F,IAAI,YAAY,WAAW,GACzB;CAEF,MAAM,OAAO,YAAY,KAAI,cAAa,OAAO,WAAW,CAAC,CAAC,KAAK,IAAI;CACvE,OAAO,KACL,0FAA0F,KAAK,oJAGjG;AACF"}
@@ -242,7 +242,7 @@ async function determineSourceMapPathFromBundle(bundlePath, bundleSource, logger
242
242
  const PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//;
243
243
  function defaultRewriteSourcesHook(source) {
244
244
  if (source.match(PROTOCOL_REGEX)) return source.replace(PROTOCOL_REGEX, "");
245
- else return path.relative(process.cwd(), path.normalize(source));
245
+ else return path.relative(process.cwd(), path.normalize(source)).split(path.sep).join("/");
246
246
  }
247
247
  export { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction, defaultRewriteSourcesHook, determineSourceMapPathFromBundle, prepareArtifactForUpload, prepareBundleForDebugIdUpload, stampDebugId, writePreparedArtifact };
248
248
 
@@ -1 +1 @@
1
- {"version":3,"file":"debug-id-upload.js","names":[],"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 type { SentryBuildPluginManager, UploadStaging } 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[], opts?: { staging?: UploadStaging }) => {\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 return sentryBuildPluginManager.uploadSourcemaps(cleanedPaths, opts);\n };\n}\n\n/** The source map of a prepared bundle. `sourceMapPath` is `undefined` for an inline map. */\nexport type PreparedBundle = { sourceMapPath: string | undefined };\n\n/** Resolves to `undefined` when the bundle was skipped. */\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<PreparedBundle | undefined> {\n let bundleContent: string;\n try {\n bundleContent = await fs.promises.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 if (determineDebugIdFromBundleSource(bundleContent) === 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 sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\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(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n }\n\n const result = prepareArtifactForUpload({\n code: bundleContent,\n mapSource: sourceMapSource,\n mapDir: path.dirname(sourceMapPath ?? bundleFilePath),\n rewriteSourcesHook,\n });\n\n if (!result.ok) {\n if (result.reason === 'invalid-source-map') {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n } else {\n // A chunk with a debug ID but no resolvable source map\n // (e.g. framework-generated stub chunks that never emit one) can't be\n // symbolicated, so uploading its minified source alone accomplishes\n // nothing and only makes the uploader warn about a missing source map ref.\n logger.debug(`Not uploading bundle without a source map: ${bundleFilePath}`);\n }\n return;\n }\n\n await writePreparedArtifact(uploadFolder, `${result.artifact.debugId}-${chunkIndex}`, result.artifact);\n return { sourceMapPath };\n}\n\nexport type PreparedUploadArtifact = {\n debugId: string;\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\nexport type PrepareArtifactResult =\n | { ok: true; artifact: PreparedUploadArtifact }\n | { ok: false; reason: 'no-debug-id' | 'no-source-map' | 'invalid-source-map' };\n\n/**\n * Prepares a bundle and its source map for the debug ID upload: stamps the debug ID into both\n * and runs the `rewriteSources` hook over the map's `sources`.\n *\n * Pass `mapSource: undefined` when the bundle has no separate source map. A bundle with an\n * inlined map is still prepared; a bundle without any map is skipped because it cannot be\n * symbolicated.\n */\nexport function prepareArtifactForUpload(input: {\n code: string;\n mapSource: string | undefined;\n /** Directory the source map lives in, passed to the `rewriteSources` hook. */\n mapDir: string;\n rewriteSourcesHook: RewriteSourcesHook;\n}): PrepareArtifactResult {\n const debugId = determineDebugIdFromBundleSource(input.code);\n if (debugId === undefined) {\n return { ok: false, reason: 'no-debug-id' };\n }\n\n const bundleSource = addDebugIdToBundleSource(input.code, debugId);\n\n if (input.mapSource === undefined) {\n if (!bundleHasInlineSourceMap(input.code)) {\n return { ok: false, reason: 'no-source-map' };\n }\n return { ok: true, artifact: { debugId, bundleSource, sourceMapSource: undefined } };\n }\n\n const map = parseSourceMap(input.mapSource);\n if (!map) {\n return { ok: false, reason: 'invalid-source-map' };\n }\n\n setDebugIdOnSourceMap(map, debugId);\n\n if (Array.isArray(map['sources'])) {\n map['sources'] = map['sources'].map((source: string) =>\n input.rewriteSourcesHook(source, map, { mapDir: input.mapDir }),\n );\n }\n\n return { ok: true, artifact: { debugId, bundleSource, sourceMapSource: JSON.stringify(map) } };\n}\n\n/**\n * Writes a prepared artifact as `<uniqueUploadName>.js` (and `.js.map`) into the upload folder.\n */\nexport async function writePreparedArtifact(\n uploadFolder: string,\n uniqueUploadName: string,\n artifact: PreparedUploadArtifact,\n): Promise<void> {\n const writes = [\n fs.promises.writeFile(path.join(uploadFolder, `${uniqueUploadName}.js`), artifact.bundleSource, 'utf-8'),\n ];\n\n if (artifact.sourceMapSource !== undefined) {\n writes.push(\n fs.promises.writeFile(path.join(uploadFolder, `${uniqueUploadName}.js.map`), artifact.sourceMapSource, 'utf-8'),\n );\n }\n\n await Promise.all(writes);\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 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 builds without an upload (`sourcemaps.upload: false`): 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 * Whether the bundle carries its source map inlined as `sourceMappingURL=data:`\n * URI, rather than referencing a separate `.map` file. Such bundles must still\n * be uploaded even when no `.map` file is found, because the source file itself\n * contains the map.\n */\nfunction bundleHasInlineSourceMap(bundleSource: string): boolean {\n return /^\\s*\\/\\/# sourceMappingURL=data:/m.test(bundleSource);\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\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"],"mappings":";;;;;;AAaA,SAAgB,4BAA4B,EAAE,4BAAwD;CACpG,OAAO,OAAO,oBAA8B,SAAuC;EAGjF,MAAM,eAAe,mBAAmB,IAAI,yBAAyB;EACrE,OAAO,yBAAyB,iBAAiB,cAAc,IAAI;CACrE;AACF;;AAMA,eAAsB,8BACpB,gBACA,cACA,YACA,QACA,oBACA,sBACqC;CACrC,IAAI;CACJ,IAAI;EACF,gBAAgB,MAAM,GAAG,SAAS,SAAS,gBAAgB,MAAM;CACnE,SAAS,GAAG;EACV,OAAO,MAAM,+DAA+D,kBAAkB,CAAC;EAC/F;CACF;CAEA,IAAI,iCAAiC,aAAa,MAAM,KAAA,GAAW;EACjE,OAAO,MACL,0KAA0K,gBAC5K;EACA;CACF;CAEA,MAAM,gBAAgB,MAAM,iCAC1B,gBACA,eACA,QACA,oBACF;CAEA,IAAI;CACJ,IAAI,eACF,IAAI;EACF,kBAAkB,MAAM,GAAG,SAAS,SAAS,eAAe,MAAM;CACpE,SAAS,GAAG;EACV,OAAO,MAAM,kDAAkD,iBAAiB,CAAC;EACjF;CACF;CAGF,MAAM,SAAS,yBAAyB;EACtC,MAAM;EACN,WAAW;EACX,QAAQ,KAAK,QAAQ,iBAAiB,cAAc;EACpD;CACF,CAAC;CAED,IAAI,CAAC,OAAO,IAAI;EACd,IAAI,OAAO,WAAW,sBACpB,OAAO,MAAM,mDAAmD,eAAe;OAM/E,OAAO,MAAM,8CAA8C,gBAAgB;EAE7E;CACF;CAEA,MAAM,sBAAsB,cAAc,GAAG,OAAO,SAAS,QAAQ,GAAG,cAAc,OAAO,QAAQ;CACrG,OAAO,EAAE,cAAc;AACzB;;;;;;;;;AAqBA,SAAgB,yBAAyB,OAMf;CACxB,MAAM,UAAU,iCAAiC,MA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AAG,gBAAgB,CAAC,CAAC;CAE9F;CAGA,gBAAgB,KAAK,GAAG,WAAW,KAAK;CAExC,KAAK,MAAM,kBAAkB,iBAC3B,IAAI;EACF,MAAM,KAAK,UAAU,GAAG,MAAM,CAAC,CAAC,cAAc;EAC9C,OAAO,MAAM,iCAAiC,WAAW,QAAQ,eAAe,GAAG;EACnF,OAAO;CACT,QAAQ,CAER;CAIF,OAAO,MACL,oDAAoD,WAAW,2BACnC,qBAAqB,KAAA,IAAY,cAAc,KAAK,iBAAiB,IAAA,8EAEzE,gBAAgB,KAAI,MAAK,KAAK,EAAE,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,EAC1E;AAEF;AAEA,MAAM,iBAAiB;AACvB,SAAgB,0BAA0B,QAAwB;CAChE,IAAI,OAAO,MAAM,cAAc,GAC7B,OAAO,OAAO,QAAQ,gBAAgB,EAAE;MAExC,OAAO,KAAK,SAAS,QAAQ,IAAI,GAAG,KAAK,UAAU,MAAM,CAAC;AAE9D"}
1
+ {"version":3,"file":"debug-id-upload.js","names":[],"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 type { SentryBuildPluginManager, UploadStaging } 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[], opts?: { staging?: UploadStaging }) => {\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 return sentryBuildPluginManager.uploadSourcemaps(cleanedPaths, opts);\n };\n}\n\n/** The source map of a prepared bundle. `sourceMapPath` is `undefined` for an inline map. */\nexport type PreparedBundle = { sourceMapPath: string | undefined };\n\n/** Resolves to `undefined` when the bundle was skipped. */\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<PreparedBundle | undefined> {\n let bundleContent: string;\n try {\n bundleContent = await fs.promises.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 if (determineDebugIdFromBundleSource(bundleContent) === 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 sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\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(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n }\n\n const result = prepareArtifactForUpload({\n code: bundleContent,\n mapSource: sourceMapSource,\n mapDir: path.dirname(sourceMapPath ?? bundleFilePath),\n rewriteSourcesHook,\n });\n\n if (!result.ok) {\n if (result.reason === 'invalid-source-map') {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n } else {\n // A chunk with a debug ID but no resolvable source map\n // (e.g. framework-generated stub chunks that never emit one) can't be\n // symbolicated, so uploading its minified source alone accomplishes\n // nothing and only makes the uploader warn about a missing source map ref.\n logger.debug(`Not uploading bundle without a source map: ${bundleFilePath}`);\n }\n return;\n }\n\n await writePreparedArtifact(uploadFolder, `${result.artifact.debugId}-${chunkIndex}`, result.artifact);\n return { sourceMapPath };\n}\n\nexport type PreparedUploadArtifact = {\n debugId: string;\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\nexport type PrepareArtifactResult =\n | { ok: true; artifact: PreparedUploadArtifact }\n | { ok: false; reason: 'no-debug-id' | 'no-source-map' | 'invalid-source-map' };\n\n/**\n * Prepares a bundle and its source map for the debug ID upload: stamps the debug ID into both\n * and runs the `rewriteSources` hook over the map's `sources`.\n *\n * Pass `mapSource: undefined` when the bundle has no separate source map. A bundle with an\n * inlined map is still prepared; a bundle without any map is skipped because it cannot be\n * symbolicated.\n */\nexport function prepareArtifactForUpload(input: {\n code: string;\n mapSource: string | undefined;\n /** Directory the source map lives in, passed to the `rewriteSources` hook. */\n mapDir: string;\n rewriteSourcesHook: RewriteSourcesHook;\n}): PrepareArtifactResult {\n const debugId = determineDebugIdFromBundleSource(input.code);\n if (debugId === undefined) {\n return { ok: false, reason: 'no-debug-id' };\n }\n\n const bundleSource = addDebugIdToBundleSource(input.code, debugId);\n\n if (input.mapSource === undefined) {\n if (!bundleHasInlineSourceMap(input.code)) {\n return { ok: false, reason: 'no-source-map' };\n }\n return { ok: true, artifact: { debugId, bundleSource, sourceMapSource: undefined } };\n }\n\n const map = parseSourceMap(input.mapSource);\n if (!map) {\n return { ok: false, reason: 'invalid-source-map' };\n }\n\n setDebugIdOnSourceMap(map, debugId);\n\n if (Array.isArray(map['sources'])) {\n map['sources'] = map['sources'].map((source: string) =>\n input.rewriteSourcesHook(source, map, { mapDir: input.mapDir }),\n );\n }\n\n return { ok: true, artifact: { debugId, bundleSource, sourceMapSource: JSON.stringify(map) } };\n}\n\n/**\n * Writes a prepared artifact as `<uniqueUploadName>.js` (and `.js.map`) into the upload folder.\n */\nexport async function writePreparedArtifact(\n uploadFolder: string,\n uniqueUploadName: string,\n artifact: PreparedUploadArtifact,\n): Promise<void> {\n const writes = [\n fs.promises.writeFile(path.join(uploadFolder, `${uniqueUploadName}.js`), artifact.bundleSource, 'utf-8'),\n ];\n\n if (artifact.sourceMapSource !== undefined) {\n writes.push(\n fs.promises.writeFile(path.join(uploadFolder, `${uniqueUploadName}.js.map`), artifact.sourceMapSource, 'utf-8'),\n );\n }\n\n await Promise.all(writes);\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 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 builds without an upload (`sourcemaps.upload: false`): 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 * Whether the bundle carries its source map inlined as `sourceMappingURL=data:`\n * URI, rather than referencing a separate `.map` file. Such bundles must still\n * be uploaded even when no `.map` file is found, because the source file itself\n * contains the map.\n */\nfunction bundleHasInlineSourceMap(bundleSource: string): boolean {\n return /^\\s*\\/\\/# sourceMappingURL=data:/m.test(bundleSource);\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\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 // Source map `sources` are URLs, so Windows separators must not leak into the uploaded map.\n return path.relative(process.cwd(), path.normalize(source)).split(path.sep).join('/');\n }\n}\n"],"mappings":";;;;;;AAaA,SAAgB,4BAA4B,EAAE,4BAAwD;CACpG,OAAO,OAAO,oBAA8B,SAAuC;EAGjF,MAAM,eAAe,mBAAmB,IAAI,yBAAyB;EACrE,OAAO,yBAAyB,iBAAiB,cAAc,IAAI;CACrE;A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,iBAAiB,IAAA,8EAEzE,gBAAgB,KAAI,MAAK,KAAK,EAAE,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,EAC1E;AAEF;AAEA,MAAM,iBAAiB;AACvB,SAAgB,0BAA0B,QAAwB;CAChE,IAAI,OAAO,MAAM,cAAc,GAC7B,OAAO,OAAO,QAAQ,gBAAgB,EAAE;MAGxC,OAAO,KAAK,SAAS,QAAQ,IAAI,GAAG,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AAExF"}
@@ -5,7 +5,8 @@ import { getCodeInjectionPosition } from "./get-code-injection-position.js";
5
5
  import { createComponentNameAnnotateHooks } from "./component-annotate-hooks.js";
6
6
  import { createSentryBuildPluginManager } from "./build-plugin-manager.js";
7
7
  import { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction, stampDebugId } from "./debug-id-upload.js";
8
- import { decideSourceMapHandling, getDeleteOption, getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps, getSourceMapFeatures } from "./sourcemap-settings.js";
8
+ import { decideSourceMapHandling, getDeleteOption, getSdkDeleteSourceMaps, getSourceMapFeatures } from "./sourcemap-settings.js";
9
+ import { hasSourceMapUploadCredentials } from "./upload-credentials.js";
9
10
  // src/core/index.ts
10
11
  /**
11
12
  * Checks if a file is a JavaScript file based on its extension.
@@ -69,6 +70,6 @@ function isInitialChunk(chunk, chunks) {
69
70
  function getDebugIdSnippet(debugId) {
70
71
  return new CodeInjection(`var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${debugId}",e._sentryDebugIdIdentifier="sentry-dbid-${debugId}");`);
71
72
  }
72
- export { CodeInjection, addDebugIdToEmittedArtifacts, createComponentNameAnnotateHooks, createDebugIdUploadFunction, createSentryBuildPluginManager, decideSourceMapHandling, generateModuleMetadataInjectorCode, generateReleaseInjectorCode, getCodeInjectionPosition, getDebugIdSnippet, getDeleteOption, getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps, getSourceMapFeatures, globFiles, isInitialChunk, isJsFile, replaceBooleanFlagsInCode, resolveReleaseName, shouldSkipCodeInjection, stampDebugId, stringToUUID };
73
+ export { CodeInjection, addDebugIdToEmittedArtifacts, createComponentNameAnnotateHooks, createDebugIdUploadFunction, createSentryBuildPluginManager, decideSourceMapHandling, generateModuleMetadataInjectorCode, generateReleaseInjectorCode, getCodeInjectionPosition, getDebugIdSnippet, getDeleteOption, getSdkDeleteSourceMaps, getSourceMapFeatures, globFiles, hasSourceMapUploadCredentials, isInitialChunk, isJsFile, replaceBooleanFlagsInCode, resolveReleaseName, shouldSkipCodeInjection, stampDebugId, stringToUUID };
73
74
 
74
75
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/index.ts"],"sourcesContent":["import { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\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 interface ChunkGraphNode {\n fileName: string;\n isEntry?: boolean;\n imports?: string[];\n}\n\nconst initialChunksCache = new WeakMap<Record<string, ChunkGraphNode>, Set<string>>();\n\nfunction getInitialChunks(chunks: Record<string, ChunkGraphNode>): Set<string> {\n const cached = initialChunksCache.get(chunks);\n if (cached) {\n return cached;\n }\n\n const initial = new Set<string>();\n const queue = Object.values(chunks).filter(chunk => chunk.isEntry);\n\n for (let chunk = queue.shift(); chunk; chunk = queue.shift()) {\n if (initial.has(chunk.fileName)) {\n continue;\n }\n initial.add(chunk.fileName);\n for (const imported of chunk.imports ?? []) {\n const importedChunk = chunks[imported];\n if (importedChunk) {\n queue.push(importedChunk);\n }\n }\n }\n\n initialChunksCache.set(chunks, initial);\n return initial;\n}\n\n/**\n * Whether a chunk loads at startup: it is an entry chunk, or an entry chunk\n * reaches it through static imports. Chunks that only dynamic imports reach\n * load later, after startup code already ran.\n *\n * Without the chunk graph every chunk counts as initial.\n */\nexport function isInitialChunk(\n chunk: Pick<ChunkGraphNode, 'fileName' | 'isEntry'>,\n chunks: Record<string, ChunkGraphNode> | undefined,\n): boolean {\n if (chunk.isEntry || !chunks) {\n return true;\n }\n\n return getInitialChunks(chunks).has(chunk.fileName);\n}\n\nexport { globFiles } from './glob';\nexport { getCodeInjectionPosition } from './get-code-injection-position';\n\nexport { createComponentNameAnnotateHooks } from './component-annotate-hooks';\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 { InternalOptions, Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n resolveReleaseName,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\nexport {\n decideSourceMapHandling,\n getDeleteOption,\n getDeleteSourcemapsAfterUpload,\n getSdkEnabledSourceMaps,\n getSourceMapFeatures,\n} from './sourcemap-settings';\nexport type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';\nexport type { UploadFilter } from './upload-filter';\n"],"mappings":";;;;;;;;;;;;;AAMA,SAAgB,SAAS,UAA2B;CAClD,MAAM,gBAAgB,0BAA0B,QAAQ;CACxD,OAAO;EAAC;EAAO;EAAQ;CAAM,CAAC,CAAC,MAAK,QAAO,cAAc,SAAS,GAAG,CAAC;AACxE;;;;;;;;;;;;;;;AAgBA,SAAgB,wBAAwB,MAAc,gBAAoD;CAExG,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB,OAAO;CAIT,IAAI,kBAAkB,0BAA0B,cAAc,CAAC,CAAC,SAAS,OAAO,GAC9E,OAAO,oBAAoB,IAAI;CAGjC,OAAO;AACT;AAQA,MAAM,qCAAqB,IAAI,QAAqD;AAEpF,SAAS,iBAAiB,QAAqD;CAC7E,MAAM,SAAS,mBAAmB,IAAI,MAAM;CAC5C,IAAI,QACF,OAAO;CAGT,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC,QAAO,UAAS,MAAM,OAAO;CAEjE,KAAK,IAAI,QAAQ,MAAM,MAAM,GAAG,OAAO,QAAQ,MAAM,MAAM,GAAG;EAC5D,IAAI,QAAQ,IAAI,MAAM,QAAQ,GAC5B;EAEF,QAAQ,IAAI,MAAM,QAAQ;EAC1B,KAAK,MAAM,YAAY,MAAM,WAAW,CAAC,GAAG;GAC1C,MAAM,gBAAgB,OAAO;GAC7B,IAAI,eACF,MAAM,KAAK,aAAa;EAE5B;CACF;CAEA,mBAAmB,IAAI,QAAQ,OAAO;CACtC,OAAO;AACT;;;;;;;;AASA,SAAgB,eACd,OACA,QACS;CACT,IAAI,MAAM,WAAW,CAAC,QACpB,OAAO;CAGT,OAAO,iBAAiB,MAAM,CAAC,CAAC,IAAI,MAAM,QAAQ;AACpD;AAOA,SAAgB,kBAAkB,SAAgC;CAChE,OAAO,IAAI,cACT,+FAA+F,QAAQ,4CAA4C,QAAQ,IAC7J;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/index.ts"],"sourcesContent":["import { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\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 interface ChunkGraphNode {\n fileName: string;\n isEntry?: boolean;\n imports?: string[];\n}\n\nconst initialChunksCache = new WeakMap<Record<string, ChunkGraphNode>, Set<string>>();\n\nfunction getInitialChunks(chunks: Record<string, ChunkGraphNode>): Set<string> {\n const cached = initialChunksCache.get(chunks);\n if (cached) {\n return cached;\n }\n\n const initial = new Set<string>();\n const queue = Object.values(chunks).filter(chunk => chunk.isEntry);\n\n for (let chunk = queue.shift(); chunk; chunk = queue.shift()) {\n if (initial.has(chunk.fileName)) {\n continue;\n }\n initial.add(chunk.fileName);\n for (const imported of chunk.imports ?? []) {\n const importedChunk = chunks[imported];\n if (importedChunk) {\n queue.push(importedChunk);\n }\n }\n }\n\n initialChunksCache.set(chunks, initial);\n return initial;\n}\n\n/**\n * Whether a chunk loads at startup: it is an entry chunk, or an entry chunk\n * reaches it through static imports. Chunks that only dynamic imports reach\n * load later, after startup code already ran.\n *\n * Without the chunk graph every chunk counts as initial.\n */\nexport function isInitialChunk(\n chunk: Pick<ChunkGraphNode, 'fileName' | 'isEntry'>,\n chunks: Record<string, ChunkGraphNode> | undefined,\n): boolean {\n if (chunk.isEntry || !chunks) {\n return true;\n }\n\n return getInitialChunks(chunks).has(chunk.fileName);\n}\n\nexport { globFiles } from './glob';\nexport { getCodeInjectionPosition } from './get-code-injection-position';\n\nexport { createComponentNameAnnotateHooks } from './component-annotate-hooks';\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 { InternalOptions, Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n resolveReleaseName,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\nexport {\n decideSourceMapHandling,\n getDeleteOption,\n getSdkDeleteSourceMaps,\n getSourceMapFeatures,\n} from './sourcemap-settings';\nexport type { SourceMapDecision, SourceMapKind } from './sourcemap-settings';\nexport { hasSourceMapUploadCredentials } from './upload-credentials';\nexport type { UploadFilter } from './upload-filter';\n"],"mappings":";;;;;;;;;;;;;;AAMA,SAAgB,SAAS,UAA2B;CAClD,MAAM,gBAAgB,0BAA0B,QAAQ;CACxD,OAAO;EAAC;EAAO;EAAQ;CAAM,CAAC,CAAC,MAAK,QAAO,cAAc,SAAS,GAAG,CAAC;AACxE;;;;;;;;;;;;;;;AAgBA,SAAgB,wBAAwB,MAAc,gBAAoD;CAExG,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB,OAAO;CAIT,IAAI,kBAAkB,0BAA0B,cAAc,CAAC,CAAC,SAAS,OAAO,GAC9E,OAAO,oBAAoB,IAAI;CAGjC,OAAO;AACT;AAQA,MAAM,qCAAqB,IAAI,QAAqD;AAEpF,SAAS,iBAAiB,QAAqD;CAC7E,MAAM,SAAS,mBAAmB,IAAI,MAAM;CAC5C,IAAI,QACF,OAAO;CAGT,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,QAAQ,OAAO,OAAO,MAAM,CAAC,CAAC,QAAO,UAAS,MAAM,OAAO;CAEjE,KAAK,IAAI,QAAQ,MAAM,MAAM,GAAG,OAAO,QAAQ,MAAM,MAAM,GAAG;EAC5D,IAAI,QAAQ,IAAI,MAAM,QAAQ,GAC5B;EAEF,QAAQ,IAAI,MAAM,QAAQ;EAC1B,KAAK,MAAM,YAAY,MAAM,WAAW,CAAC,GAAG;GAC1C,MAAM,gBAAgB,OAAO;GAC7B,IAAI,eACF,MAAM,KAAK,aAAa;EAE5B;CACF;CAEA,mBAAmB,IAAI,QAAQ,OAAO;CACtC,OAAO;AACT;;;;;;;;AASA,SAAgB,eACd,OACA,QACS;CACT,IAAI,MAAM,WAAW,CAAC,QACpB,OAAO;CAGT,OAAO,iBAAiB,MAAM,CAAC,CAAC,IAAI,MAAM,QAAQ;AACpD;AAOA,SAAgB,kBAAkB,SAAgC;CAChE,OAAO,IAAI,cACT,+FAA+F,QAAQ,4CAA4C,QAAQ,IAC7J;AACF"}
@@ -1,11 +1,12 @@
1
+ import { parseProjectEnvVar } from "./upload-credentials.js";
1
2
  import { canAutoDetectRepository, readCommitEnvVar, resolveReleaseName } from "./utils.js";
2
- import { getVercelEnv } from "@sentry/core";
3
+ import { getVercelEnv, warnOnConflictingSourceMapOptions } from "@sentry/core";
3
4
  // src/core/options-mapping.ts
4
5
  const SENTRY_SAAS_URL = "https://sentry.io";
5
6
  function normalizeUserOptions(userOptions) {
6
7
  const options = {
7
8
  org: userOptions.org ?? process.env["SENTRY_ORG"],
8
- project: userOptions.project ?? (process.env["SENTRY_PROJECT"]?.includes(",") ? process.env["SENTRY_PROJECT"].split(",").map((p) => p.trim()) : process.env["SENTRY_PROJECT"]),
9
+ project: userOptions.project ?? parseProjectEnvVar(process.env["SENTRY_PROJECT"]),
9
10
  authToken: userOptions.authToken ?? process.env["SENTRY_AUTH_TOKEN"],
10
11
  url: userOptions.url ?? process.env["SENTRY_URL"],
11
12
  headers: userOptions.headers,
@@ -80,11 +81,7 @@ function validateOptions(options, logger) {
80
81
  }
81
82
  if (setCommits.auto && setCommits.repo && setCommits) logger.warn("The `setCommits` options includes `auto` but also `repo` and `commit`.", "Ignoring `repo` and `commit`.", "Please only set either `auto` or both, `repo` and `commit`.");
82
83
  }
83
- const sourcemaps = options.sourcemaps;
84
- if ((sourcemaps?.upload !== void 0 || sourcemaps?.injectDebugIds !== void 0) && sourcemaps?.disable !== void 0) logger.warn("`sourcemaps.disable` is ignored because `sourcemaps.upload` or `sourcemaps.injectDebugIds` is set.", "Please remove `sourcemaps.disable`.");
85
- if (sourcemaps?.injectDebugIds === false && sourcemaps.upload === true) logger.warn("`sourcemaps.upload` is set, but `sourcemaps.injectDebugIds` is `false`.", "Source maps are not uploaded, because the upload matches files by debug ID.");
86
- if (sourcemaps?.delete !== void 0 && sourcemaps.deleteSourcemapsAfterUpload !== void 0) logger.warn("`sourcemaps.deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set.", "Please remove `sourcemaps.deleteSourcemapsAfterUpload`.");
87
- if (sourcemaps?.delete === false && sourcemaps.filesToDeleteAfterUpload !== void 0) logger.warn("`sourcemaps.filesToDeleteAfterUpload` still deletes the files it matches, although `sourcemaps.delete` is `false`.", "Remove `sourcemaps.filesToDeleteAfterUpload` to keep the source maps.");
84
+ warnOnConflictingSourceMapOptions(options.sourcemaps, (message) => logger.warn(message));
88
85
  if (options.release?.deploy && typeof options.release.deploy === "object" && !options.release.deploy.env) {
89
86
  logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
90
87
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"options-mapping.js","names":[],"sources":["../../../src/core/options-mapping.ts"],"sourcesContent":["import { getVercelEnv } from '@sentry/core';\nimport type { Logger } from './logger';\nimport type {\n InternalOptions as UserOptions,\n SetCommitsOptions,\n RewriteSourcesHook,\n ResolveSourceMapHook,\n IncludeEntry,\n ModuleMetadata,\n ModuleMetadataCallback,\n} from './types';\nimport { canAutoDetectRepository, readCommitEnvVar, resolveReleaseName } from './utils';\n\nexport type NormalizedOptions = {\n org: string | undefined;\n project: string | string[] | undefined;\n authToken: string | undefined;\n url: string | undefined;\n headers: Record<string, string> | undefined;\n debug: boolean;\n silent: boolean;\n errorHandler: ((err: Error) => void) | undefined;\n telemetry: boolean;\n disable: boolean;\n sourcemaps:\n | {\n disable?: boolean | 'disable-upload';\n upload?: boolean;\n injectDebugIds?: boolean;\n delete?: boolean;\n assets?: string | string[];\n ignore?: string | string[];\n rewriteSources?: RewriteSourcesHook;\n resolveSourceMap?: ResolveSourceMapHook;\n filesToDeleteAfterUpload?: string | string[] | Promise<string | string[] | undefined>;\n deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined);\n sdkEnabledSourceMaps?: boolean | ((environment?: string) => boolean | undefined);\n }\n | undefined;\n release: {\n name: string | undefined;\n inject: boolean | 'html';\n create: boolean;\n finalize: boolean;\n vcsRemote: string;\n setCommits:\n | (SetCommitsOptions & {\n shouldNotThrowOnFailure?: boolean;\n })\n | false\n | undefined;\n dist?: string;\n deploy?:\n | {\n env: string;\n started?: number | string;\n finished?: number | string;\n time?: number;\n name?: string;\n url?: string;\n }\n | false;\n uploadLegacySourcemaps?: string | IncludeEntry | Array<string | IncludeEntry>;\n };\n bundleSizeOptimizations:\n | {\n excludeDebugStatements?: boolean;\n excludeTracing?: boolean;\n excludeChannelInjection?: boolean;\n excludeReplayCanvas?: boolean;\n excludeReplayShadowDom?: boolean;\n excludeReplayIframe?: boolean;\n excludeReplayWorker?: boolean;\n }\n | undefined;\n reactComponentAnnotation:\n | {\n enabled?: boolean;\n ignoredComponents?: string[];\n _experimentalInjectIntoHtml?: boolean;\n }\n | undefined;\n _metaOptions: {\n telemetry: {\n metaFramework: string | undefined;\n bundlerMajorVersion: string | undefined;\n };\n };\n applicationKey: string | undefined;\n moduleMetadata: ModuleMetadata | ModuleMetadataCallback | undefined;\n _experiments: {\n injectBuildInformation?: boolean;\n } & Record<string, unknown>;\n};\n\nexport const SENTRY_SAAS_URL = 'https://sentry.io';\n\n// oxlint-disable-next-line complexity\nexport function normalizeUserOptions(userOptions: UserOptions): NormalizedOptions {\n const options = {\n org: userOptions.org ?? process.env['SENTRY_ORG'],\n project:\n userOptions.project ??\n (process.env['SENTRY_PROJECT']?.includes(',')\n ? process.env['SENTRY_PROJECT'].split(',').map(p => p.trim())\n : process.env['SENTRY_PROJECT']),\n authToken: userOptions.authToken ?? process.env['SENTRY_AUTH_TOKEN'],\n // No sentry.io default: the CLI then uses the server an `sntrys_` org token was issued for, and\n // sentry.io otherwise. A default here would send self-hosted tokens to sentry.io.\n url: userOptions.url ?? process.env['SENTRY_URL'],\n headers: userOptions.headers,\n debug: userOptions.debug ?? false,\n silent: userOptions.silent ?? false,\n errorHandler: userOptions.errorHandler,\n telemetry: userOptions.telemetry ?? true,\n disable: userOptions.disable ?? false,\n sourcemaps: userOptions.sourcemaps,\n release: {\n ...userOptions.release,\n name: resolveReleaseName(userOptions.release?.name),\n inject: userOptions.release?.inject ?? true,\n create: userOptions.release?.create ?? true,\n finalize: userOptions.release?.finalize ?? true,\n vcsRemote: userOptions.release?.vcsRemote ?? process.env['SENTRY_VSC_REMOTE'] ?? 'origin',\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast carries the internal `shouldNotThrowOnFailure` field; tsc errors without it\n setCommits: userOptions.release?.setCommits as\n | (SetCommitsOptions & { shouldNotThrowOnFailure?: boolean })\n | false\n | undefined,\n },\n bundleSizeOptimizations: userOptions.bundleSizeOptimizations,\n reactComponentAnnotation: userOptions.reactComponentAnnotation,\n _metaOptions: {\n telemetry: {\n metaFramework: userOptions._metaOptions?.telemetry?.metaFramework,\n bundlerMajorVersion: userOptions._metaOptions?.telemetry?.bundlerMajorVersion,\n },\n },\n applicationKey: userOptions.applicationKey,\n moduleMetadata: userOptions.moduleMetadata,\n _experiments: userOptions._experiments ?? {},\n };\n\n const vercelEnv = getVercelEnv();\n\n if (options.release.setCommits === undefined) {\n const vercelCommitSha = readCommitEnvVar('VERCEL_GIT_COMMIT_SHA');\n if (\n process.env['VERCEL'] &&\n vercelCommitSha &&\n process.env['VERCEL_GIT_REPO_SLUG'] &&\n process.env['VERCEL_GIT_REPO_OWNER'] &&\n // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for\n // preview environments because the previous commit is always the \"stem\" commit of the preview/PR causing Sentry\n // to notify you for other people creating PRs.\n vercelEnv === 'production'\n ) {\n options.release.setCommits = {\n shouldNotThrowOnFailure: true,\n commit: vercelCommitSha,\n previousCommit: readCommitEnvVar('VERCEL_GIT_PREVIOUS_SHA'),\n repo: `${process.env['VERCEL_GIT_REPO_OWNER']}/${process.env['VERCEL_GIT_REPO_SLUG']}`,\n ignoreEmpty: true,\n ignoreMissing: true,\n };\n } else if (\n process.env['VERCEL'] &&\n vercelEnv !== 'production' &&\n !canAutoDetectRepository(options.release.vcsRemote)\n ) {\n // Vercel's own builders have no git remote and no other CI variables, so commit association can only fail there.\n // Builds that have either, such as `vercel build` in GitHub Actions, keep `auto: true` below.\n options.release.setCommits = false;\n } else {\n options.release.setCommits = {\n shouldNotThrowOnFailure: true,\n auto: true,\n ignoreEmpty: true,\n ignoreMissing: true,\n };\n }\n }\n\n if (options.release.deploy === undefined && process.env['VERCEL'] && vercelEnv) {\n options.release.deploy = {\n env: vercelEnv,\n url: process.env['VERCEL_URL'] ? `https://${process.env['VERCEL_URL']}` : undefined,\n };\n }\n\n return options;\n}\n\n/**\n * Validates a few combinations of options that are not checked by Sentry CLI.\n *\n * For all other options, we can rely on Sentry CLI to validate them. In fact,\n * we can't validate them in the plugin because Sentry CLI might pick up options from\n * its config file.\n *\n * @param options the internal options\n * @param logger the logger\n *\n * @returns `true` if the options are valid, `false` otherwise\n */\nexport function validateOptions(options: NormalizedOptions, logger: Logger): boolean {\n const setCommits = options.release?.setCommits;\n if (setCommits) {\n if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {\n logger.error(\n 'The `setCommits` option was specified but is missing required properties.',\n 'Please set either `auto` or both, `repo` and `commit`.',\n );\n return false;\n }\n if (setCommits.auto && setCommits.repo && setCommits) {\n logger.warn(\n 'The `setCommits` options includes `auto` but also `repo` and `commit`.',\n 'Ignoring `repo` and `commit`.',\n 'Please only set either `auto` or both, `repo` and `commit`.',\n );\n }\n }\n\n const sourcemaps = options.sourcemaps;\n const usesFeatureOptions = sourcemaps?.upload !== undefined || sourcemaps?.injectDebugIds !== undefined;\n if (usesFeatureOptions && sourcemaps?.disable !== undefined) {\n logger.warn(\n '`sourcemaps.disable` is ignored because `sourcemaps.upload` or `sourcemaps.injectDebugIds` is set.',\n 'Please remove `sourcemaps.disable`.',\n );\n }\n if (sourcemaps?.injectDebugIds === false && sourcemaps.upload === true) {\n logger.warn(\n '`sourcemaps.upload` is set, but `sourcemaps.injectDebugIds` is `false`.',\n 'Source maps are not uploaded, because the upload matches files by debug ID.',\n );\n }\n if (sourcemaps?.delete !== undefined && sourcemaps.deleteSourcemapsAfterUpload !== undefined) {\n logger.warn(\n '`sourcemaps.deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set.',\n 'Please remove `sourcemaps.deleteSourcemapsAfterUpload`.',\n );\n }\n if (sourcemaps?.delete === false && sourcemaps.filesToDeleteAfterUpload !== undefined) {\n logger.warn(\n '`sourcemaps.filesToDeleteAfterUpload` still deletes the files it matches, although `sourcemaps.delete` is `false`.',\n 'Remove `sourcemaps.filesToDeleteAfterUpload` to keep the source maps.',\n );\n }\n\n if (options.release?.deploy && typeof options.release.deploy === 'object' && !options.release.deploy.env) {\n logger.error(\n 'The `deploy` option was specified but is missing the required `env` property.',\n 'Please set the `env` property.',\n );\n return false;\n }\n\n if (options.project && Array.isArray(options.project)) {\n if (options.project.length === 0) {\n logger.error(\n 'The `project` option was specified as an array but is empty.',\n 'Please provide at least one project slug.',\n );\n return false;\n }\n // Check each project is a non-empty string\n const invalidProjects = options.project.filter(p => typeof p !== 'string' || p.trim() === '');\n if (invalidProjects.length > 0) {\n logger.error('The `project` option contains invalid project slugs.', 'All projects must be non-empty strings.');\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;AA+FA,MAAa,kBAAkB;AAG/B,SAAgB,qBAAqB,aAA6C;CAChF,MAAM,UAAU;EACd,KAAK,YAAY,OAAO,QAAQ,IAAI;EACpC,SACE,YAAY,YACX,QAAQ,IAAI,iBAAiB,EAAE,SAAS,GAAG,IACxC,QAAQ,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,CAAC,KAAI,MAAK,EAAE,KAAK,CAAC,IAC1D,QAAQ,IAAI;EAClB,WAAW,YAAY,aAAa,QAAQ,IAAI;EAGhD,KAAK,YAAY,OAAO,QAAQ,IAAI;EACp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O;EACT;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"options-mapping.js","names":[],"sources":["../../../src/core/options-mapping.ts"],"sourcesContent":["import { getVercelEnv, warnOnConflictingSourceMapOptions } from '@sentry/core';\nimport type { Logger } from './logger';\nimport type {\n InternalOptions as UserOptions,\n SetCommitsOptions,\n RewriteSourcesHook,\n ResolveSourceMapHook,\n IncludeEntry,\n ModuleMetadata,\n ModuleMetadataCallback,\n} from './types';\nimport { parseProjectEnvVar } from './upload-credentials';\nimport { canAutoDetectRepository, readCommitEnvVar, resolveReleaseName } from './utils';\n\nexport type NormalizedOptions = {\n org: string | undefined;\n project: string | string[] | undefined;\n authToken: string | undefined;\n url: string | undefined;\n headers: Record<string, string> | undefined;\n debug: boolean;\n silent: boolean;\n errorHandler: ((err: Error) => void) | undefined;\n telemetry: boolean;\n disable: boolean;\n sourcemaps:\n | {\n disable?: boolean | 'disable-upload';\n upload?: boolean;\n injectDebugIds?: boolean;\n delete?: boolean;\n assets?: string | string[];\n ignore?: string | string[];\n rewriteSources?: RewriteSourcesHook;\n resolveSourceMap?: ResolveSourceMapHook;\n filesToDeleteAfterUpload?: string | string[] | Promise<string | string[] | undefined>;\n deleteSourcemapsAfterUpload?: boolean;\n sdkDeleteSourceMaps?: boolean | ((environment?: string) => boolean | undefined);\n }\n | undefined;\n release: {\n name: string | undefined;\n inject: boolean | 'html';\n create: boolean;\n finalize: boolean;\n vcsRemote: string;\n setCommits:\n | (SetCommitsOptions & {\n shouldNotThrowOnFailure?: boolean;\n })\n | false\n | undefined;\n dist?: string;\n deploy?:\n | {\n env: string;\n started?: number | string;\n finished?: number | string;\n time?: number;\n name?: string;\n url?: string;\n }\n | false;\n uploadLegacySourcemaps?: string | IncludeEntry | Array<string | IncludeEntry>;\n };\n bundleSizeOptimizations:\n | {\n excludeDebugStatements?: boolean;\n excludeTracing?: boolean;\n excludeChannelInjection?: boolean;\n excludeReplayCanvas?: boolean;\n excludeReplayShadowDom?: boolean;\n excludeReplayIframe?: boolean;\n excludeReplayWorker?: boolean;\n }\n | undefined;\n reactComponentAnnotation:\n | {\n enabled?: boolean;\n ignoredComponents?: string[];\n _experimentalInjectIntoHtml?: boolean;\n }\n | undefined;\n _metaOptions: {\n telemetry: {\n metaFramework: string | undefined;\n bundlerMajorVersion: string | undefined;\n };\n };\n applicationKey: string | undefined;\n moduleMetadata: ModuleMetadata | ModuleMetadataCallback | undefined;\n _experiments: {\n injectBuildInformation?: boolean;\n } & Record<string, unknown>;\n};\n\nexport const SENTRY_SAAS_URL = 'https://sentry.io';\n\n// oxlint-disable-next-line complexity\nexport function normalizeUserOptions(userOptions: UserOptions): NormalizedOptions {\n const options = {\n org: userOptions.org ?? process.env['SENTRY_ORG'],\n project: userOptions.project ?? parseProjectEnvVar(process.env['SENTRY_PROJECT']),\n authToken: userOptions.authToken ?? process.env['SENTRY_AUTH_TOKEN'],\n // No sentry.io default: the CLI then uses the server an `sntrys_` org token was issued for, and\n // sentry.io otherwise. A default here would send self-hosted tokens to sentry.io.\n url: userOptions.url ?? process.env['SENTRY_URL'],\n headers: userOptions.headers,\n debug: userOptions.debug ?? false,\n silent: userOptions.silent ?? false,\n errorHandler: userOptions.errorHandler,\n telemetry: userOptions.telemetry ?? true,\n disable: userOptions.disable ?? false,\n sourcemaps: userOptions.sourcemaps,\n release: {\n ...userOptions.release,\n name: resolveReleaseName(userOptions.release?.name),\n inject: userOptions.release?.inject ?? true,\n create: userOptions.release?.create ?? true,\n finalize: userOptions.release?.finalize ?? true,\n vcsRemote: userOptions.release?.vcsRemote ?? process.env['SENTRY_VSC_REMOTE'] ?? 'origin',\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast carries the internal `shouldNotThrowOnFailure` field; tsc errors without it\n setCommits: userOptions.release?.setCommits as\n | (SetCommitsOptions & { shouldNotThrowOnFailure?: boolean })\n | false\n | undefined,\n },\n bundleSizeOptimizations: userOptions.bundleSizeOptimizations,\n reactComponentAnnotation: userOptions.reactComponentAnnotation,\n _metaOptions: {\n telemetry: {\n metaFramework: userOptions._metaOptions?.telemetry?.metaFramework,\n bundlerMajorVersion: userOptions._metaOptions?.telemetry?.bundlerMajorVersion,\n },\n },\n applicationKey: userOptions.applicationKey,\n moduleMetadata: userOptions.moduleMetadata,\n _experiments: userOptions._experiments ?? {},\n };\n\n const vercelEnv = getVercelEnv();\n\n if (options.release.setCommits === undefined) {\n const vercelCommitSha = readCommitEnvVar('VERCEL_GIT_COMMIT_SHA');\n if (\n process.env['VERCEL'] &&\n vercelCommitSha &&\n process.env['VERCEL_GIT_REPO_SLUG'] &&\n process.env['VERCEL_GIT_REPO_OWNER'] &&\n // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for\n // preview environments because the previous commit is always the \"stem\" commit of the preview/PR causing Sentry\n // to notify you for other people creating PRs.\n vercelEnv === 'production'\n ) {\n options.release.setCommits = {\n shouldNotThrowOnFailure: true,\n commit: vercelCommitSha,\n previousCommit: readCommitEnvVar('VERCEL_GIT_PREVIOUS_SHA'),\n repo: `${process.env['VERCEL_GIT_REPO_OWNER']}/${process.env['VERCEL_GIT_REPO_SLUG']}`,\n ignoreEmpty: true,\n ignoreMissing: true,\n };\n } else if (\n process.env['VERCEL'] &&\n vercelEnv !== 'production' &&\n !canAutoDetectRepository(options.release.vcsRemote)\n ) {\n // Vercel's own builders have no git remote and no other CI variables, so commit association can only fail there.\n // Builds that have either, such as `vercel build` in GitHub Actions, keep `auto: true` below.\n options.release.setCommits = false;\n } else {\n options.release.setCommits = {\n shouldNotThrowOnFailure: true,\n auto: true,\n ignoreEmpty: true,\n ignoreMissing: true,\n };\n }\n }\n\n if (options.release.deploy === undefined && process.env['VERCEL'] && vercelEnv) {\n options.release.deploy = {\n env: vercelEnv,\n url: process.env['VERCEL_URL'] ? `https://${process.env['VERCEL_URL']}` : undefined,\n };\n }\n\n return options;\n}\n\n/**\n * Validates a few combinations of options that are not checked by Sentry CLI.\n *\n * For all other options, we can rely on Sentry CLI to validate them. In fact,\n * we can't validate them in the plugin because Sentry CLI might pick up options from\n * its config file.\n *\n * @param options the internal options\n * @param logger the logger\n *\n * @returns `true` if the options are valid, `false` otherwise\n */\nexport function validateOptions(options: NormalizedOptions, logger: Logger): boolean {\n const setCommits = options.release?.setCommits;\n if (setCommits) {\n if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {\n logger.error(\n 'The `setCommits` option was specified but is missing required properties.',\n 'Please set either `auto` or both, `repo` and `commit`.',\n );\n return false;\n }\n if (setCommits.auto && setCommits.repo && setCommits) {\n logger.warn(\n 'The `setCommits` options includes `auto` but also `repo` and `commit`.',\n 'Ignoring `repo` and `commit`.',\n 'Please only set either `auto` or both, `repo` and `commit`.',\n );\n }\n }\n\n warnOnConflictingSourceMapOptions(options.sourcemaps, message => logger.warn(message));\n\n if (options.release?.deploy && typeof options.release.deploy === 'object' && !options.release.deploy.env) {\n logger.error(\n 'The `deploy` option was specified but is missing the required `env` property.',\n 'Please set the `env` property.',\n );\n return false;\n }\n\n if (options.project && Array.isArray(options.project)) {\n if (options.project.length === 0) {\n logger.error(\n 'The `project` option was specified as an array but is empty.',\n 'Please provide at least one project slug.',\n );\n return false;\n }\n // Check each project is a non-empty string\n const invalidProjects = options.project.filter(p => typeof p !== 'string' || p.trim() === '');\n if (invalidProjects.length > 0) {\n logger.error('The `project` option contains invalid project slugs.', 'All projects must be non-empty strings.');\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;AAgGA,MAAa,kBAAkB;AAG/B,SAAgB,qBAAqB,aAA6C;CAChF,MAAM,UAAU;EACd,KAAK,YAAY,OAAO,QAAQ,IAAI;EACpC,SAAS,YAAY,WAAW,mBAAmB,QAAQ,IAAI,iBAAiB;EAChF,WAAW,YAAY,aAAa,QAAQ,IAAI;EAGhD,KAAK,YAAY,OAAO,QAAQ,IAAI;EACpC,SAAS,YAAY;EACrB,OAAO,YAAY,SAAS;EAC5B,QAAQ,YAAY,UAAU;EAC9B,cAAc,YAAY;EAC1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,IAAI,kBAAkB,KAAA;CAC5E;CAGF,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,SAA4B,QAAyB;CACnF,MAAM,aAAa,QAAQ,SAAS;CACpC,IAAI,YAAY;EACd,IAAI,CAAC,WAAW,QAAQ,EAAE,WAAW,QAAQ,WAAW,SAAS;GAC/D,OAAO,MACL,6EACA,wDACF;GACA,OAAO;EACT;EACA,IAAI,WAAW,QAAQ,WAAW,QAAQ,YACxC,OAAO,KACL,0EACA,iCACA,6DACF;CAEJ;CAEA,kCAAkC,QAAQ,aAAY,YAAW,OAAO,KAAK,OAAO,CAAC;CAErF,IAAI,QAAQ,SAAS,UAAU,OAAO,QAAQ,QAAQ,WAAW,YAAY,CAAC,QAAQ,QAAQ,OAAO,KAAK;EACxG,OAAO,MACL,iFACA,gCACF;EACA,OAAO;CACT;CAEA,IAAI,QAAQ,WAAW,MAAM,QAAQ,QAAQ,OAAO,GAAG;EACrD,IAAI,QAAQ,QAAQ,WAAW,GAAG;GAChC,OAAO,MACL,gEACA,2CACF;GACA,OAAO;EACT;EAGA,IADwB,QAAQ,QAAQ,QAAO,MAAK,OAAO,MAAM,YAAY,EAAE,KAAK,MAAM,EACxE,CAAC,CAAC,SAAS,GAAG;GAC9B,OAAO,MAAM,wDAAwD,yCAAyC;GAC9G,OAAO;EACT;CACF;CAEA,OAAO;AACT"}
@@ -62,7 +62,7 @@ function setTelemetryDataOnScope(options, scope, buildTool, buildToolMajorVersio
62
62
  scope.setTag("custom-error-handler", !!errorHandler);
63
63
  scope.setTag("sourcemaps-assets", !!sourcemaps?.assets);
64
64
  scope.setTag("delete-after-upload", !!sourcemaps?.filesToDeleteAfterUpload);
65
- scope.setTag("delete-sourcemaps-after-upload", typeof sourcemaps?.deleteSourcemapsAfterUpload === "function" ? "function" : sourcemaps?.deleteSourcemapsAfterUpload === void 0 ? "auto" : String(sourcemaps.deleteSourcemapsAfterUpload));
65
+ scope.setTag("delete-sourcemaps-after-upload", sourcemaps?.deleteSourcemapsAfterUpload === void 0 ? "auto" : String(sourcemaps.deleteSourcemapsAfterUpload));
66
66
  scope.setTag("sourcemaps-disabled", !!sourcemaps?.disable);
67
67
  scope.setTag("sourcemaps-upload", sourcemaps?.upload === void 0 ? "auto" : String(sourcemaps.upload));
68
68
  scope.setTag("sourcemaps-inject-debug-ids", sourcemaps?.injectDebugIds === void 0 ? "auto" : String(sourcemaps.injectDebugIds));