@sentry/bundler-plugins 11.15.0 → 11.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/core/build-plugin-manager.js +1 -1
- package/build/cjs/core/build-plugin-manager.js.map +1 -1
- package/build/cjs/core/cli.js +10 -3
- package/build/cjs/core/cli.js.map +1 -1
- package/build/cjs/core/options-mapping.js +1 -1
- package/build/cjs/core/options-mapping.js.map +1 -1
- package/build/cjs/core/utils.js +40 -3
- package/build/cjs/core/utils.js.map +1 -1
- package/build/cjs/core/version.js +1 -1
- package/build/cjs/core/version.js.map +1 -1
- package/build/esm/core/build-plugin-manager.js +1 -1
- package/build/esm/core/build-plugin-manager.js.map +1 -1
- package/build/esm/core/cli.js +11 -4
- package/build/esm/core/cli.js.map +1 -1
- package/build/esm/core/options-mapping.js +1 -1
- package/build/esm/core/options-mapping.js.map +1 -1
- package/build/esm/core/utils.js +39 -4
- package/build/esm/core/utils.js.map +1 -1
- package/build/esm/core/version.js +1 -1
- package/build/esm/core/version.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/core/cli.d.ts +5 -1
- package/build/types/core/cli.d.ts.map +1 -1
- package/build/types/core/options-mapping.d.ts.map +1 -1
- package/build/types/core/types.d.ts +3 -0
- package/build/types/core/types.d.ts.map +1 -1
- package/build/types/core/utils.d.ts +8 -2
- package/build/types/core/utils.d.ts.map +1 -1
- package/build/types/core/version.d.ts +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["path","os","fs","crypto","childProcess","getReleaseFromCommitEnv","readCoreCommitEnvVar","stringifyForCodeInjection","MagicString"],"sources":["../../../src/core/utils.ts"],"sourcesContent":["/* oxlint-disable max-lines */\nimport path from 'path';\nimport fs from 'fs';\nimport os from 'os';\nimport crypto from 'crypto';\nimport childProcess from 'child_process';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport {\n _INTERNAL_getReleaseFromCommitEnv as getReleaseFromCommitEnv,\n _INTERNAL_readCommitEnvVar as readCoreCommitEnvVar,\n} from '@sentry/core/server';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify<T = unknown>(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\ntype PackageJson = Record<string, unknown>;\n\n/**\n * Get the closes package.json from a given starting point upwards.\n * This handles a few edge cases:\n * * Check if a given file package.json appears to be an actual NPM package.json file\n * * Stop at the home dir, to avoid looking too deeply\n */\nexport function getPackageJson({ cwd, stopAt }: { cwd?: string; stopAt?: string } = {}): PackageJson | undefined {\n return lookupPackageJson(cwd ?? process.cwd(), path.normalize(stopAt ?? os.homedir()));\n}\n\nexport function parseMajorVersion(ver: string): number | undefined {\n let version = ver;\n // if it has a `v` prefix, remove it\n if (version.startsWith('v')) {\n version = version.slice(1);\n }\n\n // First, try simple lookup of exact, ~ and ^ versions\n const regex = /^[\\^~]?(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n\n const match = version.match(regex);\n if (match) {\n return parseInt(match[1] as string, 10);\n }\n\n // Try to parse e.g. 1.x\n const coerced = parseInt(version, 10);\n if (!Number.isNaN(coerced)) {\n return coerced;\n }\n\n // Match <= and >= ranges.\n const gteLteRegex = /^[<>]=\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const gteLteMatch = version.match(gteLteRegex);\n if (gteLteMatch) {\n return parseInt(gteLteMatch[1] as string, 10);\n }\n\n // match < ranges\n const ltRegex = /^<\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const ltMatch = version.match(ltRegex);\n if (ltMatch) {\n // Two scenarios:\n // a) < 2.0.0 --> return 1\n // b) < 2.1.0 --> return 2\n\n const major = parseInt(ltMatch[1] as string, 10);\n\n if (\n // minor version > 0\n (typeof ltMatch[2] === 'string' && parseInt(ltMatch[2].slice(1), 10) > 0) ||\n // patch version > 0\n (typeof ltMatch[3] === 'string' && parseInt(ltMatch[3].slice(1), 10) > 0)\n ) {\n return major;\n }\n\n return major - 1;\n }\n\n // match > ranges\n const gtRegex = /^>\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const gtMatch = version.match(gtRegex);\n if (gtMatch) {\n // We always return the version here, even though it _may_ be incorrect\n // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3\n // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists\n return parseInt(gtMatch[1] as string, 10);\n }\n return undefined;\n}\n\n// This is an explicit list of packages where we want to include the (major) version number.\nconst PACKAGES_TO_INCLUDE_VERSION = [\n 'react',\n '@angular/core',\n 'vue',\n 'ember-source',\n 'svelte',\n '@sveltejs/kit',\n 'webpack',\n 'vite',\n 'gatsby',\n 'next',\n 'remix',\n 'rollup',\n 'esbuild',\n];\n\nexport function getDependencies(packageJson: PackageJson): {\n deps: string[];\n depsVersions: Record<string, number>;\n} {\n const dependencies: Record<string, string> = Object.assign(\n {},\n packageJson['devDependencies'] ?? {},\n packageJson['dependencies'] ?? {},\n );\n\n const deps = Object.keys(dependencies).sort();\n\n const depsVersions: Record<string, number> = deps.reduce(\n (depsVersions, depName) => {\n if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {\n const version = dependencies[depName] as string;\n const majorVersion = parseMajorVersion(version);\n if (majorVersion) {\n depsVersions[depName] = majorVersion;\n }\n }\n return depsVersions;\n },\n {} as Record<string, number>,\n );\n\n return { deps, depsVersions };\n}\n\nfunction findPackageJson(cwd: string, stopAt: string): string | undefined {\n let dirName = path.resolve(cwd);\n\n for (;;) {\n // Stop if we reach this dir\n if (path.normalize(dirName) === stopAt) {\n return undefined;\n }\n\n const jsonPath = path.join(dirName, 'package.json');\n if (fs.existsSync(jsonPath)) {\n return jsonPath;\n }\n\n const parentDirName = path.dirname(dirName);\n // We reached the file system root\n if (parentDirName === dirName) {\n return undefined;\n }\n\n dirName = parentDirName;\n }\n}\n\nfunction lookupPackageJson(cwd: string, stopAt: string): PackageJson | undefined {\n const jsonPath = findPackageJson(cwd, stopAt);\n\n if (!jsonPath) {\n return undefined;\n }\n\n try {\n const jsonStr = fs.readFileSync(jsonPath, 'utf8');\n const json = JSON.parse(jsonStr) as PackageJson;\n\n // Ensure it is an actual package.json\n // This is very much not bulletproof, but should be good enough\n if ('name' in json || 'private' in json) {\n return json;\n }\n } catch {\n // Ignore and walk up\n }\n\n // Continue up the tree, if we find a fitting package.json\n const newCwd = path.dirname(path.resolve(`${jsonPath}/..`));\n return lookupPackageJson(newCwd, stopAt);\n}\n\n/**\n * Deterministically hashes a string and turns the hash into a uuid.\n */\nexport function stringToUUID(str: string): string {\n const sha256Hash = crypto.createHash('sha256').update(str).digest('hex');\n\n // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)\n // RFC 4122 section 4.4\n const v4variant = ['8', '9', 'a', 'b'][sha256Hash.substring(16, 17).charCodeAt(0) % 4] as string;\n\n return `${sha256Hash.substring(0, 8)}-${sha256Hash.substring(8, 12)}-4${sha256Hash.substring(13, 16)}-${v4variant}${sha256Hash.substring(17, 20)}-${sha256Hash.substring(20, 32)}`.toLowerCase();\n}\n\nfunction gitRevision(): string | undefined {\n let gitRevision: string | undefined;\n try {\n gitRevision = childProcess\n .execSync('git rev-parse HEAD', { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })\n .toString()\n .trim();\n } catch {\n // noop\n }\n return gitRevision;\n}\n\n// Mirrors the CLI's `set-commits --auto` fallback for builds without an `origin` remote. Vercel is left out\n// because the CLI only reads `VERCEL_GIT_*` on production builds.\nconst CI_REPOSITORY_ENV_VARS = [\n 'GITHUB_REPOSITORY',\n 'CI_PROJECT_PATH',\n 'BITBUCKET_REPO_FULL_NAME',\n 'RENDER_GIT_REPO_SLUG',\n 'RAILWAY_GIT_REPO_NAME',\n 'CIRCLE_PROJECT_REPONAME',\n 'BUILDKITE_REPO',\n 'BUILD_REPOSITORY_URI',\n] as const;\n\n/**\n * Whether `set-commits --auto` can find the repository: from the `origin` git remote, or from CI variables.\n */\nexport function canAutoDetectRepository(): boolean {\n if (\n CI_REPOSITORY_ENV_VARS.some(name => process.env[name]) ||\n (process.env['NETLIFY'] && process.env['REPOSITORY_URL'])\n ) {\n return true;\n }\n try {\n childProcess.execSync('git remote get-url origin', { stdio: 'ignore', windowsHide: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tries to guess a release name based on environmental data.\n */\nexport function determineReleaseName(): string | undefined {\n return getReleaseFromCommitEnv(warnAboutPlaceholderCommitEnvVar) || gitRevision();\n}\n\n/**\n * Resolves the release name the way the bundler plugins do: the configured name, then the `SENTRY_RELEASE`\n * environment variable, then a name detected from CI environment variables or git.\n *\n * Framework SDKs that pass the release to the SDK at runtime use this to get the same name the plugin uses.\n */\nexport function resolveReleaseName(name?: string): string | undefined {\n return name ?? process.env['SENTRY_RELEASE'] ?? determineReleaseName();\n}\n\n// Release detection and commit association can read the same variable in one build.\nconst warnedPlaceholderEnvVars = new Set<string>();\n\nfunction warnAboutPlaceholderCommitEnvVar(name: string): void {\n if (warnedPlaceholderEnvVars.has(name)) {\n return;\n }\n warnedPlaceholderEnvVars.add(name);\n // This runs before the plugin logger exists, so `silent: true` does not suppress it. That is\n // deliberate: a warning that is easy to miss is how this misconfiguration went unnoticed.\n // eslint-disable-next-line no-console\n console.warn(\n `[@sentry/bundler-plugins] Ignoring the ${name} environment variable as a release name, because its value is its own name. Set the release explicitly, or fix the variable in your build environment.`,\n );\n}\n\n/**\n * Reads an environment variable that should hold a commit SHA, ignoring a value that is the\n * variable's own name. See `_INTERNAL_readCommitEnvVar` in `@sentry/core/server`.\n */\nexport function readCommitEnvVar(name: string): string | undefined {\n return readCoreCommitEnvVar(name, warnAboutPlaceholderCommitEnvVar);\n}\n\n/**\n * Generates code for the global injector which is responsible for setting the global\n * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.\n */\nexport function generateReleaseInjectorCode({\n release,\n injectBuildInformation,\n}: {\n release: string;\n injectBuildInformation: boolean;\n}): CodeInjection {\n let code = `e.SENTRY_RELEASE={id:${stringifyForCodeInjection(release)}};`;\n\n if (injectBuildInformation) {\n const buildInfo = getBuildInformation();\n\n code += `e.SENTRY_BUILD_INFO=${stringifyForCodeInjection(buildInfo)};`;\n }\n\n return new CodeInjection(code);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function generateModuleMetadataInjectorCode(metadata: any): CodeInjection {\n // We are merging the metadata objects in case modules are bundled twice with the plugin\n // Use try-catch to avoid issues when bundlers rename global variables like 'window' to 'k'\n return new CodeInjection(\n `e._sentryModuleMetadata=e._sentryModuleMetadata||{},e._sentryModuleMetadata[(new e.Error).stack]=function(e){for(var n=1;n<arguments.length;n++){var a=arguments[n];if(null!=a)for(var t in a)a.hasOwnProperty(t)&&(e[t]=a[t])}return e}({},e._sentryModuleMetadata[(new e.Error).stack],${stringifyForCodeInjection(\n metadata,\n )});`,\n );\n}\n\nexport function getBuildInformation(): {\n deps: string[];\n depsVersions: Record<string, number>;\n nodeVersion: number | undefined;\n} {\n const packageJson = getPackageJson();\n\n const { deps, depsVersions } = packageJson ? getDependencies(packageJson) : { deps: [], depsVersions: {} };\n\n return {\n deps,\n depsVersions,\n nodeVersion: parseMajorVersion(process.version),\n };\n}\n\nexport function stripQueryAndHashFromPath(path: string): string {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return path.split('?')[0]!.split('#')[0]!;\n}\n\nexport function replaceBooleanFlagsInCode(\n code: string,\n replacementValues: Record<string, boolean | undefined>,\n): { code: string; map: SourceMap } | null {\n const ms = new MagicString(code);\n\n Object.keys(replacementValues).forEach(key => {\n const value = replacementValues[key];\n\n if (typeof value === 'boolean') {\n ms.replaceAll(key, JSON.stringify(value));\n }\n });\n\n if (ms.hasChanged()) {\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: 'boundary' }),\n };\n }\n\n return null;\n}\n\n// https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks\nexport function getTurborepoEnvPassthroughWarning(envVarName: string): string {\n return process.env['TURBO_HASH']\n ? `\\nYou seem to be using Turborepo, did you forget to put ${envVarName} in \\`passThroughEnv\\`? https://turbo.build/repo/docs/reference/configuration#passthroughenv`\n : '';\n}\n\n/**\n * Gets the projects from the project option. This might be a single project or an array of projects.\n */\nexport function getProjects(project: string | string[] | undefined): string[] | undefined {\n if (Array.isArray(project)) {\n return project;\n }\n\n if (project) {\n return [project];\n }\n\n return undefined;\n}\n\n/**\n * Checks if a chunk contains only import/export statements and no substantial code.\n *\n * In Vite MPA (multi-page application) mode, HTML entry points create \"facade\" chunks\n * that only contain import statements to load shared modules. These should not have\n * Sentry code injected. However, in SPA mode, the main bundle also has an HTML facade\n * but contains substantial application code that SHOULD have debug IDs injected.\n *\n * @ref https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n * @ref https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/839\n */\nexport function containsOnlyImports(code: string): boolean {\n const codeWithoutImports = code\n // Remove side effect imports: import '/path'; or import \"./path\";\n // Using explicit negated character classes to avoid polynomial backtracking\n .replace(/^\\s*import\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove named/default imports: import x from '/path'; import { x } from '/path';\n .replace(/^\\s*import\\b[^'\"`\\n]*\\bfrom\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove re-exports: export * from '/path'; export { x } from '/path';\n .replace(/^\\s*export\\b[^'\"`\\n]*\\bfrom\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove block comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n // Remove line comments\n .replace(/\\/\\/.*$/gm, '')\n // Remove \"use strict\" directives\n .replace(/[\"']use strict[\"']\\s*;?/g, '')\n .trim();\n\n return codeWithoutImports.length === 0;\n}\n\nexport class CodeInjection {\n // The code below is mostly ternary operators because it saves bundle size.\n // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)\n private readonly header: string;\n private readonly footer: string;\n\n constructor(private body: string = '') {\n // `globalThis` is checked first so the other identifiers are never evaluated\n // where it exists. A downstream bundler that runs over an already-injected\n // chunk can turn a free `global` into a `const` it declares further down the\n // file (Nitro's node compat does this). Reading that binding from the top of\n // the file hits the temporal dead zone, and `typeof` throws there instead of\n // returning \"undefined\", so the whole injection was silently swallowed by the\n // `catch` below and the chunk registered no debug ID.\n this.header = `!function(){try{var e=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{};`;\n this.footer = '}catch(e){}}();';\n }\n\n public code(): string {\n if (this.isEmpty()) {\n return '';\n }\n\n return this.header + this.body + this.footer;\n }\n\n public isEmpty(): boolean {\n return this.body.length === 0;\n }\n\n public append(code: CodeInjection | string): void {\n if (code instanceof CodeInjection) {\n this.body += code.body;\n } else {\n this.body += code;\n }\n }\n\n public clear(): void {\n this.body = '';\n }\n\n public clone(): CodeInjection {\n return new CodeInjection(this.body);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,SAAsB,YAA0B;CAC9D,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;;;;AAUA,SAAgB,eAAe,EAAE,KAAK,WAA8C,CAAC,GAA4B;CAC/G,OAAO,kBAAkB,OAAO,QAAQ,IAAI,GAAGA,KAAAA,QAAK,UAAU,UAAUC,GAAAA,QAAG,QAAQ,CAAC,CAAC;AACvF;AAEA,SAAgB,kBAAkB,KAAiC;CACjE,IAAI,UAAU;CAEd,IAAI,QAAQ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,CACvC,KAEqB,CAAC,CAAC,WAAW;AACvC;AAEA,IAAa,gBAAb,MAAa,cAAc;CAMzB,YAAoB,OAAe,IAAI;EAAnB,KAAA,OAAA;EAQlB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEO,OAAe;EACpB,IAAI,KAAK,QAAQ,GACf,OAAO;EAGT,OAAO,KAAK,SAAS,KAAK,OAAO,KAAK;CACxC;CAEO,UAAmB;EACxB,OAAO,KAAK,KAAK,WAAW;CAC9B;CAEO,OAAO,MAAoC;EAChD,IAAI,gBAAgB,eAClB,KAAK,QAAQ,KAAK;OAElB,KAAK,QAAQ;CAEjB;CAEO,QAAc;EACnB,KAAK,OAAO;CACd;CAEO,QAAuB;EAC5B,OAAO,IAAI,cAAc,KAAK,IAAI;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["path","os","fs","crypto","childProcess","getReleaseFromCommitEnv","readCoreCommitEnvVar","stringifyForCodeInjection","MagicString"],"sources":["../../../src/core/utils.ts"],"sourcesContent":["/* oxlint-disable max-lines */\nimport path from 'path';\nimport fs from 'fs';\nimport os from 'os';\nimport crypto from 'crypto';\nimport childProcess from 'child_process';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport {\n _INTERNAL_getReleaseFromCommitEnv as getReleaseFromCommitEnv,\n _INTERNAL_readCommitEnvVar as readCoreCommitEnvVar,\n} from '@sentry/core/server';\nimport { stringifyForCodeInjection } from '@sentry/core';\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify<T = unknown>(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\ntype PackageJson = Record<string, unknown>;\n\n/**\n * Get the closes package.json from a given starting point upwards.\n * This handles a few edge cases:\n * * Check if a given file package.json appears to be an actual NPM package.json file\n * * Stop at the home dir, to avoid looking too deeply\n */\nexport function getPackageJson({ cwd, stopAt }: { cwd?: string; stopAt?: string } = {}): PackageJson | undefined {\n return lookupPackageJson(cwd ?? process.cwd(), path.normalize(stopAt ?? os.homedir()));\n}\n\nexport function parseMajorVersion(ver: string): number | undefined {\n let version = ver;\n // if it has a `v` prefix, remove it\n if (version.startsWith('v')) {\n version = version.slice(1);\n }\n\n // First, try simple lookup of exact, ~ and ^ versions\n const regex = /^[\\^~]?(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n\n const match = version.match(regex);\n if (match) {\n return parseInt(match[1] as string, 10);\n }\n\n // Try to parse e.g. 1.x\n const coerced = parseInt(version, 10);\n if (!Number.isNaN(coerced)) {\n return coerced;\n }\n\n // Match <= and >= ranges.\n const gteLteRegex = /^[<>]=\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const gteLteMatch = version.match(gteLteRegex);\n if (gteLteMatch) {\n return parseInt(gteLteMatch[1] as string, 10);\n }\n\n // match < ranges\n const ltRegex = /^<\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const ltMatch = version.match(ltRegex);\n if (ltMatch) {\n // Two scenarios:\n // a) < 2.0.0 --> return 1\n // b) < 2.1.0 --> return 2\n\n const major = parseInt(ltMatch[1] as string, 10);\n\n if (\n // minor version > 0\n (typeof ltMatch[2] === 'string' && parseInt(ltMatch[2].slice(1), 10) > 0) ||\n // patch version > 0\n (typeof ltMatch[3] === 'string' && parseInt(ltMatch[3].slice(1), 10) > 0)\n ) {\n return major;\n }\n\n return major - 1;\n }\n\n // match > ranges\n const gtRegex = /^>\\s*(\\d+)(\\.\\d+)?(\\.\\d+)?(-.+)?/;\n const gtMatch = version.match(gtRegex);\n if (gtMatch) {\n // We always return the version here, even though it _may_ be incorrect\n // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3\n // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists\n return parseInt(gtMatch[1] as string, 10);\n }\n return undefined;\n}\n\n// This is an explicit list of packages where we want to include the (major) version number.\nconst PACKAGES_TO_INCLUDE_VERSION = [\n 'react',\n '@angular/core',\n 'vue',\n 'ember-source',\n 'svelte',\n '@sveltejs/kit',\n 'webpack',\n 'vite',\n 'gatsby',\n 'next',\n 'remix',\n 'rollup',\n 'esbuild',\n];\n\nexport function getDependencies(packageJson: PackageJson): {\n deps: string[];\n depsVersions: Record<string, number>;\n} {\n const dependencies: Record<string, string> = Object.assign(\n {},\n packageJson['devDependencies'] ?? {},\n packageJson['dependencies'] ?? {},\n );\n\n const deps = Object.keys(dependencies).sort();\n\n const depsVersions: Record<string, number> = deps.reduce(\n (depsVersions, depName) => {\n if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {\n const version = dependencies[depName] as string;\n const majorVersion = parseMajorVersion(version);\n if (majorVersion) {\n depsVersions[depName] = majorVersion;\n }\n }\n return depsVersions;\n },\n {} as Record<string, number>,\n );\n\n return { deps, depsVersions };\n}\n\nfunction findPackageJson(cwd: string, stopAt: string): string | undefined {\n let dirName = path.resolve(cwd);\n\n for (;;) {\n // Stop if we reach this dir\n if (path.normalize(dirName) === stopAt) {\n return undefined;\n }\n\n const jsonPath = path.join(dirName, 'package.json');\n if (fs.existsSync(jsonPath)) {\n return jsonPath;\n }\n\n const parentDirName = path.dirname(dirName);\n // We reached the file system root\n if (parentDirName === dirName) {\n return undefined;\n }\n\n dirName = parentDirName;\n }\n}\n\nfunction lookupPackageJson(cwd: string, stopAt: string): PackageJson | undefined {\n const jsonPath = findPackageJson(cwd, stopAt);\n\n if (!jsonPath) {\n return undefined;\n }\n\n try {\n const jsonStr = fs.readFileSync(jsonPath, 'utf8');\n const json = JSON.parse(jsonStr) as PackageJson;\n\n // Ensure it is an actual package.json\n // This is very much not bulletproof, but should be good enough\n if ('name' in json || 'private' in json) {\n return json;\n }\n } catch {\n // Ignore and walk up\n }\n\n // Continue up the tree, if we find a fitting package.json\n const newCwd = path.dirname(path.resolve(`${jsonPath}/..`));\n return lookupPackageJson(newCwd, stopAt);\n}\n\n/**\n * Deterministically hashes a string and turns the hash into a uuid.\n */\nexport function stringToUUID(str: string): string {\n const sha256Hash = crypto.createHash('sha256').update(str).digest('hex');\n\n // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)\n // RFC 4122 section 4.4\n const v4variant = ['8', '9', 'a', 'b'][sha256Hash.substring(16, 17).charCodeAt(0) % 4] as string;\n\n return `${sha256Hash.substring(0, 8)}-${sha256Hash.substring(8, 12)}-4${sha256Hash.substring(13, 16)}-${v4variant}${sha256Hash.substring(17, 20)}-${sha256Hash.substring(20, 32)}`.toLowerCase();\n}\n\nexport function gitRevision(): string | undefined {\n let gitRevision: string | undefined;\n try {\n gitRevision = childProcess\n .execSync('git rev-parse HEAD', { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })\n .toString()\n .trim();\n } catch {\n // noop\n }\n return gitRevision;\n}\n\n// Mirrors the CLI's `set-commits` fallback for builds without an `origin` remote. Vercel is left out\n// because the CLI only reads `VERCEL_GIT_*` on production builds.\nconst CI_REPOSITORY_ENV_VARS = [\n 'GITHUB_REPOSITORY',\n 'CI_PROJECT_PATH',\n 'BITBUCKET_REPO_FULL_NAME',\n 'RENDER_GIT_REPO_SLUG',\n 'RAILWAY_GIT_REPO_NAME',\n 'CIRCLE_PROJECT_REPONAME',\n 'BUILDKITE_REPO',\n 'BUILD_REPOSITORY_URI',\n] as const;\n\n/**\n * Whether commit association can find the repository: from the given git remote, or from CI variables.\n */\nexport function canAutoDetectRepository(remote = 'origin'): boolean {\n if (\n CI_REPOSITORY_ENV_VARS.some(name => process.env[name]) ||\n (process.env['NETLIFY'] && process.env['REPOSITORY_URL'])\n ) {\n return true;\n }\n try {\n childProcess.execFileSync('git', ['remote', 'get-url', remote], { stdio: 'ignore', windowsHide: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reads the `owner/repo` path of a git remote, e.g. `getsentry/sentry-javascript` for\n * `git@github.com:getsentry/sentry-javascript.git`.\n */\nexport function getGitRemoteRepository(remote: string): string | undefined {\n let url: string;\n try {\n url = childProcess\n .execFileSync('git', ['remote', 'get-url', remote], { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })\n .toString()\n .trim();\n } catch {\n return undefined;\n }\n\n let repoPath: string;\n try {\n repoPath = new URL(url).pathname;\n } catch {\n // scp-like syntax, `git@host:owner/repo.git`\n repoPath = url.slice(url.indexOf(':') + 1);\n }\n const repository = repoPath.replace(/^\\/+|\\/+$/g, '').replace(/\\.git$/, '');\n return repository.includes('/') ? repository : undefined;\n}\n\n/**\n * Tries to guess a release name based on environmental data.\n */\nexport function determineReleaseName(): string | undefined {\n return getReleaseFromCommitEnv(warnAboutPlaceholderCommitEnvVar) || gitRevision();\n}\n\n/**\n * Resolves the release name the way the bundler plugins do: the configured name, then the `SENTRY_RELEASE`\n * environment variable, then a name detected from CI environment variables or git.\n *\n * Framework SDKs that pass the release to the SDK at runtime use this to get the same name the plugin uses.\n */\nexport function resolveReleaseName(name?: string): string | undefined {\n return name ?? process.env['SENTRY_RELEASE'] ?? determineReleaseName();\n}\n\n// Release detection and commit association can read the same variable in one build.\nconst warnedPlaceholderEnvVars = new Set<string>();\n\nfunction warnAboutPlaceholderCommitEnvVar(name: string): void {\n if (warnedPlaceholderEnvVars.has(name)) {\n return;\n }\n warnedPlaceholderEnvVars.add(name);\n // This runs before the plugin logger exists, so `silent: true` does not suppress it. That is\n // deliberate: a warning that is easy to miss is how this misconfiguration went unnoticed.\n // eslint-disable-next-line no-console\n console.warn(\n `[@sentry/bundler-plugins] Ignoring the ${name} environment variable as a release name, because its value is its own name. Set the release explicitly, or fix the variable in your build environment.`,\n );\n}\n\n/**\n * Reads an environment variable that should hold a commit SHA, ignoring a value that is the\n * variable's own name. See `_INTERNAL_readCommitEnvVar` in `@sentry/core/server`.\n */\nexport function readCommitEnvVar(name: string): string | undefined {\n return readCoreCommitEnvVar(name, warnAboutPlaceholderCommitEnvVar);\n}\n\n/**\n * Generates code for the global injector which is responsible for setting the global\n * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.\n */\nexport function generateReleaseInjectorCode({\n release,\n injectBuildInformation,\n}: {\n release: string;\n injectBuildInformation: boolean;\n}): CodeInjection {\n let code = `e.SENTRY_RELEASE={id:${stringifyForCodeInjection(release)}};`;\n\n if (injectBuildInformation) {\n const buildInfo = getBuildInformation();\n\n code += `e.SENTRY_BUILD_INFO=${stringifyForCodeInjection(buildInfo)};`;\n }\n\n return new CodeInjection(code);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function generateModuleMetadataInjectorCode(metadata: any): CodeInjection {\n // We are merging the metadata objects in case modules are bundled twice with the plugin\n // Use try-catch to avoid issues when bundlers rename global variables like 'window' to 'k'\n return new CodeInjection(\n `e._sentryModuleMetadata=e._sentryModuleMetadata||{},e._sentryModuleMetadata[(new e.Error).stack]=function(e){for(var n=1;n<arguments.length;n++){var a=arguments[n];if(null!=a)for(var t in a)a.hasOwnProperty(t)&&(e[t]=a[t])}return e}({},e._sentryModuleMetadata[(new e.Error).stack],${stringifyForCodeInjection(\n metadata,\n )});`,\n );\n}\n\nexport function getBuildInformation(): {\n deps: string[];\n depsVersions: Record<string, number>;\n nodeVersion: number | undefined;\n} {\n const packageJson = getPackageJson();\n\n const { deps, depsVersions } = packageJson ? getDependencies(packageJson) : { deps: [], depsVersions: {} };\n\n return {\n deps,\n depsVersions,\n nodeVersion: parseMajorVersion(process.version),\n };\n}\n\nexport function stripQueryAndHashFromPath(path: string): string {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return path.split('?')[0]!.split('#')[0]!;\n}\n\nexport function replaceBooleanFlagsInCode(\n code: string,\n replacementValues: Record<string, boolean | undefined>,\n): { code: string; map: SourceMap } | null {\n const ms = new MagicString(code);\n\n Object.keys(replacementValues).forEach(key => {\n const value = replacementValues[key];\n\n if (typeof value === 'boolean') {\n ms.replaceAll(key, JSON.stringify(value));\n }\n });\n\n if (ms.hasChanged()) {\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: 'boundary' }),\n };\n }\n\n return null;\n}\n\n// https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks\nexport function getTurborepoEnvPassthroughWarning(envVarName: string): string {\n return process.env['TURBO_HASH']\n ? `\\nYou seem to be using Turborepo, did you forget to put ${envVarName} in \\`passThroughEnv\\`? https://turbo.build/repo/docs/reference/configuration#passthroughenv`\n : '';\n}\n\n/**\n * Gets the projects from the project option. This might be a single project or an array of projects.\n */\nexport function getProjects(project: string | string[] | undefined): string[] | undefined {\n if (Array.isArray(project)) {\n return project;\n }\n\n if (project) {\n return [project];\n }\n\n return undefined;\n}\n\n/**\n * Checks if a chunk contains only import/export statements and no substantial code.\n *\n * In Vite MPA (multi-page application) mode, HTML entry points create \"facade\" chunks\n * that only contain import statements to load shared modules. These should not have\n * Sentry code injected. However, in SPA mode, the main bundle also has an HTML facade\n * but contains substantial application code that SHOULD have debug IDs injected.\n *\n * @ref https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n * @ref https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/839\n */\nexport function containsOnlyImports(code: string): boolean {\n const codeWithoutImports = code\n // Remove side effect imports: import '/path'; or import \"./path\";\n // Using explicit negated character classes to avoid polynomial backtracking\n .replace(/^\\s*import\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove named/default imports: import x from '/path'; import { x } from '/path';\n .replace(/^\\s*import\\b[^'\"`\\n]*\\bfrom\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove re-exports: export * from '/path'; export { x } from '/path';\n .replace(/^\\s*export\\b[^'\"`\\n]*\\bfrom\\s+(?:'[^'\\n]*'|\"[^\"\\n]*\"|`[^`\\n]*`)[\\s;]*$/gm, '')\n // Remove block comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n // Remove line comments\n .replace(/\\/\\/.*$/gm, '')\n // Remove \"use strict\" directives\n .replace(/[\"']use strict[\"']\\s*;?/g, '')\n .trim();\n\n return codeWithoutImports.length === 0;\n}\n\nexport class CodeInjection {\n // The code below is mostly ternary operators because it saves bundle size.\n // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)\n private readonly header: string;\n private readonly footer: string;\n\n constructor(private body: string = '') {\n // `globalThis` is checked first so the other identifiers are never evaluated\n // where it exists. A downstream bundler that runs over an already-injected\n // chunk can turn a free `global` into a `const` it declares further down the\n // file (Nitro's node compat does this). Reading that binding from the top of\n // the file hits the temporal dead zone, and `typeof` throws there instead of\n // returning \"undefined\", so the whole injection was silently swallowed by the\n // `catch` below and the chunk registered no debug ID.\n this.header = `!function(){try{var e=\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{};`;\n this.footer = '}catch(e){}}();';\n }\n\n public code(): string {\n if (this.isEmpty()) {\n return '';\n }\n\n return this.header + this.body + this.footer;\n }\n\n public isEmpty(): boolean {\n return this.body.length === 0;\n }\n\n public append(code: CodeInjection | string): void {\n if (code instanceof CodeInjection) {\n this.body += code.body;\n } else {\n this.body += code;\n }\n }\n\n public clear(): void {\n this.body = '';\n }\n\n public clone(): CodeInjection {\n return new CodeInjection(this.body);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,SAAsB,YAA0B;CAC9D,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;;;;AAUA,SAAgB,eAAe,EAAE,KAAK,WAA8C,CAAC,GAA4B;CAC/G,OAAO,kBAAkB,OAAO,QAAQ,IAAI,GAAGA,KAAAA,QAAK,UAAU,UAAUC,GAAAA,QAAG,QAAQ,CAAC,CAAC;AACvF;AAEA,SAAgB,kBAAkB,KAAiC;CACjE,IAAI,UAAU;CAEd,IAAI,QAAQ,WAAW,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AAG,SAAS;EAClB,KAAK,GAAG,YAAY,EAAE,OAAO,WAAW,CAAC;CAC3C;CAGF,OAAO;AACT;AAGA,SAAgB,kCAAkC,YAA4B;CAC5E,OAAO,QAAQ,IAAI,gBACf,2DAA2D,WAAW,gGACtE;AACN;;;;AAKA,SAAgB,YAAY,SAA8D;CACxF,IAAI,MAAM,QAAQ,OAAO,GACvB,OAAO;CAGT,IAAI,SACF,OAAO,CAAC,OAAO;AAInB;;;;;;;;;;;;AAaA,SAAgB,oBAAoB,MAAuB;CAiBzD,OAhB2B,KAGxB,QAAQ,2DAA2D,EAAE,CAAC,CAEtE,QAAQ,4EAA4E,EAAE,CAAC,CAEvF,QAAQ,4EAA4E,EAAE,CAAC,CAEvF,QAAQ,qBAAqB,EAAE,CAAC,CAEhC,QAAQ,aAAa,EAAE,CAAC,CAExB,QAAQ,4BAA4B,EAAE,CAAC,CACvC,KAEqB,CAAC,CAAC,WAAW;AACvC;AAEA,IAAa,gBAAb,MAAa,cAAc;CAMzB,YAAoB,OAAe,IAAI;EAAnB,KAAA,OAAA;EAQlB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEO,OAAe;EACpB,IAAI,KAAK,QAAQ,GACf,OAAO;EAGT,OAAO,KAAK,SAAS,KAAK,OAAO,KAAK;CACxC;CAEO,UAAmB;EACxB,OAAO,KAAK,KAAK,WAAW;CAC9B;CAEO,OAAO,MAAoC;EAChD,IAAI,gBAAgB,eAClB,KAAK,QAAQ,KAAK;OAElB,KAAK,QAAQ;CAEjB;CAEO,QAAc;EACnB,KAAK,OAAO;CACd;CAEO,QAAuB;EAC5B,OAAO,IAAI,cAAc,KAAK,IAAI;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.17.0\";\n"],"mappings":";AAAA,MAAa,cAAc"}
|
|
@@ -276,7 +276,7 @@ async emitBundlerPluginExecutionSignal() {
|
|
|
276
276
|
if (options.release.setCommits !== false) try {
|
|
277
277
|
await cliInstance.setCommits(releaseName, options.release.setCommits);
|
|
278
278
|
} catch (e) {
|
|
279
|
-
if (options.release.setCommits && "shouldNotThrowOnFailure" in options.release.setCommits && options.release.setCommits.shouldNotThrowOnFailure) logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release
|
|
279
|
+
if (options.release.setCommits && "shouldNotThrowOnFailure" in options.release.setCommits && options.release.setCommits.shouldNotThrowOnFailure) logger.debug("An error occurred setting commits on release (this message can be ignored unless you want commits set on the release):", e);
|
|
280
280
|
else throw e;
|
|
281
281
|
}
|
|
282
282
|
if (options.release.finalize) await cliInstance.finalizeRelease(releaseName);
|
|
@@ -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 commits on release are desired):',\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;EACA,kBAAkB,aAAa;GAAE,UAAU;GAAO,wBAAwB,CAAC;EAAE;EAC7E,qBAAqB,aAAa;GA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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 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;CA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IAAI,oCACX,MAAM,GAAG,SAAS,QAAQ,KAAK,KAAK,GAAG,OAAO,GAAG,+BAA+B,CAAC;AAEtF;AAIA,SAAS,0BAA0B,SAA4B,WAAwD;CACrH,IAAI,CAAC,qBAAqB,OAAO,CAAC,CAAC,QACjC,OAAO;CAET,IAAI,MAAM,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"}
|
package/build/esm/core/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { arrayify, getProjects } from "./utils.js";
|
|
1
|
+
import { arrayify, getGitRemoteRepository, getProjects, gitRevision } from "./utils.js";
|
|
2
2
|
import _classPrivateMethodInitSpec from "../_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateMethodInitSpec.js";
|
|
3
3
|
import _classPrivateFieldInitSpec from "../_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateFieldInitSpec.js";
|
|
4
4
|
import _classPrivateFieldSet2 from "../_virtual/_@oxc-project_runtime@0.158.0/helpers/esm/classPrivateFieldSet2.js";
|
|
@@ -44,14 +44,21 @@ var SentryCliAdapter = class {
|
|
|
44
44
|
* Associate commits with a release. Translates the plugin's {@link SetCommitsOptions} `auto` /
|
|
45
45
|
* `repo`+`commit` union into the flags accepted by `sentry release set-commits`. The old CLI's
|
|
46
46
|
* `ignoreMissing`/`ignoreEmpty` toggles have no equivalent flag on the new CLI; the caller's
|
|
47
|
-
* `shouldNotThrowOnFailure` handling
|
|
47
|
+
* `shouldNotThrowOnFailure` handling swallows the failures, for example a build without a git checkout.
|
|
48
|
+
*
|
|
49
|
+
* `auto: true` runs `set-commits` without a mode flag, not with `--auto`. Without a flag, the CLI
|
|
50
|
+
* links commits through the repository integration and falls back to local git history when no
|
|
51
|
+
* integration matches the repository, as `--auto` of the old CLI did. The new `--auto` fails instead.
|
|
48
52
|
*/
|
|
49
53
|
async setCommits(name, setCommitsOptions) {
|
|
50
54
|
const { auto, repo, commit, previousCommit } = setCommitsOptions;
|
|
51
|
-
const
|
|
55
|
+
const { vcsRemote } = _classPrivateFieldGet2(_options, this).release;
|
|
56
|
+
const remoteRepo = auto === true && vcsRemote !== "origin" ? getGitRemoteRepository(vcsRemote) : void 0;
|
|
57
|
+
const head = remoteRepo ? gitRevision() : void 0;
|
|
58
|
+
const remoteCommitSpec = remoteRepo && head ? `${remoteRepo}@${head}` : void 0;
|
|
59
|
+
const commitSpec = repo && commit ? `${repo}@${previousCommit ? `${previousCommit}..${commit}` : commit}` : remoteCommitSpec;
|
|
52
60
|
await _classPrivateFieldGet2(_sdk, this).release["set-commits"]({
|
|
53
61
|
orgVersion: name,
|
|
54
|
-
auto: auto === true,
|
|
55
62
|
commit: commitSpec
|
|
56
63
|
});
|
|
57
64
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../../../src/core/cli.ts"],"sourcesContent":["import { createSentrySDK } from 'sentry';\nimport type { NormalizedOptions } from './options-mapping';\nimport type { SetCommitsOptions } from './types';\nimport { arrayify, getProjects } from './utils';\n\ntype SentrySDK = ReturnType<typeof createSentrySDK>;\ntype SentryOptions = NonNullable<Parameters<typeof createSentrySDK>[0]>;\n\n/**\n * The CLI accepts `headers` since 0.44.0, but its bundled type declarations do not list the\n * option yet.\n * TODO: Drop once `SentryOptions` in the `sentry` package declares `headers`: https://github.com/getsentry/cli/pull/1500\n */\ntype SentryOptionsWithHeaders = SentryOptions & { headers?: Record<string, string> };\n\n/** Comma-joined list of ignore globs, or `undefined` when nothing should be ignored. */\nfunction serializeIgnore(ignore: string | string[] | undefined): string | undefined {\n if (!ignore) {\n return undefined;\n }\n const patterns = arrayify(ignore);\n return patterns.length > 0 ? patterns.join(',') : undefined;\n}\n\n/** A single sourcemap directory to upload plus the flags that apply to it. */\ninterface UploadTarget {\n directory: string;\n dist?: string;\n ext?: string[];\n ignore?: string | string[];\n ignoreFile?: string;\n urlPrefix?: string;\n}\n\n/**\n * Thin wrapper around the Sentry CLI's programmatic SDK. The bundler plugin used to drive the\n * old `@sentry/cli` binary through a `SentryCli` class; the new CLI exposes typed methods via\n * `createSentrySDK()` instead. This adapter maps the plugin's structured option shapes onto\n * those methods and keeps all translation logic in one place.\n */\nexport class SentryCliAdapter {\n readonly #options: NormalizedOptions;\n /** Client for every command that is not scoped to a specific project. */\n readonly #sdk: SentrySDK;\n\n public constructor(options: NormalizedOptions) {\n this.#options = options;\n this.#sdk = this.#createClient();\n }\n\n /**\n * The CLI binds `org`/`project`/`url` when the client is created rather than per call, so a\n * client scoped to a different project needs to be a different client.\n *\n * Creating one is free: it reads no config and opens no connection, it only closes over these\n * options. Everything happens when a command is actually invoked.\n */\n #createClient(project?: string): SentrySDK {\n const options: SentryOptionsWithHeaders = {\n token: this.#options.authToken,\n org: this.#options.org,\n project,\n url: this.#options.url,\n headers: this.#options.headers,\n };\n\n return createSentrySDK(options);\n }\n\n /** Create a release and associate it with the configured project(s). */\n public async createRelease(name: string): Promise<unknown> {\n // Sentry rejects a release without projects, and the unscoped client carries none.\n return this.#sdk.release.create({ orgVersion: name, project: getProjects(this.#options.project)?.join(',') });\n }\n\n /** Finalize a release by stamping an end timestamp. */\n public async finalizeRelease(name: string): Promise<void> {\n await this.#sdk.release.finalize({ orgVersion: name });\n }\n\n /**\n * Associate commits with a release. Translates the plugin's {@link SetCommitsOptions} `auto` /\n * `repo`+`commit` union into the flags accepted by `sentry release set-commits`. The old CLI's\n * `ignoreMissing`/`ignoreEmpty` toggles have no equivalent flag on the new CLI; the caller's\n * `shouldNotThrowOnFailure` handling still swallows the \"no repository\" failure case.\n */\n public async setCommits(name: string, setCommitsOptions: SetCommitsOptions): Promise<void> {\n const { auto, repo, commit, previousCommit } = setCommitsOptions;\n\n // Manual mode is expressed as `REPO@SHA` (optionally `REPO@PREV..SHA`).\n const commitSpec =\n repo && commit ? `${repo}@${previousCommit ? `${previousCommit}..${commit}` : commit}` : undefined;\n\n await this.#sdk.release['set-commits']({\n orgVersion: name,\n auto: auto === true,\n commit: commitSpec,\n });\n }\n\n /** Create a deploy for a release. */\n public async newDeploy(name: string, deploy: NonNullable<NormalizedOptions['release']['deploy']>): Promise<void> {\n if (deploy === false) {\n return;\n }\n\n await this.#sdk.release.deploy({\n orgVersion: name,\n environment: deploy.env,\n name: deploy.name,\n url: deploy.url,\n started: deploy.started !== undefined ? String(deploy.started) : undefined,\n finished: deploy.finished !== undefined ? String(deploy.finished) : undefined,\n time: deploy.time !== undefined ? String(deploy.time) : undefined,\n });\n }\n\n /**\n * Upload sourcemaps for one or more directories. The old CLI accepted a structured `include`\n * array; the new `sourcemap upload` command takes a single directory, so we upload each target\n * separately. A client is created per project because project selection is bound at client\n * creation time.\n *\n * Empty directories must not abort the loop: `@sentry/nextjs` uploads `.next/server` first, and\n * a server build without source maps would otherwise skip every client directory after it.\n *\n * @returns The directories that had no source maps to upload.\n */\n public async uploadSourcemaps(name: string, targets: UploadTarget[]): Promise<string[]> {\n const projects = getProjects(this.#options.project) ?? [undefined];\n const emptyDirectories = new Set<string>();\n\n for (const project of projects) {\n const sdk = this.#createClient(project);\n for (const target of targets) {\n const result = (await sdk.sourcemap.upload({\n directory: target.directory,\n release: name,\n dist: target.dist ?? this.#options.release.dist,\n ext: target.ext?.join(','),\n ignore: serializeIgnore(target.ignore),\n ignoreFile: target.ignoreFile,\n urlPrefix: target.urlPrefix,\n allowEmpty: true,\n })) as { filesUploaded?: number } | undefined;\n if (result?.filesUploaded === 0) {\n emptyDirectories.add(target.directory);\n }\n }\n }\n\n return [...emptyDirectories];\n }\n\n /** Inject debug IDs into the given build artifacts. */\n public async injectDebugIds(directories: string[], ignore: string | string[] | undefined): Promise<void> {\n // Preserve the previous CLI's default of ignoring `node_modules` when nothing else is configured.\n const serializedIgnore = serializeIgnore(ignore) ?? 'node_modules';\n for (const directory of directories) {\n await this.#sdk.sourcemap.inject({ directory, ignore: serializedIgnore });\n }\n }\n\n /**\n * Resolve the Sentry server URL the CLI is configured to talk to. Used by the telemetry guard\n * to decide whether the current build targets Sentry SaaS. Returns `undefined` on error.\n */\n public async getServerUrl(): Promise<string | undefined> {\n try {\n const info = (await this.#sdk.run('info')) as { config?: { url?: string } };\n return info.config?.url;\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,SAAS,gBAAgB,QAA2D;CAClF,IAAI,CAAC,QACH;CAEF,MAAM,WAAW,SAAS,MAAM;CAChC,OAAO,SAAS,SAAS,IAAI,SAAS,KAAK,GAAG,IAAI,KAAA;AACpD;;;;;;;;;;AAkBA,IAAa,mBAAb,MAA8B;CAKrB,YAAY,SAA4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cli.ts"],"sourcesContent":["import { createSentrySDK } from 'sentry';\nimport type { NormalizedOptions } from './options-mapping';\nimport type { SetCommitsOptions } from './types';\nimport { arrayify, getGitRemoteRepository, getProjects, gitRevision } from './utils';\n\ntype SentrySDK = ReturnType<typeof createSentrySDK>;\ntype SentryOptions = NonNullable<Parameters<typeof createSentrySDK>[0]>;\n\n/**\n * The CLI accepts `headers` since 0.44.0, but its bundled type declarations do not list the\n * option yet.\n * TODO: Drop once `SentryOptions` in the `sentry` package declares `headers`: https://github.com/getsentry/cli/pull/1500\n */\ntype SentryOptionsWithHeaders = SentryOptions & { headers?: Record<string, string> };\n\n/** Comma-joined list of ignore globs, or `undefined` when nothing should be ignored. */\nfunction serializeIgnore(ignore: string | string[] | undefined): string | undefined {\n if (!ignore) {\n return undefined;\n }\n const patterns = arrayify(ignore);\n return patterns.length > 0 ? patterns.join(',') : undefined;\n}\n\n/** A single sourcemap directory to upload plus the flags that apply to it. */\ninterface UploadTarget {\n directory: string;\n dist?: string;\n ext?: string[];\n ignore?: string | string[];\n ignoreFile?: string;\n urlPrefix?: string;\n}\n\n/**\n * Thin wrapper around the Sentry CLI's programmatic SDK. The bundler plugin used to drive the\n * old `@sentry/cli` binary through a `SentryCli` class; the new CLI exposes typed methods via\n * `createSentrySDK()` instead. This adapter maps the plugin's structured option shapes onto\n * those methods and keeps all translation logic in one place.\n */\nexport class SentryCliAdapter {\n readonly #options: NormalizedOptions;\n /** Client for every command that is not scoped to a specific project. */\n readonly #sdk: SentrySDK;\n\n public constructor(options: NormalizedOptions) {\n this.#options = options;\n this.#sdk = this.#createClient();\n }\n\n /**\n * The CLI binds `org`/`project`/`url` when the client is created rather than per call, so a\n * client scoped to a different project needs to be a different client.\n *\n * Creating one is free: it reads no config and opens no connection, it only closes over these\n * options. Everything happens when a command is actually invoked.\n */\n #createClient(project?: string): SentrySDK {\n const options: SentryOptionsWithHeaders = {\n token: this.#options.authToken,\n org: this.#options.org,\n project,\n url: this.#options.url,\n headers: this.#options.headers,\n };\n\n return createSentrySDK(options);\n }\n\n /** Create a release and associate it with the configured project(s). */\n public async createRelease(name: string): Promise<unknown> {\n // Sentry rejects a release without projects, and the unscoped client carries none.\n return this.#sdk.release.create({ orgVersion: name, project: getProjects(this.#options.project)?.join(',') });\n }\n\n /** Finalize a release by stamping an end timestamp. */\n public async finalizeRelease(name: string): Promise<void> {\n await this.#sdk.release.finalize({ orgVersion: name });\n }\n\n /**\n * Associate commits with a release. Translates the plugin's {@link SetCommitsOptions} `auto` /\n * `repo`+`commit` union into the flags accepted by `sentry release set-commits`. The old CLI's\n * `ignoreMissing`/`ignoreEmpty` toggles have no equivalent flag on the new CLI; the caller's\n * `shouldNotThrowOnFailure` handling swallows the failures, for example a build without a git checkout.\n *\n * `auto: true` runs `set-commits` without a mode flag, not with `--auto`. Without a flag, the CLI\n * links commits through the repository integration and falls back to local git history when no\n * integration matches the repository, as `--auto` of the old CLI did. The new `--auto` fails instead.\n */\n public async setCommits(name: string, setCommitsOptions: SetCommitsOptions): Promise<void> {\n const { auto, repo, commit, previousCommit } = setCommitsOptions;\n const { vcsRemote } = this.#options.release;\n\n // The CLI only reads the `origin` remote, so other remotes go through manual mode. CI checkouts\n // often lack the named remote; the CLI then still finds the repository from CI variables.\n const remoteRepo = auto === true && vcsRemote !== 'origin' ? getGitRemoteRepository(vcsRemote) : undefined;\n const head = remoteRepo ? gitRevision() : undefined;\n const remoteCommitSpec = remoteRepo && head ? `${remoteRepo}@${head}` : undefined;\n\n // Manual mode is expressed as `REPO@SHA` (optionally `REPO@PREV..SHA`).\n const commitSpec =\n repo && commit ? `${repo}@${previousCommit ? `${previousCommit}..${commit}` : commit}` : remoteCommitSpec;\n\n await this.#sdk.release['set-commits']({\n orgVersion: name,\n commit: commitSpec,\n });\n }\n\n /** Create a deploy for a release. */\n public async newDeploy(name: string, deploy: NonNullable<NormalizedOptions['release']['deploy']>): Promise<void> {\n if (deploy === false) {\n return;\n }\n\n await this.#sdk.release.deploy({\n orgVersion: name,\n environment: deploy.env,\n name: deploy.name,\n url: deploy.url,\n started: deploy.started !== undefined ? String(deploy.started) : undefined,\n finished: deploy.finished !== undefined ? String(deploy.finished) : undefined,\n time: deploy.time !== undefined ? String(deploy.time) : undefined,\n });\n }\n\n /**\n * Upload sourcemaps for one or more directories. The old CLI accepted a structured `include`\n * array; the new `sourcemap upload` command takes a single directory, so we upload each target\n * separately. A client is created per project because project selection is bound at client\n * creation time.\n *\n * Empty directories must not abort the loop: `@sentry/nextjs` uploads `.next/server` first, and\n * a server build without source maps would otherwise skip every client directory after it.\n *\n * @returns The directories that had no source maps to upload.\n */\n public async uploadSourcemaps(name: string, targets: UploadTarget[]): Promise<string[]> {\n const projects = getProjects(this.#options.project) ?? [undefined];\n const emptyDirectories = new Set<string>();\n\n for (const project of projects) {\n const sdk = this.#createClient(project);\n for (const target of targets) {\n const result = (await sdk.sourcemap.upload({\n directory: target.directory,\n release: name,\n dist: target.dist ?? this.#options.release.dist,\n ext: target.ext?.join(','),\n ignore: serializeIgnore(target.ignore),\n ignoreFile: target.ignoreFile,\n urlPrefix: target.urlPrefix,\n allowEmpty: true,\n })) as { filesUploaded?: number } | undefined;\n if (result?.filesUploaded === 0) {\n emptyDirectories.add(target.directory);\n }\n }\n }\n\n return [...emptyDirectories];\n }\n\n /** Inject debug IDs into the given build artifacts. */\n public async injectDebugIds(directories: string[], ignore: string | string[] | undefined): Promise<void> {\n // Preserve the previous CLI's default of ignoring `node_modules` when nothing else is configured.\n const serializedIgnore = serializeIgnore(ignore) ?? 'node_modules';\n for (const directory of directories) {\n await this.#sdk.sourcemap.inject({ directory, ignore: serializedIgnore });\n }\n }\n\n /**\n * Resolve the Sentry server URL the CLI is configured to talk to. Used by the telemetry guard\n * to decide whether the current build targets Sentry SaaS. Returns `undefined` on error.\n */\n public async getServerUrl(): Promise<string | undefined> {\n try {\n const info = (await this.#sdk.run('info')) as { config?: { url?: string } };\n return info.config?.url;\n } catch {\n return undefined;\n }\n }\n}\n"],"m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AEF,QAAO,MAAA,uBAAA,MADa,IAAA,CAAA,CAAU,IAAI,MAAM,EAAA,CAC5B,QAAQ;EACtB,QAAQ;GACN;EACF;CACF;AACF;;;;;;;;AAhIE,SAAA,cAAc,SAA6B;CACzC,MAAM,UAAoC;EACxC,OAAA,uBAAA,UAAO,IAAA,CAAA,CAAc;EACrB,KAAA,uBAAA,UAAK,IAAA,CAAA,CAAc;EACnB;EACA,KAAA,uBAAA,UAAK,IAAA,CAAA,CAAc;EACnB,SAAA,uBAAA,UAAS,IAAA,CAAA,CAAc;CACzB;CAEA,OAAO,gBAAgB,OAAO;AAChC"}
|
|
@@ -45,7 +45,7 @@ function normalizeUserOptions(userOptions) {
|
|
|
45
45
|
ignoreEmpty: true,
|
|
46
46
|
ignoreMissing: true
|
|
47
47
|
};
|
|
48
|
-
else if (process.env["VERCEL"] && vercelEnv !== "production" && !canAutoDetectRepository()) options.release.setCommits = false;
|
|
48
|
+
else if (process.env["VERCEL"] && vercelEnv !== "production" && !canAutoDetectRepository(options.release.vcsRemote)) options.release.setCommits = false;
|
|
49
49
|
else options.release.setCommits = {
|
|
50
50
|
shouldNotThrowOnFailure: true,
|
|
51
51
|
auto: true,
|
|
@@ -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 (process.env['VERCEL'] && vercelEnv !== 'production' && !canAutoDetectRepository()) {\n // Vercel's own builders have no git remote and no other CI variables, so `--auto` can only fail there.\n // Builds that have either, such as `vercel build` in GitHub Actions, keep `--auto` 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,iBA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ChC,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"}
|
|
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;EACpC,SAAS,YAAY;EACrB,OAAO,YAAY,SAAS;EAC5B,QAAQ,YAAY,UAAU;EAC9B,cAAc,YAAY;EAC1B,WAAW,YAAY,aAAa;EACpC,SAAS,YAAY,WAAW;EAChC,YAAY,YAAY;EACxB,SAAS;GACP,GAAG,YAAY;GACf,MAAM,mBAAmB,YAAY,SAAS,IAAI;GAClD,QAAQ,YAAY,SAAS,UAAU;GACvC,QAAQ,YAAY,SAAS,UAAU;GACvC,UAAU,YAAY,S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