@sentry/bundler-plugin-core 3.2.3 → 3.3.0-alpha.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/dist/cjs/index.js CHANGED
@@ -2,23 +2,23 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var SentryCli = require('@sentry/cli');
6
5
  var core = require('@babel/core');
7
6
  var componentNameAnnotatePlugin = require('@sentry/babel-plugin-component-annotate');
7
+ var SentryCli = require('@sentry/cli');
8
8
  var fs = require('fs');
9
- var path = require('path');
9
+ var glob = require('glob');
10
10
  var MagicString = require('magic-string');
11
+ var path = require('path');
11
12
  var unplugin = require('unplugin');
12
- var findUp = require('find-up');
13
+ var dotenv = require('dotenv');
13
14
  var os = require('os');
15
+ var findUp = require('find-up');
14
16
  var crypto = require('crypto');
15
17
  var childProcess = require('child_process');
16
- var glob = require('glob');
17
- var util = require('util');
18
18
  var https = require('node:https');
19
19
  var node_stream = require('node:stream');
20
20
  var node_zlib = require('node:zlib');
21
- var dotenv = require('dotenv');
21
+ var util = require('util');
22
22
 
23
23
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
24
 
@@ -40,20 +40,21 @@ function _interopNamespace(e) {
40
40
  return Object.freeze(n);
41
41
  }
42
42
 
43
- var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
44
43
  var componentNameAnnotatePlugin__default = /*#__PURE__*/_interopDefaultLegacy(componentNameAnnotatePlugin);
44
+ var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
45
45
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
46
46
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
47
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
47
48
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
48
49
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
49
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
50
- var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
50
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
51
51
  var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
52
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
53
+ var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
52
54
  var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
53
55
  var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
54
- var util__namespace = /*#__PURE__*/_interopNamespace(util);
55
56
  var https__namespace = /*#__PURE__*/_interopNamespace(https);
56
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
57
+ var util__namespace = /*#__PURE__*/_interopNamespace(util);
57
58
 
58
59
  function ownKeys(object, enumerableOnly) {
59
60
  var keys = Object.keys(object);
@@ -445,555 +446,168 @@ function _toPropertyKey(arg) {
445
446
  return typeof key === "symbol" ? key : String(key);
446
447
  }
447
448
 
449
+ // eslint-disable-next-line @typescript-eslint/unbound-method
450
+ const objectToString = Object.prototype.toString;
451
+
448
452
  /**
449
- * Checks whether the given input is already an array, and if it isn't, wraps it in one.
453
+ * Checks whether given value's type is one of a few Error or Error-like
454
+ * {@link isError}.
450
455
  *
451
- * @param maybeArray Input to turn into an array, if necessary
452
- * @returns The input, if already an array, or an array with the input as the only element, if not
456
+ * @param wat A value to be checked.
457
+ * @returns A boolean representing the result.
453
458
  */
454
- function arrayify$1(maybeArray) {
455
- return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
459
+ function isError(wat) {
460
+ switch (objectToString.call(wat)) {
461
+ case '[object Error]':
462
+ case '[object Exception]':
463
+ case '[object DOMException]':
464
+ return true;
465
+ default:
466
+ return isInstanceOf(wat, Error);
467
+ }
456
468
  }
457
469
  /**
458
- * Get the closes package.json from a given starting point upwards.
459
- * This handles a few edge cases:
460
- * * Check if a given file package.json appears to be an actual NPM package.json file
461
- * * Stop at the home dir, to avoid looking too deeply
470
+ * Checks whether given value is an instance of the given built-in class.
471
+ *
472
+ * @param wat The value to be checked
473
+ * @param className
474
+ * @returns A boolean representing the result.
462
475
  */
463
- function getPackageJson() {
464
- var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
465
- cwd = _ref.cwd,
466
- stopAt = _ref.stopAt;
467
- return lookupPackageJson(cwd !== null && cwd !== void 0 ? cwd : process.cwd(), path__default["default"].normalize(stopAt !== null && stopAt !== void 0 ? stopAt : os__default["default"].homedir()));
476
+ function isBuiltin(wat, className) {
477
+ return objectToString.call(wat) === `[object ${className}]`;
468
478
  }
469
- function parseMajorVersion(version) {
470
- // if it has a `v` prefix, remove it
471
- if (version.startsWith("v")) {
472
- version = version.slice(1);
473
- }
474
479
 
475
- // First, try simple lookup of exact, ~ and ^ versions
476
- var regex = /^[\^~]?(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
477
- var match = version.match(regex);
478
- if (match) {
479
- return parseInt(match[1], 10);
480
- }
481
-
482
- // Try to parse e.g. 1.x
483
- var coerced = parseInt(version, 10);
484
- if (!Number.isNaN(coerced)) {
485
- return coerced;
486
- }
487
-
488
- // Match <= and >= ranges.
489
- var gteLteRegex = /^[<>]=\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
490
- var gteLteMatch = version.match(gteLteRegex);
491
- if (gteLteMatch) {
492
- return parseInt(gteLteMatch[1], 10);
493
- }
494
-
495
- // match < ranges
496
- var ltRegex = /^<\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
497
- var ltMatch = version.match(ltRegex);
498
- if (ltMatch) {
499
- // Two scenarios:
500
- // a) < 2.0.0 --> return 1
501
- // b) < 2.1.0 --> return 2
502
-
503
- var major = parseInt(ltMatch[1], 10);
504
- if (
505
- // minor version > 0
506
- typeof ltMatch[2] === "string" && parseInt(ltMatch[2].slice(1), 10) > 0 ||
507
- // patch version > 0
508
- typeof ltMatch[3] === "string" && parseInt(ltMatch[3].slice(1), 10) > 0) {
509
- return major;
510
- }
511
- return major - 1;
512
- }
513
-
514
- // match > ranges
515
- var gtRegex = /^>\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
516
- var gtMatch = version.match(gtRegex);
517
- if (gtMatch) {
518
- // We always return the version here, even though it _may_ be incorrect
519
- // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3
520
- // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists
521
- return parseInt(gtMatch[1], 10);
522
- }
523
- return undefined;
480
+ /**
481
+ * Checks whether given value's type is ErrorEvent
482
+ * {@link isErrorEvent}.
483
+ *
484
+ * @param wat A value to be checked.
485
+ * @returns A boolean representing the result.
486
+ */
487
+ function isErrorEvent$1(wat) {
488
+ return isBuiltin(wat, 'ErrorEvent');
524
489
  }
525
490
 
526
- // This is an explicit list of packages where we want to include the (major) version number.
527
- var PACKAGES_TO_INCLUDE_VERSION = ["react", "@angular/core", "vue", "ember-source", "svelte", "@sveltejs/kit", "webpack", "vite", "gatsby", "next", "remix", "rollup", "esbuild"];
528
- function getDependencies(packageJson) {
529
- var _packageJson$devDepen, _packageJson$dependen;
530
- var dependencies = Object.assign({}, (_packageJson$devDepen = packageJson["devDependencies"]) !== null && _packageJson$devDepen !== void 0 ? _packageJson$devDepen : {}, (_packageJson$dependen = packageJson["dependencies"]) !== null && _packageJson$dependen !== void 0 ? _packageJson$dependen : {});
531
- var deps = Object.keys(dependencies).sort();
532
- var depsVersions = deps.reduce(function (depsVersions, depName) {
533
- if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {
534
- var version = dependencies[depName];
535
- var majorVersion = parseMajorVersion(version);
536
- if (majorVersion) {
537
- depsVersions[depName] = majorVersion;
538
- }
539
- }
540
- return depsVersions;
541
- }, {});
542
- return {
543
- deps: deps,
544
- depsVersions: depsVersions
545
- };
491
+ /**
492
+ * Checks whether given value's type is a string
493
+ * {@link isString}.
494
+ *
495
+ * @param wat A value to be checked.
496
+ * @returns A boolean representing the result.
497
+ */
498
+ function isString(wat) {
499
+ return isBuiltin(wat, 'String');
546
500
  }
547
- function lookupPackageJson(cwd, stopAt) {
548
- var jsonPath = findUp__default["default"].sync(function (dirName) {
549
- // Stop if we reach this dir
550
- if (path__default["default"].normalize(dirName) === stopAt) {
551
- return findUp__default["default"].stop;
552
- }
553
- return findUp__default["default"].sync.exists(dirName + "/package.json") ? "package.json" : undefined;
554
- }, {
555
- cwd: cwd
556
- });
557
- if (!jsonPath) {
558
- return undefined;
559
- }
560
- try {
561
- var jsonStr = fs__default["default"].readFileSync(jsonPath, "utf8");
562
- var json = JSON.parse(jsonStr);
563
-
564
- // Ensure it is an actual package.json
565
- // This is very much not bulletproof, but should be good enough
566
- if ("name" in json || "private" in json) {
567
- return json;
568
- }
569
- } catch (error) {
570
- // Ignore and walk up
571
- }
572
501
 
573
- // Continue up the tree, if we find a fitting package.json
574
- var newCwd = path__default["default"].dirname(path__default["default"].resolve(jsonPath + "/.."));
575
- return lookupPackageJson(newCwd, stopAt);
502
+ /**
503
+ * Checks whether given string is parameterized
504
+ * {@link isParameterizedString}.
505
+ *
506
+ * @param wat A value to be checked.
507
+ * @returns A boolean representing the result.
508
+ */
509
+ function isParameterizedString(wat) {
510
+ return (
511
+ typeof wat === 'object' &&
512
+ wat !== null &&
513
+ '__sentry_template_string__' in wat &&
514
+ '__sentry_template_values__' in wat
515
+ );
576
516
  }
577
517
 
578
518
  /**
579
- * Deterministically hashes a string and turns the hash into a uuid.
519
+ * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
520
+ * {@link isPrimitive}.
521
+ *
522
+ * @param wat A value to be checked.
523
+ * @returns A boolean representing the result.
580
524
  */
581
- function stringToUUID(str) {
582
- var sha256Hash = crypto__default["default"].createHash("sha256").update(str).digest("hex");
525
+ function isPrimitive(wat) {
526
+ return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
527
+ }
583
528
 
584
- // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)
585
- // RFC 4122 section 4.4
586
- var v4variant = ["8", "9", "a", "b"][sha256Hash.substring(16, 17).charCodeAt(0) % 4];
587
- return (sha256Hash.substring(0, 8) + "-" + sha256Hash.substring(8, 12) + "-4" + sha256Hash.substring(13, 16) + "-" + v4variant + sha256Hash.substring(17, 20) + "-" + sha256Hash.substring(20, 32)).toLowerCase();
529
+ /**
530
+ * Checks whether given value's type is an object literal, or a class instance.
531
+ * {@link isPlainObject}.
532
+ *
533
+ * @param wat A value to be checked.
534
+ * @returns A boolean representing the result.
535
+ */
536
+ function isPlainObject(wat) {
537
+ return isBuiltin(wat, 'Object');
588
538
  }
589
- function gitRevision() {
590
- var gitRevision;
591
- try {
592
- gitRevision = childProcess__default["default"].execSync("git rev-parse HEAD", {
593
- stdio: ["ignore", "pipe", "ignore"]
594
- }).toString().trim();
595
- } catch (e) {
596
- // noop
597
- }
598
- return gitRevision;
539
+
540
+ /**
541
+ * Checks whether given value's type is an Event instance
542
+ * {@link isEvent}.
543
+ *
544
+ * @param wat A value to be checked.
545
+ * @returns A boolean representing the result.
546
+ */
547
+ function isEvent(wat) {
548
+ return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
599
549
  }
600
550
 
601
551
  /**
602
- * Tries to guess a release name based on environmental data.
552
+ * Checks whether given value's type is an Element instance
553
+ * {@link isElement}.
554
+ *
555
+ * @param wat A value to be checked.
556
+ * @returns A boolean representing the result.
603
557
  */
604
- function determineReleaseName() {
605
- // This list is in approximate alpha order, separated into 3 categories:
606
- // 1. Git providers
607
- // 2. CI providers with specific environment variables (has the provider name in the variable name)
608
- // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)
609
-
610
- var possibleReleaseNameOfGitProvider =
611
- // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
612
- process.env["GITHUB_SHA"] ||
613
- // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
614
- process.env["CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"] || process.env["CI_BUILD_REF"] || process.env["CI_COMMIT_SHA"] ||
615
- // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/
616
- process.env["BITBUCKET_COMMIT"];
617
- var possibleReleaseNameOfCiProvidersWithSpecificEnvVar =
618
- // AppVeyor - https://www.appveyor.com/docs/environment-variables/
619
- process.env["APPVEYOR_PULL_REQUEST_HEAD_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"] ||
620
- // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
621
- process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] ||
622
- // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
623
- process.env["AWS_COMMIT_ID"] ||
624
- // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
625
- process.env["BUILD_SOURCEVERSION"] ||
626
- // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/
627
- process.env["GIT_CLONE_COMMIT_HASH"] ||
628
- // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables
629
- process.env["BUDDY_EXECUTION_REVISION"] ||
630
- // Builtkite - https://buildkite.com/docs/pipelines/environment-variables
631
- process.env["BUILDKITE_COMMIT"] ||
632
- // CircleCI - https://circleci.com/docs/variables/
633
- process.env["CIRCLE_SHA1"] ||
634
- // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables
635
- process.env["CIRRUS_CHANGE_IN_REPO"] ||
636
- // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/
637
- process.env["CF_REVISION"] ||
638
- // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/
639
- process.env["CM_COMMIT"] ||
640
- // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
641
- process.env["CF_PAGES_COMMIT_SHA"] ||
642
- // Drone - https://docs.drone.io/pipeline/environment/reference/
643
- process.env["DRONE_COMMIT_SHA"] ||
644
- // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables
645
- process.env["FC_GIT_COMMIT_SHA"] ||
646
- // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci
647
- process.env["HEROKU_TEST_RUN_COMMIT_VERSION"] ||
648
- // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases
649
- process.env["HEROKU_SLUG_COMMIT"] ||
650
- // Railway - https://docs.railway.app/reference/variables#git-variables
651
- process.env["RAILWAY_GIT_COMMIT_SHA"] ||
652
- // Render - https://render.com/docs/environment-variables
653
- process.env["RENDER_GIT_COMMIT"] ||
654
- // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables
655
- process.env["SEMAPHORE_GIT_SHA"] ||
656
- // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
657
- process.env["TRAVIS_PULL_REQUEST_SHA"] ||
658
- // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
659
- process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] ||
660
- // Zeit (now known as Vercel)
661
- process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"];
662
- var possibleReleaseNameOfCiProvidersWithGenericEnvVar =
663
- // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables
664
- process.env["CI_COMMIT_ID"] ||
665
- // Coolify - https://coolify.io/docs/knowledge-base/environment-variables
666
- process.env["SOURCE_COMMIT"] ||
667
- // Heroku #3 https://devcenter.heroku.com/changelog-items/630
668
- process.env["SOURCE_VERSION"] ||
669
- // Jenkins - https://plugins.jenkins.io/git/#environment-variables
670
- process.env["GIT_COMMIT"] ||
671
- // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
672
- process.env["COMMIT_REF"] ||
673
- // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html
674
- process.env["BUILD_VCS_NUMBER"] ||
675
- // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment
676
- process.env["CI_COMMIT_SHA"];
677
- return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || gitRevision();
678
- }
558
+ function isElement(wat) {
559
+ return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
560
+ }
679
561
 
680
562
  /**
681
- * Generates code for the global injector which is responsible for setting the global
682
- * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
563
+ * Checks whether given value has a then function.
564
+ * @param wat A value to be checked.
683
565
  */
684
- function generateGlobalInjectorCode(_ref2) {
685
- var release = _ref2.release,
686
- injectBuildInformation = _ref2.injectBuildInformation;
687
- // The code below is mostly ternary operators because it saves bundle size.
688
- // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
689
- var code = "{\n let _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof globalThis !== 'undefined' ?\n globalThis :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:".concat(JSON.stringify(release), "};");
690
- if (injectBuildInformation) {
691
- var buildInfo = getBuildInformation$1();
692
- code += "\n _global.SENTRY_BUILD_INFO=".concat(JSON.stringify(buildInfo), ";");
693
- }
694
- code += "}";
695
- return code;
696
- }
697
-
698
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
699
- function generateModuleMetadataInjectorCode(metadata) {
700
- // The code below is mostly ternary operators because it saves bundle size.
701
- // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
702
- // We are merging the metadata objects in case modules are bundled twice with the plugin
703
- return "{\n let _sentryModuleMetadataGlobal =\n typeof window !== \"undefined\"\n ? window\n : typeof global !== \"undefined\"\n ? global\n : typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata =\n _sentryModuleMetadataGlobal._sentryModuleMetadata || {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack] =\n Object.assign(\n {},\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack],\n ".concat(JSON.stringify(metadata), "\n );\n}");
704
- }
705
- function getBuildInformation$1() {
706
- var packageJson = getPackageJson();
707
- var _ref3 = packageJson ? getDependencies(packageJson) : {
708
- deps: [],
709
- depsVersions: {}
710
- },
711
- deps = _ref3.deps,
712
- depsVersions = _ref3.depsVersions;
713
- return {
714
- deps: deps,
715
- depsVersions: depsVersions,
716
- nodeVersion: parseMajorVersion(process.version)
717
- };
718
- }
719
- function stripQueryAndHashFromPath(path) {
720
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
721
- return path.split("?")[0].split("#")[0];
722
- }
723
- function replaceBooleanFlagsInCode(code, replacementValues) {
724
- var ms = new MagicString__default["default"](code);
725
- Object.keys(replacementValues).forEach(function (key) {
726
- var value = replacementValues[key];
727
- if (typeof value === "boolean") {
728
- ms.replaceAll(key, JSON.stringify(value));
729
- }
730
- });
731
- if (ms.hasChanged()) {
732
- return {
733
- code: ms.toString(),
734
- map: ms.generateMap({
735
- hires: "boundary"
736
- })
737
- };
738
- }
739
- return null;
740
- }
741
-
742
- var SENTRY_SAAS_URL = "https://sentry.io";
743
- function normalizeUserOptions(userOptions) {
744
- var _userOptions$org, _userOptions$project, _userOptions$authToke, _ref, _userOptions$url, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$disable, _ref2, _userOptions$release$, _userOptions$release, _userOptions$release$2, _userOptions$release2, _userOptions$release$3, _userOptions$release3, _userOptions$release$4, _userOptions$release4, _ref3, _userOptions$release$5, _userOptions$release5, _userOptions$release6, _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$_experim;
745
- var options = {
746
- org: (_userOptions$org = userOptions.org) !== null && _userOptions$org !== void 0 ? _userOptions$org : process.env["SENTRY_ORG"],
747
- project: (_userOptions$project = userOptions.project) !== null && _userOptions$project !== void 0 ? _userOptions$project : process.env["SENTRY_PROJECT"],
748
- authToken: (_userOptions$authToke = userOptions.authToken) !== null && _userOptions$authToke !== void 0 ? _userOptions$authToke : process.env["SENTRY_AUTH_TOKEN"],
749
- url: (_ref = (_userOptions$url = userOptions.url) !== null && _userOptions$url !== void 0 ? _userOptions$url : process.env["SENTRY_URL"]) !== null && _ref !== void 0 ? _ref : SENTRY_SAAS_URL,
750
- headers: userOptions.headers,
751
- debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false,
752
- silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
753
- errorHandler: userOptions.errorHandler,
754
- telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
755
- disable: (_userOptions$disable = userOptions.disable) !== null && _userOptions$disable !== void 0 ? _userOptions$disable : false,
756
- sourcemaps: userOptions.sourcemaps,
757
- release: _objectSpread2(_objectSpread2({}, userOptions.release), {}, {
758
- name: (_ref2 = (_userOptions$release$ = (_userOptions$release = userOptions.release) === null || _userOptions$release === void 0 ? void 0 : _userOptions$release.name) !== null && _userOptions$release$ !== void 0 ? _userOptions$release$ : process.env["SENTRY_RELEASE"]) !== null && _ref2 !== void 0 ? _ref2 : determineReleaseName(),
759
- inject: (_userOptions$release$2 = (_userOptions$release2 = userOptions.release) === null || _userOptions$release2 === void 0 ? void 0 : _userOptions$release2.inject) !== null && _userOptions$release$2 !== void 0 ? _userOptions$release$2 : true,
760
- create: (_userOptions$release$3 = (_userOptions$release3 = userOptions.release) === null || _userOptions$release3 === void 0 ? void 0 : _userOptions$release3.create) !== null && _userOptions$release$3 !== void 0 ? _userOptions$release$3 : true,
761
- finalize: (_userOptions$release$4 = (_userOptions$release4 = userOptions.release) === null || _userOptions$release4 === void 0 ? void 0 : _userOptions$release4.finalize) !== null && _userOptions$release$4 !== void 0 ? _userOptions$release$4 : true,
762
- vcsRemote: (_ref3 = (_userOptions$release$5 = (_userOptions$release5 = userOptions.release) === null || _userOptions$release5 === void 0 ? void 0 : _userOptions$release5.vcsRemote) !== null && _userOptions$release$5 !== void 0 ? _userOptions$release$5 : process.env["SENTRY_VSC_REMOTE"]) !== null && _ref3 !== void 0 ? _ref3 : "origin",
763
- setCommits: (_userOptions$release6 = userOptions.release) === null || _userOptions$release6 === void 0 ? void 0 : _userOptions$release6.setCommits
764
- }),
765
- bundleSizeOptimizations: userOptions.bundleSizeOptimizations,
766
- reactComponentAnnotation: userOptions.reactComponentAnnotation,
767
- _metaOptions: {
768
- telemetry: {
769
- metaFramework: (_userOptions$_metaOpt = userOptions._metaOptions) === null || _userOptions$_metaOpt === void 0 ? void 0 : (_userOptions$_metaOpt2 = _userOptions$_metaOpt.telemetry) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.metaFramework
770
- }
771
- },
772
- applicationKey: userOptions.applicationKey,
773
- moduleMetadata: userOptions.moduleMetadata,
774
- _experiments: (_userOptions$_experim = userOptions._experiments) !== null && _userOptions$_experim !== void 0 ? _userOptions$_experim : {}
775
- };
776
- if (options.release.setCommits === undefined) {
777
- if (process.env["VERCEL"] && process.env["VERCEL_GIT_COMMIT_SHA"] && process.env["VERCEL_GIT_REPO_SLUG"] && process.env["VERCEL_GIT_REPO_OWNER"]) {
778
- options.release.setCommits = {
779
- shouldNotThrowOnFailure: true,
780
- commit: process.env["VERCEL_GIT_COMMIT_SHA"],
781
- previousCommit: process.env["VERCEL_GIT_PREVIOUS_SHA"],
782
- repo: "".concat(process.env["VERCEL_GIT_REPO_OWNER"], "/").concat(process.env["VERCEL_GIT_REPO_SLUG"]),
783
- ignoreEmpty: true,
784
- ignoreMissing: true
785
- };
786
- } else {
787
- options.release.setCommits = {
788
- shouldNotThrowOnFailure: true,
789
- auto: true,
790
- ignoreEmpty: true,
791
- ignoreMissing: true
792
- };
793
- }
794
- }
795
- if (options.release.deploy === undefined && process.env["VERCEL"] && process.env["VERCEL_TARGET_ENV"]) {
796
- options.release.deploy = {
797
- env: "vercel-".concat(process.env["VERCEL_TARGET_ENV"]),
798
- url: process.env["VERCEL_URL"] ? "https://".concat(process.env["VERCEL_URL"]) : undefined
799
- };
800
- }
801
- return options;
566
+ function isThenable(wat) {
567
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
568
+ return Boolean(wat && wat.then && typeof wat.then === 'function');
802
569
  }
803
570
 
804
571
  /**
805
- * Validates a few combinations of options that are not checked by Sentry CLI.
806
- *
807
- * For all other options, we can rely on Sentry CLI to validate them. In fact,
808
- * we can't validate them in the plugin because Sentry CLI might pick up options from
809
- * its config file.
810
- *
811
- * @param options the internal options
812
- * @param logger the logger
572
+ * Checks whether given value's type is a SyntheticEvent
573
+ * {@link isSyntheticEvent}.
813
574
  *
814
- * @returns `true` if the options are valid, `false` otherwise
575
+ * @param wat A value to be checked.
576
+ * @returns A boolean representing the result.
815
577
  */
816
- function validateOptions(options, logger) {
817
- var _options$release, _options$release2, _options$release3;
818
- var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
819
- if (setCommits) {
820
- if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
821
- logger.error("The `setCommits` option was specified but is missing required properties.", "Please set either `auto` or both, `repo` and `commit`.");
822
- return false;
823
- }
824
- if (setCommits.auto && setCommits.repo && setCommits) {
825
- logger.warn("The `setCommits` options includes `auto` but also `repo` and `commit`.", "Ignoring `repo` and `commit`.", "Please only set either `auto` or both, `repo` and `commit`.");
826
- }
827
- }
828
- if ((_options$release2 = options.release) !== null && _options$release2 !== void 0 && _options$release2.deploy && !((_options$release3 = options.release) !== null && _options$release3 !== void 0 && _options$release3.deploy.env)) {
829
- logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
830
- return false;
831
- }
832
- return true;
578
+ function isSyntheticEvent(wat) {
579
+ return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
833
580
  }
834
581
 
835
- // eslint-disable-next-line @typescript-eslint/unbound-method
836
- const objectToString = Object.prototype.toString;
837
-
838
582
  /**
839
- * Checks whether given value's type is one of a few Error or Error-like
840
- * {@link isError}.
583
+ * Checks whether given value's type is an instance of provided constructor.
584
+ * {@link isInstanceOf}.
841
585
  *
842
586
  * @param wat A value to be checked.
587
+ * @param base A constructor to be used in a check.
843
588
  * @returns A boolean representing the result.
844
589
  */
845
- function isError(wat) {
846
- switch (objectToString.call(wat)) {
847
- case '[object Error]':
848
- case '[object Exception]':
849
- case '[object DOMException]':
850
- return true;
851
- default:
852
- return isInstanceOf(wat, Error);
590
+ function isInstanceOf(wat, base) {
591
+ try {
592
+ return wat instanceof base;
593
+ } catch (_e) {
594
+ return false;
853
595
  }
854
596
  }
597
+
855
598
  /**
856
- * Checks whether given value is an instance of the given built-in class.
599
+ * Checks whether given value's type is a Vue ViewModel.
857
600
  *
858
- * @param wat The value to be checked
859
- * @param className
601
+ * @param wat A value to be checked.
860
602
  * @returns A boolean representing the result.
861
603
  */
862
- function isBuiltin(wat, className) {
863
- return objectToString.call(wat) === `[object ${className}]`;
604
+ function isVueViewModel(wat) {
605
+ // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
606
+ return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
864
607
  }
865
608
 
866
609
  /**
867
- * Checks whether given value's type is ErrorEvent
868
- * {@link isErrorEvent}.
869
- *
870
- * @param wat A value to be checked.
871
- * @returns A boolean representing the result.
872
- */
873
- function isErrorEvent$1(wat) {
874
- return isBuiltin(wat, 'ErrorEvent');
875
- }
876
-
877
- /**
878
- * Checks whether given value's type is a string
879
- * {@link isString}.
880
- *
881
- * @param wat A value to be checked.
882
- * @returns A boolean representing the result.
883
- */
884
- function isString(wat) {
885
- return isBuiltin(wat, 'String');
886
- }
887
-
888
- /**
889
- * Checks whether given string is parameterized
890
- * {@link isParameterizedString}.
891
- *
892
- * @param wat A value to be checked.
893
- * @returns A boolean representing the result.
894
- */
895
- function isParameterizedString(wat) {
896
- return (
897
- typeof wat === 'object' &&
898
- wat !== null &&
899
- '__sentry_template_string__' in wat &&
900
- '__sentry_template_values__' in wat
901
- );
902
- }
903
-
904
- /**
905
- * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
906
- * {@link isPrimitive}.
907
- *
908
- * @param wat A value to be checked.
909
- * @returns A boolean representing the result.
910
- */
911
- function isPrimitive(wat) {
912
- return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
913
- }
914
-
915
- /**
916
- * Checks whether given value's type is an object literal, or a class instance.
917
- * {@link isPlainObject}.
918
- *
919
- * @param wat A value to be checked.
920
- * @returns A boolean representing the result.
921
- */
922
- function isPlainObject(wat) {
923
- return isBuiltin(wat, 'Object');
924
- }
925
-
926
- /**
927
- * Checks whether given value's type is an Event instance
928
- * {@link isEvent}.
929
- *
930
- * @param wat A value to be checked.
931
- * @returns A boolean representing the result.
932
- */
933
- function isEvent(wat) {
934
- return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
935
- }
936
-
937
- /**
938
- * Checks whether given value's type is an Element instance
939
- * {@link isElement}.
940
- *
941
- * @param wat A value to be checked.
942
- * @returns A boolean representing the result.
943
- */
944
- function isElement(wat) {
945
- return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
946
- }
947
-
948
- /**
949
- * Checks whether given value has a then function.
950
- * @param wat A value to be checked.
951
- */
952
- function isThenable(wat) {
953
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
954
- return Boolean(wat && wat.then && typeof wat.then === 'function');
955
- }
956
-
957
- /**
958
- * Checks whether given value's type is a SyntheticEvent
959
- * {@link isSyntheticEvent}.
960
- *
961
- * @param wat A value to be checked.
962
- * @returns A boolean representing the result.
963
- */
964
- function isSyntheticEvent(wat) {
965
- return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
966
- }
967
-
968
- /**
969
- * Checks whether given value's type is an instance of provided constructor.
970
- * {@link isInstanceOf}.
971
- *
972
- * @param wat A value to be checked.
973
- * @param base A constructor to be used in a check.
974
- * @returns A boolean representing the result.
975
- */
976
- function isInstanceOf(wat, base) {
977
- try {
978
- return wat instanceof base;
979
- } catch (_e) {
980
- return false;
981
- }
982
- }
983
-
984
- /**
985
- * Checks whether given value's type is a Vue ViewModel.
986
- *
987
- * @param wat A value to be checked.
988
- * @returns A boolean representing the result.
989
- */
990
- function isVueViewModel(wat) {
991
- // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
992
- return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
993
- }
994
-
995
- /**
996
- * Truncates given string to the maximum characters count
610
+ * Truncates given string to the maximum characters count
997
611
  *
998
612
  * @param str An object that contains serializable values
999
613
  * @param max Maximum number of characters in truncated string (0 = unlimited)
@@ -2105,7 +1719,7 @@ function checkOrSetAlreadyCaught(exception) {
2105
1719
  * @param maybeArray Input to turn into an array, if necessary
2106
1720
  * @returns The input, if already an array, or an array with the input as the only element, if not
2107
1721
  */
2108
- function arrayify(maybeArray) {
1722
+ function arrayify$1(maybeArray) {
2109
1723
  return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
2110
1724
  }
2111
1725
 
@@ -6225,7 +5839,7 @@ function applySpanToEvent(event, span) {
6225
5839
  */
6226
5840
  function applyFingerprintToEvent(event, fingerprint) {
6227
5841
  // Make sure it's an array first and we actually have something in place
6228
- event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
5842
+ event.fingerprint = event.fingerprint ? arrayify$1(event.fingerprint) : [];
6229
5843
 
6230
5844
  // If we have something on the scope, then merge it with event
6231
5845
  if (fingerprint) {
@@ -7909,91 +7523,533 @@ function createTransport(
7909
7523
  if (filteredEnvelopeItems.length === 0) {
7910
7524
  return resolvedSyncPromise({});
7911
7525
  }
7912
-
7913
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7914
- const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );
7915
-
7916
- // Creates client report for each item in an envelope
7917
- const recordEnvelopeLoss = (reason) => {
7918
- forEachEnvelopeItem(filteredEnvelope, (item, type) => {
7919
- const event = getEventForEnvelopeItem(item, type);
7920
- options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);
7921
- });
7922
- };
7923
-
7924
- const requestTask = () =>
7925
- makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(
7926
- response => {
7927
- // We don't want to throw on NOK responses, but we want to at least log them
7928
- if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {
7929
- DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
7930
- }
7931
-
7932
- rateLimits = updateRateLimits(rateLimits, response);
7933
- return response;
7934
- },
7935
- error => {
7936
- recordEnvelopeLoss('network_error');
7937
- throw error;
7938
- },
7939
- );
7940
-
7941
- return buffer.add(requestTask).then(
7942
- result => result,
7943
- error => {
7944
- if (error instanceof SentryError) {
7945
- DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');
7946
- recordEnvelopeLoss('queue_overflow');
7947
- return resolvedSyncPromise({});
7948
- } else {
7949
- throw error;
7950
- }
7951
- },
7952
- );
7526
+
7527
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7528
+ const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );
7529
+
7530
+ // Creates client report for each item in an envelope
7531
+ const recordEnvelopeLoss = (reason) => {
7532
+ forEachEnvelopeItem(filteredEnvelope, (item, type) => {
7533
+ const event = getEventForEnvelopeItem(item, type);
7534
+ options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);
7535
+ });
7536
+ };
7537
+
7538
+ const requestTask = () =>
7539
+ makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(
7540
+ response => {
7541
+ // We don't want to throw on NOK responses, but we want to at least log them
7542
+ if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {
7543
+ DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
7544
+ }
7545
+
7546
+ rateLimits = updateRateLimits(rateLimits, response);
7547
+ return response;
7548
+ },
7549
+ error => {
7550
+ recordEnvelopeLoss('network_error');
7551
+ throw error;
7552
+ },
7553
+ );
7554
+
7555
+ return buffer.add(requestTask).then(
7556
+ result => result,
7557
+ error => {
7558
+ if (error instanceof SentryError) {
7559
+ DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');
7560
+ recordEnvelopeLoss('queue_overflow');
7561
+ return resolvedSyncPromise({});
7562
+ } else {
7563
+ throw error;
7564
+ }
7565
+ },
7566
+ );
7567
+ }
7568
+
7569
+ return {
7570
+ send,
7571
+ flush,
7572
+ };
7573
+ }
7574
+
7575
+ function getEventForEnvelopeItem(item, type) {
7576
+ if (type !== 'event' && type !== 'transaction') {
7577
+ return undefined;
7578
+ }
7579
+
7580
+ return Array.isArray(item) ? (item )[1] : undefined;
7581
+ }
7582
+
7583
+ /**
7584
+ * A builder for the SDK metadata in the options for the SDK initialization.
7585
+ *
7586
+ * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
7587
+ * We don't extract it for bundle size reasons.
7588
+ * @see https://github.com/getsentry/sentry-javascript/pull/7404
7589
+ * @see https://github.com/getsentry/sentry-javascript/pull/4196
7590
+ *
7591
+ * If you make changes to this function consider updating the others as well.
7592
+ *
7593
+ * @param options SDK options object that gets mutated
7594
+ * @param names list of package names
7595
+ */
7596
+ function applySdkMetadata(options, name, names = [name], source = 'npm') {
7597
+ const metadata = options._metadata || {};
7598
+
7599
+ if (!metadata.sdk) {
7600
+ metadata.sdk = {
7601
+ name: `sentry.javascript.${name}`,
7602
+ packages: names.map(name => ({
7603
+ name: `${source}:@sentry/${name}`,
7604
+ version: SDK_VERSION,
7605
+ })),
7606
+ version: SDK_VERSION,
7607
+ };
7608
+ }
7609
+
7610
+ options._metadata = metadata;
7611
+ }
7612
+
7613
+ /**
7614
+ * Checks whether the given input is already an array, and if it isn't, wraps it in one.
7615
+ *
7616
+ * @param maybeArray Input to turn into an array, if necessary
7617
+ * @returns The input, if already an array, or an array with the input as the only element, if not
7618
+ */
7619
+ function arrayify(maybeArray) {
7620
+ return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
7621
+ }
7622
+ /**
7623
+ * Get the closes package.json from a given starting point upwards.
7624
+ * This handles a few edge cases:
7625
+ * * Check if a given file package.json appears to be an actual NPM package.json file
7626
+ * * Stop at the home dir, to avoid looking too deeply
7627
+ */
7628
+ function getPackageJson() {
7629
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
7630
+ cwd = _ref.cwd,
7631
+ stopAt = _ref.stopAt;
7632
+ return lookupPackageJson(cwd !== null && cwd !== void 0 ? cwd : process.cwd(), path__default["default"].normalize(stopAt !== null && stopAt !== void 0 ? stopAt : os__default["default"].homedir()));
7633
+ }
7634
+ function parseMajorVersion(version) {
7635
+ // if it has a `v` prefix, remove it
7636
+ if (version.startsWith("v")) {
7637
+ version = version.slice(1);
7638
+ }
7639
+
7640
+ // First, try simple lookup of exact, ~ and ^ versions
7641
+ var regex = /^[\^~]?(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7642
+ var match = version.match(regex);
7643
+ if (match) {
7644
+ return parseInt(match[1], 10);
7645
+ }
7646
+
7647
+ // Try to parse e.g. 1.x
7648
+ var coerced = parseInt(version, 10);
7649
+ if (!Number.isNaN(coerced)) {
7650
+ return coerced;
7651
+ }
7652
+
7653
+ // Match <= and >= ranges.
7654
+ var gteLteRegex = /^[<>]=\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7655
+ var gteLteMatch = version.match(gteLteRegex);
7656
+ if (gteLteMatch) {
7657
+ return parseInt(gteLteMatch[1], 10);
7658
+ }
7659
+
7660
+ // match < ranges
7661
+ var ltRegex = /^<\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7662
+ var ltMatch = version.match(ltRegex);
7663
+ if (ltMatch) {
7664
+ // Two scenarios:
7665
+ // a) < 2.0.0 --> return 1
7666
+ // b) < 2.1.0 --> return 2
7667
+
7668
+ var major = parseInt(ltMatch[1], 10);
7669
+ if (
7670
+ // minor version > 0
7671
+ typeof ltMatch[2] === "string" && parseInt(ltMatch[2].slice(1), 10) > 0 ||
7672
+ // patch version > 0
7673
+ typeof ltMatch[3] === "string" && parseInt(ltMatch[3].slice(1), 10) > 0) {
7674
+ return major;
7675
+ }
7676
+ return major - 1;
7677
+ }
7678
+
7679
+ // match > ranges
7680
+ var gtRegex = /^>\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
7681
+ var gtMatch = version.match(gtRegex);
7682
+ if (gtMatch) {
7683
+ // We always return the version here, even though it _may_ be incorrect
7684
+ // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3
7685
+ // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists
7686
+ return parseInt(gtMatch[1], 10);
7687
+ }
7688
+ return undefined;
7689
+ }
7690
+
7691
+ // This is an explicit list of packages where we want to include the (major) version number.
7692
+ var PACKAGES_TO_INCLUDE_VERSION = ["react", "@angular/core", "vue", "ember-source", "svelte", "@sveltejs/kit", "webpack", "vite", "gatsby", "next", "remix", "rollup", "esbuild"];
7693
+ function getDependencies(packageJson) {
7694
+ var _packageJson$devDepen, _packageJson$dependen;
7695
+ var dependencies = Object.assign({}, (_packageJson$devDepen = packageJson["devDependencies"]) !== null && _packageJson$devDepen !== void 0 ? _packageJson$devDepen : {}, (_packageJson$dependen = packageJson["dependencies"]) !== null && _packageJson$dependen !== void 0 ? _packageJson$dependen : {});
7696
+ var deps = Object.keys(dependencies).sort();
7697
+ var depsVersions = deps.reduce(function (depsVersions, depName) {
7698
+ if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {
7699
+ var version = dependencies[depName];
7700
+ var majorVersion = parseMajorVersion(version);
7701
+ if (majorVersion) {
7702
+ depsVersions[depName] = majorVersion;
7703
+ }
7704
+ }
7705
+ return depsVersions;
7706
+ }, {});
7707
+ return {
7708
+ deps: deps,
7709
+ depsVersions: depsVersions
7710
+ };
7711
+ }
7712
+ function lookupPackageJson(cwd, stopAt) {
7713
+ var jsonPath = findUp__default["default"].sync(function (dirName) {
7714
+ // Stop if we reach this dir
7715
+ if (path__default["default"].normalize(dirName) === stopAt) {
7716
+ return findUp__default["default"].stop;
7717
+ }
7718
+ return findUp__default["default"].sync.exists(dirName + "/package.json") ? "package.json" : undefined;
7719
+ }, {
7720
+ cwd: cwd
7721
+ });
7722
+ if (!jsonPath) {
7723
+ return undefined;
7724
+ }
7725
+ try {
7726
+ var jsonStr = fs__default["default"].readFileSync(jsonPath, "utf8");
7727
+ var json = JSON.parse(jsonStr);
7728
+
7729
+ // Ensure it is an actual package.json
7730
+ // This is very much not bulletproof, but should be good enough
7731
+ if ("name" in json || "private" in json) {
7732
+ return json;
7733
+ }
7734
+ } catch (error) {
7735
+ // Ignore and walk up
7736
+ }
7737
+
7738
+ // Continue up the tree, if we find a fitting package.json
7739
+ var newCwd = path__default["default"].dirname(path__default["default"].resolve(jsonPath + "/.."));
7740
+ return lookupPackageJson(newCwd, stopAt);
7741
+ }
7742
+
7743
+ /**
7744
+ * Deterministically hashes a string and turns the hash into a uuid.
7745
+ */
7746
+ function stringToUUID(str) {
7747
+ var sha256Hash = crypto__default["default"].createHash("sha256").update(str).digest("hex");
7748
+
7749
+ // Position 16 is fixed to either 8, 9, a, or b in the uuid v4 spec (10xx in binary)
7750
+ // RFC 4122 section 4.4
7751
+ var v4variant = ["8", "9", "a", "b"][sha256Hash.substring(16, 17).charCodeAt(0) % 4];
7752
+ return (sha256Hash.substring(0, 8) + "-" + sha256Hash.substring(8, 12) + "-4" + sha256Hash.substring(13, 16) + "-" + v4variant + sha256Hash.substring(17, 20) + "-" + sha256Hash.substring(20, 32)).toLowerCase();
7753
+ }
7754
+ function gitRevision() {
7755
+ var gitRevision;
7756
+ try {
7757
+ gitRevision = childProcess__default["default"].execSync("git rev-parse HEAD", {
7758
+ stdio: ["ignore", "pipe", "ignore"]
7759
+ }).toString().trim();
7760
+ } catch (e) {
7761
+ // noop
7762
+ }
7763
+ return gitRevision;
7764
+ }
7765
+
7766
+ /**
7767
+ * Tries to guess a release name based on environmental data.
7768
+ */
7769
+ function determineReleaseName() {
7770
+ // This list is in approximate alpha order, separated into 3 categories:
7771
+ // 1. Git providers
7772
+ // 2. CI providers with specific environment variables (has the provider name in the variable name)
7773
+ // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)
7774
+
7775
+ var possibleReleaseNameOfGitProvider =
7776
+ // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
7777
+ process.env["GITHUB_SHA"] ||
7778
+ // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
7779
+ process.env["CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"] || process.env["CI_BUILD_REF"] || process.env["CI_COMMIT_SHA"] ||
7780
+ // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/
7781
+ process.env["BITBUCKET_COMMIT"];
7782
+ var possibleReleaseNameOfCiProvidersWithSpecificEnvVar =
7783
+ // AppVeyor - https://www.appveyor.com/docs/environment-variables/
7784
+ process.env["APPVEYOR_PULL_REQUEST_HEAD_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"] ||
7785
+ // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
7786
+ process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] ||
7787
+ // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
7788
+ process.env["AWS_COMMIT_ID"] ||
7789
+ // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
7790
+ process.env["BUILD_SOURCEVERSION"] ||
7791
+ // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/
7792
+ process.env["GIT_CLONE_COMMIT_HASH"] ||
7793
+ // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables
7794
+ process.env["BUDDY_EXECUTION_REVISION"] ||
7795
+ // Builtkite - https://buildkite.com/docs/pipelines/environment-variables
7796
+ process.env["BUILDKITE_COMMIT"] ||
7797
+ // CircleCI - https://circleci.com/docs/variables/
7798
+ process.env["CIRCLE_SHA1"] ||
7799
+ // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables
7800
+ process.env["CIRRUS_CHANGE_IN_REPO"] ||
7801
+ // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/
7802
+ process.env["CF_REVISION"] ||
7803
+ // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/
7804
+ process.env["CM_COMMIT"] ||
7805
+ // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
7806
+ process.env["CF_PAGES_COMMIT_SHA"] ||
7807
+ // Drone - https://docs.drone.io/pipeline/environment/reference/
7808
+ process.env["DRONE_COMMIT_SHA"] ||
7809
+ // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables
7810
+ process.env["FC_GIT_COMMIT_SHA"] ||
7811
+ // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci
7812
+ process.env["HEROKU_TEST_RUN_COMMIT_VERSION"] ||
7813
+ // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases
7814
+ process.env["HEROKU_SLUG_COMMIT"] ||
7815
+ // Railway - https://docs.railway.app/reference/variables#git-variables
7816
+ process.env["RAILWAY_GIT_COMMIT_SHA"] ||
7817
+ // Render - https://render.com/docs/environment-variables
7818
+ process.env["RENDER_GIT_COMMIT"] ||
7819
+ // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables
7820
+ process.env["SEMAPHORE_GIT_SHA"] ||
7821
+ // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
7822
+ process.env["TRAVIS_PULL_REQUEST_SHA"] ||
7823
+ // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
7824
+ process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] ||
7825
+ // Zeit (now known as Vercel)
7826
+ process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"];
7827
+ var possibleReleaseNameOfCiProvidersWithGenericEnvVar =
7828
+ // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables
7829
+ process.env["CI_COMMIT_ID"] ||
7830
+ // Coolify - https://coolify.io/docs/knowledge-base/environment-variables
7831
+ process.env["SOURCE_COMMIT"] ||
7832
+ // Heroku #3 https://devcenter.heroku.com/changelog-items/630
7833
+ process.env["SOURCE_VERSION"] ||
7834
+ // Jenkins - https://plugins.jenkins.io/git/#environment-variables
7835
+ process.env["GIT_COMMIT"] ||
7836
+ // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
7837
+ process.env["COMMIT_REF"] ||
7838
+ // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html
7839
+ process.env["BUILD_VCS_NUMBER"] ||
7840
+ // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment
7841
+ process.env["CI_COMMIT_SHA"];
7842
+ return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || gitRevision();
7843
+ }
7844
+
7845
+ /**
7846
+ * Generates code for the global injector which is responsible for setting the global
7847
+ * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
7848
+ */
7849
+ function generateGlobalInjectorCode(_ref2) {
7850
+ var release = _ref2.release,
7851
+ injectBuildInformation = _ref2.injectBuildInformation;
7852
+ // The code below is mostly ternary operators because it saves bundle size.
7853
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
7854
+ var code = "{\n let _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof globalThis !== 'undefined' ?\n globalThis :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:".concat(JSON.stringify(release), "};");
7855
+ if (injectBuildInformation) {
7856
+ var buildInfo = getBuildInformation$1();
7857
+ code += "\n _global.SENTRY_BUILD_INFO=".concat(JSON.stringify(buildInfo), ";");
7858
+ }
7859
+ code += "}";
7860
+ return code;
7861
+ }
7862
+
7863
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7864
+ function generateModuleMetadataInjectorCode(metadata) {
7865
+ // The code below is mostly ternary operators because it saves bundle size.
7866
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
7867
+ // We are merging the metadata objects in case modules are bundled twice with the plugin
7868
+ return "{\n let _sentryModuleMetadataGlobal =\n typeof window !== \"undefined\"\n ? window\n : typeof global !== \"undefined\"\n ? global\n : typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata =\n _sentryModuleMetadataGlobal._sentryModuleMetadata || {};\n\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack] =\n Object.assign(\n {},\n _sentryModuleMetadataGlobal._sentryModuleMetadata[new _sentryModuleMetadataGlobal.Error().stack],\n ".concat(JSON.stringify(metadata), "\n );\n}");
7869
+ }
7870
+ function getBuildInformation$1() {
7871
+ var packageJson = getPackageJson();
7872
+ var _ref3 = packageJson ? getDependencies(packageJson) : {
7873
+ deps: [],
7874
+ depsVersions: {}
7875
+ },
7876
+ deps = _ref3.deps,
7877
+ depsVersions = _ref3.depsVersions;
7878
+ return {
7879
+ deps: deps,
7880
+ depsVersions: depsVersions,
7881
+ nodeVersion: parseMajorVersion(process.version)
7882
+ };
7883
+ }
7884
+ function stripQueryAndHashFromPath(path) {
7885
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
7886
+ return path.split("?")[0].split("#")[0];
7887
+ }
7888
+ function replaceBooleanFlagsInCode(code, replacementValues) {
7889
+ var ms = new MagicString__default["default"](code);
7890
+ Object.keys(replacementValues).forEach(function (key) {
7891
+ var value = replacementValues[key];
7892
+ if (typeof value === "boolean") {
7893
+ ms.replaceAll(key, JSON.stringify(value));
7894
+ }
7895
+ });
7896
+ if (ms.hasChanged()) {
7897
+ return {
7898
+ code: ms.toString(),
7899
+ map: ms.generateMap({
7900
+ hires: "boundary"
7901
+ })
7902
+ };
7903
+ }
7904
+ return null;
7905
+ }
7906
+
7907
+ // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
7908
+ function getTurborepoEnvPassthroughWarning(envVarName) {
7909
+ return process.env["TURBO_HASH"] ? "\nYou seem to be using Turborepo, did you forget to put ".concat(envVarName, " in `passThroughEnv`? https://turbo.build/repo/docs/reference/configuration#passthroughenv") : "";
7910
+ }
7911
+
7912
+ var SENTRY_SAAS_URL = "https://sentry.io";
7913
+ function normalizeUserOptions(userOptions) {
7914
+ var _userOptions$org, _userOptions$project, _userOptions$authToke, _ref, _userOptions$url, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$disable, _ref2, _userOptions$release$, _userOptions$release, _userOptions$release$2, _userOptions$release2, _userOptions$release$3, _userOptions$release3, _userOptions$release$4, _userOptions$release4, _ref3, _userOptions$release$5, _userOptions$release5, _userOptions$release6, _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$_experim;
7915
+ var options = {
7916
+ org: (_userOptions$org = userOptions.org) !== null && _userOptions$org !== void 0 ? _userOptions$org : process.env["SENTRY_ORG"],
7917
+ project: (_userOptions$project = userOptions.project) !== null && _userOptions$project !== void 0 ? _userOptions$project : process.env["SENTRY_PROJECT"],
7918
+ authToken: (_userOptions$authToke = userOptions.authToken) !== null && _userOptions$authToke !== void 0 ? _userOptions$authToke : process.env["SENTRY_AUTH_TOKEN"],
7919
+ url: (_ref = (_userOptions$url = userOptions.url) !== null && _userOptions$url !== void 0 ? _userOptions$url : process.env["SENTRY_URL"]) !== null && _ref !== void 0 ? _ref : SENTRY_SAAS_URL,
7920
+ headers: userOptions.headers,
7921
+ debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false,
7922
+ silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
7923
+ errorHandler: userOptions.errorHandler,
7924
+ telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
7925
+ disable: (_userOptions$disable = userOptions.disable) !== null && _userOptions$disable !== void 0 ? _userOptions$disable : false,
7926
+ sourcemaps: userOptions.sourcemaps,
7927
+ release: _objectSpread2(_objectSpread2({}, userOptions.release), {}, {
7928
+ name: (_ref2 = (_userOptions$release$ = (_userOptions$release = userOptions.release) === null || _userOptions$release === void 0 ? void 0 : _userOptions$release.name) !== null && _userOptions$release$ !== void 0 ? _userOptions$release$ : process.env["SENTRY_RELEASE"]) !== null && _ref2 !== void 0 ? _ref2 : determineReleaseName(),
7929
+ inject: (_userOptions$release$2 = (_userOptions$release2 = userOptions.release) === null || _userOptions$release2 === void 0 ? void 0 : _userOptions$release2.inject) !== null && _userOptions$release$2 !== void 0 ? _userOptions$release$2 : true,
7930
+ create: (_userOptions$release$3 = (_userOptions$release3 = userOptions.release) === null || _userOptions$release3 === void 0 ? void 0 : _userOptions$release3.create) !== null && _userOptions$release$3 !== void 0 ? _userOptions$release$3 : true,
7931
+ finalize: (_userOptions$release$4 = (_userOptions$release4 = userOptions.release) === null || _userOptions$release4 === void 0 ? void 0 : _userOptions$release4.finalize) !== null && _userOptions$release$4 !== void 0 ? _userOptions$release$4 : true,
7932
+ vcsRemote: (_ref3 = (_userOptions$release$5 = (_userOptions$release5 = userOptions.release) === null || _userOptions$release5 === void 0 ? void 0 : _userOptions$release5.vcsRemote) !== null && _userOptions$release$5 !== void 0 ? _userOptions$release$5 : process.env["SENTRY_VSC_REMOTE"]) !== null && _ref3 !== void 0 ? _ref3 : "origin",
7933
+ setCommits: (_userOptions$release6 = userOptions.release) === null || _userOptions$release6 === void 0 ? void 0 : _userOptions$release6.setCommits
7934
+ }),
7935
+ bundleSizeOptimizations: userOptions.bundleSizeOptimizations,
7936
+ reactComponentAnnotation: userOptions.reactComponentAnnotation,
7937
+ _metaOptions: {
7938
+ telemetry: {
7939
+ metaFramework: (_userOptions$_metaOpt = userOptions._metaOptions) === null || _userOptions$_metaOpt === void 0 ? void 0 : (_userOptions$_metaOpt2 = _userOptions$_metaOpt.telemetry) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.metaFramework
7940
+ }
7941
+ },
7942
+ applicationKey: userOptions.applicationKey,
7943
+ moduleMetadata: userOptions.moduleMetadata,
7944
+ _experiments: (_userOptions$_experim = userOptions._experiments) !== null && _userOptions$_experim !== void 0 ? _userOptions$_experim : {}
7945
+ };
7946
+ if (options.release.setCommits === undefined) {
7947
+ if (process.env["VERCEL"] && process.env["VERCEL_GIT_COMMIT_SHA"] && process.env["VERCEL_GIT_REPO_SLUG"] && process.env["VERCEL_GIT_REPO_OWNER"] &&
7948
+ // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for
7949
+ // preview environments because the previous commit is always the "stem" commit of the preview/PR causing Sentry
7950
+ // to notify you for other people creating PRs.
7951
+ process.env["VERCEL_TARGET_ENV"] === "production") {
7952
+ options.release.setCommits = {
7953
+ shouldNotThrowOnFailure: true,
7954
+ commit: process.env["VERCEL_GIT_COMMIT_SHA"],
7955
+ previousCommit: process.env["VERCEL_GIT_PREVIOUS_SHA"],
7956
+ repo: "".concat(process.env["VERCEL_GIT_REPO_OWNER"], "/").concat(process.env["VERCEL_GIT_REPO_SLUG"]),
7957
+ ignoreEmpty: true,
7958
+ ignoreMissing: true
7959
+ };
7960
+ } else {
7961
+ options.release.setCommits = {
7962
+ shouldNotThrowOnFailure: true,
7963
+ auto: true,
7964
+ ignoreEmpty: true,
7965
+ ignoreMissing: true
7966
+ };
7967
+ }
7953
7968
  }
7954
-
7955
- return {
7956
- send,
7957
- flush,
7958
- };
7959
- }
7960
-
7961
- function getEventForEnvelopeItem(item, type) {
7962
- if (type !== 'event' && type !== 'transaction') {
7963
- return undefined;
7969
+ if (options.release.deploy === undefined && process.env["VERCEL"] && process.env["VERCEL_TARGET_ENV"]) {
7970
+ options.release.deploy = {
7971
+ env: "vercel-".concat(process.env["VERCEL_TARGET_ENV"]),
7972
+ url: process.env["VERCEL_URL"] ? "https://".concat(process.env["VERCEL_URL"]) : undefined
7973
+ };
7964
7974
  }
7965
-
7966
- return Array.isArray(item) ? (item )[1] : undefined;
7975
+ return options;
7967
7976
  }
7968
7977
 
7969
7978
  /**
7970
- * A builder for the SDK metadata in the options for the SDK initialization.
7979
+ * Validates a few combinations of options that are not checked by Sentry CLI.
7971
7980
  *
7972
- * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.
7973
- * We don't extract it for bundle size reasons.
7974
- * @see https://github.com/getsentry/sentry-javascript/pull/7404
7975
- * @see https://github.com/getsentry/sentry-javascript/pull/4196
7981
+ * For all other options, we can rely on Sentry CLI to validate them. In fact,
7982
+ * we can't validate them in the plugin because Sentry CLI might pick up options from
7983
+ * its config file.
7976
7984
  *
7977
- * If you make changes to this function consider updating the others as well.
7985
+ * @param options the internal options
7986
+ * @param logger the logger
7978
7987
  *
7979
- * @param options SDK options object that gets mutated
7980
- * @param names list of package names
7988
+ * @returns `true` if the options are valid, `false` otherwise
7981
7989
  */
7982
- function applySdkMetadata(options, name, names = [name], source = 'npm') {
7983
- const metadata = options._metadata || {};
7984
-
7985
- if (!metadata.sdk) {
7986
- metadata.sdk = {
7987
- name: `sentry.javascript.${name}`,
7988
- packages: names.map(name => ({
7989
- name: `${source}:@sentry/${name}`,
7990
- version: SDK_VERSION,
7991
- })),
7992
- version: SDK_VERSION,
7993
- };
7990
+ function validateOptions(options, logger) {
7991
+ var _options$release, _options$release2, _options$release3;
7992
+ var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
7993
+ if (setCommits) {
7994
+ if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
7995
+ logger.error("The `setCommits` option was specified but is missing required properties.", "Please set either `auto` or both, `repo` and `commit`.");
7996
+ return false;
7997
+ }
7998
+ if (setCommits.auto && setCommits.repo && setCommits) {
7999
+ logger.warn("The `setCommits` options includes `auto` but also `repo` and `commit`.", "Ignoring `repo` and `commit`.", "Please only set either `auto` or both, `repo` and `commit`.");
8000
+ }
8001
+ }
8002
+ if ((_options$release2 = options.release) !== null && _options$release2 !== void 0 && _options$release2.deploy && !((_options$release3 = options.release) !== null && _options$release3 !== void 0 && _options$release3.deploy.env)) {
8003
+ logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
8004
+ return false;
7994
8005
  }
8006
+ return true;
8007
+ }
7995
8008
 
7996
- options._metadata = metadata;
8009
+ // Logging everything to stderr not to interfere with stdout
8010
+ function createLogger(options) {
8011
+ return {
8012
+ info: function info(message) {
8013
+ if (!options.silent) {
8014
+ var _console;
8015
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
8016
+ params[_key - 1] = arguments[_key];
8017
+ }
8018
+ // eslint-disable-next-line no-console
8019
+ (_console = console).info.apply(_console, ["".concat(options.prefix, " Info: ").concat(message)].concat(params));
8020
+ }
8021
+ },
8022
+ warn: function warn(message) {
8023
+ if (!options.silent) {
8024
+ var _console2;
8025
+ for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
8026
+ params[_key2 - 1] = arguments[_key2];
8027
+ }
8028
+ // eslint-disable-next-line no-console
8029
+ (_console2 = console).warn.apply(_console2, ["".concat(options.prefix, " Warning: ").concat(message)].concat(params));
8030
+ }
8031
+ },
8032
+ error: function error(message) {
8033
+ if (!options.silent) {
8034
+ var _console3;
8035
+ for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
8036
+ params[_key3 - 1] = arguments[_key3];
8037
+ }
8038
+ // eslint-disable-next-line no-console
8039
+ (_console3 = console).error.apply(_console3, ["".concat(options.prefix, " Error: ").concat(message)].concat(params));
8040
+ }
8041
+ },
8042
+ debug: function debug(message) {
8043
+ if (!options.silent && options.debug) {
8044
+ var _console4;
8045
+ for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
8046
+ params[_key4 - 1] = arguments[_key4];
8047
+ }
8048
+ // eslint-disable-next-line no-console
8049
+ (_console4 = console).debug.apply(_console4, ["".concat(options.prefix, " Debug: ").concat(message)].concat(params));
8050
+ }
8051
+ }
8052
+ };
7997
8053
  }
7998
8054
 
7999
8055
  // Estimated maximum size for reasonable standalone event
@@ -8127,7 +8183,7 @@ function makeOptionallyEnabledNodeTransport(shouldSendTelemetry) {
8127
8183
 
8128
8184
  var SENTRY_SAAS_HOSTNAME = "sentry.io";
8129
8185
  var stackParser = createStackParser(nodeStackLineParser());
8130
- function createSentryInstance(options, shouldSendTelemetry, bundler) {
8186
+ function createSentryInstance(options, shouldSendTelemetry, buildTool) {
8131
8187
  var clientOptions = {
8132
8188
  platform: "node",
8133
8189
  runtime: {
@@ -8137,7 +8193,7 @@ function createSentryInstance(options, shouldSendTelemetry, bundler) {
8137
8193
  dsn: "https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737",
8138
8194
  tracesSampleRate: 1,
8139
8195
  sampleRate: 1,
8140
- release: "3.2.3",
8196
+ release: "3.3.0-alpha.0",
8141
8197
  integrations: [],
8142
8198
  tracePropagationTargets: ["sentry.io/api"],
8143
8199
  stackParser: stackParser,
@@ -8161,13 +8217,13 @@ function createSentryInstance(options, shouldSendTelemetry, bundler) {
8161
8217
  var client = new ServerRuntimeClient(clientOptions);
8162
8218
  var scope = new Scope();
8163
8219
  scope.setClient(client);
8164
- setTelemetryDataOnScope(options, scope, bundler);
8220
+ setTelemetryDataOnScope(options, scope, buildTool);
8165
8221
  return {
8166
8222
  sentryScope: scope,
8167
8223
  sentryClient: client
8168
8224
  };
8169
8225
  }
8170
- function setTelemetryDataOnScope(options, scope, bundler) {
8226
+ function setTelemetryDataOnScope(options, scope, buildTool) {
8171
8227
  var _options$_metaOptions;
8172
8228
  var org = options.org,
8173
8229
  project = options.project,
@@ -8205,7 +8261,7 @@ function setTelemetryDataOnScope(options, scope, bundler) {
8205
8261
  scope.setTags({
8206
8262
  organization: org,
8207
8263
  project: project,
8208
- bundler: bundler
8264
+ bundler: buildTool
8209
8265
  });
8210
8266
  scope.setUser({
8211
8267
  id: org
@@ -8302,388 +8358,99 @@ function _safeFlushTelemetry() {
8302
8358
  }
8303
8359
 
8304
8360
  function createDebugIdUploadFunction(_ref) {
8305
- var assets = _ref.assets,
8306
- ignore = _ref.ignore,
8307
- logger = _ref.logger,
8308
- releaseName = _ref.releaseName,
8309
- dist = _ref.dist,
8310
- handleRecoverableError = _ref.handleRecoverableError,
8311
- sentryScope = _ref.sentryScope,
8312
- sentryClient = _ref.sentryClient,
8313
- sentryCliOptions = _ref.sentryCliOptions,
8314
- rewriteSourcesHook = _ref.rewriteSourcesHook,
8315
- createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8316
- var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8361
+ var sentryBuildPluginManager = _ref.sentryBuildPluginManager;
8317
8362
  return /*#__PURE__*/function () {
8318
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(buildArtifactPaths) {
8319
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
8320
- while (1) switch (_context9.prev = _context9.next) {
8363
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(buildArtifactPaths) {
8364
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8365
+ while (1) switch (_context.prev = _context.next) {
8321
8366
  case 0:
8322
- _context9.next = 2;
8323
- return startSpan(
8324
- // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.
8325
- {
8326
- name: "debug-id-sourcemap-upload",
8327
- scope: sentryScope,
8328
- forceTransaction: true
8329
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
8330
- var folderToCleanUp, freeUploadDependencyOnSourcemapFiles, tmpUploadFolder, globAssets, globResult, debugIdChunkFilePaths;
8331
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
8332
- while (1) switch (_context8.prev = _context8.next) {
8333
- case 0:
8334
- // 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`)
8335
- // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
8336
- freeUploadDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8337
- _context8.prev = 1;
8338
- _context8.next = 4;
8339
- return startSpan({
8340
- name: "mkdtemp",
8341
- scope: sentryScope
8342
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8343
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8344
- while (1) switch (_context.prev = _context.next) {
8345
- case 0:
8346
- _context.next = 2;
8347
- return fs__default["default"].promises.mkdtemp(path__default["default"].join(os__default["default"].tmpdir(), "sentry-bundler-plugin-upload-"));
8348
- case 2:
8349
- return _context.abrupt("return", _context.sent);
8350
- case 3:
8351
- case "end":
8352
- return _context.stop();
8353
- }
8354
- }, _callee);
8355
- })));
8356
- case 4:
8357
- tmpUploadFolder = _context8.sent;
8358
- folderToCleanUp = tmpUploadFolder;
8359
- if (assets) {
8360
- globAssets = assets;
8361
- } else {
8362
- logger.debug("No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.");
8363
- globAssets = buildArtifactPaths;
8364
- }
8365
- _context8.next = 9;
8366
- return startSpan({
8367
- name: "glob",
8368
- scope: sentryScope
8369
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
8370
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8371
- while (1) switch (_context2.prev = _context2.next) {
8372
- case 0:
8373
- _context2.next = 2;
8374
- return glob.glob(globAssets, {
8375
- absolute: true,
8376
- nodir: true,
8377
- ignore: ignore
8378
- });
8379
- case 2:
8380
- return _context2.abrupt("return", _context2.sent);
8381
- case 3:
8382
- case "end":
8383
- return _context2.stop();
8384
- }
8385
- }, _callee2);
8386
- })));
8387
- case 9:
8388
- globResult = _context8.sent;
8389
- debugIdChunkFilePaths = globResult.filter(function (debugIdChunkFilePath) {
8390
- return !!stripQueryAndHashFromPath(debugIdChunkFilePath).match(/\.(js|mjs|cjs)$/);
8391
- }); // The order of the files output by glob() is not deterministic
8392
- // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent
8393
- debugIdChunkFilePaths.sort();
8394
- if (!(Array.isArray(assets) && assets.length === 0)) {
8395
- _context8.next = 16;
8396
- break;
8397
- }
8398
- logger.debug("Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.");
8399
- _context8.next = 23;
8400
- break;
8401
- case 16:
8402
- if (!(debugIdChunkFilePaths.length === 0)) {
8403
- _context8.next = 20;
8404
- break;
8405
- }
8406
- logger.warn("Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.");
8407
- _context8.next = 23;
8408
- break;
8409
- case 20:
8410
- _context8.next = 22;
8411
- return startSpan({
8412
- name: "prepare-bundles",
8413
- scope: sentryScope
8414
- }, /*#__PURE__*/function () {
8415
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(prepBundlesSpan) {
8416
- var preparationTasks, workers, worker, workerIndex, files, stats, uploadSize;
8417
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
8418
- while (1) switch (_context6.prev = _context6.next) {
8419
- case 0:
8420
- // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so
8421
- // instead we do it with a maximum of 16 concurrent workers
8422
- preparationTasks = debugIdChunkFilePaths.map(function (chunkFilePath, chunkIndex) {
8423
- return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
8424
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8425
- while (1) switch (_context3.prev = _context3.next) {
8426
- case 0:
8427
- _context3.next = 2;
8428
- return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, chunkIndex, logger, rewriteSourcesHook !== null && rewriteSourcesHook !== void 0 ? rewriteSourcesHook : defaultRewriteSourcesHook);
8429
- case 2:
8430
- case "end":
8431
- return _context3.stop();
8432
- }
8433
- }, _callee3);
8434
- }));
8435
- });
8436
- workers = [];
8437
- worker = /*#__PURE__*/function () {
8438
- var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
8439
- var task;
8440
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8441
- while (1) switch (_context4.prev = _context4.next) {
8442
- case 0:
8443
- if (!(preparationTasks.length > 0)) {
8444
- _context4.next = 7;
8445
- break;
8446
- }
8447
- task = preparationTasks.shift();
8448
- if (!task) {
8449
- _context4.next = 5;
8450
- break;
8451
- }
8452
- _context4.next = 5;
8453
- return task();
8454
- case 5:
8455
- _context4.next = 0;
8456
- break;
8457
- case 7:
8458
- case "end":
8459
- return _context4.stop();
8460
- }
8461
- }, _callee4);
8462
- }));
8463
- return function worker() {
8464
- return _ref8.apply(this, arguments);
8465
- };
8466
- }();
8467
- for (workerIndex = 0; workerIndex < 16; workerIndex++) {
8468
- workers.push(worker());
8469
- }
8470
- _context6.next = 6;
8471
- return Promise.all(workers);
8472
- case 6:
8473
- _context6.next = 8;
8474
- return fs__default["default"].promises.readdir(tmpUploadFolder);
8475
- case 8:
8476
- files = _context6.sent;
8477
- stats = files.map(function (file) {
8478
- return fs__default["default"].promises.stat(path__default["default"].join(tmpUploadFolder, file));
8479
- });
8480
- _context6.next = 12;
8481
- return Promise.all(stats);
8482
- case 12:
8483
- uploadSize = _context6.sent.reduce(function (accumulator, _ref9) {
8484
- var size = _ref9.size;
8485
- return accumulator + size;
8486
- }, 0);
8487
- setMeasurement("files", files.length, "none", prepBundlesSpan);
8488
- setMeasurement("upload_size", uploadSize, "byte", prepBundlesSpan);
8489
- _context6.next = 17;
8490
- return startSpan({
8491
- name: "upload",
8492
- scope: sentryScope
8493
- }, /*#__PURE__*/function () {
8494
- var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(uploadSpan) {
8495
- var cliInstance;
8496
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8497
- while (1) switch (_context5.prev = _context5.next) {
8498
- case 0:
8499
- cliInstance = new SentryCli__default["default"](null, _objectSpread2(_objectSpread2({}, sentryCliOptions), {}, {
8500
- headers: _objectSpread2({
8501
- "sentry-trace": spanToTraceHeader(uploadSpan),
8502
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
8503
- baggage: dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(uploadSpan))
8504
- }, sentryCliOptions.headers)
8505
- }));
8506
- _context5.next = 3;
8507
- return cliInstance.releases.uploadSourceMaps(releaseName !== null && releaseName !== void 0 ? releaseName : "undefined",
8508
- // unfortunately this needs a value for now but it will not matter since debug IDs overpower releases anyhow
8509
- {
8510
- include: [{
8511
- paths: [tmpUploadFolder],
8512
- rewrite: false,
8513
- dist: dist
8514
- }],
8515
- useArtifactBundle: true
8516
- });
8517
- case 3:
8518
- case "end":
8519
- return _context5.stop();
8520
- }
8521
- }, _callee5);
8522
- }));
8523
- return function (_x3) {
8524
- return _ref10.apply(this, arguments);
8525
- };
8526
- }());
8527
- case 17:
8528
- case "end":
8529
- return _context6.stop();
8530
- }
8531
- }, _callee6);
8532
- }));
8533
- return function (_x2) {
8534
- return _ref6.apply(this, arguments);
8535
- };
8536
- }());
8537
- case 22:
8538
- logger.info("Successfully uploaded source maps to Sentry");
8539
- case 23:
8540
- _context8.next = 29;
8541
- break;
8542
- case 25:
8543
- _context8.prev = 25;
8544
- _context8.t0 = _context8["catch"](1);
8545
- sentryScope.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
8546
- handleRecoverableError(_context8.t0, false);
8547
- case 29:
8548
- _context8.prev = 29;
8549
- if (folderToCleanUp) {
8550
- void startSpan({
8551
- name: "cleanup",
8552
- scope: sentryScope
8553
- }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
8554
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
8555
- while (1) switch (_context7.prev = _context7.next) {
8556
- case 0:
8557
- if (!folderToCleanUp) {
8558
- _context7.next = 3;
8559
- break;
8560
- }
8561
- _context7.next = 3;
8562
- return fs__default["default"].promises.rm(folderToCleanUp, {
8563
- recursive: true,
8564
- force: true
8565
- });
8566
- case 3:
8567
- case "end":
8568
- return _context7.stop();
8569
- }
8570
- }, _callee7);
8571
- })));
8572
- }
8573
- freeGlobalDependencyOnSourcemapFiles();
8574
- freeUploadDependencyOnSourcemapFiles();
8575
- _context8.next = 35;
8576
- return safeFlushTelemetry(sentryClient);
8577
- case 35:
8578
- return _context8.finish(29);
8579
- case 36:
8580
- case "end":
8581
- return _context8.stop();
8582
- }
8583
- }, _callee8, null, [[1, 25, 29, 36]]);
8584
- })));
8367
+ _context.next = 2;
8368
+ return sentryBuildPluginManager.uploadSourcemaps(buildArtifactPaths);
8585
8369
  case 2:
8586
8370
  case "end":
8587
- return _context9.stop();
8371
+ return _context.stop();
8588
8372
  }
8589
- }, _callee9);
8373
+ }, _callee);
8590
8374
  }));
8591
8375
  return function (_x) {
8592
8376
  return _ref2.apply(this, arguments);
8593
8377
  };
8594
8378
  }();
8595
8379
  }
8596
- function prepareBundleForDebugIdUpload(_x4, _x5, _x6, _x7, _x8) {
8380
+ function prepareBundleForDebugIdUpload(_x2, _x3, _x4, _x5, _x6) {
8597
8381
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8598
8382
  }
8383
+
8384
+ /**
8385
+ * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle
8386
+ * source and extracts the bundle's debug ID from it.
8387
+ *
8388
+ * The string pattern is injected via the debug ID injection snipped.
8389
+ */
8599
8390
  function _prepareBundleForDebugIdUpload() {
8600
- _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8601
- var bundleContent, debugId, uniqueSourceFileUploadPath, writeSourceFilePromise, writeSourceMapFilePromise;
8602
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
8603
- while (1) switch (_context11.prev = _context11.next) {
8391
+ _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(bundleFilePath, uploadFolder, chunkIndex, logger, rewriteSourcesHook) {
8392
+ var bundleContent, debugId, uniqueUploadName, writeSourceFilePromise, writeSourceMapFilePromise;
8393
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8394
+ while (1) switch (_context3.prev = _context3.next) {
8604
8395
  case 0:
8605
- _context11.prev = 0;
8606
- _context11.next = 3;
8396
+ _context3.prev = 0;
8397
+ _context3.next = 3;
8607
8398
  return util.promisify(fs__default["default"].readFile)(bundleFilePath, "utf8");
8608
8399
  case 3:
8609
- bundleContent = _context11.sent;
8610
- _context11.next = 10;
8400
+ bundleContent = _context3.sent;
8401
+ _context3.next = 10;
8611
8402
  break;
8612
8403
  case 6:
8613
- _context11.prev = 6;
8614
- _context11.t0 = _context11["catch"](0);
8615
- logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context11.t0);
8616
- return _context11.abrupt("return");
8404
+ _context3.prev = 6;
8405
+ _context3.t0 = _context3["catch"](0);
8406
+ logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context3.t0);
8407
+ return _context3.abrupt("return");
8617
8408
  case 10:
8618
8409
  debugId = determineDebugIdFromBundleSource(bundleContent);
8619
8410
  if (!(debugId === undefined)) {
8620
- _context11.next = 14;
8411
+ _context3.next = 14;
8621
8412
  break;
8622
8413
  }
8623
8414
  logger.debug("Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ".concat(bundleFilePath));
8624
- return _context11.abrupt("return");
8415
+ return _context3.abrupt("return");
8625
8416
  case 14:
8626
- uniqueSourceFileUploadPath = getUniqueUploadPath(uploadFolder, chunkIndex, bundleFilePath);
8417
+ uniqueUploadName = "".concat(debugId, "-").concat(chunkIndex);
8627
8418
  bundleContent += "\n//# debugId=".concat(debugId);
8628
- writeSourceFilePromise = fs__default["default"].promises.mkdir(path__default["default"].dirname(uniqueSourceFileUploadPath), {
8629
- recursive: true
8630
- }).then(function () {
8631
- return fs__default["default"].promises.writeFile(uniqueSourceFileUploadPath, bundleContent, "utf-8");
8632
- });
8419
+ writeSourceFilePromise = fs__default["default"].promises.writeFile(path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js")), bundleContent, "utf-8");
8633
8420
  writeSourceMapFilePromise = determineSourceMapPathFromBundle(bundleFilePath, bundleContent, logger).then( /*#__PURE__*/function () {
8634
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(sourceMapPath) {
8635
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
8636
- while (1) switch (_context10.prev = _context10.next) {
8421
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(sourceMapPath) {
8422
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8423
+ while (1) switch (_context2.prev = _context2.next) {
8637
8424
  case 0:
8638
8425
  if (!sourceMapPath) {
8639
- _context10.next = 3;
8426
+ _context2.next = 3;
8640
8427
  break;
8641
8428
  }
8642
- _context10.next = 3;
8643
- return prepareSourceMapForDebugIdUpload(sourceMapPath, getUniqueUploadPath(uploadFolder, chunkIndex, sourceMapPath), debugId, rewriteSourcesHook, logger);
8429
+ _context2.next = 3;
8430
+ return prepareSourceMapForDebugIdUpload(sourceMapPath, path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js.map")), debugId, rewriteSourcesHook, logger);
8644
8431
  case 3:
8645
8432
  case "end":
8646
- return _context10.stop();
8433
+ return _context2.stop();
8647
8434
  }
8648
- }, _callee10);
8435
+ }, _callee2);
8649
8436
  }));
8650
- return function (_x17) {
8651
- return _ref12.apply(this, arguments);
8437
+ return function (_x15) {
8438
+ return _ref3.apply(this, arguments);
8652
8439
  };
8653
8440
  }());
8654
- _context11.next = 20;
8441
+ _context3.next = 20;
8655
8442
  return writeSourceFilePromise;
8656
8443
  case 20:
8657
- _context11.next = 22;
8444
+ _context3.next = 22;
8658
8445
  return writeSourceMapFilePromise;
8659
8446
  case 22:
8660
8447
  case "end":
8661
- return _context11.stop();
8448
+ return _context3.stop();
8662
8449
  }
8663
- }, _callee11, null, [[0, 6]]);
8450
+ }, _callee3, null, [[0, 6]]);
8664
8451
  }));
8665
8452
  return _prepareBundleForDebugIdUpload.apply(this, arguments);
8666
8453
  }
8667
- function getUniqueUploadPath(uploadFolder, chunkIndex, filePath) {
8668
- return path__default["default"].join(uploadFolder, // We add a "chunk index" segment to the path that is a simple incrementing number to avoid name collisions.
8669
- // Name collisions can happen when files are located "outside" of the current working directory, at different levels but they share a subpath.
8670
- // Example:
8671
- // - CWD: /root/foo/cwd
8672
- // - File 1: /root/foo/index.js -> ../foo/index.js -> foo/index.js
8673
- // - File 2: /foo/index.js -> ../../foo/index.js -> foo/index.js
8674
- "".concat(chunkIndex), path__default["default"].normalize(path__default["default"].relative(process.cwd(), filePath).split(path__default["default"].sep)
8675
- // We filter out these "navigation" segments because a) they look ugly b) they will cause us to break out of the upload folder.
8676
- .filter(function (segment) {
8677
- return segment !== ".." && segment !== ".";
8678
- }).join(path__default["default"].sep)));
8679
- }
8680
-
8681
- /**
8682
- * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle
8683
- * source and extracts the bundle's debug ID from it.
8684
- *
8685
- * The string pattern is injected via the debug ID injection snipped.
8686
- */
8687
8454
  function determineDebugIdFromBundleSource(code) {
8688
8455
  var match = code.match(/sentry-dbid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/);
8689
8456
  if (match) {
@@ -8698,22 +8465,22 @@ function determineDebugIdFromBundleSource(code) {
8698
8465
  *
8699
8466
  * @returns the path to the bundle's source map or `undefined` if none could be found.
8700
8467
  */
8701
- function determineSourceMapPathFromBundle(_x9, _x10, _x11) {
8468
+ function determineSourceMapPathFromBundle(_x7, _x8, _x9) {
8702
8469
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8703
8470
  }
8704
8471
  /**
8705
8472
  * Reads a source map, injects debug ID fields, and writes the source map to the target path.
8706
8473
  */
8707
8474
  function _determineSourceMapPathFromBundle() {
8708
- _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(bundlePath, bundleSource, logger) {
8475
+ _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(bundlePath, bundleSource, logger) {
8709
8476
  var sourceMappingUrlMatch, sourceMappingUrl, isUrl, isSupportedUrl, url, absoluteSourceMapPath, adjacentSourceMapFilePath;
8710
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
8711
- while (1) switch (_context12.prev = _context12.next) {
8477
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8478
+ while (1) switch (_context4.prev = _context4.next) {
8712
8479
  case 0:
8713
8480
  // 1. try to find source map at `sourceMappingURL` location
8714
8481
  sourceMappingUrlMatch = bundleSource.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);
8715
8482
  if (!sourceMappingUrlMatch) {
8716
- _context12.next = 14;
8483
+ _context4.next = 14;
8717
8484
  break;
8718
8485
  }
8719
8486
  sourceMappingUrl = path__default["default"].normalize(sourceMappingUrlMatch[1]);
@@ -8733,104 +8500,99 @@ function _determineSourceMapPathFromBundle() {
8733
8500
  absoluteSourceMapPath = path__default["default"].join(path__default["default"].dirname(bundlePath), sourceMappingUrl);
8734
8501
  }
8735
8502
  if (!absoluteSourceMapPath) {
8736
- _context12.next = 14;
8503
+ _context4.next = 14;
8737
8504
  break;
8738
8505
  }
8739
- _context12.prev = 6;
8740
- _context12.next = 9;
8506
+ _context4.prev = 6;
8507
+ _context4.next = 9;
8741
8508
  return util__namespace.promisify(fs__default["default"].access)(absoluteSourceMapPath);
8742
8509
  case 9:
8743
- return _context12.abrupt("return", absoluteSourceMapPath);
8510
+ return _context4.abrupt("return", absoluteSourceMapPath);
8744
8511
  case 12:
8745
- _context12.prev = 12;
8746
- _context12.t0 = _context12["catch"](6);
8512
+ _context4.prev = 12;
8513
+ _context4.t0 = _context4["catch"](6);
8747
8514
  case 14:
8748
- _context12.prev = 14;
8515
+ _context4.prev = 14;
8749
8516
  adjacentSourceMapFilePath = bundlePath + ".map";
8750
- _context12.next = 18;
8517
+ _context4.next = 18;
8751
8518
  return util__namespace.promisify(fs__default["default"].access)(adjacentSourceMapFilePath);
8752
8519
  case 18:
8753
- return _context12.abrupt("return", adjacentSourceMapFilePath);
8520
+ return _context4.abrupt("return", adjacentSourceMapFilePath);
8754
8521
  case 21:
8755
- _context12.prev = 21;
8756
- _context12.t1 = _context12["catch"](14);
8522
+ _context4.prev = 21;
8523
+ _context4.t1 = _context4["catch"](14);
8757
8524
  case 23:
8758
8525
  // This is just a debug message because it can be quite spammy for some frameworks
8759
8526
  logger.debug("Could not determine source map path for bundle: ".concat(bundlePath, " - Did you turn on source map generation in your bundler?"));
8760
- return _context12.abrupt("return", undefined);
8527
+ return _context4.abrupt("return", undefined);
8761
8528
  case 25:
8762
8529
  case "end":
8763
- return _context12.stop();
8530
+ return _context4.stop();
8764
8531
  }
8765
- }, _callee12, null, [[6, 12], [14, 21]]);
8532
+ }, _callee4, null, [[6, 12], [14, 21]]);
8766
8533
  }));
8767
8534
  return _determineSourceMapPathFromBundle.apply(this, arguments);
8768
8535
  }
8769
- function prepareSourceMapForDebugIdUpload(_x12, _x13, _x14, _x15, _x16) {
8536
+ function prepareSourceMapForDebugIdUpload(_x10, _x11, _x12, _x13, _x14) {
8770
8537
  return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8771
8538
  }
8772
8539
  function _prepareSourceMapForDebugIdUpload() {
8773
- _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8540
+ _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(sourceMapPath, targetPath, debugId, rewriteSourcesHook, logger) {
8774
8541
  var sourceMapFileContent, map;
8775
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
8776
- while (1) switch (_context13.prev = _context13.next) {
8542
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
8543
+ while (1) switch (_context5.prev = _context5.next) {
8777
8544
  case 0:
8778
- _context13.prev = 0;
8779
- _context13.next = 3;
8545
+ _context5.prev = 0;
8546
+ _context5.next = 3;
8780
8547
  return util__namespace.promisify(fs__default["default"].readFile)(sourceMapPath, {
8781
8548
  encoding: "utf8"
8782
8549
  });
8783
8550
  case 3:
8784
- sourceMapFileContent = _context13.sent;
8785
- _context13.next = 10;
8551
+ sourceMapFileContent = _context5.sent;
8552
+ _context5.next = 10;
8786
8553
  break;
8787
8554
  case 6:
8788
- _context13.prev = 6;
8789
- _context13.t0 = _context13["catch"](0);
8790
- logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context13.t0);
8791
- return _context13.abrupt("return");
8555
+ _context5.prev = 6;
8556
+ _context5.t0 = _context5["catch"](0);
8557
+ logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context5.t0);
8558
+ return _context5.abrupt("return");
8792
8559
  case 10:
8793
- _context13.prev = 10;
8560
+ _context5.prev = 10;
8794
8561
  map = JSON.parse(sourceMapFileContent);
8795
8562
  // For now we write both fields until we know what will become the standard - if ever.
8796
8563
  map["debug_id"] = debugId;
8797
8564
  map["debugId"] = debugId;
8798
- _context13.next = 20;
8565
+ _context5.next = 20;
8799
8566
  break;
8800
8567
  case 16:
8801
- _context13.prev = 16;
8802
- _context13.t1 = _context13["catch"](10);
8568
+ _context5.prev = 16;
8569
+ _context5.t1 = _context5["catch"](10);
8803
8570
  logger.error("Failed to parse source map for debug ID upload: ".concat(sourceMapPath));
8804
- return _context13.abrupt("return");
8571
+ return _context5.abrupt("return");
8805
8572
  case 20:
8806
8573
  if (map["sources"] && Array.isArray(map["sources"])) {
8807
8574
  map["sources"] = map["sources"].map(function (source) {
8808
8575
  return rewriteSourcesHook(source, map);
8809
8576
  });
8810
8577
  }
8811
- _context13.prev = 21;
8812
- _context13.next = 24;
8813
- return fs__default["default"].promises.mkdir(path__default["default"].dirname(targetPath), {
8814
- recursive: true
8815
- });
8816
- case 24:
8817
- _context13.next = 26;
8818
- return fs__default["default"].promises.writeFile(targetPath, JSON.stringify(map), {
8578
+ _context5.prev = 21;
8579
+ _context5.next = 24;
8580
+ return util__namespace.promisify(fs__default["default"].writeFile)(targetPath, JSON.stringify(map), {
8819
8581
  encoding: "utf8"
8820
8582
  });
8821
- case 26:
8822
- _context13.next = 32;
8583
+ case 24:
8584
+ _context5.next = 30;
8823
8585
  break;
8824
- case 28:
8825
- _context13.prev = 28;
8826
- _context13.t2 = _context13["catch"](21);
8827
- logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context13.t2);
8828
- return _context13.abrupt("return");
8829
- case 32:
8586
+ case 26:
8587
+ _context5.prev = 26;
8588
+ _context5.t2 = _context5["catch"](21);
8589
+ logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context5.t2);
8590
+ return _context5.abrupt("return");
8591
+ case 30:
8830
8592
  case "end":
8831
- return _context13.stop();
8593
+ return _context5.stop();
8832
8594
  }
8833
- }, _callee13, null, [[0, 6], [10, 16], [21, 28]]);
8595
+ }, _callee5, null, [[0, 6], [10, 16], [21, 26]]);
8834
8596
  }));
8835
8597
  return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
8836
8598
  }
@@ -8844,50 +8606,329 @@ function defaultRewriteSourcesHook(source) {
8844
8606
  }
8845
8607
 
8846
8608
  /**
8847
- * Creates a plugin that creates releases, sets commits, deploys and finalizes releases.
8609
+ * Creates a build plugin manager that exposes primitives for everything that a Sentry JavaScript SDK or build tooling may do during a build.
8848
8610
  *
8849
- * Additionally, if legacy upload options are set, it uploads source maps in the legacy (non-debugId) way.
8850
- */
8851
- function releaseManagementPlugin(_ref) {
8852
- var logger = _ref.logger,
8853
- releaseName = _ref.releaseName,
8854
- include = _ref.include,
8855
- dist = _ref.dist,
8856
- setCommitsOption = _ref.setCommitsOption,
8857
- shouldCreateRelease = _ref.shouldCreateRelease,
8858
- shouldFinalizeRelease = _ref.shouldFinalizeRelease,
8859
- deployOptions = _ref.deployOptions,
8860
- handleRecoverableError = _ref.handleRecoverableError,
8861
- sentryScope = _ref.sentryScope,
8862
- sentryClient = _ref.sentryClient,
8863
- sentryCliOptions = _ref.sentryCliOptions,
8864
- createDependencyOnSourcemapFiles = _ref.createDependencyOnSourcemapFiles;
8865
- var freeGlobalDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8611
+ * The build plugin manager's behavior strongly depends on the options that are passed in.
8612
+ */
8613
+ function createSentryBuildPluginManager(userOptions, bundlerPluginMetaContext) {
8614
+ var _userOptions$silent, _userOptions$debug;
8615
+ var logger = createLogger({
8616
+ prefix: bundlerPluginMetaContext.loggerPrefix,
8617
+ silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
8618
+ debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false
8619
+ });
8620
+ try {
8621
+ var dotenvFile = fs__namespace.readFileSync(path__namespace.join(process.cwd(), ".env.sentry-build-plugin"), "utf-8");
8622
+ // 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.
8623
+ var dotenvResult = dotenv__namespace.parse(dotenvFile);
8624
+
8625
+ // Vite has a bug/behaviour where spreading into process.env will cause it to crash
8626
+ // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
8627
+ Object.assign(process.env, dotenvResult);
8628
+ logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
8629
+ } catch (e) {
8630
+ // Ignore "file not found" errors but throw all others
8631
+ if (_typeof(e) === "object" && e && "code" in e && e.code !== "ENOENT") {
8632
+ throw e;
8633
+ }
8634
+ }
8635
+ var options = normalizeUserOptions(userOptions);
8636
+ var shouldSendTelemetry = allowedToSendTelemetry(options);
8637
+ var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, bundlerPluginMetaContext.buildTool),
8638
+ sentryScope = _createSentryInstance.sentryScope,
8639
+ sentryClient = _createSentryInstance.sentryClient;
8640
+ var _sentryClient$getOpti = sentryClient.getOptions(),
8641
+ release = _sentryClient$getOpti.release,
8642
+ _sentryClient$getOpti2 = _sentryClient$getOpti.environment,
8643
+ environment = _sentryClient$getOpti2 === void 0 ? DEFAULT_ENVIRONMENT : _sentryClient$getOpti2;
8644
+ var sentrySession = makeSession({
8645
+ release: release,
8646
+ environment: environment
8647
+ });
8648
+ sentryScope.setSession(sentrySession);
8649
+ // Send the start of the session
8650
+ sentryClient.captureSession(sentrySession);
8651
+ var sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
8652
+
8653
+ function endSession() {
8654
+ if (sessionHasEnded) {
8655
+ return;
8656
+ }
8657
+ closeSession(sentrySession);
8658
+ sentryClient.captureSession(sentrySession);
8659
+ sessionHasEnded = true;
8660
+ }
8661
+
8662
+ // We also need to manually end sessions on errors because beforeExit is not called on crashes
8663
+ process.on("beforeExit", function () {
8664
+ endSession();
8665
+ });
8666
+
8667
+ // Set the User-Agent that Sentry CLI will use when interacting with Sentry
8668
+ process.env["SENTRY_PIPELINE"] = "".concat(bundlerPluginMetaContext.buildTool, "-plugin/", "3.3.0-alpha.0");
8669
+
8670
+ // Not a bulletproof check but should be good enough to at least sometimes determine
8671
+ // if the plugin is called in dev/watch mode or for a prod build. The important part
8672
+ // here is to avoid a false positive. False negatives are okay.
8673
+ var isDevMode = process.env["NODE_ENV"] === "development";
8674
+
8675
+ /**
8676
+ * Handles errors caught and emitted in various areas of the plugin.
8677
+ *
8678
+ * Also sets the sentry session status according to the error handling.
8679
+ *
8680
+ * If users specify their custom `errorHandler` we'll leave the decision to throw
8681
+ * or continue up to them. By default, @param throwByDefault controls if the plugin
8682
+ * should throw an error (which causes a build fail in most bundlers) or continue.
8683
+ */
8684
+ function handleRecoverableError(unknownError, throwByDefault) {
8685
+ sentrySession.status = "abnormal";
8686
+ try {
8687
+ if (options.errorHandler) {
8688
+ try {
8689
+ if (unknownError instanceof Error) {
8690
+ options.errorHandler(unknownError);
8691
+ } else {
8692
+ options.errorHandler(new Error("An unknown error occurred"));
8693
+ }
8694
+ } catch (e) {
8695
+ sentrySession.status = "crashed";
8696
+ throw e;
8697
+ }
8698
+ } else {
8699
+ // setting the session to "crashed" b/c from a plugin perspective this run failed.
8700
+ // However, we're intentionally not rethrowing the error to avoid breaking the user build.
8701
+ sentrySession.status = "crashed";
8702
+ if (throwByDefault) {
8703
+ throw unknownError;
8704
+ }
8705
+ logger.error("An error occurred. Couldn't finish all operations:", unknownError);
8706
+ }
8707
+ } finally {
8708
+ endSession();
8709
+ }
8710
+ }
8711
+ if (!validateOptions(options, logger)) {
8712
+ // Throwing by default to avoid a misconfigured plugin going unnoticed.
8713
+ handleRecoverableError(new Error("Options were not set correctly. See output above for more details."), true);
8714
+ }
8715
+
8716
+ // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)
8717
+ // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.
8718
+ // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).
8719
+ // Since the plugins among themselves are not aware of when they run and finish, we need a system to
8720
+ // track their dependencies on the generated files, so that we can initiate the file deletion only after
8721
+ // nothing depends on the files anymore.
8722
+ var dependenciesOnBuildArtifacts = new Set();
8723
+ var buildArtifactsDependencySubscribers = [];
8724
+ function notifyBuildArtifactDependencySubscribers() {
8725
+ buildArtifactsDependencySubscribers.forEach(function (subscriber) {
8726
+ subscriber();
8727
+ });
8728
+ }
8729
+ function createDependencyOnBuildArtifacts() {
8730
+ var dependencyIdentifier = Symbol();
8731
+ dependenciesOnBuildArtifacts.add(dependencyIdentifier);
8732
+ return function freeDependencyOnBuildArtifacts() {
8733
+ dependenciesOnBuildArtifacts["delete"](dependencyIdentifier);
8734
+ notifyBuildArtifactDependencySubscribers();
8735
+ };
8736
+ }
8737
+
8738
+ /**
8739
+ * Returns a Promise that resolves when all the currently active dependencies are freed again.
8740
+ *
8741
+ * It is very important that this function is called as late as possible before wanting to await the Promise to give
8742
+ * the dependency producers as much time as possible to register themselves.
8743
+ */
8744
+ function waitUntilBuildArtifactDependenciesAreFreed() {
8745
+ return new Promise(function (resolve) {
8746
+ buildArtifactsDependencySubscribers.push(function () {
8747
+ if (dependenciesOnBuildArtifacts.size === 0) {
8748
+ resolve();
8749
+ }
8750
+ });
8751
+ if (dependenciesOnBuildArtifacts.size === 0) {
8752
+ resolve();
8753
+ }
8754
+ });
8755
+ }
8756
+ var bundleSizeOptimizationReplacementValues = {};
8757
+ if (options.bundleSizeOptimizations) {
8758
+ var bundleSizeOptimizations = options.bundleSizeOptimizations;
8759
+ if (bundleSizeOptimizations.excludeDebugStatements) {
8760
+ bundleSizeOptimizationReplacementValues["__SENTRY_DEBUG__"] = false;
8761
+ }
8762
+ if (bundleSizeOptimizations.excludeTracing) {
8763
+ bundleSizeOptimizationReplacementValues["__SENTRY_TRACING__"] = false;
8764
+ }
8765
+ if (bundleSizeOptimizations.excludeReplayCanvas) {
8766
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
8767
+ }
8768
+ if (bundleSizeOptimizations.excludeReplayIframe) {
8769
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
8770
+ }
8771
+ if (bundleSizeOptimizations.excludeReplayShadowDom) {
8772
+ bundleSizeOptimizationReplacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
8773
+ }
8774
+ if (bundleSizeOptimizations.excludeReplayWorker) {
8775
+ bundleSizeOptimizationReplacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
8776
+ }
8777
+ }
8778
+ var bundleMetadata = {};
8779
+ if (options.moduleMetadata || options.applicationKey) {
8780
+ if (options.applicationKey) {
8781
+ // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.
8782
+ // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple
8783
+ // injections, the first injection will always "win" because it comes last in the code. We would generally be
8784
+ // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing
8785
+ // the app keys in different object keys.
8786
+ // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.
8787
+ bundleMetadata["_sentryBundlerPluginAppKey:".concat(options.applicationKey)] = true;
8788
+ }
8789
+ if (typeof options.moduleMetadata === "function") {
8790
+ var args = {
8791
+ org: options.org,
8792
+ project: options.project,
8793
+ release: options.release.name
8794
+ };
8795
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
8796
+ bundleMetadata = _objectSpread2(_objectSpread2({}, bundleMetadata), options.moduleMetadata(args));
8797
+ } else {
8798
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
8799
+ bundleMetadata = _objectSpread2(_objectSpread2({}, bundleMetadata), options.moduleMetadata);
8800
+ }
8801
+ }
8866
8802
  return {
8867
- name: "sentry-release-management-plugin",
8868
- writeBundle: function writeBundle() {
8869
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8803
+ /**
8804
+ * A logger instance that takes the options passed to the build plugin manager into account. (for silencing and log level etc.)
8805
+ */
8806
+ logger: logger,
8807
+ /**
8808
+ * Options after normalization. Includes things like the inferred release name.
8809
+ */
8810
+ normalizedOptions: options,
8811
+ /**
8812
+ * Magic strings and their replacement values that can be used for bundle size optimizations. This already takes
8813
+ * into account the options passed to the build plugin manager.
8814
+ */
8815
+ bundleSizeOptimizationReplacementValues: bundleSizeOptimizationReplacementValues,
8816
+ /**
8817
+ * Metadata that should be injected into bundles if possible. Takes into account options passed to the build plugin manager.
8818
+ */
8819
+ // See `generateModuleMetadataInjectorCode` for how this should be used exactly
8820
+ bundleMetadata: bundleMetadata,
8821
+ /**
8822
+ * Contains utility functions for emitting telemetry via the build plugin manager.
8823
+ */
8824
+ telemetry: {
8825
+ /**
8826
+ * Emits a `Sentry Bundler Plugin execution` signal.
8827
+ */
8828
+ emitBundlerPluginExecutionSignal: function emitBundlerPluginExecutionSignal() {
8829
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8830
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
8831
+ while (1) switch (_context.prev = _context.next) {
8832
+ case 0:
8833
+ _context.next = 2;
8834
+ return shouldSendTelemetry;
8835
+ case 2:
8836
+ if (!_context.sent) {
8837
+ _context.next = 7;
8838
+ break;
8839
+ }
8840
+ logger.info("Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
8841
+ startSpan({
8842
+ name: "Sentry Bundler Plugin execution",
8843
+ scope: sentryScope
8844
+ }, function () {
8845
+ //
8846
+ });
8847
+ _context.next = 7;
8848
+ return safeFlushTelemetry(sentryClient);
8849
+ case 7:
8850
+ case "end":
8851
+ return _context.stop();
8852
+ }
8853
+ }, _callee);
8854
+ }))();
8855
+ }
8856
+ },
8857
+ /**
8858
+ * Will potentially create a release based on the build plugin manager options.
8859
+ *
8860
+ * Also
8861
+ * - finalizes the release
8862
+ * - sets commits
8863
+ * - uploads legacy sourcemaps
8864
+ * - adds deploy information
8865
+ */
8866
+ createRelease: function createRelease() {
8867
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
8870
8868
  var freeWriteBundleInvocationDependencyOnSourcemapFiles, cliInstance, normalizedInclude;
8871
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8872
- while (1) switch (_context.prev = _context.next) {
8869
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
8870
+ while (1) switch (_context2.prev = _context2.next) {
8873
8871
  case 0:
8872
+ if (options.release.name) {
8873
+ _context2.next = 5;
8874
+ break;
8875
+ }
8876
+ logger.debug("No release name provided. Will not create release. Please set the `release.name` option to identify your release.");
8877
+ return _context2.abrupt("return");
8878
+ case 5:
8879
+ if (!isDevMode) {
8880
+ _context2.next = 10;
8881
+ break;
8882
+ }
8883
+ logger.debug("Running in development mode. Will not create release.");
8884
+ return _context2.abrupt("return");
8885
+ case 10:
8886
+ if (options.authToken) {
8887
+ _context2.next = 15;
8888
+ break;
8889
+ }
8890
+ logger.warn("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"));
8891
+ return _context2.abrupt("return");
8892
+ case 15:
8893
+ if (!(!options.org && !options.authToken.startsWith("sntrys_"))) {
8894
+ _context2.next = 20;
8895
+ break;
8896
+ }
8897
+ logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
8898
+ return _context2.abrupt("return");
8899
+ case 20:
8900
+ if (options.project) {
8901
+ _context2.next = 23;
8902
+ break;
8903
+ }
8904
+ logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
8905
+ return _context2.abrupt("return");
8906
+ case 23:
8874
8907
  // 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`)
8875
8908
  // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
8876
- freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnSourcemapFiles();
8877
- _context.prev = 1;
8878
- cliInstance = new SentryCli__default["default"](null, sentryCliOptions);
8879
- if (!shouldCreateRelease) {
8880
- _context.next = 6;
8909
+ freeWriteBundleInvocationDependencyOnSourcemapFiles = createDependencyOnBuildArtifacts();
8910
+ _context2.prev = 24;
8911
+ cliInstance = new SentryCli__default["default"](null, {
8912
+ authToken: options.authToken,
8913
+ org: options.org,
8914
+ project: options.project,
8915
+ silent: options.silent,
8916
+ url: options.url,
8917
+ vcsRemote: options.release.vcsRemote,
8918
+ headers: options.headers
8919
+ });
8920
+ if (!options.release.create) {
8921
+ _context2.next = 29;
8881
8922
  break;
8882
8923
  }
8883
- _context.next = 6;
8884
- return cliInstance.releases["new"](releaseName);
8885
- case 6:
8886
- if (!include) {
8887
- _context.next = 10;
8924
+ _context2.next = 29;
8925
+ return cliInstance.releases["new"](options.release.name);
8926
+ case 29:
8927
+ if (!options.release.uploadLegacySourcemaps) {
8928
+ _context2.next = 33;
8888
8929
  break;
8889
8930
  }
8890
- normalizedInclude = arrayify$1(include).map(function (includeItem) {
8931
+ normalizedInclude = arrayify(options.release.uploadLegacySourcemaps).map(function (includeItem) {
8891
8932
  return typeof includeItem === "string" ? {
8892
8933
  paths: [includeItem]
8893
8934
  } : includeItem;
@@ -8898,202 +8939,409 @@ function releaseManagementPlugin(_ref) {
8898
8939
  ext: includeEntry.ext ? includeEntry.ext.map(function (extension) {
8899
8940
  return ".".concat(extension.replace(/^\./, ""));
8900
8941
  }) : [".js", ".map", ".jsbundle", ".bundle"],
8901
- ignore: includeEntry.ignore ? arrayify$1(includeEntry.ignore) : undefined
8942
+ ignore: includeEntry.ignore ? arrayify(includeEntry.ignore) : undefined
8902
8943
  });
8903
8944
  });
8904
- _context.next = 10;
8905
- return cliInstance.releases.uploadSourceMaps(releaseName, {
8945
+ _context2.next = 33;
8946
+ return cliInstance.releases.uploadSourceMaps(options.release.name, {
8906
8947
  include: normalizedInclude,
8907
- dist: dist
8948
+ dist: options.release.dist
8908
8949
  });
8909
- case 10:
8910
- if (!(setCommitsOption !== false)) {
8911
- _context.next = 23;
8950
+ case 33:
8951
+ if (!(options.release.setCommits !== false)) {
8952
+ _context2.next = 46;
8912
8953
  break;
8913
8954
  }
8914
- _context.prev = 11;
8915
- _context.next = 14;
8916
- return cliInstance.releases.setCommits(releaseName, setCommitsOption);
8917
- case 14:
8918
- _context.next = 23;
8955
+ _context2.prev = 34;
8956
+ _context2.next = 37;
8957
+ return cliInstance.releases.setCommits(options.release.name,
8958
+ // set commits always exists due to the normalize function
8959
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
8960
+ options.release.setCommits);
8961
+ case 37:
8962
+ _context2.next = 46;
8919
8963
  break;
8920
- case 16:
8921
- _context.prev = 16;
8922
- _context.t0 = _context["catch"](11);
8923
- if (!("shouldNotThrowOnFailure" in setCommitsOption && setCommitsOption.shouldNotThrowOnFailure)) {
8924
- _context.next = 22;
8964
+ case 39:
8965
+ _context2.prev = 39;
8966
+ _context2.t0 = _context2["catch"](34);
8967
+ if (!(options.release.setCommits && "shouldNotThrowOnFailure" in options.release.setCommits && options.release.setCommits.shouldNotThrowOnFailure)) {
8968
+ _context2.next = 45;
8925
8969
  break;
8926
8970
  }
8927
- logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release are desired):", _context.t0);
8928
- _context.next = 23;
8971
+ logger.debug("An error occurred setting commits on release (this message can be ignored unless you commits on release are desired):", _context2.t0);
8972
+ _context2.next = 46;
8929
8973
  break;
8930
- case 22:
8931
- throw _context.t0;
8932
- case 23:
8933
- if (!shouldFinalizeRelease) {
8934
- _context.next = 26;
8974
+ case 45:
8975
+ throw _context2.t0;
8976
+ case 46:
8977
+ if (!options.release.finalize) {
8978
+ _context2.next = 49;
8935
8979
  break;
8936
8980
  }
8937
- _context.next = 26;
8938
- return cliInstance.releases.finalize(releaseName);
8939
- case 26:
8940
- if (!deployOptions) {
8941
- _context.next = 29;
8981
+ _context2.next = 49;
8982
+ return cliInstance.releases.finalize(options.release.name);
8983
+ case 49:
8984
+ if (!options.release.deploy) {
8985
+ _context2.next = 52;
8942
8986
  break;
8943
8987
  }
8944
- _context.next = 29;
8945
- return cliInstance.releases.newDeploy(releaseName, deployOptions);
8946
- case 29:
8947
- _context.next = 37;
8988
+ _context2.next = 52;
8989
+ return cliInstance.releases.newDeploy(options.release.name, options.release.deploy);
8990
+ case 52:
8991
+ _context2.next = 60;
8948
8992
  break;
8949
- case 31:
8950
- _context.prev = 31;
8951
- _context.t1 = _context["catch"](1);
8993
+ case 54:
8994
+ _context2.prev = 54;
8995
+ _context2.t1 = _context2["catch"](24);
8952
8996
  sentryScope.captureException('Error in "releaseManagementPlugin" writeBundle hook');
8953
- _context.next = 36;
8997
+ _context2.next = 59;
8954
8998
  return safeFlushTelemetry(sentryClient);
8955
- case 36:
8956
- handleRecoverableError(_context.t1, false);
8957
- case 37:
8958
- _context.prev = 37;
8959
- freeGlobalDependencyOnSourcemapFiles();
8999
+ case 59:
9000
+ handleRecoverableError(_context2.t1, false);
9001
+ case 60:
9002
+ _context2.prev = 60;
8960
9003
  freeWriteBundleInvocationDependencyOnSourcemapFiles();
8961
- return _context.finish(37);
8962
- case 41:
9004
+ return _context2.finish(60);
9005
+ case 63:
8963
9006
  case "end":
8964
- return _context.stop();
9007
+ return _context2.stop();
8965
9008
  }
8966
- }, _callee, null, [[1, 31, 37, 41], [11, 16]]);
9009
+ }, _callee2, null, [[24, 54, 60, 63], [34, 39]]);
8967
9010
  }))();
8968
- }
8969
- };
8970
- }
8971
-
8972
- function telemetryPlugin(_ref) {
8973
- var sentryClient = _ref.sentryClient,
8974
- sentryScope = _ref.sentryScope,
8975
- shouldSendTelemetry = _ref.shouldSendTelemetry,
8976
- logger = _ref.logger;
8977
- return {
8978
- name: "sentry-telemetry-plugin",
8979
- buildStart: function buildStart() {
8980
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
8981
- return _regeneratorRuntime().wrap(function _callee$(_context) {
8982
- while (1) switch (_context.prev = _context.next) {
9011
+ },
9012
+ /**
9013
+ * Uploads sourcemaps using the "Debug ID" method. This function takes a list of build artifact paths that will be uploaded
9014
+ */
9015
+ uploadSourcemaps: function uploadSourcemaps(buildArtifactPaths) {
9016
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
9017
+ var _options$sourcemaps;
9018
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
9019
+ while (1) switch (_context11.prev = _context11.next) {
8983
9020
  case 0:
8984
- _context.next = 2;
8985
- return shouldSendTelemetry;
8986
- case 2:
8987
- if (!_context.sent) {
8988
- _context.next = 7;
8989
- break;
9021
+ if ((_options$sourcemaps = options.sourcemaps) !== null && _options$sourcemaps !== void 0 && _options$sourcemaps.disable) {
9022
+ logger.debug("Source map upload was disabled. Will not upload sourcemaps using debug ID process.");
9023
+ } else if (isDevMode) {
9024
+ logger.debug("Running in development mode. Will not upload sourcemaps.");
9025
+ } else if (!options.authToken) {
9026
+ logger.warn("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"));
9027
+ } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9028
+ logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9029
+ } else if (!options.project) {
9030
+ logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
8990
9031
  }
8991
- logger.info("Sending telemetry data on issues and performance to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
8992
- startSpan({
8993
- name: "Sentry Bundler Plugin execution",
8994
- scope: sentryScope
8995
- }, function () {
8996
- //
8997
- });
8998
- _context.next = 7;
8999
- return safeFlushTelemetry(sentryClient);
9000
- case 7:
9032
+ _context11.next = 3;
9033
+ return startSpan(
9034
+ // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions.
9035
+ {
9036
+ name: "debug-id-sourcemap-upload",
9037
+ scope: sentryScope,
9038
+ forceTransaction: true
9039
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
9040
+ var folderToCleanUp, freeUploadDependencyOnBuildArtifacts, _options$sourcemaps2, tmpUploadFolder, assets, globAssets, globResult, debugIdChunkFilePaths;
9041
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
9042
+ while (1) switch (_context10.prev = _context10.next) {
9043
+ case 0:
9044
+ // 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`)
9045
+ // Therefore we need to actually register the execution of this hook as dependency on the sourcemap files.
9046
+ freeUploadDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
9047
+ _context10.prev = 1;
9048
+ _context10.next = 4;
9049
+ return startSpan({
9050
+ name: "mkdtemp",
9051
+ scope: sentryScope
9052
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
9053
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
9054
+ while (1) switch (_context3.prev = _context3.next) {
9055
+ case 0:
9056
+ _context3.next = 2;
9057
+ return fs__namespace.promises.mkdtemp(path__namespace.join(os__namespace.tmpdir(), "sentry-bundler-plugin-upload-"));
9058
+ case 2:
9059
+ return _context3.abrupt("return", _context3.sent);
9060
+ case 3:
9061
+ case "end":
9062
+ return _context3.stop();
9063
+ }
9064
+ }, _callee3);
9065
+ })));
9066
+ case 4:
9067
+ tmpUploadFolder = _context10.sent;
9068
+ folderToCleanUp = tmpUploadFolder;
9069
+ assets = (_options$sourcemaps2 = options.sourcemaps) === null || _options$sourcemaps2 === void 0 ? void 0 : _options$sourcemaps2.assets;
9070
+ if (assets) {
9071
+ globAssets = assets;
9072
+ } else {
9073
+ logger.debug("No `sourcemaps.assets` option provided, falling back to uploading detected build artifacts.");
9074
+ globAssets = buildArtifactPaths;
9075
+ }
9076
+ _context10.next = 10;
9077
+ return startSpan({
9078
+ name: "glob",
9079
+ scope: sentryScope
9080
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
9081
+ var _options$sourcemaps3;
9082
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
9083
+ while (1) switch (_context4.prev = _context4.next) {
9084
+ case 0:
9085
+ _context4.next = 2;
9086
+ return glob.glob(globAssets, {
9087
+ absolute: true,
9088
+ nodir: true,
9089
+ ignore: (_options$sourcemaps3 = options.sourcemaps) === null || _options$sourcemaps3 === void 0 ? void 0 : _options$sourcemaps3.ignore
9090
+ });
9091
+ case 2:
9092
+ return _context4.abrupt("return", _context4.sent);
9093
+ case 3:
9094
+ case "end":
9095
+ return _context4.stop();
9096
+ }
9097
+ }, _callee4);
9098
+ })));
9099
+ case 10:
9100
+ globResult = _context10.sent;
9101
+ debugIdChunkFilePaths = globResult.filter(function (debugIdChunkFilePath) {
9102
+ return !!stripQueryAndHashFromPath(debugIdChunkFilePath).match(/\.(js|mjs|cjs)$/);
9103
+ }); // The order of the files output by glob() is not deterministic
9104
+ // Ensure order within the files so that {debug-id}-{chunkIndex} coupling is consistent
9105
+ debugIdChunkFilePaths.sort();
9106
+ if (!(Array.isArray(assets) && assets.length === 0)) {
9107
+ _context10.next = 17;
9108
+ break;
9109
+ }
9110
+ logger.debug("Empty `sourcemaps.assets` option provided. Will not upload sourcemaps with debug ID.");
9111
+ _context10.next = 24;
9112
+ break;
9113
+ case 17:
9114
+ if (!(debugIdChunkFilePaths.length === 0)) {
9115
+ _context10.next = 21;
9116
+ break;
9117
+ }
9118
+ logger.warn("Didn't find any matching sources for debug ID upload. Please check the `sourcemaps.assets` option.");
9119
+ _context10.next = 24;
9120
+ break;
9121
+ case 21:
9122
+ _context10.next = 23;
9123
+ return startSpan({
9124
+ name: "prepare-bundles",
9125
+ scope: sentryScope
9126
+ }, /*#__PURE__*/function () {
9127
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(prepBundlesSpan) {
9128
+ var preparationTasks, workers, worker, workerIndex, files, stats, uploadSize;
9129
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
9130
+ while (1) switch (_context8.prev = _context8.next) {
9131
+ case 0:
9132
+ // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so
9133
+ // instead we do it with a maximum of 16 concurrent workers
9134
+ preparationTasks = debugIdChunkFilePaths.map(function (chunkFilePath, chunkIndex) {
9135
+ return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
9136
+ var _options$sourcemaps$r, _options$sourcemaps4;
9137
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
9138
+ while (1) switch (_context5.prev = _context5.next) {
9139
+ case 0:
9140
+ _context5.next = 2;
9141
+ return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, chunkIndex, logger, (_options$sourcemaps$r = (_options$sourcemaps4 = options.sourcemaps) === null || _options$sourcemaps4 === void 0 ? void 0 : _options$sourcemaps4.rewriteSources) !== null && _options$sourcemaps$r !== void 0 ? _options$sourcemaps$r : defaultRewriteSourcesHook);
9142
+ case 2:
9143
+ case "end":
9144
+ return _context5.stop();
9145
+ }
9146
+ }, _callee5);
9147
+ }));
9148
+ });
9149
+ workers = [];
9150
+ worker = /*#__PURE__*/function () {
9151
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
9152
+ var task;
9153
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
9154
+ while (1) switch (_context6.prev = _context6.next) {
9155
+ case 0:
9156
+ if (!(preparationTasks.length > 0)) {
9157
+ _context6.next = 7;
9158
+ break;
9159
+ }
9160
+ task = preparationTasks.shift();
9161
+ if (!task) {
9162
+ _context6.next = 5;
9163
+ break;
9164
+ }
9165
+ _context6.next = 5;
9166
+ return task();
9167
+ case 5:
9168
+ _context6.next = 0;
9169
+ break;
9170
+ case 7:
9171
+ case "end":
9172
+ return _context6.stop();
9173
+ }
9174
+ }, _callee6);
9175
+ }));
9176
+ return function worker() {
9177
+ return _ref6.apply(this, arguments);
9178
+ };
9179
+ }();
9180
+ for (workerIndex = 0; workerIndex < 16; workerIndex++) {
9181
+ workers.push(worker());
9182
+ }
9183
+ _context8.next = 6;
9184
+ return Promise.all(workers);
9185
+ case 6:
9186
+ _context8.next = 8;
9187
+ return fs__namespace.promises.readdir(tmpUploadFolder);
9188
+ case 8:
9189
+ files = _context8.sent;
9190
+ stats = files.map(function (file) {
9191
+ return fs__namespace.promises.stat(path__namespace.join(tmpUploadFolder, file));
9192
+ });
9193
+ _context8.next = 12;
9194
+ return Promise.all(stats);
9195
+ case 12:
9196
+ uploadSize = _context8.sent.reduce(function (accumulator, _ref7) {
9197
+ var size = _ref7.size;
9198
+ return accumulator + size;
9199
+ }, 0);
9200
+ setMeasurement("files", files.length, "none", prepBundlesSpan);
9201
+ setMeasurement("upload_size", uploadSize, "byte", prepBundlesSpan);
9202
+ _context8.next = 17;
9203
+ return startSpan({
9204
+ name: "upload",
9205
+ scope: sentryScope
9206
+ }, /*#__PURE__*/function () {
9207
+ var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(uploadSpan) {
9208
+ var _options$release$name;
9209
+ var cliInstance;
9210
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
9211
+ while (1) switch (_context7.prev = _context7.next) {
9212
+ case 0:
9213
+ cliInstance = new SentryCli__default["default"](null, {
9214
+ authToken: options.authToken,
9215
+ org: options.org,
9216
+ project: options.project,
9217
+ silent: options.silent,
9218
+ url: options.url,
9219
+ vcsRemote: options.release.vcsRemote,
9220
+ headers: _objectSpread2({
9221
+ "sentry-trace": spanToTraceHeader(uploadSpan),
9222
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9223
+ baggage: dynamicSamplingContextToSentryBaggageHeader(getDynamicSamplingContextFromSpan(uploadSpan))
9224
+ }, options.headers)
9225
+ });
9226
+ _context7.next = 3;
9227
+ return cliInstance.releases.uploadSourceMaps((_options$release$name = options.release.name) !== null && _options$release$name !== void 0 ? _options$release$name : "undefined",
9228
+ // unfortunately this needs a value for now but it will not matter since debug IDs overpower releases anyhow
9229
+ {
9230
+ include: [{
9231
+ paths: [tmpUploadFolder],
9232
+ rewrite: false,
9233
+ dist: options.release.dist
9234
+ }]
9235
+ });
9236
+ case 3:
9237
+ case "end":
9238
+ return _context7.stop();
9239
+ }
9240
+ }, _callee7);
9241
+ }));
9242
+ return function (_x2) {
9243
+ return _ref8.apply(this, arguments);
9244
+ };
9245
+ }());
9246
+ case 17:
9247
+ case "end":
9248
+ return _context8.stop();
9249
+ }
9250
+ }, _callee8);
9251
+ }));
9252
+ return function (_x) {
9253
+ return _ref4.apply(this, arguments);
9254
+ };
9255
+ }());
9256
+ case 23:
9257
+ logger.info("Successfully uploaded source maps to Sentry");
9258
+ case 24:
9259
+ _context10.next = 30;
9260
+ break;
9261
+ case 26:
9262
+ _context10.prev = 26;
9263
+ _context10.t0 = _context10["catch"](1);
9264
+ sentryScope.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
9265
+ handleRecoverableError(_context10.t0, false);
9266
+ case 30:
9267
+ _context10.prev = 30;
9268
+ if (folderToCleanUp) {
9269
+ void startSpan({
9270
+ name: "cleanup",
9271
+ scope: sentryScope
9272
+ }, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
9273
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
9274
+ while (1) switch (_context9.prev = _context9.next) {
9275
+ case 0:
9276
+ if (!folderToCleanUp) {
9277
+ _context9.next = 3;
9278
+ break;
9279
+ }
9280
+ _context9.next = 3;
9281
+ return fs__namespace.promises.rm(folderToCleanUp, {
9282
+ recursive: true,
9283
+ force: true
9284
+ });
9285
+ case 3:
9286
+ case "end":
9287
+ return _context9.stop();
9288
+ }
9289
+ }, _callee9);
9290
+ })));
9291
+ }
9292
+ freeUploadDependencyOnBuildArtifacts();
9293
+ _context10.next = 35;
9294
+ return safeFlushTelemetry(sentryClient);
9295
+ case 35:
9296
+ return _context10.finish(30);
9297
+ case 36:
9298
+ case "end":
9299
+ return _context10.stop();
9300
+ }
9301
+ }, _callee10, null, [[1, 26, 30, 36]]);
9302
+ })));
9303
+ case 3:
9001
9304
  case "end":
9002
- return _context.stop();
9305
+ return _context11.stop();
9003
9306
  }
9004
- }, _callee);
9307
+ }, _callee11);
9005
9308
  }))();
9006
- }
9007
- };
9008
- }
9009
-
9010
- // Logging everything to stderr not to interfere with stdout
9011
- function createLogger(options) {
9012
- return {
9013
- info: function info(message) {
9014
- if (!options.silent) {
9015
- var _console;
9016
- for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
9017
- params[_key - 1] = arguments[_key];
9018
- }
9019
- // eslint-disable-next-line no-console
9020
- (_console = console).info.apply(_console, ["".concat(options.prefix, " Info: ").concat(message)].concat(params));
9021
- }
9022
- },
9023
- warn: function warn(message) {
9024
- if (!options.silent) {
9025
- var _console2;
9026
- for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
9027
- params[_key2 - 1] = arguments[_key2];
9028
- }
9029
- // eslint-disable-next-line no-console
9030
- (_console2 = console).warn.apply(_console2, ["".concat(options.prefix, " Warning: ").concat(message)].concat(params));
9031
- }
9032
- },
9033
- error: function error(message) {
9034
- if (!options.silent) {
9035
- var _console3;
9036
- for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
9037
- params[_key3 - 1] = arguments[_key3];
9038
- }
9039
- // eslint-disable-next-line no-console
9040
- (_console3 = console).error.apply(_console3, ["".concat(options.prefix, " Error: ").concat(message)].concat(params));
9041
- }
9042
9309
  },
9043
- debug: function debug(message) {
9044
- if (!options.silent && options.debug) {
9045
- var _console4;
9046
- for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
9047
- params[_key4 - 1] = arguments[_key4];
9048
- }
9049
- // eslint-disable-next-line no-console
9050
- (_console4 = console).debug.apply(_console4, ["".concat(options.prefix, " Debug: ").concat(message)].concat(params));
9051
- }
9052
- }
9053
- };
9054
- }
9055
-
9056
- function fileDeletionPlugin(_ref) {
9057
- var handleRecoverableError = _ref.handleRecoverableError,
9058
- sentryScope = _ref.sentryScope,
9059
- sentryClient = _ref.sentryClient,
9060
- filesToDeleteAfterUpload = _ref.filesToDeleteAfterUpload,
9061
- waitUntilSourcemapFileDependenciesAreFreed = _ref.waitUntilSourcemapFileDependenciesAreFreed,
9062
- logger = _ref.logger;
9063
- return {
9064
- name: "sentry-file-deletion-plugin",
9065
- writeBundle: function writeBundle() {
9066
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9067
- var filesToDelete, filePathsToDelete;
9068
- return _regeneratorRuntime().wrap(function _callee$(_context) {
9069
- while (1) switch (_context.prev = _context.next) {
9310
+ /**
9311
+ * Will delete artifacts based on the passed `sourcemaps.filesToDeleteAfterUpload` option.
9312
+ */
9313
+ deleteArtifacts: function deleteArtifacts() {
9314
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
9315
+ var _options$sourcemaps5, filesToDelete, filePathsToDelete;
9316
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
9317
+ while (1) switch (_context12.prev = _context12.next) {
9070
9318
  case 0:
9071
- _context.prev = 0;
9072
- _context.next = 3;
9073
- return filesToDeleteAfterUpload;
9319
+ _context12.prev = 0;
9320
+ _context12.next = 3;
9321
+ return (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.filesToDeleteAfterUpload;
9074
9322
  case 3:
9075
- filesToDelete = _context.sent;
9323
+ filesToDelete = _context12.sent;
9076
9324
  if (!(filesToDelete !== undefined)) {
9077
- _context.next = 14;
9325
+ _context12.next = 14;
9078
9326
  break;
9079
9327
  }
9080
- _context.next = 7;
9328
+ _context12.next = 7;
9081
9329
  return glob.glob(filesToDelete, {
9082
9330
  absolute: true,
9083
9331
  nodir: true
9084
9332
  });
9085
9333
  case 7:
9086
- filePathsToDelete = _context.sent;
9334
+ filePathsToDelete = _context12.sent;
9087
9335
  logger.debug("Waiting for dependencies on generated files to be freed before deleting...");
9088
- _context.next = 11;
9089
- return waitUntilSourcemapFileDependenciesAreFreed();
9336
+ _context12.next = 11;
9337
+ return waitUntilBuildArtifactDependenciesAreFreed();
9090
9338
  case 11:
9091
9339
  filePathsToDelete.forEach(function (filePathToDelete) {
9092
9340
  logger.debug("Deleting asset after upload: ".concat(filePathToDelete));
9093
9341
  });
9094
- _context.next = 14;
9342
+ _context12.next = 14;
9095
9343
  return Promise.all(filePathsToDelete.map(function (filePathToDelete) {
9096
- return fs__default["default"].promises.rm(filePathToDelete, {
9344
+ return fs__namespace.promises.rm(filePathToDelete, {
9097
9345
  force: true
9098
9346
  })["catch"](function (e) {
9099
9347
  // This is allowed to fail - we just don't do anything
@@ -9101,53 +9349,31 @@ function fileDeletionPlugin(_ref) {
9101
9349
  });
9102
9350
  }));
9103
9351
  case 14:
9104
- _context.next = 22;
9352
+ _context12.next = 22;
9105
9353
  break;
9106
9354
  case 16:
9107
- _context.prev = 16;
9108
- _context.t0 = _context["catch"](0);
9355
+ _context12.prev = 16;
9356
+ _context12.t0 = _context12["catch"](0);
9109
9357
  sentryScope.captureException('Error in "sentry-file-deletion-plugin" buildEnd hook');
9110
- _context.next = 21;
9358
+ _context12.next = 21;
9111
9359
  return safeFlushTelemetry(sentryClient);
9112
9360
  case 21:
9113
9361
  // We throw by default if we get here b/c not being able to delete
9114
9362
  // source maps could leak them to production
9115
- handleRecoverableError(_context.t0, true);
9363
+ handleRecoverableError(_context12.t0, true);
9116
9364
  case 22:
9117
9365
  case "end":
9118
- return _context.stop();
9366
+ return _context12.stop();
9119
9367
  }
9120
- }, _callee, null, [[0, 16]]);
9368
+ }, _callee12, null, [[0, 16]]);
9121
9369
  }))();
9122
- }
9370
+ },
9371
+ createDependencyOnBuildArtifacts: createDependencyOnBuildArtifacts
9123
9372
  };
9124
9373
  }
9125
9374
 
9126
9375
  /**
9127
- * The sentry bundler plugin concerns itself with two things:
9128
- * - Release injection
9129
- * - Sourcemaps upload
9130
- *
9131
- * Release injection:
9132
- * Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
9133
- * that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector";`)
9134
- * to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
9135
- * by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
9136
- * If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
9137
- *
9138
- * Source maps upload:
9139
- *
9140
- * The sentry bundler plugin will also take care of uploading source maps to Sentry. This
9141
- * is all done in the `writeBundle` hook. In this hook the sentry plugin will execute the
9142
- * release creation pipeline:
9143
- *
9144
- * 1. Create a new release
9145
- * 2. Upload sourcemaps based on `include` and source-map-specific options
9146
- * 3. Associate a range of commits with the release (if `setCommits` is specified)
9147
- * 4. Finalize the release (unless `finalize` is disabled)
9148
- * 5. Add deploy information to the release (if `deploy` is specified)
9149
- *
9150
- * This release creation pipeline relies on Sentry CLI to execute the different steps.
9376
+ * Creates an unplugin instance used to create Sentry plugins for Vite, Rollup, esbuild, and Webpack.
9151
9377
  */
9152
9378
  function sentryUnpluginFactory(_ref) {
9153
9379
  var releaseInjectionPlugin = _ref.releaseInjectionPlugin,
@@ -9157,189 +9383,46 @@ function sentryUnpluginFactory(_ref) {
9157
9383
  debugIdUploadPlugin = _ref.debugIdUploadPlugin,
9158
9384
  bundleSizeOptimizationsPlugin = _ref.bundleSizeOptimizationsPlugin;
9159
9385
  return unplugin.createUnplugin(function () {
9160
- var _userOptions$_metaOpt, _userOptions$_metaOpt2, _userOptions$silent, _userOptions$debug, _options$sourcemaps, _options$sourcemaps2, _options$sourcemaps6;
9386
+ var _userOptions$_metaOpt, _userOptions$_metaOpt2, _options$sourcemaps;
9161
9387
  var userOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
9162
9388
  var unpluginMetaContext = arguments.length > 1 ? arguments[1] : undefined;
9163
- var logger = createLogger({
9164
- prefix: (_userOptions$_metaOpt = (_userOptions$_metaOpt2 = userOptions._metaOptions) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.loggerPrefixOverride) !== null && _userOptions$_metaOpt !== void 0 ? _userOptions$_metaOpt : "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
9165
- silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
9166
- debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false
9389
+ var sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {
9390
+ loggerPrefix: (_userOptions$_metaOpt = (_userOptions$_metaOpt2 = userOptions._metaOptions) === null || _userOptions$_metaOpt2 === void 0 ? void 0 : _userOptions$_metaOpt2.loggerPrefixOverride) !== null && _userOptions$_metaOpt !== void 0 ? _userOptions$_metaOpt : "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
9391
+ buildTool: unpluginMetaContext.framework
9167
9392
  });
9168
-
9169
- // Not a bulletproof check but should be good enough to at least sometimes determine
9170
- // if the plugin is called in dev/watch mode or for a prod build. The important part
9171
- // here is to avoid a false positive. False negatives are okay.
9172
- var isDevMode = process.env["NODE_ENV"] === "development";
9173
- try {
9174
- var dotenvFile = fs__namespace.readFileSync(path__namespace.join(process.cwd(), ".env.sentry-build-plugin"), "utf-8");
9175
- // 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.
9176
- var dotenvResult = dotenv__namespace.parse(dotenvFile);
9177
-
9178
- // Vite has a bug/behaviour where spreading into process.env will cause it to crash
9179
- // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251
9180
- Object.assign(process.env, dotenvResult);
9181
- logger.info('Using environment variables configured in ".env.sentry-build-plugin".');
9182
- } catch (e) {
9183
- // Ignore "file not found" errors but throw all others
9184
- if (_typeof(e) === "object" && e && "code" in e && e.code !== "ENOENT") {
9185
- throw e;
9186
- }
9187
- }
9188
- var options = normalizeUserOptions(userOptions);
9393
+ var logger = sentryBuildPluginManager.logger,
9394
+ options = sentryBuildPluginManager.normalizedOptions,
9395
+ bundleSizeOptimizationReplacementValues = sentryBuildPluginManager.bundleSizeOptimizationReplacementValues;
9189
9396
  if (options.disable) {
9190
9397
  return [{
9191
9398
  name: "sentry-noop-plugin"
9192
9399
  }];
9193
9400
  }
9194
- var shouldSendTelemetry = allowedToSendTelemetry(options);
9195
- var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, unpluginMetaContext.framework),
9196
- sentryScope = _createSentryInstance.sentryScope,
9197
- sentryClient = _createSentryInstance.sentryClient;
9198
- var _sentryClient$getOpti = sentryClient.getOptions(),
9199
- release = _sentryClient$getOpti.release,
9200
- _sentryClient$getOpti2 = _sentryClient$getOpti.environment,
9201
- environment = _sentryClient$getOpti2 === void 0 ? DEFAULT_ENVIRONMENT : _sentryClient$getOpti2;
9202
- var sentrySession = makeSession({
9203
- release: release,
9204
- environment: environment
9205
- });
9206
- sentryScope.setSession(sentrySession);
9207
- // Send the start of the session
9208
- sentryClient.captureSession(sentrySession);
9209
- var sessionHasEnded = false; // Just to prevent infinite loops with beforeExit, which is called whenever the event loop empties out
9210
-
9211
- function endSession() {
9212
- if (sessionHasEnded) {
9213
- return;
9214
- }
9215
- closeSession(sentrySession);
9216
- sentryClient.captureSession(sentrySession);
9217
- sessionHasEnded = true;
9218
- }
9219
-
9220
- // We also need to manually end sessions on errors because beforeExit is not called on crashes
9221
- process.on("beforeExit", function () {
9222
- endSession();
9223
- });
9224
-
9225
- // Set the User-Agent that Sentry CLI will use when interacting with Sentry
9226
- process.env["SENTRY_PIPELINE"] = "".concat(unpluginMetaContext.framework, "-plugin/", "3.2.3");
9227
-
9228
- /**
9229
- * Handles errors caught and emitted in various areas of the plugin.
9230
- *
9231
- * Also sets the sentry session status according to the error handling.
9232
- *
9233
- * If users specify their custom `errorHandler` we'll leave the decision to throw
9234
- * or continue up to them. By default, @param throwByDefault controls if the plugin
9235
- * should throw an error (which causes a build fail in most bundlers) or continue.
9236
- */
9237
- function handleRecoverableError(unknownError, throwByDefault) {
9238
- sentrySession.status = "abnormal";
9239
- try {
9240
- if (options.errorHandler) {
9241
- try {
9242
- if (unknownError instanceof Error) {
9243
- options.errorHandler(unknownError);
9244
- } else {
9245
- options.errorHandler(new Error("An unknown error occured"));
9246
- }
9247
- } catch (e) {
9248
- sentrySession.status = "crashed";
9249
- throw e;
9250
- }
9251
- } else {
9252
- // setting the session to "crashed" b/c from a plugin perspective this run failed.
9253
- // However, we're intentionally not rethrowing the error to avoid breaking the user build.
9254
- sentrySession.status = "crashed";
9255
- if (throwByDefault) {
9256
- throw unknownError;
9257
- }
9258
- logger.error("An error occurred. Couldn't finish all operations:", unknownError);
9259
- }
9260
- } finally {
9261
- endSession();
9262
- }
9263
- }
9264
- if (!validateOptions(options, logger)) {
9265
- // Throwing by default to avoid a misconfigured plugin going unnoticed.
9266
- handleRecoverableError(new Error("Options were not set correctly. See output above for more details."), true);
9267
- }
9268
9401
  if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) {
9269
9402
  logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
9270
9403
  }
9271
9404
  var plugins = [];
9272
- plugins.push(telemetryPlugin({
9273
- sentryClient: sentryClient,
9274
- sentryScope: sentryScope,
9275
- logger: logger,
9276
- shouldSendTelemetry: shouldSendTelemetry
9277
- }));
9278
9405
 
9279
- // We have multiple plugins depending on generated source map files. (debug ID upload, legacy upload)
9280
- // Additionally, we also want to have the functionality to delete files after uploading sourcemaps.
9281
- // All of these plugins and the delete functionality need to run in the same hook (`writeBundle`).
9282
- // Since the plugins among themselves are not aware of when they run and finish, we need a system to
9283
- // track their dependencies on the generated files, so that we can initiate the file deletion only after
9284
- // nothing depends on the files anymore.
9285
- var dependenciesOnSourcemapFiles = new Set();
9286
- var sourcemapFileDependencySubscribers = [];
9287
- function notifySourcemapFileDependencySubscribers() {
9288
- sourcemapFileDependencySubscribers.forEach(function (subscriber) {
9289
- subscriber();
9290
- });
9291
- }
9292
- function createDependencyOnSourcemapFiles() {
9293
- var dependencyIdentifier = Symbol();
9294
- dependenciesOnSourcemapFiles.add(dependencyIdentifier);
9295
- return function freeDependencyOnSourcemapFiles() {
9296
- dependenciesOnSourcemapFiles["delete"](dependencyIdentifier);
9297
- notifySourcemapFileDependencySubscribers();
9298
- };
9299
- }
9300
-
9301
- /**
9302
- * Returns a Promise that resolves when all the currently active dependencies are freed again.
9303
- *
9304
- * It is very important that this function is called as late as possible before wanting to await the Promise to give
9305
- * the dependency producers as much time as possible to register themselves.
9306
- */
9307
- function waitUntilSourcemapFileDependenciesAreFreed() {
9308
- return new Promise(function (resolve) {
9309
- sourcemapFileDependencySubscribers.push(function () {
9310
- if (dependenciesOnSourcemapFiles.size === 0) {
9311
- resolve();
9312
- }
9313
- });
9314
- if (dependenciesOnSourcemapFiles.size === 0) {
9315
- resolve();
9316
- }
9317
- });
9318
- }
9319
- if (options.bundleSizeOptimizations) {
9320
- var bundleSizeOptimizations = options.bundleSizeOptimizations;
9321
- var replacementValues = {};
9322
- if (bundleSizeOptimizations.excludeDebugStatements) {
9323
- replacementValues["__SENTRY_DEBUG__"] = false;
9324
- }
9325
- if (bundleSizeOptimizations.excludeTracing) {
9326
- replacementValues["__SENTRY_TRACING__"] = false;
9327
- }
9328
- if (bundleSizeOptimizations.excludeReplayCanvas) {
9329
- replacementValues["__RRWEB_EXCLUDE_CANVAS__"] = true;
9330
- }
9331
- if (bundleSizeOptimizations.excludeReplayIframe) {
9332
- replacementValues["__RRWEB_EXCLUDE_IFRAME__"] = true;
9333
- }
9334
- if (bundleSizeOptimizations.excludeReplayShadowDom) {
9335
- replacementValues["__RRWEB_EXCLUDE_SHADOW_DOM__"] = true;
9336
- }
9337
- if (bundleSizeOptimizations.excludeReplayWorker) {
9338
- replacementValues["__SENTRY_EXCLUDE_REPLAY_WORKER__"] = true;
9339
- }
9340
- if (Object.keys(replacementValues).length > 0) {
9341
- plugins.push(bundleSizeOptimizationsPlugin(replacementValues));
9406
+ // Add plugin to emit a telemetry signal when the build starts
9407
+ plugins.push({
9408
+ name: "sentry-telemetry-plugin",
9409
+ buildStart: function buildStart() {
9410
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9411
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
9412
+ while (1) switch (_context.prev = _context.next) {
9413
+ case 0:
9414
+ _context.next = 2;
9415
+ return sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal();
9416
+ case 2:
9417
+ case "end":
9418
+ return _context.stop();
9419
+ }
9420
+ }, _callee);
9421
+ }))();
9342
9422
  }
9423
+ });
9424
+ if (Object.keys(bundleSizeOptimizationReplacementValues).length > 0) {
9425
+ plugins.push(bundleSizeOptimizationsPlugin(bundleSizeOptimizationReplacementValues));
9343
9426
  }
9344
9427
  if (!options.release.inject) {
9345
9428
  logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
@@ -9352,113 +9435,44 @@ function sentryUnpluginFactory(_ref) {
9352
9435
  });
9353
9436
  plugins.push(releaseInjectionPlugin(_injectionCode));
9354
9437
  }
9355
- if (options.moduleMetadata || options.applicationKey) {
9356
- var metadata = {};
9357
- if (options.applicationKey) {
9358
- // We use different keys so that if user-code receives multiple bundling passes, we will store the application keys of all the passes.
9359
- // It is a bit unfortunate that we have to inject the metadata snippet at the top, because after multiple
9360
- // injections, the first injection will always "win" because it comes last in the code. We would generally be
9361
- // fine with making the last bundling pass win. But because it cannot win, we have to use a workaround of storing
9362
- // the app keys in different object keys.
9363
- // We can simply use the `_sentryBundlerPluginAppKey:` to filter for app keys in the SDK.
9364
- metadata["_sentryBundlerPluginAppKey:".concat(options.applicationKey)] = true;
9365
- }
9366
- if (typeof options.moduleMetadata === "function") {
9367
- var args = {
9368
- org: options.org,
9369
- project: options.project,
9370
- release: options.release.name
9371
- };
9372
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9373
- metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata(args));
9374
- } else {
9375
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9376
- metadata = _objectSpread2(_objectSpread2({}, metadata), options.moduleMetadata);
9377
- }
9378
- var _injectionCode2 = generateModuleMetadataInjectorCode(metadata);
9438
+ if (Object.keys(sentryBuildPluginManager.bundleMetadata).length > 0) {
9439
+ var _injectionCode2 = generateModuleMetadataInjectorCode(sentryBuildPluginManager.bundleMetadata);
9379
9440
  plugins.push(moduleMetadataInjectionPlugin(_injectionCode2));
9380
9441
  }
9381
- // https://turbo.build/repo/docs/reference/system-environment-variables#environment-variables-in-tasks
9382
- var isRunningInTurborepo = Boolean(process.env["TURBO_HASH"]);
9383
- var getTurborepoEnvPassthroughWarning = function getTurborepoEnvPassthroughWarning(envVarName) {
9384
- return isRunningInTurborepo ? "\nYou seem to be using Turborepo, did you forget to put ".concat(envVarName, " in `passThroughEnv`? https://turbo.build/repo/docs/reference/configuration#passthroughenv") : "";
9385
- };
9386
- if (!options.release.name) {
9387
- logger.debug("No release name provided. Will not create release. Please set the `release.name` option to identify your release.");
9388
- } else if (isDevMode) {
9389
- logger.debug("Running in development mode. Will not create release.");
9390
- } else if (!options.authToken) {
9391
- logger.warn("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"));
9392
- } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9393
- logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9394
- } else if (!options.project) {
9395
- logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9396
- } else {
9397
- plugins.push(releaseManagementPlugin({
9398
- logger: logger,
9399
- releaseName: options.release.name,
9400
- shouldCreateRelease: options.release.create,
9401
- shouldFinalizeRelease: options.release.finalize,
9402
- include: options.release.uploadLegacySourcemaps,
9403
- // setCommits has a default defined by the options mappings
9404
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
9405
- setCommitsOption: options.release.setCommits,
9406
- deployOptions: options.release.deploy,
9407
- dist: options.release.dist,
9408
- handleRecoverableError: handleRecoverableError,
9409
- sentryScope: sentryScope,
9410
- sentryClient: sentryClient,
9411
- sentryCliOptions: {
9412
- authToken: options.authToken,
9413
- org: options.org,
9414
- project: options.project,
9415
- silent: options.silent,
9416
- url: options.url,
9417
- vcsRemote: options.release.vcsRemote,
9418
- headers: options.headers
9419
- },
9420
- createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles
9421
- }));
9422
- }
9442
+
9443
+ // Add plugin to create and finalize releases, and also take care of adding commits and legacy sourcemaps
9444
+ var freeGlobalDependencyOnBuildArtifacts = sentryBuildPluginManager.createDependencyOnBuildArtifacts();
9445
+ plugins.push({
9446
+ name: "sentry-release-management-plugin",
9447
+ writeBundle: function writeBundle() {
9448
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
9449
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
9450
+ while (1) switch (_context2.prev = _context2.next) {
9451
+ case 0:
9452
+ _context2.prev = 0;
9453
+ _context2.next = 3;
9454
+ return sentryBuildPluginManager.createRelease();
9455
+ case 3:
9456
+ _context2.prev = 3;
9457
+ freeGlobalDependencyOnBuildArtifacts();
9458
+ return _context2.finish(3);
9459
+ case 6:
9460
+ case "end":
9461
+ return _context2.stop();
9462
+ }
9463
+ }, _callee2, null, [[0,, 3, 6]]);
9464
+ }))();
9465
+ }
9466
+ });
9423
9467
  if (!((_options$sourcemaps = options.sourcemaps) !== null && _options$sourcemaps !== void 0 && _options$sourcemaps.disable)) {
9424
9468
  plugins.push(debugIdInjectionPlugin(logger));
9425
9469
  }
9426
- if ((_options$sourcemaps2 = options.sourcemaps) !== null && _options$sourcemaps2 !== void 0 && _options$sourcemaps2.disable) {
9427
- logger.debug("Source map upload was disabled. Will not upload sourcemaps using debug ID process.");
9428
- } else if (isDevMode) {
9429
- logger.debug("Running in development mode. Will not upload sourcemaps.");
9430
- } else if (!options.authToken) {
9431
- logger.warn("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"));
9432
- } else if (!options.org && !options.authToken.startsWith("sntrys_")) {
9433
- logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug." + getTurborepoEnvPassthroughWarning("SENTRY_ORG"));
9434
- } else if (!options.project) {
9435
- logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug." + getTurborepoEnvPassthroughWarning("SENTRY_PROJECT"));
9436
- } else {
9437
- var _options$sourcemaps3, _options$sourcemaps4, _options$sourcemaps5;
9438
- // This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
9439
- var _webpack_forceExitOnBuildComplete = typeof options._experiments["forceExitOnBuildCompletion"] === "boolean" ? options._experiments["forceExitOnBuildCompletion"] : undefined;
9440
- plugins.push(debugIdUploadPlugin(createDebugIdUploadFunction({
9441
- assets: (_options$sourcemaps3 = options.sourcemaps) === null || _options$sourcemaps3 === void 0 ? void 0 : _options$sourcemaps3.assets,
9442
- ignore: (_options$sourcemaps4 = options.sourcemaps) === null || _options$sourcemaps4 === void 0 ? void 0 : _options$sourcemaps4.ignore,
9443
- createDependencyOnSourcemapFiles: createDependencyOnSourcemapFiles,
9444
- dist: options.release.dist,
9445
- releaseName: options.release.name,
9446
- logger: logger,
9447
- handleRecoverableError: handleRecoverableError,
9448
- rewriteSourcesHook: (_options$sourcemaps5 = options.sourcemaps) === null || _options$sourcemaps5 === void 0 ? void 0 : _options$sourcemaps5.rewriteSources,
9449
- sentryScope: sentryScope,
9450
- sentryClient: sentryClient,
9451
- sentryCliOptions: {
9452
- authToken: options.authToken,
9453
- org: options.org,
9454
- project: options.project,
9455
- silent: options.silent,
9456
- url: options.url,
9457
- vcsRemote: options.release.vcsRemote,
9458
- headers: options.headers
9459
- }
9460
- }), logger, _webpack_forceExitOnBuildComplete));
9461
- }
9470
+
9471
+ // This option is only strongly typed for the webpack plugin, where it is used. It has no effect on other plugins
9472
+ var webpack_forceExitOnBuildComplete = typeof options._experiments["forceExitOnBuildCompletion"] === "boolean" ? options._experiments["forceExitOnBuildCompletion"] : undefined;
9473
+ plugins.push(debugIdUploadPlugin(createDebugIdUploadFunction({
9474
+ sentryBuildPluginManager: sentryBuildPluginManager
9475
+ }), logger, sentryBuildPluginManager.createDependencyOnBuildArtifacts, webpack_forceExitOnBuildComplete));
9462
9476
  if (options.reactComponentAnnotation) {
9463
9477
  if (!options.reactComponentAnnotation.enabled) {
9464
9478
  logger.debug("The component name annotate plugin is currently disabled. Skipping component name annotations.");
@@ -9468,17 +9482,33 @@ function sentryUnpluginFactory(_ref) {
9468
9482
  componentNameAnnotatePlugin && plugins.push(componentNameAnnotatePlugin(options.reactComponentAnnotation.ignoredComponents));
9469
9483
  }
9470
9484
  }
9471
- plugins.push(fileDeletionPlugin({
9472
- waitUntilSourcemapFileDependenciesAreFreed: waitUntilSourcemapFileDependenciesAreFreed,
9473
- filesToDeleteAfterUpload: (_options$sourcemaps6 = options.sourcemaps) === null || _options$sourcemaps6 === void 0 ? void 0 : _options$sourcemaps6.filesToDeleteAfterUpload,
9474
- logger: logger,
9475
- handleRecoverableError: handleRecoverableError,
9476
- sentryScope: sentryScope,
9477
- sentryClient: sentryClient
9478
- }));
9485
+
9486
+ // Add plugin to delete unwanted artifacts like source maps after the uploads have completed
9487
+ plugins.push({
9488
+ name: "sentry-file-deletion-plugin",
9489
+ writeBundle: function writeBundle() {
9490
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
9491
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
9492
+ while (1) switch (_context3.prev = _context3.next) {
9493
+ case 0:
9494
+ _context3.next = 2;
9495
+ return sentryBuildPluginManager.deleteArtifacts();
9496
+ case 2:
9497
+ case "end":
9498
+ return _context3.stop();
9499
+ }
9500
+ }, _callee3);
9501
+ }))();
9502
+ }
9503
+ });
9479
9504
  return plugins;
9480
9505
  });
9481
9506
  }
9507
+
9508
+ /**
9509
+ * @deprecated
9510
+ */
9511
+ // TODO(v4): Don't export this from the package
9482
9512
  function getBuildInformation() {
9483
9513
  var packageJson = getPackageJson();
9484
9514
  var _ref2 = packageJson ? getDependencies(packageJson) : {
@@ -9639,20 +9669,22 @@ function createRollupModuleMetadataInjectionHooks(injectionCode) {
9639
9669
  };
9640
9670
  }
9641
9671
 
9642
- function createRollupDebugIdUploadHooks(upload) {
9672
+ function createRollupDebugIdUploadHooks(upload, _logger, createDependencyOnBuildArtifacts) {
9673
+ var freeGlobalDependencyOnDebugIdSourcemapArtifacts = createDependencyOnBuildArtifacts();
9643
9674
  return {
9644
9675
  writeBundle: function writeBundle(outputOptions, bundle) {
9645
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
9676
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
9646
9677
  var outputDir, _buildArtifacts, _buildArtifacts2;
9647
- return _regeneratorRuntime().wrap(function _callee$(_context) {
9648
- while (1) switch (_context.prev = _context.next) {
9678
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
9679
+ while (1) switch (_context4.prev = _context4.next) {
9649
9680
  case 0:
9681
+ _context4.prev = 0;
9650
9682
  if (!outputOptions.dir) {
9651
- _context.next = 9;
9683
+ _context4.next = 10;
9652
9684
  break;
9653
9685
  }
9654
9686
  outputDir = outputOptions.dir;
9655
- _context.next = 4;
9687
+ _context4.next = 5;
9656
9688
  return glob.glob(["/**/*.js", "/**/*.mjs", "/**/*.cjs", "/**/*.js.map", "/**/*.mjs.map", "/**/*.cjs.map"].map(function (q) {
9657
9689
  return "".concat(q, "?(\\?*)?(#*)");
9658
9690
  }),
@@ -9662,34 +9694,38 @@ function createRollupDebugIdUploadHooks(upload) {
9662
9694
  absolute: true,
9663
9695
  nodir: true
9664
9696
  });
9665
- case 4:
9666
- _buildArtifacts = _context.sent;
9667
- _context.next = 7;
9697
+ case 5:
9698
+ _buildArtifacts = _context4.sent;
9699
+ _context4.next = 8;
9668
9700
  return upload(_buildArtifacts);
9669
- case 7:
9670
- _context.next = 17;
9701
+ case 8:
9702
+ _context4.next = 18;
9671
9703
  break;
9672
- case 9:
9704
+ case 10:
9673
9705
  if (!outputOptions.file) {
9674
- _context.next = 14;
9706
+ _context4.next = 15;
9675
9707
  break;
9676
9708
  }
9677
- _context.next = 12;
9709
+ _context4.next = 13;
9678
9710
  return upload([outputOptions.file]);
9679
- case 12:
9680
- _context.next = 17;
9711
+ case 13:
9712
+ _context4.next = 18;
9681
9713
  break;
9682
- case 14:
9714
+ case 15:
9683
9715
  _buildArtifacts2 = Object.keys(bundle).map(function (asset) {
9684
9716
  return path__namespace.join(path__namespace.resolve(), asset);
9685
9717
  });
9686
- _context.next = 17;
9718
+ _context4.next = 18;
9687
9719
  return upload(_buildArtifacts2);
9688
- case 17:
9720
+ case 18:
9721
+ _context4.prev = 18;
9722
+ freeGlobalDependencyOnDebugIdSourcemapArtifacts();
9723
+ return _context4.finish(18);
9724
+ case 21:
9689
9725
  case "end":
9690
- return _context.stop();
9726
+ return _context4.stop();
9691
9727
  }
9692
- }, _callee);
9728
+ }, _callee4, null, [[0,, 18, 21]]);
9693
9729
  }))();
9694
9730
  }
9695
9731
  };
@@ -9697,26 +9733,26 @@ function createRollupDebugIdUploadHooks(upload) {
9697
9733
  function createComponentNameAnnotateHooks(ignoredComponents) {
9698
9734
  return {
9699
9735
  transform: function transform(code, id) {
9700
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
9736
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
9701
9737
  var idWithoutQueryAndHash, parserPlugins, _result$code, result;
9702
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
9703
- while (1) switch (_context2.prev = _context2.next) {
9738
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
9739
+ while (1) switch (_context5.prev = _context5.next) {
9704
9740
  case 0:
9705
9741
  // id may contain query and hash which will trip up our file extension logic below
9706
9742
  idWithoutQueryAndHash = stripQueryAndHashFromPath(id);
9707
9743
  if (!idWithoutQueryAndHash.match(/\\node_modules\\|\/node_modules\//)) {
9708
- _context2.next = 3;
9744
+ _context5.next = 3;
9709
9745
  break;
9710
9746
  }
9711
- return _context2.abrupt("return", null);
9747
+ return _context5.abrupt("return", null);
9712
9748
  case 3:
9713
9749
  if ([".jsx", ".tsx"].some(function (ending) {
9714
9750
  return idWithoutQueryAndHash.endsWith(ending);
9715
9751
  })) {
9716
- _context2.next = 5;
9752
+ _context5.next = 5;
9717
9753
  break;
9718
9754
  }
9719
- return _context2.abrupt("return", null);
9755
+ return _context5.abrupt("return", null);
9720
9756
  case 5:
9721
9757
  parserPlugins = [];
9722
9758
  if (idWithoutQueryAndHash.endsWith(".jsx")) {
@@ -9724,8 +9760,8 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9724
9760
  } else if (idWithoutQueryAndHash.endsWith(".tsx")) {
9725
9761
  parserPlugins.push("jsx", "typescript");
9726
9762
  }
9727
- _context2.prev = 7;
9728
- _context2.next = 10;
9763
+ _context5.prev = 7;
9764
+ _context5.next = 10;
9729
9765
  return core.transformAsync(code, {
9730
9766
  plugins: [[componentNameAnnotatePlugin__default["default"], {
9731
9767
  ignoredComponents: ignoredComponents
@@ -9742,24 +9778,24 @@ function createComponentNameAnnotateHooks(ignoredComponents) {
9742
9778
  sourceMaps: true
9743
9779
  });
9744
9780
  case 10:
9745
- result = _context2.sent;
9746
- return _context2.abrupt("return", {
9781
+ result = _context5.sent;
9782
+ return _context5.abrupt("return", {
9747
9783
  code: (_result$code = result === null || result === void 0 ? void 0 : result.code) !== null && _result$code !== void 0 ? _result$code : code,
9748
9784
  map: result === null || result === void 0 ? void 0 : result.map
9749
9785
  });
9750
9786
  case 14:
9751
- _context2.prev = 14;
9752
- _context2.t0 = _context2["catch"](7);
9753
- logger.error("Failed to apply react annotate plugin", _context2.t0);
9787
+ _context5.prev = 14;
9788
+ _context5.t0 = _context5["catch"](7);
9789
+ logger.error("Failed to apply react annotate plugin", _context5.t0);
9754
9790
  case 17:
9755
- return _context2.abrupt("return", {
9791
+ return _context5.abrupt("return", {
9756
9792
  code: code
9757
9793
  });
9758
9794
  case 18:
9759
9795
  case "end":
9760
- return _context2.stop();
9796
+ return _context5.stop();
9761
9797
  }
9762
- }, _callee2, null, [[7, 14]]);
9798
+ }, _callee5, null, [[7, 14]]);
9763
9799
  }))();
9764
9800
  }
9765
9801
  };