@sentry/bundler-plugin-core 2.0.0-alpha.0 → 2.0.0-alpha.2

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,18 +2,74 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var unplugin$1 = require('unplugin');
6
- var MagicString = require('magic-string');
7
5
  var SentryCli = require('@sentry/cli');
8
- var node = require('@sentry/node');
9
- require('@sentry/tracing');
6
+ var fs = require('fs');
7
+ var MagicString = require('magic-string');
8
+ var unplugin = require('unplugin');
9
+ var findUp = require('find-up');
10
10
  var path = require('path');
11
+ var os = require('os');
12
+ var crypto = require('crypto');
13
+ var childProcess = require('child_process');
14
+ var glob = require('glob');
15
+ var util = require('util');
16
+ var node = require('@sentry/node');
11
17
 
12
18
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
19
 
14
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
20
+ function _interopNamespace(e) {
21
+ if (e && e.__esModule) return e;
22
+ var n = Object.create(null);
23
+ if (e) {
24
+ Object.keys(e).forEach(function (k) {
25
+ if (k !== 'default') {
26
+ var d = Object.getOwnPropertyDescriptor(e, k);
27
+ Object.defineProperty(n, k, d.get ? d : {
28
+ enumerable: true,
29
+ get: function () { return e[k]; }
30
+ });
31
+ }
32
+ });
33
+ }
34
+ n["default"] = e;
35
+ return Object.freeze(n);
36
+ }
37
+
15
38
  var SentryCli__default = /*#__PURE__*/_interopDefaultLegacy(SentryCli);
39
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
40
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
41
+ var findUp__default = /*#__PURE__*/_interopDefaultLegacy(findUp);
16
42
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
43
+ var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
44
+ var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
45
+ var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
46
+ var util__namespace = /*#__PURE__*/_interopNamespace(util);
47
+
48
+ function ownKeys(object, enumerableOnly) {
49
+ var keys = Object.keys(object);
50
+
51
+ if (Object.getOwnPropertySymbols) {
52
+ var symbols = Object.getOwnPropertySymbols(object);
53
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
54
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
55
+ })), keys.push.apply(keys, symbols);
56
+ }
57
+
58
+ return keys;
59
+ }
60
+
61
+ function _objectSpread2(target) {
62
+ for (var i = 1; i < arguments.length; i++) {
63
+ var source = null != arguments[i] ? arguments[i] : {};
64
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
65
+ _defineProperty(target, key, source[key]);
66
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
67
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
68
+ });
69
+ }
70
+
71
+ return target;
72
+ }
17
73
 
18
74
  function _regeneratorRuntime() {
19
75
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
@@ -396,502 +452,260 @@ function _asyncToGenerator(fn) {
396
452
  };
397
453
  }
398
454
 
399
- /** Internal global with common properties and Sentry extensions */
400
-
401
- // The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification
402
- // https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js
403
- // core-js has the following licence:
404
- //
405
- // Copyright (c) 2014-2022 Denis Pushkarev
406
- //
407
- // Permission is hereby granted, free of charge, to any person obtaining a copy
408
- // of this software and associated documentation files (the "Software"), to deal
409
- // in the Software without restriction, including without limitation the rights
410
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
411
- // copies of the Software, and to permit persons to whom the Software is
412
- // furnished to do so, subject to the following conditions:
413
- //
414
- // The above copyright notice and this permission notice shall be included in
415
- // all copies or substantial portions of the Software.
416
- //
417
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
418
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
419
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
420
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
421
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
422
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
423
- // THE SOFTWARE.
424
-
425
- /** Returns 'obj' if it's the global object, otherwise returns undefined */
426
- function isGlobalObj(obj) {
427
- return obj && obj.Math == Math ? obj : undefined;
428
- }
429
-
430
- /** Get's the global object for the current JavaScript runtime */
431
- const GLOBAL_OBJ =
432
- (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||
433
- // eslint-disable-next-line no-restricted-globals
434
- (typeof window == 'object' && isGlobalObj(window)) ||
435
- (typeof self == 'object' && isGlobalObj(self)) ||
436
- (typeof global == 'object' && isGlobalObj(global)) ||
437
- (function () {
438
- return this;
439
- })() ||
440
- {};
455
+ function _defineProperty(obj, key, value) {
456
+ if (key in obj) {
457
+ Object.defineProperty(obj, key, {
458
+ value: value,
459
+ enumerable: true,
460
+ configurable: true,
461
+ writable: true
462
+ });
463
+ } else {
464
+ obj[key] = value;
465
+ }
441
466
 
442
- /**
443
- * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8
444
- */
445
- function getGlobalObject() {
446
- return GLOBAL_OBJ ;
467
+ return obj;
447
468
  }
448
469
 
449
470
  /**
450
- * Returns a global singleton contained in the global `__SENTRY__` object.
451
- *
452
- * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
453
- * function and added to the `__SENTRY__` object.
471
+ * Checks whether the given input is already an array, and if it isn't, wraps it in one.
454
472
  *
455
- * @param name name of the global singleton on __SENTRY__
456
- * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
457
- * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
458
- * @returns the singleton
473
+ * @param maybeArray Input to turn into an array, if necessary
474
+ * @returns The input, if already an array, or an array with the input as the only element, if not
459
475
  */
460
- function getGlobalSingleton(name, creator, obj) {
461
- const gbl = (obj || GLOBAL_OBJ) ;
462
- const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});
463
- const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());
464
- return singleton;
465
- }
466
476
 
467
- /** Prefix for logging strings */
468
- const PREFIX = 'Sentry Logger ';
469
-
470
- const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ;
477
+ function arrayify(maybeArray) {
478
+ return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
479
+ }
471
480
 
472
481
  /**
473
- * Temporarily disable sentry console instrumentations.
474
- *
475
- * @param callback The function to run against the original `console` messages
476
- * @returns The results of the callback
482
+ * Get the closes package.json from a given starting point upwards.
483
+ * This handles a few edge cases:
484
+ * * Check if a given file package.json appears to be an actual NPM package.json file
485
+ * * Stop at the home dir, to avoid looking too deeply
477
486
  */
478
- function consoleSandbox(callback) {
479
- if (!('console' in GLOBAL_OBJ)) {
480
- return callback();
481
- }
487
+ function getPackageJson() {
488
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
489
+ cwd = _ref.cwd,
490
+ stopAt = _ref.stopAt;
482
491
 
483
- const originalConsole = GLOBAL_OBJ.console ;
484
- const wrappedLevels = {};
485
-
486
- // Restore all wrapped console methods
487
- CONSOLE_LEVELS.forEach(level => {
488
- // TODO(v7): Remove this check as it's only needed for Node 6
489
- const originalWrappedFunc =
490
- originalConsole[level] && (originalConsole[level] ).__sentry_original__;
491
- if (level in originalConsole && originalWrappedFunc) {
492
- wrappedLevels[level] = originalConsole[level] ;
493
- originalConsole[level] = originalWrappedFunc ;
494
- }
495
- });
496
-
497
- try {
498
- return callback();
499
- } finally {
500
- // Revert restoration to wrapped state
501
- Object.keys(wrappedLevels).forEach(level => {
502
- originalConsole[level] = wrappedLevels[level ];
503
- });
504
- }
492
+ return lookupPackageJson(cwd !== null && cwd !== void 0 ? cwd : process.cwd(), path__default["default"].normalize(stopAt !== null && stopAt !== void 0 ? stopAt : os__default["default"].homedir()));
505
493
  }
494
+ function parseMajorVersion(version) {
495
+ // if it has a `v` prefix, remove it
496
+ if (version.startsWith("v")) {
497
+ version = version.slice(1);
498
+ } // First, try simple lookup of exact, ~ and ^ versions
506
499
 
507
- function makeLogger() {
508
- let enabled = false;
509
- const logger = {
510
- enable: () => {
511
- enabled = true;
512
- },
513
- disable: () => {
514
- enabled = false;
515
- },
516
- };
517
500
 
518
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {
519
- CONSOLE_LEVELS.forEach(name => {
520
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
521
- logger[name] = (...args) => {
522
- if (enabled) {
523
- consoleSandbox(() => {
524
- GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
525
- });
526
- }
527
- };
528
- });
529
- } else {
530
- CONSOLE_LEVELS.forEach(name => {
531
- logger[name] = () => undefined;
532
- });
533
- }
501
+ var regex = /^[\^~]?(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
502
+ var match = version.match(regex);
534
503
 
535
- return logger ;
536
- }
504
+ if (match) {
505
+ return parseInt(match[1], 10);
506
+ } // Try to parse e.g. 1.x
537
507
 
538
- // Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used
539
- let logger;
540
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {
541
- logger = getGlobalSingleton('logger', makeLogger);
542
- } else {
543
- logger = makeLogger();
544
- }
545
508
 
546
- /*
547
- * This module exists for optimizations in the build process through rollup and terser. We define some global
548
- * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these
549
- * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will
550
- * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to
551
- * `logger` and preventing node-related code from appearing in browser bundles.
552
- *
553
- * Attention:
554
- * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by
555
- * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack)
556
- * having issues tree-shaking these constants across package boundaries.
557
- * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want
558
- * users to be able to shake away expressions that it guards.
559
- */
509
+ var coerced = parseInt(version, 10);
560
510
 
561
- /**
562
- * Figures out if we're building a browser bundle.
563
- *
564
- * @returns true if this is a browser bundle build.
565
- */
566
- function isBrowserBundle() {
567
- return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;
568
- }
511
+ if (!Number.isNaN(coerced)) {
512
+ return coerced;
513
+ } // Match <= and >= ranges.
569
514
 
570
- /**
571
- * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
572
- * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.
573
- */
574
515
 
575
- /**
576
- * Checks whether we're in the Node.js or Browser environment
577
- *
578
- * @returns Answer to given question
579
- */
580
- function isNodeEnv() {
581
- // explicitly check for browser bundles as those can be optimized statically
582
- // by terser/rollup.
583
- return (
584
- !isBrowserBundle() &&
585
- Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'
586
- );
587
- }
516
+ var gteLteRegex = /^[<>]=\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
517
+ var gteLteMatch = version.match(gteLteRegex);
588
518
 
589
- /**
590
- * Requires a module which is protected against bundler minification.
591
- *
592
- * @param request The module path to resolve
593
- */
594
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
595
- function dynamicRequire(mod, request) {
596
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
597
- return mod.require(request);
598
- }
519
+ if (gteLteMatch) {
520
+ return parseInt(gteLteMatch[1], 10);
521
+ } // match < ranges
599
522
 
600
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
601
523
 
602
- /** SyncPromise internal states */
603
- var States; (function (States) {
604
- /** Pending */
605
- const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING";
606
- /** Resolved / OK */
607
- const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED";
608
- /** Rejected / Error */
609
- const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED";
610
- })(States || (States = {}));
524
+ var ltRegex = /^<\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
525
+ var ltMatch = version.match(ltRegex);
611
526
 
612
- // eslint-disable-next-line deprecation/deprecation
613
- const WINDOW = getGlobalObject();
527
+ if (ltMatch) {
528
+ // Two scenarios:
529
+ // a) < 2.0.0 --> return 1
530
+ // b) < 2.1.0 --> return 2
531
+ var major = parseInt(ltMatch[1], 10);
614
532
 
615
- /**
616
- * An object that can return the current timestamp in seconds since the UNIX epoch.
617
- */
533
+ if ( // minor version > 0
534
+ typeof ltMatch[2] === "string" && parseInt(ltMatch[2].slice(1), 10) > 0 || // patch version > 0
535
+ typeof ltMatch[3] === "string" && parseInt(ltMatch[3].slice(1), 10) > 0) {
536
+ return major;
537
+ }
618
538
 
619
- /**
620
- * A TimestampSource implementation for environments that do not support the Performance Web API natively.
621
- *
622
- * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier
623
- * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It
624
- * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration".
625
- */
626
- const dateTimestampSource = {
627
- nowSeconds: () => Date.now() / 1000,
628
- };
539
+ return major - 1;
540
+ } // match > ranges
629
541
 
630
- /**
631
- * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}
632
- * for accessing a high-resolution monotonic clock.
633
- */
634
542
 
635
- /**
636
- * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
637
- * support the API.
638
- *
639
- * Wrapping the native API works around differences in behavior from different browsers.
640
- */
641
- function getBrowserPerformance() {
642
- const { performance } = WINDOW;
643
- if (!performance || !performance.now) {
644
- return undefined;
543
+ var gtRegex = /^>\s*(\d+)(\.\d+)?(\.\d+)?(-.+)?/;
544
+ var gtMatch = version.match(gtRegex);
545
+
546
+ if (gtMatch) {
547
+ // We always return the version here, even though it _may_ be incorrect
548
+ // E.g. if given > 2.0.0, it should be 2 if there exists any 2.x.x version, else 3
549
+ // Since there is no way for us to know this, we're going to assume any kind of patch/feature release probably exists
550
+ return parseInt(gtMatch[1], 10);
645
551
  }
646
552
 
647
- // Replace performance.timeOrigin with our own timeOrigin based on Date.now().
648
- //
649
- // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +
650
- // performance.now() gives a date arbitrarily in the past.
651
- //
652
- // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is
653
- // undefined.
654
- //
655
- // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to
656
- // interact with data coming out of performance entries.
657
- //
658
- // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that
659
- // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes
660
- // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have
661
- // observed skews that can be as long as days, weeks or months.
662
- //
663
- // See https://github.com/getsentry/sentry-javascript/issues/2590.
664
- //
665
- // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload
666
- // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation
667
- // transactions of long-lived web pages.
668
- const timeOrigin = Date.now() - performance.now();
553
+ return undefined;
554
+ } // This is an explicit list of packages where we want to include the (major) version number.
669
555
 
556
+ var PACKAGES_TO_INCLUDE_VERSION = ["react", "@angular/core", "vue", "ember-source", "svelte", "@sveltejs/kit", "webpack", "vite", "gatsby", "next", "remix", "rollup", "esbuild"];
557
+ function getDependencies(packageJson) {
558
+ var _packageJson$devDepen, _packageJson$dependen;
559
+
560
+ 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 : {});
561
+ var deps = Object.keys(dependencies).sort();
562
+ var depsVersions = deps.reduce(function (depsVersions, depName) {
563
+ if (PACKAGES_TO_INCLUDE_VERSION.includes(depName)) {
564
+ var version = dependencies[depName];
565
+ var majorVersion = parseMajorVersion(version);
566
+
567
+ if (majorVersion) {
568
+ depsVersions[depName] = majorVersion;
569
+ }
570
+ }
571
+
572
+ return depsVersions;
573
+ }, {});
670
574
  return {
671
- now: () => performance.now(),
672
- timeOrigin,
575
+ deps: deps,
576
+ depsVersions: depsVersions
673
577
  };
674
578
  }
675
579
 
676
- /**
677
- * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't
678
- * implement the API.
679
- */
680
- function getNodePerformance() {
681
- try {
682
- const perfHooks = dynamicRequire(module, 'perf_hooks') ;
683
- return perfHooks.performance;
684
- } catch (_) {
580
+ function lookupPackageJson(cwd, stopAt) {
581
+ var jsonPath = findUp__default["default"].sync(function (dirName) {
582
+ // Stop if we reach this dir
583
+ if (path__default["default"].normalize(dirName) === stopAt) {
584
+ return findUp__default["default"].stop;
585
+ }
586
+
587
+ return findUp__default["default"].sync.exists(dirName + "/package.json") ? "package.json" : undefined;
588
+ }, {
589
+ cwd: cwd
590
+ });
591
+
592
+ if (!jsonPath) {
685
593
  return undefined;
686
594
  }
687
- }
688
595
 
689
- /**
690
- * The Performance API implementation for the current platform, if available.
691
- */
692
- const platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();
596
+ try {
597
+ var jsonStr = fs__default["default"].readFileSync(jsonPath, "utf8");
598
+ var json = JSON.parse(jsonStr); // Ensure it is an actual package.json
599
+ // This is very much not bulletproof, but should be good enough
693
600
 
694
- const timestampSource =
695
- platformPerformance === undefined
696
- ? dateTimestampSource
697
- : {
698
- nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,
699
- };
601
+ if ("name" in json || "private" in json) {
602
+ return json;
603
+ }
604
+ } catch (error) {// Ignore and walk up
605
+ } // Continue up the tree, if we find a fitting package.json
700
606
 
701
- /**
702
- * Returns a timestamp in seconds since the UNIX epoch using the Date API.
703
- */
704
- dateTimestampSource.nowSeconds.bind(dateTimestampSource);
705
607
 
608
+ var newCwd = path__default["default"].dirname(path__default["default"].resolve(jsonPath + "/.."));
609
+ return lookupPackageJson(newCwd, stopAt);
610
+ }
706
611
  /**
707
- * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
708
- * availability of the Performance API.
709
- *
710
- * See `usingPerformanceAPI` to test whether the Performance API is used.
711
- *
712
- * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is
713
- * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The
714
- * skew can grow to arbitrary amounts like days, weeks or months.
715
- * See https://github.com/getsentry/sentry-javascript/issues/2590.
612
+ * Deterministically hashes a string and turns the hash into a uuid.
716
613
  */
717
- timestampSource.nowSeconds.bind(timestampSource);
718
614
 
615
+
616
+ function stringToUUID(str) {
617
+ var md5sum = crypto__default["default"].createHash("md5");
618
+ md5sum.update(str);
619
+ var md5Hash = md5sum.digest("hex");
620
+ return (md5Hash.substring(0, 8) + "-" + md5Hash.substring(8, 12) + "-4" + md5Hash.substring(13, 16) + "-" + md5Hash.substring(16, 20) + "-" + md5Hash.substring(20)).toLowerCase();
621
+ }
719
622
  /**
720
- * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the
721
- * performance API is available.
623
+ * Tries to guess a release name based on environmental data.
722
624
  */
723
- (() => {
724
- // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or
725
- // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin
726
- // data as reliable if they are within a reasonable threshold of the current time.
727
625
 
728
- const { performance } = WINDOW;
729
- if (!performance || !performance.now) {
730
- return undefined;
731
- }
626
+ function determineReleaseName() {
627
+ var gitRevision;
732
628
 
733
- const threshold = 3600 * 1000;
734
- const performanceNow = performance.now();
735
- const dateNow = Date.now();
736
-
737
- // if timeOrigin isn't available set delta to threshold so it isn't used
738
- const timeOriginDelta = performance.timeOrigin
739
- ? Math.abs(performance.timeOrigin + performanceNow - dateNow)
740
- : threshold;
741
- const timeOriginIsReliable = timeOriginDelta < threshold;
742
-
743
- // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin
744
- // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.
745
- // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always
746
- // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the
747
- // Date API.
748
- // eslint-disable-next-line deprecation/deprecation
749
- const navigationStart = performance.timing && performance.timing.navigationStart;
750
- const hasNavigationStart = typeof navigationStart === 'number';
751
- // if navigationStart isn't available set delta to threshold so it isn't used
752
- const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
753
- const navigationStartIsReliable = navigationStartDelta < threshold;
754
-
755
- if (timeOriginIsReliable || navigationStartIsReliable) {
756
- // Use the more reliable time origin
757
- if (timeOriginDelta <= navigationStartDelta) {
758
- return performance.timeOrigin;
759
- } else {
760
- return navigationStart;
761
- }
629
+ try {
630
+ gitRevision = childProcess__default["default"].execSync("git rev-parse --short HEAD").toString().trim();
631
+ } catch (e) {// noop
762
632
  }
763
- return dateNow;
764
- })();
765
633
 
634
+ return (// GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
635
+ process.env["GITHUB_SHA"] || // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
636
+ process.env["COMMIT_REF"] || // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables
637
+ process.env["CF_PAGES_COMMIT_SHA"] || // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
638
+ process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] || // CircleCI - https://circleci.com/docs/2.0/env-vars/
639
+ process.env["CIRCLE_SHA1"] || // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
640
+ process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] || // Zeit (now known as Vercel)
641
+ process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"] || gitRevision
642
+ );
643
+ }
766
644
  /**
767
- * Checks whether the given input is already an array, and if it isn't, wraps it in one.
768
- *
769
- * @param maybeArray Input to turn into an array, if necessary
770
- * @returns The input, if already an array, or an array with the input as the only element, if not
645
+ * Generates code for the global injector which is responsible for setting the global
646
+ * `SENTRY_RELEASE` & `SENTRY_BUILD_INFO` variables.
771
647
  */
772
- function arrayify(maybeArray) {
773
- return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
648
+
649
+ function generateGlobalInjectorCode(_ref2) {
650
+ var release = _ref2.release,
651
+ injectBuildInformation = _ref2.injectBuildInformation;
652
+ // The code below is mostly ternary operators because it saves bundle size.
653
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
654
+ var code = "\n var _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:\"".concat(release, "\"};");
655
+
656
+ if (injectBuildInformation) {
657
+ var buildInfo = getBuildInformation$1();
658
+ code += "\n _global.SENTRY_BUILD_INFO=".concat(JSON.stringify(buildInfo), ";");
659
+ }
660
+
661
+ return code;
662
+ }
663
+
664
+ function getBuildInformation$1() {
665
+ var packageJson = getPackageJson();
666
+
667
+ var _ref3 = packageJson ? getDependencies(packageJson) : {
668
+ deps: [],
669
+ depsVersions: {}
670
+ },
671
+ deps = _ref3.deps,
672
+ depsVersions = _ref3.depsVersions;
673
+
674
+ return {
675
+ deps: deps,
676
+ depsVersions: depsVersions,
677
+ nodeVersion: parseMajorVersion(process.version)
678
+ };
774
679
  }
775
680
 
776
681
  var SENTRY_SAAS_URL = "https://sentry.io";
777
682
  function normalizeUserOptions(userOptions) {
778
- var _userOptions$org, _userOptions$project, _ref, _userOptions$release, _ref2, _userOptions$url, _userOptions$finalize, _userOptions$cleanArt, _userOptions$dryRun, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$injectRe;
683
+ var _userOptions$org, _userOptions$project, _userOptions$authToke, _ref, _userOptions$url, _userOptions$debug, _userOptions$silent, _userOptions$telemetr, _userOptions$disable, _process$env$SENTRY_V, _userOptions$_experim;
779
684
 
780
685
  var options = {
781
- // include is the only strictly required option
782
- // (normalizeInclude needs all userOptions to access top-level include options)
783
- include: normalizeInclude(userOptions),
784
- // These options must be set b/c we need them for release injection.
785
- // They can also be set as environment variables. Technically, they
786
- // could be set in the config file but this would be too late for
787
- // release injection because we only pass the config file path
788
- // to the CLI
789
686
  org: (_userOptions$org = userOptions.org) !== null && _userOptions$org !== void 0 ? _userOptions$org : process.env["SENTRY_ORG"],
790
687
  project: (_userOptions$project = userOptions.project) !== null && _userOptions$project !== void 0 ? _userOptions$project : process.env["SENTRY_PROJECT"],
791
- // Falling back to the empty string here b/c at a later point, we use
792
- // Sentry CLI to determine a release if none was specified via options
793
- // or env vars. In case we don't find one, we'll bail at that point.
794
- release: (_ref = (_userOptions$release = userOptions.release) !== null && _userOptions$release !== void 0 ? _userOptions$release : process.env["SENTRY_RELEASE"]) !== null && _ref !== void 0 ? _ref : "",
795
- // We technically don't need the URL for anything release-specific
796
- // but we want to make sure that we're only sending Sentry data
797
- // of SaaS customers. Hence we want to read it anyway.
798
- url: (_ref2 = (_userOptions$url = userOptions.url) !== null && _userOptions$url !== void 0 ? _userOptions$url : process.env["SENTRY_URL"]) !== null && _ref2 !== void 0 ? _ref2 : SENTRY_SAAS_URL,
799
- // Options with default values
800
- finalize: (_userOptions$finalize = userOptions.finalize) !== null && _userOptions$finalize !== void 0 ? _userOptions$finalize : true,
801
- cleanArtifacts: (_userOptions$cleanArt = userOptions.cleanArtifacts) !== null && _userOptions$cleanArt !== void 0 ? _userOptions$cleanArt : false,
802
- dryRun: (_userOptions$dryRun = userOptions.dryRun) !== null && _userOptions$dryRun !== void 0 ? _userOptions$dryRun : false,
688
+ authToken: (_userOptions$authToke = userOptions.authToken) !== null && _userOptions$authToke !== void 0 ? _userOptions$authToke : process.env["SENTRY_AUTH_TOKEN"],
689
+ 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,
690
+ headers: userOptions.headers,
803
691
  debug: (_userOptions$debug = userOptions.debug) !== null && _userOptions$debug !== void 0 ? _userOptions$debug : false,
804
692
  silent: (_userOptions$silent = userOptions.silent) !== null && _userOptions$silent !== void 0 ? _userOptions$silent : false,
805
- telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
806
- injectReleasesMap: (_userOptions$injectRe = userOptions.injectReleasesMap) !== null && _userOptions$injectRe !== void 0 ? _userOptions$injectRe : false,
807
- // These options and can also be set via env variables or the config file.
808
- // If they're set in the options, we simply pass them to the CLI constructor.
809
- // Sentry CLI will internally query env variables and read its config file if
810
- // the passed options are undefined.
811
- authToken: userOptions.authToken,
812
- // env var: `SENTRY_AUTH_TOKEN`
813
- headers: userOptions.headers,
814
- vcsRemote: userOptions.vcsRemote,
815
- // env var: `SENTRY_VSC_REMOTE`
816
- // Optional options
817
- setCommits: userOptions.setCommits,
818
- deploy: userOptions.deploy,
819
- releaseInjectionTargets: normalizeReleaseInjectionTargets(userOptions.releaseInjectionTargets),
820
- dist: userOptions.dist,
821
693
  errorHandler: userOptions.errorHandler,
822
- configFile: userOptions.configFile
694
+ telemetry: (_userOptions$telemetr = userOptions.telemetry) !== null && _userOptions$telemetr !== void 0 ? _userOptions$telemetr : true,
695
+ disable: (_userOptions$disable = userOptions.disable) !== null && _userOptions$disable !== void 0 ? _userOptions$disable : false,
696
+ sourcemaps: userOptions.sourcemaps,
697
+ release: _objectSpread2({
698
+ name: determineReleaseName(),
699
+ inject: true,
700
+ create: true,
701
+ finalize: true,
702
+ vcsRemote: (_process$env$SENTRY_V = process.env["SENTRY_VSC_REMOTE"]) !== null && _process$env$SENTRY_V !== void 0 ? _process$env$SENTRY_V : "origin",
703
+ cleanArtifacts: false
704
+ }, userOptions.release),
705
+ _experiments: (_userOptions$_experim = userOptions._experiments) !== null && _userOptions$_experim !== void 0 ? _userOptions$_experim : {}
823
706
  };
824
707
  return options;
825
708
  }
826
- /**
827
- * Converts the user-facing `releaseInjectionTargets` option to the internal
828
- * `releaseInjectionTargets` option
829
- */
830
-
831
- function normalizeReleaseInjectionTargets(userReleaseInjectionTargets) {
832
- if (userReleaseInjectionTargets === undefined) {
833
- return undefined;
834
- } else if (typeof userReleaseInjectionTargets === "function") {
835
- return userReleaseInjectionTargets;
836
- } else {
837
- return arrayify(userReleaseInjectionTargets);
838
- }
839
- }
840
- /**
841
- * Converts the user-facing `include` option to the internal `include` option,
842
- * resulting in an array of `InternalIncludeEntry` objects. This later on lets us
843
- * work with only one type of include data structure instead of multiple.
844
- *
845
- * During the process, we hoist top-level include options (e.g. urlPrefix) into each
846
- * object if they were not alrady specified in an `IncludeEntry`, making every object
847
- * fully self-contained. This is also the reason why we pass the entire options
848
- * object and not just `include`.
849
- *
850
- * @param userOptions the entire user-facing `options` object
851
- *
852
- * @return an array of `InternalIncludeEntry` objects.
853
- */
854
-
855
-
856
- function normalizeInclude(userOptions) {
857
- return arrayify(userOptions.include).map(function (includeItem) {
858
- return typeof includeItem === "string" ? {
859
- paths: [includeItem]
860
- } : includeItem;
861
- }).map(function (userIncludeEntry) {
862
- return normalizeIncludeEntry(userOptions, userIncludeEntry);
863
- });
864
- }
865
- /**
866
- * Besides array-ifying the `ignore` option, this function hoists top level options into the items of the `include`
867
- * option. This is to simplify the handling of of the `include` items later on.
868
- */
869
-
870
-
871
- function normalizeIncludeEntry(userOptions, includeEntry) {
872
- var _ref3, _includeEntry$ignore, _ref4, _includeEntry$ext, _includeEntry$ignoreF, _includeEntry$urlPref, _includeEntry$urlSuff, _includeEntry$stripPr, _ref5, _includeEntry$stripCo, _ref6, _includeEntry$sourceM, _ref7, _includeEntry$rewrite, _ref8, _includeEntry$validat;
873
-
874
- var ignoreOption = (_ref3 = (_includeEntry$ignore = includeEntry.ignore) !== null && _includeEntry$ignore !== void 0 ? _includeEntry$ignore : userOptions.ignore) !== null && _ref3 !== void 0 ? _ref3 : ["node_modules"];
875
- var ignore = Array.isArray(ignoreOption) ? ignoreOption : [ignoreOption]; // We're prefixing all entries in the `ext` option with a `.` (if it isn't already) to align with Node.js' `path.extname()`
876
-
877
- var ext = (_ref4 = (_includeEntry$ext = includeEntry.ext) !== null && _includeEntry$ext !== void 0 ? _includeEntry$ext : userOptions.ext) !== null && _ref4 !== void 0 ? _ref4 : ["js", "map", "jsbundle", "bundle"];
878
- var dotPrefixedExt = ext.map(function (extension) {
879
- return ".".concat(extension.replace(/^\./, ""));
880
- });
881
- return {
882
- paths: includeEntry.paths,
883
- ignore: ignore,
884
- ignoreFile: (_includeEntry$ignoreF = includeEntry.ignoreFile) !== null && _includeEntry$ignoreF !== void 0 ? _includeEntry$ignoreF : userOptions.ignoreFile,
885
- ext: dotPrefixedExt,
886
- urlPrefix: (_includeEntry$urlPref = includeEntry.urlPrefix) !== null && _includeEntry$urlPref !== void 0 ? _includeEntry$urlPref : userOptions.urlPrefix,
887
- urlSuffix: (_includeEntry$urlSuff = includeEntry.urlSuffix) !== null && _includeEntry$urlSuff !== void 0 ? _includeEntry$urlSuff : userOptions.urlSuffix,
888
- stripPrefix: (_includeEntry$stripPr = includeEntry.stripPrefix) !== null && _includeEntry$stripPr !== void 0 ? _includeEntry$stripPr : userOptions.stripPrefix,
889
- stripCommonPrefix: (_ref5 = (_includeEntry$stripCo = includeEntry.stripCommonPrefix) !== null && _includeEntry$stripCo !== void 0 ? _includeEntry$stripCo : userOptions.stripCommonPrefix) !== null && _ref5 !== void 0 ? _ref5 : false,
890
- sourceMapReference: (_ref6 = (_includeEntry$sourceM = includeEntry.sourceMapReference) !== null && _includeEntry$sourceM !== void 0 ? _includeEntry$sourceM : userOptions.sourceMapReference) !== null && _ref6 !== void 0 ? _ref6 : true,
891
- rewrite: (_ref7 = (_includeEntry$rewrite = includeEntry.rewrite) !== null && _includeEntry$rewrite !== void 0 ? _includeEntry$rewrite : userOptions.rewrite) !== null && _ref7 !== void 0 ? _ref7 : true,
892
- validate: (_ref8 = (_includeEntry$validat = includeEntry.validate) !== null && _includeEntry$validat !== void 0 ? _includeEntry$validat : userOptions.validate) !== null && _ref8 !== void 0 ? _ref8 : false
893
- };
894
- }
895
709
  /**
896
710
  * Validates a few combinations of options that are not checked by Sentry CLI.
897
711
  *
@@ -905,14 +719,10 @@ function normalizeIncludeEntry(userOptions, includeEntry) {
905
719
  * @returns `true` if the options are valid, `false` otherwise
906
720
  */
907
721
 
908
-
909
722
  function validateOptions(options, logger) {
910
- if (options.injectReleasesMap && !options.org) {
911
- logger.error("The `injectReleasesMap` option was set but it is only supported when the `org` option is also specified.", "Please set the `org` option (you can also set the SENTRY_ORG environment variable) or disable the `injectReleasesMap` option.");
912
- return false;
913
- }
723
+ var _options$release, _options$release2, _options$release3;
914
724
 
915
- var setCommits = options.setCommits;
725
+ var setCommits = (_options$release = options.release) === null || _options$release === void 0 ? void 0 : _options$release.setCommits;
916
726
 
917
727
  if (setCommits) {
918
728
  if (!setCommits.auto && !(setCommits.repo && setCommits.commit)) {
@@ -925,7 +735,7 @@ function validateOptions(options, logger) {
925
735
  }
926
736
  }
927
737
 
928
- if (options.deploy && !options.deploy.env) {
738
+ 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)) {
929
739
  logger.error("The `deploy` option was specified but is missing the required `env` property.", "Please set the `env` property.");
930
740
  return false;
931
741
  }
@@ -933,595 +743,502 @@ function validateOptions(options, logger) {
933
743
  return true;
934
744
  }
935
745
 
936
- var SENTRY_SAAS_HOSTNAME = "sentry.io";
937
- function makeSentryClient(dsn, allowedToSendTelemetryPromise, userProject) {
938
- var client = new node.NodeClient({
939
- dsn: dsn,
940
- tracesSampleRate: 1,
941
- sampleRate: 1,
942
- // We're also sending the user project in dist because it is an indexed fieldso we can use this data effectively in
943
- // a dashboard.
944
- // Yes, this is slightly abusing the purpose of this field.
945
- dist: userProject,
946
- release: "2.0.0-alpha.0",
947
- integrations: [],
948
- tracePropagationTargets: ["sentry.io/api"],
949
- stackParser: node.defaultStackParser,
950
- beforeSend: function beforeSend(event) {
951
- var _event$exception, _event$exception$valu;
952
-
953
- (_event$exception = event.exception) === null || _event$exception === void 0 ? void 0 : (_event$exception$valu = _event$exception.values) === null || _event$exception$valu === void 0 ? void 0 : _event$exception$valu.forEach(function (exception) {
954
- delete exception.stacktrace;
955
- });
956
- delete event.server_name; // Server name might contain PII
746
+ function debugIdUploadPlugin(_ref) {
747
+ var assets = _ref.assets,
748
+ ignore = _ref.ignore,
749
+ logger = _ref.logger,
750
+ releaseName = _ref.releaseName,
751
+ dist = _ref.dist,
752
+ handleRecoverableError = _ref.handleRecoverableError,
753
+ sentryHub = _ref.sentryHub,
754
+ sentryClient = _ref.sentryClient,
755
+ sentryCliOptions = _ref.sentryCliOptions;
756
+ return {
757
+ name: "sentry-debug-id-upload-plugin",
758
+ writeBundle: function writeBundle() {
759
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
760
+ var folderToCleanUp, cliInstance, tmpUploadFolder, debugIdChunkFilePaths;
761
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
762
+ while (1) {
763
+ switch (_context2.prev = _context2.next) {
764
+ case 0:
765
+ cliInstance = new SentryCli__default["default"](null, sentryCliOptions);
766
+ _context2.prev = 1;
767
+ _context2.next = 4;
768
+ return fs__default["default"].promises.mkdtemp(path__default["default"].join(os__default["default"].tmpdir(), "sentry-bundler-plugin-upload-"));
769
+
770
+ case 4:
771
+ tmpUploadFolder = _context2.sent;
772
+ folderToCleanUp = tmpUploadFolder;
773
+ _context2.next = 8;
774
+ return glob.glob(assets, {
775
+ absolute: true,
776
+ nodir: true,
777
+ ignore: ignore
778
+ });
957
779
 
958
- return event;
959
- },
960
- beforeSendTransaction: function beforeSendTransaction(event) {
961
- delete event.server_name; // Server name might contain PII
780
+ case 8:
781
+ debugIdChunkFilePaths = _context2.sent.filter(function (debugIdChunkFilePath) {
782
+ return debugIdChunkFilePath.endsWith(".js") || debugIdChunkFilePath.endsWith(".mjs") || debugIdChunkFilePath.endsWith(".cjs");
783
+ });
784
+ _context2.next = 11;
785
+ return Promise.all(debugIdChunkFilePaths.map( /*#__PURE__*/function () {
786
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(chunkFilePath, chunkIndex) {
787
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
788
+ while (1) {
789
+ switch (_context.prev = _context.next) {
790
+ case 0:
791
+ _context.next = 2;
792
+ return prepareBundleForDebugIdUpload(chunkFilePath, tmpUploadFolder, String(chunkIndex), logger);
793
+
794
+ case 2:
795
+ case "end":
796
+ return _context.stop();
797
+ }
798
+ }
799
+ }, _callee);
800
+ }));
801
+
802
+ return function (_x, _x2) {
803
+ return _ref2.apply(this, arguments);
804
+ };
805
+ }()));
962
806
 
963
- return event;
964
- },
965
- // We create a transport that stalls sending events until we know that we're allowed to (i.e. when Sentry CLI told
966
- // us that the upload URL is the Sentry SaaS URL)
967
- transport: function transport(nodeTransportOptions) {
968
- var nodeTransport = node.makeNodeTransport(nodeTransportOptions);
969
- return {
970
- flush: function flush(timeout) {
971
- return nodeTransport.flush(timeout);
972
- },
973
- send: function () {
974
- var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) {
975
- var isAllowedToSend;
976
- return _regeneratorRuntime().wrap(function _callee$(_context) {
977
- while (1) {
978
- switch (_context.prev = _context.next) {
979
- case 0:
980
- _context.next = 2;
981
- return allowedToSendTelemetryPromise;
807
+ case 11:
808
+ _context2.next = 13;
809
+ return cliInstance.releases.uploadSourceMaps(releaseName !== null && releaseName !== void 0 ? releaseName : "", {
810
+ include: [{
811
+ paths: [tmpUploadFolder],
812
+ rewrite: false,
813
+ dist: dist
814
+ }],
815
+ useArtifactBundle: true
816
+ });
982
817
 
983
- case 2:
984
- isAllowedToSend = _context.sent;
818
+ case 13:
819
+ _context2.next = 21;
820
+ break;
985
821
 
986
- if (!isAllowedToSend) {
987
- _context.next = 7;
988
- break;
989
- }
822
+ case 15:
823
+ _context2.prev = 15;
824
+ _context2.t0 = _context2["catch"](1);
825
+ sentryHub.captureException('Error in "debugIdUploadPlugin" writeBundle hook');
826
+ _context2.next = 20;
827
+ return sentryClient.flush();
990
828
 
991
- return _context.abrupt("return", nodeTransport.send(request));
829
+ case 20:
830
+ handleRecoverableError(_context2.t0);
992
831
 
993
- case 7:
994
- return _context.abrupt("return", undefined);
832
+ case 21:
833
+ _context2.prev = 21;
995
834
 
996
- case 8:
997
- case "end":
998
- return _context.stop();
835
+ if (folderToCleanUp) {
836
+ void fs__default["default"].promises.rm(folderToCleanUp, {
837
+ recursive: true,
838
+ force: true
839
+ });
999
840
  }
1000
- }
1001
- }, _callee);
1002
- }));
1003
841
 
1004
- function send(_x) {
1005
- return _send.apply(this, arguments);
1006
- }
842
+ return _context2.finish(21);
1007
843
 
1008
- return send;
1009
- }()
1010
- };
844
+ case 24:
845
+ case "end":
846
+ return _context2.stop();
847
+ }
848
+ }
849
+ }, _callee2, null, [[1, 15, 21, 24]]);
850
+ }))();
1011
851
  }
1012
- });
1013
- var hub = new node.Hub(client);
1014
- return {
1015
- sentryClient: client,
1016
- sentryHub: hub
1017
852
  };
1018
853
  }
854
+ function prepareBundleForDebugIdUpload(_x3, _x4, _x5, _x6) {
855
+ return _prepareBundleForDebugIdUpload.apply(this, arguments);
856
+ }
1019
857
  /**
1020
- * Adds a span to the passed parentSpan or to the current transaction that's on the passed hub's scope.
858
+ * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle
859
+ * source and extracts the bundle's debug ID from it.
860
+ *
861
+ * The string pattern is injected via the debug ID injection snipped.
1021
862
  */
1022
863
 
1023
- function addSpanToTransaction(ctx, op, description) {
1024
- var _hub$getScope;
1025
-
1026
- var hub = ctx.hub,
1027
- parentSpan = ctx.parentSpan;
1028
- var actualSpan = parentSpan || ((_hub$getScope = hub.getScope()) === null || _hub$getScope === void 0 ? void 0 : _hub$getScope.getTransaction());
1029
- var span = actualSpan === null || actualSpan === void 0 ? void 0 : actualSpan.startChild({
1030
- op: op,
1031
- description: description
1032
- });
1033
- hub.configureScope(function (scope) {
1034
- return scope.setSpan(span);
1035
- });
1036
- return span;
1037
- }
1038
- function addPluginOptionInformationToHub(options, hub, bundler) {
1039
- var org = options.org,
1040
- project = options.project,
1041
- cleanArtifacts = options.cleanArtifacts,
1042
- finalize = options.finalize,
1043
- setCommits = options.setCommits,
1044
- injectReleasesMap = options.injectReleasesMap,
1045
- dryRun = options.dryRun,
1046
- errorHandler = options.errorHandler,
1047
- deploy = options.deploy,
1048
- include = options.include;
1049
- hub.setTag("include", include.length > 1 ? "multiple-entries" : "single-entry"); // Optional release pipeline steps
1050
-
1051
- if (cleanArtifacts) {
1052
- hub.setTag("clean-artifacts", true);
1053
- }
1054
-
1055
- if (setCommits) {
1056
- hub.setTag("set-commits", setCommits.auto === true ? "auto" : "manual");
1057
- }
1058
-
1059
- if (finalize) {
1060
- hub.setTag("finalize-release", true);
1061
- }
1062
-
1063
- if (deploy) {
1064
- hub.setTag("add-deploy", true);
1065
- } // Miscelaneous options
1066
-
1067
-
1068
- if (dryRun) {
1069
- hub.setTag("dry-run", true);
1070
- }
1071
-
1072
- if (injectReleasesMap) {
1073
- hub.setTag("inject-releases-map", true);
1074
- }
1075
-
1076
- if (errorHandler) {
1077
- hub.setTag("error-handler", "custom");
1078
- }
1079
-
1080
- hub.setTag("node", process.version);
1081
- hub.setTags({
1082
- organization: org,
1083
- project: project,
1084
- bundler: bundler
1085
- });
1086
- hub.setUser({
1087
- id: org
1088
- });
1089
- }
1090
- function shouldSendTelemetry(_x2) {
1091
- return _shouldSendTelemetry.apply(this, arguments);
1092
- }
1093
-
1094
- function _shouldSendTelemetry() {
1095
- _shouldSendTelemetry = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(options) {
1096
- var _cliInfo$split$, _cliInfo$split$$repla;
1097
-
1098
- var silent, org, project, authToken, url, vcsRemote, headers, telemetry, dryRun, cli, cliInfo, cliInfoUrl;
1099
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
864
+ function _prepareBundleForDebugIdUpload() {
865
+ _prepareBundleForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(bundleFilePath, uploadFolder, uniqueUploadName, logger) {
866
+ var bundleContent, debugId, writeSourceFilePromise, writeSourceMapFilePromise;
867
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1100
868
  while (1) {
1101
- switch (_context2.prev = _context2.next) {
869
+ switch (_context4.prev = _context4.next) {
1102
870
  case 0:
1103
- silent = options.silent, org = options.org, project = options.project, authToken = options.authToken, url = options.url, vcsRemote = options.vcsRemote, headers = options.headers, telemetry = options.telemetry, dryRun = options.dryRun; // `options.telemetry` defaults to true
1104
-
1105
- if (!(telemetry === false)) {
1106
- _context2.next = 3;
1107
- break;
1108
- }
1109
-
1110
- return _context2.abrupt("return", false);
871
+ _context4.prev = 0;
872
+ _context4.next = 3;
873
+ return util.promisify(fs__default["default"].readFile)(bundleFilePath, "utf8");
1111
874
 
1112
875
  case 3:
1113
- if (!dryRun) {
1114
- _context2.next = 5;
1115
- break;
1116
- }
1117
-
1118
- return _context2.abrupt("return", false);
1119
-
1120
- case 5:
1121
- if (!(url === SENTRY_SAAS_URL)) {
1122
- _context2.next = 7;
1123
- break;
1124
- }
1125
-
1126
- return _context2.abrupt("return", true);
1127
-
1128
- case 7:
1129
- cli = new SentryCli__default["default"](options.configFile, {
1130
- url: url,
1131
- authToken: authToken,
1132
- org: org,
1133
- project: project,
1134
- vcsRemote: vcsRemote,
1135
- silent: silent,
1136
- headers: headers
1137
- });
1138
- _context2.prev = 8;
1139
- _context2.next = 11;
1140
- return cli.execute(["info"], false);
1141
-
1142
- case 11:
1143
- cliInfo = _context2.sent;
1144
- _context2.next = 17;
876
+ bundleContent = _context4.sent;
877
+ _context4.next = 10;
1145
878
  break;
1146
879
 
1147
- case 14:
1148
- _context2.prev = 14;
1149
- _context2.t0 = _context2["catch"](8);
1150
- throw new Error('Sentry CLI "info" command failed, make sure you have an auth token configured, and your `url` option is correct.');
880
+ case 6:
881
+ _context4.prev = 6;
882
+ _context4.t0 = _context4["catch"](0);
883
+ logger.error("Could not read bundle to determine debug ID and source map: ".concat(bundleFilePath), _context4.t0);
884
+ return _context4.abrupt("return");
1151
885
 
1152
- case 17:
1153
- cliInfoUrl = (_cliInfo$split$ = cliInfo.split(/(\r\n|\n|\r)/)[0]) === null || _cliInfo$split$ === void 0 ? void 0 : (_cliInfo$split$$repla = _cliInfo$split$.replace(/^Sentry Server: /, "")) === null || _cliInfo$split$$repla === void 0 ? void 0 : _cliInfo$split$$repla.trim();
886
+ case 10:
887
+ debugId = determineDebugIdFromBundleSource(bundleContent);
1154
888
 
1155
- if (!(cliInfoUrl === undefined)) {
1156
- _context2.next = 20;
889
+ if (!(debugId === undefined)) {
890
+ _context4.next = 14;
1157
891
  break;
1158
892
  }
1159
893
 
1160
- return _context2.abrupt("return", false);
894
+ logger.warn("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));
895
+ return _context4.abrupt("return");
1161
896
 
1162
- case 20:
1163
- return _context2.abrupt("return", new URL(cliInfoUrl).hostname === SENTRY_SAAS_HOSTNAME);
897
+ case 14:
898
+ bundleContent += "\n//# debugId=".concat(debugId);
899
+ writeSourceFilePromise = fs__default["default"].promises.writeFile(path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js")), bundleContent, "utf-8");
900
+ writeSourceMapFilePromise = determineSourceMapPathFromBundle(bundleFilePath, bundleContent, logger).then( /*#__PURE__*/function () {
901
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(sourceMapPath) {
902
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
903
+ while (1) {
904
+ switch (_context3.prev = _context3.next) {
905
+ case 0:
906
+ if (!sourceMapPath) {
907
+ _context3.next = 4;
908
+ break;
909
+ }
910
+
911
+ _context3.next = 3;
912
+ return prepareSourceMapForDebugIdUpload(sourceMapPath, path__default["default"].join(uploadFolder, "".concat(uniqueUploadName, ".js.map")), debugId, logger);
913
+
914
+ case 3:
915
+ return _context3.abrupt("return", _context3.sent);
916
+
917
+ case 4:
918
+ case "end":
919
+ return _context3.stop();
920
+ }
921
+ }
922
+ }, _callee3);
923
+ }));
924
+
925
+ return function (_x14) {
926
+ return _ref3.apply(this, arguments);
927
+ };
928
+ }());
929
+ return _context4.abrupt("return", Promise.all([writeSourceFilePromise, writeSourceMapFilePromise]));
1164
930
 
1165
- case 21:
931
+ case 18:
1166
932
  case "end":
1167
- return _context2.stop();
933
+ return _context4.stop();
1168
934
  }
1169
935
  }
1170
- }, _callee2, null, [[8, 14]]);
936
+ }, _callee4, null, [[0, 6]]);
1171
937
  }));
1172
- return _shouldSendTelemetry.apply(this, arguments);
1173
- }
1174
-
1175
- function createNewRelease(_x, _x2, _x3) {
1176
- return _createNewRelease.apply(this, arguments);
938
+ return _prepareBundleForDebugIdUpload.apply(this, arguments);
1177
939
  }
1178
940
 
1179
- function _createNewRelease() {
1180
- _createNewRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(options, ctx, releaseName) {
1181
- var span;
1182
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1183
- while (1) {
1184
- switch (_context.prev = _context.next) {
1185
- case 0:
1186
- span = addSpanToTransaction(ctx, "function.plugin.create_release");
1187
- _context.prev = 1;
1188
- _context.next = 4;
1189
- return ctx.cli.releases["new"](releaseName);
1190
-
1191
- case 4:
1192
- _context.next = 10;
1193
- break;
941
+ function determineDebugIdFromBundleSource(code) {
942
+ 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})/);
1194
943
 
1195
- case 6:
1196
- _context.prev = 6;
1197
- _context.t0 = _context["catch"](1);
1198
- ctx.hub.captureException(new Error("CLI Error: Creating new release failed"));
1199
- throw _context.t0;
944
+ if (match) {
945
+ return match[1];
946
+ } else {
947
+ return undefined;
948
+ }
949
+ }
950
+ /**
951
+ * Applies a set of heuristics to find the source map for a particular bundle.
952
+ *
953
+ * @returns the path to the bundle's source map or `undefined` if none could be found.
954
+ */
1200
955
 
1201
- case 10:
1202
- _context.prev = 10;
1203
- span === null || span === void 0 ? void 0 : span.finish();
1204
- return _context.finish(10);
1205
-
1206
- case 13:
1207
- ctx.hub.addBreadcrumb({
1208
- level: "info",
1209
- message: "Successfully created release."
1210
- });
1211
- ctx.logger.info("Successfully created release.");
1212
956
 
1213
- case 15:
1214
- case "end":
1215
- return _context.stop();
1216
- }
1217
- }
1218
- }, _callee, null, [[1, 6, 10, 13]]);
1219
- }));
1220
- return _createNewRelease.apply(this, arguments);
957
+ function determineSourceMapPathFromBundle(_x7, _x8, _x9) {
958
+ return _determineSourceMapPathFromBundle.apply(this, arguments);
1221
959
  }
960
+ /**
961
+ * Reads a source map, injects debug ID fields, and writes the source map to the target path.
962
+ */
1222
963
 
1223
- function cleanArtifacts(_x4, _x5, _x6) {
1224
- return _cleanArtifacts.apply(this, arguments);
1225
- }
1226
964
 
1227
- function _cleanArtifacts() {
1228
- _cleanArtifacts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(options, ctx, releaseName) {
1229
- var span;
1230
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
965
+ function _determineSourceMapPathFromBundle() {
966
+ _determineSourceMapPathFromBundle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(bundlePath, bundleSource, logger) {
967
+ var sourceMappingUrlMatch, sourceMappingUrl, adjacentSourceMapFilePath;
968
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1231
969
  while (1) {
1232
- switch (_context2.prev = _context2.next) {
970
+ switch (_context5.prev = _context5.next) {
1233
971
  case 0:
1234
- if (options.cleanArtifacts) {
1235
- _context2.next = 3;
972
+ // 1. try to find source map at `sourceMappingURL` location
973
+ sourceMappingUrlMatch = bundleSource.match(/^\/\/# sourceMappingURL=(.*)$/);
974
+
975
+ if (!sourceMappingUrlMatch) {
976
+ _context5.next = 8;
1236
977
  break;
1237
978
  }
1238
979
 
1239
- logger.debug("Skipping artifact cleanup.");
1240
- return _context2.abrupt("return");
980
+ sourceMappingUrl = path__default["default"].normalize(sourceMappingUrlMatch[1]);
1241
981
 
1242
- case 3:
1243
- span = addSpanToTransaction(ctx, "function.plugin.clean_artifacts");
1244
- _context2.prev = 4;
1245
- _context2.next = 7;
1246
- return ctx.cli.releases.execute(["releases", "files", releaseName, "delete", "--all"], true);
982
+ if (!path__default["default"].isAbsolute(sourceMappingUrl)) {
983
+ _context5.next = 7;
984
+ break;
985
+ }
986
+
987
+ return _context5.abrupt("return", sourceMappingUrl);
1247
988
 
1248
989
  case 7:
1249
- _context2.next = 13;
1250
- break;
990
+ return _context5.abrupt("return", path__default["default"].join(path__default["default"].dirname(bundlePath), sourceMappingUrl));
1251
991
 
1252
- case 9:
1253
- _context2.prev = 9;
1254
- _context2.t0 = _context2["catch"](4);
1255
- ctx.hub.captureException(new Error("CLI Error: Deleting release files failed"));
1256
- throw _context2.t0;
992
+ case 8:
993
+ _context5.prev = 8;
994
+ adjacentSourceMapFilePath = bundlePath + ".map";
995
+ _context5.next = 12;
996
+ return util__namespace.promisify(fs__default["default"].access)(adjacentSourceMapFilePath);
1257
997
 
1258
- case 13:
1259
- _context2.prev = 13;
1260
- span === null || span === void 0 ? void 0 : span.finish();
1261
- return _context2.finish(13);
998
+ case 12:
999
+ return _context5.abrupt("return", adjacentSourceMapFilePath);
1262
1000
 
1263
- case 16:
1264
- ctx.hub.addBreadcrumb({
1265
- level: "info",
1266
- message: "Successfully cleaned previous artifacts."
1267
- });
1268
- ctx.logger.info("Successfully cleaned previous artifacts.");
1001
+ case 15:
1002
+ _context5.prev = 15;
1003
+ _context5.t0 = _context5["catch"](8);
1269
1004
 
1270
- case 18:
1005
+ case 17:
1006
+ logger.warn("Could not determine source map path for bundle: ".concat(bundlePath));
1007
+ return _context5.abrupt("return", undefined);
1008
+
1009
+ case 19:
1271
1010
  case "end":
1272
- return _context2.stop();
1011
+ return _context5.stop();
1273
1012
  }
1274
1013
  }
1275
- }, _callee2, null, [[4, 9, 13, 16]]);
1014
+ }, _callee5, null, [[8, 15]]);
1276
1015
  }));
1277
- return _cleanArtifacts.apply(this, arguments);
1016
+ return _determineSourceMapPathFromBundle.apply(this, arguments);
1278
1017
  }
1279
1018
 
1280
- function uploadSourceMaps(_x7, _x8, _x9) {
1281
- return _uploadSourceMaps.apply(this, arguments);
1019
+ function prepareSourceMapForDebugIdUpload(_x10, _x11, _x12, _x13) {
1020
+ return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
1282
1021
  }
1283
1022
 
1284
- function _uploadSourceMaps() {
1285
- _uploadSourceMaps = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(options, ctx, releaseName) {
1286
- var span;
1287
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1023
+ function _prepareSourceMapForDebugIdUpload() {
1024
+ _prepareSourceMapForDebugIdUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(sourceMapPath, targetPath, debugId, logger) {
1025
+ var sourceMapFileContent, map;
1026
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1288
1027
  while (1) {
1289
- switch (_context3.prev = _context3.next) {
1028
+ switch (_context6.prev = _context6.next) {
1290
1029
  case 0:
1291
- span = addSpanToTransaction(ctx, "function.plugin.upload_sourcemaps");
1292
- ctx.logger.info("Uploading Sourcemaps."); // Since our internal include entries contain all top-level sourcemaps options,
1293
- // we only need to pass the include option here.
1294
-
1295
- _context3.prev = 2;
1296
- _context3.next = 5;
1297
- return ctx.cli.releases.uploadSourceMaps(releaseName, {
1298
- include: options.include,
1299
- dist: options.dist
1030
+ _context6.prev = 0;
1031
+ _context6.next = 3;
1032
+ return util__namespace.promisify(fs__default["default"].readFile)(sourceMapPath, {
1033
+ encoding: "utf8"
1300
1034
  });
1301
1035
 
1302
- case 5:
1303
- _context3.next = 11;
1036
+ case 3:
1037
+ sourceMapFileContent = _context6.sent;
1038
+ _context6.next = 10;
1304
1039
  break;
1305
1040
 
1306
- case 7:
1307
- _context3.prev = 7;
1308
- _context3.t0 = _context3["catch"](2);
1309
- ctx.hub.captureException(new Error("CLI Error: Uploading source maps failed"));
1310
- throw _context3.t0;
1041
+ case 6:
1042
+ _context6.prev = 6;
1043
+ _context6.t0 = _context6["catch"](0);
1044
+ logger.error("Failed to read source map for debug ID upload: ".concat(sourceMapPath), _context6.t0);
1045
+ return _context6.abrupt("return");
1311
1046
 
1312
- case 11:
1313
- _context3.prev = 11;
1314
- span === null || span === void 0 ? void 0 : span.finish();
1315
- return _context3.finish(11);
1047
+ case 10:
1048
+ _context6.prev = 10;
1049
+ map = JSON.parse(sourceMapFileContent); // For now we write both fields until we know what will become the standard - if ever.
1316
1050
 
1317
- case 14:
1318
- ctx.hub.addBreadcrumb({
1319
- level: "info",
1320
- message: "Successfully uploaded source maps."
1321
- });
1322
- ctx.logger.info("Successfully uploaded source maps.");
1051
+ map["debug_id"] = debugId;
1052
+ map["debugId"] = debugId;
1053
+ _context6.next = 20;
1054
+ break;
1323
1055
 
1324
1056
  case 16:
1325
- case "end":
1326
- return _context3.stop();
1327
- }
1328
- }
1329
- }, _callee3, null, [[2, 7, 11, 14]]);
1330
- }));
1331
- return _uploadSourceMaps.apply(this, arguments);
1332
- }
1333
-
1334
- function setCommits(_x10, _x11, _x12) {
1335
- return _setCommits.apply(this, arguments);
1336
- }
1337
-
1338
- function _setCommits() {
1339
- _setCommits = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(options, ctx, releaseName) {
1340
- var span, _options$setCommits, auto, repo, commit, previousCommit, ignoreMissing, ignoreEmpty;
1341
-
1342
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1343
- while (1) {
1344
- switch (_context4.prev = _context4.next) {
1345
- case 0:
1346
- if (options.setCommits) {
1347
- _context4.next = 3;
1348
- break;
1349
- }
1350
-
1351
- logger.debug("Skipping setting commits to release.");
1352
- return _context4.abrupt("return");
1057
+ _context6.prev = 16;
1058
+ _context6.t1 = _context6["catch"](10);
1059
+ logger.error("Failed to parse source map for debug ID upload: ".concat(sourceMapPath));
1060
+ return _context6.abrupt("return");
1353
1061
 
1354
- case 3:
1355
- span = addSpanToTransaction(ctx, "function.plugin.set_commits");
1356
- _options$setCommits = options.setCommits, auto = _options$setCommits.auto, repo = _options$setCommits.repo, commit = _options$setCommits.commit, previousCommit = _options$setCommits.previousCommit, ignoreMissing = _options$setCommits.ignoreMissing, ignoreEmpty = _options$setCommits.ignoreEmpty;
1357
- _context4.prev = 5;
1358
- _context4.next = 8;
1359
- return ctx.cli.releases.setCommits(releaseName, {
1360
- commit: commit,
1361
- previousCommit: previousCommit,
1362
- repo: repo,
1363
- auto: auto,
1364
- ignoreMissing: ignoreMissing,
1365
- ignoreEmpty: ignoreEmpty
1062
+ case 20:
1063
+ _context6.prev = 20;
1064
+ _context6.next = 23;
1065
+ return util__namespace.promisify(fs__default["default"].writeFile)(targetPath, JSON.stringify(map), {
1066
+ encoding: "utf8"
1366
1067
  });
1367
1068
 
1368
- case 8:
1369
- _context4.next = 14;
1069
+ case 23:
1070
+ _context6.next = 29;
1370
1071
  break;
1371
1072
 
1372
- case 10:
1373
- _context4.prev = 10;
1374
- _context4.t0 = _context4["catch"](5);
1375
- ctx.hub.captureException(new Error("CLI Error: Setting commits failed"));
1376
- throw _context4.t0;
1377
-
1378
- case 14:
1379
- _context4.prev = 14;
1380
- span === null || span === void 0 ? void 0 : span.finish();
1381
- return _context4.finish(14);
1382
-
1383
- case 17:
1384
- ctx.logger.info("Successfully set commits.");
1073
+ case 25:
1074
+ _context6.prev = 25;
1075
+ _context6.t2 = _context6["catch"](20);
1076
+ logger.error("Failed to prepare source map for debug ID upload: ".concat(sourceMapPath), _context6.t2);
1077
+ return _context6.abrupt("return");
1385
1078
 
1386
- case 18:
1079
+ case 29:
1387
1080
  case "end":
1388
- return _context4.stop();
1081
+ return _context6.stop();
1389
1082
  }
1390
1083
  }
1391
- }, _callee4, null, [[5, 10, 14, 17]]);
1084
+ }, _callee6, null, [[0, 6], [10, 16], [20, 25]]);
1392
1085
  }));
1393
- return _setCommits.apply(this, arguments);
1394
- }
1395
-
1396
- function finalizeRelease(_x13, _x14, _x15) {
1397
- return _finalizeRelease.apply(this, arguments);
1086
+ return _prepareSourceMapForDebugIdUpload.apply(this, arguments);
1398
1087
  }
1399
1088
 
1400
- function _finalizeRelease() {
1401
- _finalizeRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(options, ctx, releaseName) {
1402
- var span;
1403
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1404
- while (1) {
1405
- switch (_context5.prev = _context5.next) {
1406
- case 0:
1407
- if (options.finalize) {
1408
- _context5.next = 4;
1409
- break;
1410
- }
1089
+ function releaseManagementPlugin(_ref) {
1090
+ var releaseName = _ref.releaseName,
1091
+ include = _ref.include,
1092
+ dist = _ref.dist,
1093
+ setCommitsOption = _ref.setCommitsOption,
1094
+ shouldCreateRelease = _ref.shouldCreateRelease,
1095
+ shouldCleanArtifacts = _ref.shouldCleanArtifacts,
1096
+ shouldFinalizeRelease = _ref.shouldFinalizeRelease,
1097
+ deployOptions = _ref.deployOptions,
1098
+ handleRecoverableError = _ref.handleRecoverableError,
1099
+ sentryHub = _ref.sentryHub,
1100
+ sentryClient = _ref.sentryClient,
1101
+ sentryCliOptions = _ref.sentryCliOptions;
1102
+ return {
1103
+ name: "sentry-debug-id-upload-plugin",
1104
+ writeBundle: function writeBundle() {
1105
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1106
+ var cliInstance, normalizedInclude;
1107
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1108
+ while (1) {
1109
+ switch (_context.prev = _context.next) {
1110
+ case 0:
1111
+ _context.prev = 0;
1112
+ cliInstance = new SentryCli__default["default"](null, sentryCliOptions);
1411
1113
 
1412
- ctx.hub.addBreadcrumb({
1413
- level: "info",
1414
- message: "Skipping release finalization."
1415
- });
1416
- logger.debug("Skipping release finalization.");
1417
- return _context5.abrupt("return");
1114
+ if (!shouldCreateRelease) {
1115
+ _context.next = 5;
1116
+ break;
1117
+ }
1418
1118
 
1419
- case 4:
1420
- span = addSpanToTransaction(ctx, "function.plugin.finalize_release");
1421
- _context5.prev = 5;
1422
- _context5.next = 8;
1423
- return ctx.cli.releases.finalize(releaseName);
1119
+ _context.next = 5;
1120
+ return cliInstance.releases["new"](releaseName);
1424
1121
 
1425
- case 8:
1426
- _context5.next = 14;
1427
- break;
1122
+ case 5:
1123
+ if (!shouldCleanArtifacts) {
1124
+ _context.next = 8;
1125
+ break;
1126
+ }
1428
1127
 
1429
- case 10:
1430
- _context5.prev = 10;
1431
- _context5.t0 = _context5["catch"](5);
1432
- ctx.hub.captureException(new Error("CLI Error: Finalizing release failed"));
1433
- throw _context5.t0;
1128
+ _context.next = 8;
1129
+ return cliInstance.releases.execute(["releases", "files", releaseName, "delete", "--all"], true);
1434
1130
 
1435
- case 14:
1436
- _context5.prev = 14;
1437
- span === null || span === void 0 ? void 0 : span.finish();
1438
- return _context5.finish(14);
1131
+ case 8:
1132
+ if (!include) {
1133
+ _context.next = 12;
1134
+ break;
1135
+ }
1439
1136
 
1440
- case 17:
1441
- ctx.hub.addBreadcrumb({
1442
- level: "info",
1443
- message: "Successfully finalized release."
1444
- });
1445
- ctx.logger.info("Successfully finalized release.");
1137
+ normalizedInclude = arrayify(include).map(function (includeItem) {
1138
+ return typeof includeItem === "string" ? {
1139
+ paths: [includeItem]
1140
+ } : includeItem;
1141
+ }).map(function (includeEntry) {
1142
+ var _includeEntry$validat;
1143
+
1144
+ return _objectSpread2(_objectSpread2({}, includeEntry), {}, {
1145
+ validate: (_includeEntry$validat = includeEntry.validate) !== null && _includeEntry$validat !== void 0 ? _includeEntry$validat : false,
1146
+ ext: includeEntry.ext ? includeEntry.ext.map(function (extension) {
1147
+ return ".".concat(extension.replace(/^\./, ""));
1148
+ }) : [".js", ".map", ".jsbundle", ".bundle"],
1149
+ ignore: includeEntry.ignore ? arrayify(includeEntry.ignore) : undefined
1150
+ });
1151
+ });
1152
+ _context.next = 12;
1153
+ return cliInstance.releases.uploadSourceMaps(releaseName, {
1154
+ include: normalizedInclude,
1155
+ dist: dist
1156
+ });
1446
1157
 
1447
- case 19:
1448
- case "end":
1449
- return _context5.stop();
1450
- }
1451
- }
1452
- }, _callee5, null, [[5, 10, 14, 17]]);
1453
- }));
1454
- return _finalizeRelease.apply(this, arguments);
1455
- }
1158
+ case 12:
1159
+ if (!setCommitsOption) {
1160
+ _context.next = 15;
1161
+ break;
1162
+ }
1456
1163
 
1457
- function addDeploy(_x16, _x17, _x18) {
1458
- return _addDeploy.apply(this, arguments);
1459
- }
1164
+ _context.next = 15;
1165
+ return cliInstance.releases.setCommits(releaseName, setCommitsOption);
1460
1166
 
1461
- function _addDeploy() {
1462
- _addDeploy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(options, ctx, releaseName) {
1463
- var span, _options$deploy, env, started, finished, time, name, url;
1167
+ case 15:
1168
+ if (!shouldFinalizeRelease) {
1169
+ _context.next = 18;
1170
+ break;
1171
+ }
1464
1172
 
1465
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1466
- while (1) {
1467
- switch (_context6.prev = _context6.next) {
1468
- case 0:
1469
- if (options.deploy) {
1470
- _context6.next = 4;
1471
- break;
1472
- }
1173
+ _context.next = 18;
1174
+ return cliInstance.releases.finalize(releaseName);
1473
1175
 
1474
- ctx.hub.addBreadcrumb({
1475
- level: "info",
1476
- message: "Skipping adding deploy info to release."
1477
- });
1478
- logger.debug("Skipping adding deploy info to release.");
1479
- return _context6.abrupt("return");
1176
+ case 18:
1177
+ if (!deployOptions) {
1178
+ _context.next = 21;
1179
+ break;
1180
+ }
1480
1181
 
1481
- case 4:
1482
- span = addSpanToTransaction(ctx, "function.plugin.deploy");
1483
- _options$deploy = options.deploy, env = _options$deploy.env, started = _options$deploy.started, finished = _options$deploy.finished, time = _options$deploy.time, name = _options$deploy.name, url = _options$deploy.url;
1484
- _context6.prev = 6;
1485
- _context6.next = 9;
1486
- return ctx.cli.releases.newDeploy(releaseName, {
1487
- env: env,
1488
- started: started,
1489
- finished: finished,
1490
- time: time,
1491
- name: name,
1492
- url: url
1493
- });
1182
+ _context.next = 21;
1183
+ return cliInstance.releases.newDeploy(releaseName, deployOptions);
1494
1184
 
1495
- case 9:
1496
- _context6.next = 15;
1497
- break;
1185
+ case 21:
1186
+ _context.next = 29;
1187
+ break;
1498
1188
 
1499
- case 11:
1500
- _context6.prev = 11;
1501
- _context6.t0 = _context6["catch"](6);
1502
- ctx.hub.captureException(new Error("CLI Error: Adding deploy info failed"));
1503
- throw _context6.t0;
1189
+ case 23:
1190
+ _context.prev = 23;
1191
+ _context.t0 = _context["catch"](0);
1192
+ sentryHub.captureException('Error in "releaseManagementPlugin" writeBundle hook');
1193
+ _context.next = 28;
1194
+ return sentryClient.flush();
1504
1195
 
1505
- case 15:
1506
- _context6.prev = 15;
1507
- span === null || span === void 0 ? void 0 : span.finish();
1508
- return _context6.finish(15);
1196
+ case 28:
1197
+ handleRecoverableError(_context.t0);
1509
1198
 
1510
- case 18:
1511
- ctx.hub.addBreadcrumb({
1512
- level: "info",
1513
- message: "Successfully added deploy."
1514
- });
1515
- ctx.logger.info("Successfully added deploy.");
1199
+ case 29:
1200
+ case "end":
1201
+ return _context.stop();
1202
+ }
1203
+ }
1204
+ }, _callee, null, [[0, 23]]);
1205
+ }))();
1206
+ }
1207
+ };
1208
+ }
1516
1209
 
1517
- case 20:
1518
- case "end":
1519
- return _context6.stop();
1520
- }
1521
- }
1522
- }, _callee6, null, [[6, 11, 15, 18]]);
1523
- }));
1524
- return _addDeploy.apply(this, arguments);
1210
+ function telemetryPlugin(_ref) {
1211
+ var sentryClient = _ref.sentryClient,
1212
+ pluginExecutionTransaction = _ref.pluginExecutionTransaction,
1213
+ shouldSendTelemetry = _ref.shouldSendTelemetry,
1214
+ logger = _ref.logger;
1215
+ return {
1216
+ name: "sentry-telemetry-plugin",
1217
+ buildStart: function buildStart() {
1218
+ void shouldSendTelemetry.then(function () {
1219
+ logger.info("Sending error and performance telemetry data to Sentry. To disable telemetry, set `options.telemetry` to `false`.");
1220
+ });
1221
+ pluginExecutionTransaction.startTimestamp = Date.now() / 1000;
1222
+ },
1223
+ writeBundle: function writeBundle() {
1224
+ return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1225
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1226
+ while (1) {
1227
+ switch (_context.prev = _context.next) {
1228
+ case 0:
1229
+ pluginExecutionTransaction.finish();
1230
+ _context.next = 3;
1231
+ return sentryClient.flush();
1232
+
1233
+ case 3:
1234
+ case "end":
1235
+ return _context.stop();
1236
+ }
1237
+ }
1238
+ }, _callee);
1239
+ }))();
1240
+ }
1241
+ };
1525
1242
  }
1526
1243
 
1527
1244
  function createLogger(options) {
@@ -1577,91 +1294,222 @@ function createLogger(options) {
1577
1294
  };
1578
1295
  }
1579
1296
 
1580
- /**
1581
- * Creates a new Sentry CLI instance.
1582
- *
1583
- * In case, users selected the `dryRun` options, this returns a stub
1584
- * that makes no-ops out of most CLI operations
1585
- */
1586
- function getSentryCli(internalOptions, logger) {
1587
- var silent = internalOptions.silent,
1588
- org = internalOptions.org,
1589
- project = internalOptions.project,
1590
- authToken = internalOptions.authToken,
1591
- url = internalOptions.url,
1592
- vcsRemote = internalOptions.vcsRemote,
1593
- headers = internalOptions.headers;
1594
- var cli = new SentryCli__default["default"](internalOptions.configFile, {
1595
- url: url,
1596
- authToken: authToken,
1597
- org: org,
1598
- project: project,
1599
- vcsRemote: vcsRemote,
1600
- silent: silent,
1601
- headers: headers
1297
+ var SENTRY_SAAS_HOSTNAME = "sentry.io";
1298
+ function createSentryInstance(options, shouldSendTelemetry, bundler) {
1299
+ var client = new node.NodeClient({
1300
+ dsn: "https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737",
1301
+ tracesSampleRate: 1,
1302
+ sampleRate: 1,
1303
+ release: "2.0.0-alpha.2",
1304
+ integrations: [],
1305
+ tracePropagationTargets: ["sentry.io/api"],
1306
+ stackParser: node.defaultStackParser,
1307
+ beforeSend: function beforeSend(event) {
1308
+ var _event$exception, _event$exception$valu;
1309
+
1310
+ (_event$exception = event.exception) === null || _event$exception === void 0 ? void 0 : (_event$exception$valu = _event$exception.values) === null || _event$exception$valu === void 0 ? void 0 : _event$exception$valu.forEach(function (exception) {
1311
+ delete exception.stacktrace;
1312
+ });
1313
+ delete event.server_name; // Server name might contain PII
1314
+
1315
+ return event;
1316
+ },
1317
+ beforeSendTransaction: function beforeSendTransaction(event) {
1318
+ delete event.server_name; // Server name might contain PII
1319
+
1320
+ return event;
1321
+ },
1322
+ // We create a transport that stalls sending events until we know that we're allowed to (i.e. when Sentry CLI told
1323
+ // us that the upload URL is the Sentry SaaS URL)
1324
+ transport: function transport(nodeTransportOptions) {
1325
+ var nodeTransport = node.makeNodeTransport(nodeTransportOptions);
1326
+ return {
1327
+ flush: function flush(timeout) {
1328
+ return nodeTransport.flush(timeout);
1329
+ },
1330
+ send: function () {
1331
+ var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) {
1332
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1333
+ while (1) {
1334
+ switch (_context.prev = _context.next) {
1335
+ case 0:
1336
+ _context.next = 2;
1337
+ return shouldSendTelemetry;
1338
+
1339
+ case 2:
1340
+ if (!_context.sent) {
1341
+ _context.next = 6;
1342
+ break;
1343
+ }
1344
+
1345
+ return _context.abrupt("return", nodeTransport.send(request));
1346
+
1347
+ case 6:
1348
+ return _context.abrupt("return", undefined);
1349
+
1350
+ case 7:
1351
+ case "end":
1352
+ return _context.stop();
1353
+ }
1354
+ }
1355
+ }, _callee);
1356
+ }));
1357
+
1358
+ function send(_x) {
1359
+ return _send.apply(this, arguments);
1360
+ }
1361
+
1362
+ return send;
1363
+ }()
1364
+ };
1365
+ }
1602
1366
  });
1367
+ var hub = new node.Hub(client);
1368
+ setTelemetryDataOnHub(options, hub, bundler);
1369
+ return {
1370
+ sentryHub: hub,
1371
+ sentryClient: client
1372
+ };
1373
+ }
1374
+ function setTelemetryDataOnHub(options, hub, bundler) {
1375
+ var org = options.org,
1376
+ project = options.project,
1377
+ release = options.release,
1378
+ errorHandler = options.errorHandler,
1379
+ sourcemaps = options.sourcemaps;
1380
+
1381
+ if (release.uploadLegacySourcemaps) {
1382
+ hub.setTag("uploadLegacySourcemapsEntries", Array.isArray(release.uploadLegacySourcemaps) ? release.uploadLegacySourcemaps.length : 1);
1383
+ } // Optional release pipeline steps
1384
+
1385
+
1386
+ if (release.cleanArtifacts) {
1387
+ hub.setTag("clean-artifacts", true);
1388
+ }
1389
+
1390
+ if (release.setCommits) {
1391
+ hub.setTag("set-commits", release.setCommits.auto === true ? "auto" : "manual");
1392
+ }
1393
+
1394
+ if (release.finalize) {
1395
+ hub.setTag("finalize-release", true);
1396
+ }
1397
+
1398
+ if (release.deploy) {
1399
+ hub.setTag("add-deploy", true);
1400
+ } // Miscelaneous options
1401
+
1603
1402
 
1604
- if (internalOptions.dryRun) {
1605
- logger.info("In DRY RUN Mode");
1606
- return getDryRunCLI(cli, logger);
1403
+ if (errorHandler) {
1404
+ hub.setTag("error-handler", "custom");
1607
1405
  }
1608
1406
 
1609
- return cli;
1407
+ if (sourcemaps !== null && sourcemaps !== void 0 && sourcemaps.assets) {
1408
+ hub.setTag("debug-id-upload", true);
1409
+ }
1410
+
1411
+ if (sourcemaps !== null && sourcemaps !== void 0 && sourcemaps.deleteAfterUpload) {
1412
+ hub.setTag("delete-after-upload", true);
1413
+ }
1414
+
1415
+ hub.setTag("node", process.version);
1416
+ hub.setTags({
1417
+ organization: org,
1418
+ project: project,
1419
+ bundler: bundler
1420
+ });
1421
+ hub.setUser({
1422
+ id: org
1423
+ });
1424
+ }
1425
+ function allowedToSendTelemetry(_x2) {
1426
+ return _allowedToSendTelemetry.apply(this, arguments);
1610
1427
  }
1611
1428
 
1612
- function getDryRunCLI(cli, logger) {
1613
- return {
1614
- releases: {
1615
- proposeVersion: function proposeVersion() {
1616
- return cli.releases.proposeVersion().then(function (version) {
1617
- logger.info("Proposed version:\n", version);
1618
- return version;
1619
- });
1620
- },
1621
- "new": function _new(release) {
1622
- logger.info("Creating new release:\n", release);
1623
- return Promise.resolve(release);
1624
- },
1625
- uploadSourceMaps: function uploadSourceMaps(release, config) {
1626
- logger.info("Calling upload-sourcemaps with:\n", config);
1627
- return Promise.resolve(release);
1628
- },
1629
- finalize: function finalize(release) {
1630
- logger.info("Finalizing release:\n", release);
1631
- return Promise.resolve(release);
1632
- },
1633
- setCommits: function setCommits(release, config) {
1634
- logger.info("Calling set-commits with:\n", config);
1635
- return Promise.resolve(release);
1636
- },
1637
- newDeploy: function newDeploy(release, config) {
1638
- logger.info("Calling deploy with:\n", config);
1639
- return Promise.resolve(release);
1640
- },
1641
- execute: function execute(args, live) {
1642
- logger.info("Executing", args, "live:", live);
1643
- return Promise.resolve("");
1429
+ function _allowedToSendTelemetry() {
1430
+ _allowedToSendTelemetry = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(options) {
1431
+ var _cliInfo$split$, _cliInfo$split$$repla;
1432
+
1433
+ var silent, org, project, authToken, url, headers, telemetry, release, cli, cliInfo, cliInfoUrl;
1434
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1435
+ while (1) {
1436
+ switch (_context2.prev = _context2.next) {
1437
+ case 0:
1438
+ silent = options.silent, org = options.org, project = options.project, authToken = options.authToken, url = options.url, headers = options.headers, telemetry = options.telemetry, release = options.release; // `options.telemetry` defaults to true
1439
+
1440
+ if (!(telemetry === false)) {
1441
+ _context2.next = 3;
1442
+ break;
1443
+ }
1444
+
1445
+ return _context2.abrupt("return", false);
1446
+
1447
+ case 3:
1448
+ if (!(url === SENTRY_SAAS_URL)) {
1449
+ _context2.next = 5;
1450
+ break;
1451
+ }
1452
+
1453
+ return _context2.abrupt("return", true);
1454
+
1455
+ case 5:
1456
+ cli = new SentryCli__default["default"](null, {
1457
+ url: url,
1458
+ authToken: authToken,
1459
+ org: org,
1460
+ project: project,
1461
+ vcsRemote: release.vcsRemote,
1462
+ silent: silent,
1463
+ headers: headers
1464
+ });
1465
+ _context2.prev = 6;
1466
+ _context2.next = 9;
1467
+ return cli.execute(["info"], false);
1468
+
1469
+ case 9:
1470
+ cliInfo = _context2.sent;
1471
+ _context2.next = 15;
1472
+ break;
1473
+
1474
+ case 12:
1475
+ _context2.prev = 12;
1476
+ _context2.t0 = _context2["catch"](6);
1477
+ return _context2.abrupt("return", false);
1478
+
1479
+ case 15:
1480
+ cliInfoUrl = (_cliInfo$split$ = cliInfo.split(/(\r\n|\n|\r)/)[0]) === null || _cliInfo$split$ === void 0 ? void 0 : (_cliInfo$split$$repla = _cliInfo$split$.replace(/^Sentry Server: /, "")) === null || _cliInfo$split$$repla === void 0 ? void 0 : _cliInfo$split$$repla.trim();
1481
+
1482
+ if (!(cliInfoUrl === undefined)) {
1483
+ _context2.next = 18;
1484
+ break;
1485
+ }
1486
+
1487
+ return _context2.abrupt("return", false);
1488
+
1489
+ case 18:
1490
+ return _context2.abrupt("return", new URL(cliInfoUrl).hostname === SENTRY_SAAS_HOSTNAME);
1491
+
1492
+ case 19:
1493
+ case "end":
1494
+ return _context2.stop();
1495
+ }
1644
1496
  }
1645
- },
1646
- execute: function execute(args, live) {
1647
- logger.info("Executing", args, "live:", live);
1648
- return Promise.resolve("Executed");
1649
- }
1650
- };
1497
+ }, _callee2, null, [[6, 12]]);
1498
+ }));
1499
+ return _allowedToSendTelemetry.apply(this, arguments);
1651
1500
  }
1652
1501
 
1653
- var ALLOWED_TRANSFORMATION_FILE_ENDINGS = [".js", ".ts", ".jsx", ".tsx", ".mjs"];
1654
1502
  /**
1655
1503
  * The sentry bundler plugin concerns itself with two things:
1656
1504
  * - Release injection
1657
1505
  * - Sourcemaps upload
1658
1506
  *
1659
1507
  * Release injection:
1660
- * Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into
1661
- * each JavaScript/TypeScript entrypoint. On a technical level this is done by identifying
1662
- * entrypoints in the `resolveId` hook and prepending user code in the `transform` hook.
1663
- * If a user wants to inject the release into a particular set of modules instead,
1664
- * they can use the `releaseInjectionTargets` option.
1508
+ * Per default the sentry bundler plugin will inject a global `SENTRY_RELEASE` into each JavaScript/TypeScript module
1509
+ * that is part of the bundle. On a technical level this is done by appending an import (`import "sentry-release-injector;"`)
1510
+ * to all entrypoint files of the user code (see `transformInclude` and `transform` hooks). This import is then resolved
1511
+ * by the sentry plugin to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
1512
+ * If a user wants to inject the release into a particular set of modules they can use the `releaseInjectionTargets` option.
1665
1513
  *
1666
1514
  * Source maps upload:
1667
1515
  *
@@ -1678,395 +1526,271 @@ var ALLOWED_TRANSFORMATION_FILE_ENDINGS = [".js", ".ts", ".jsx", ".tsx", ".mjs"]
1678
1526
  *
1679
1527
  * This release creation pipeline relies on Sentry CLI to execute the different steps.
1680
1528
  */
1681
-
1682
- var unplugin = unplugin$1.createUnplugin(function (options, unpluginMetaContext) {
1683
- var internalOptions = normalizeUserOptions(options);
1684
- var allowedToSendTelemetryPromise = shouldSendTelemetry(internalOptions);
1685
-
1686
- var _makeSentryClient = makeSentryClient("https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737", allowedToSendTelemetryPromise, internalOptions.project),
1687
- sentryHub = _makeSentryClient.sentryHub,
1688
- sentryClient = _makeSentryClient.sentryClient;
1689
-
1690
- addPluginOptionInformationToHub(internalOptions, sentryHub, unpluginMetaContext.framework); //TODO: This call is problematic because as soon as we set our hub as the current hub
1691
- // we might interfere with other plugins that use Sentry. However, for now, we'll
1692
- // leave it in because without it, we can't get distributed traces (which are pretty nice)
1693
- // Let's keep it until someone complains about interference.
1694
- // The ideal solution would be a code change in the JS SDK but it's not a straight-forward fix.
1695
-
1696
- node.makeMain(sentryHub);
1697
- var logger = createLogger({
1698
- prefix: "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
1699
- silent: internalOptions.silent,
1700
- debug: internalOptions.debug
1701
- });
1702
-
1703
- if (!validateOptions(internalOptions, logger)) {
1704
- handleError(new Error("Options were not set correctly. See output above for more details."), logger, internalOptions.errorHandler);
1705
- }
1706
-
1707
- var cli = getSentryCli(internalOptions, logger);
1708
- var releaseNamePromise = new Promise(function (resolve) {
1709
- if (options.release) {
1710
- resolve(options.release);
1711
- } else {
1712
- resolve(cli.releases.proposeVersion());
1529
+ function sentryUnpluginFactory(_ref) {
1530
+ var releaseInjectionPlugin = _ref.releaseInjectionPlugin,
1531
+ debugIdInjectionPlugin = _ref.debugIdInjectionPlugin;
1532
+ return unplugin.createUnplugin(function (userOptions, unpluginMetaContext) {
1533
+ var options = normalizeUserOptions(userOptions);
1534
+
1535
+ if (unpluginMetaContext.watchMode || options.disable) {
1536
+ return [{
1537
+ name: "sentry-noop-plugin"
1538
+ }];
1713
1539
  }
1714
- });
1715
- var transaction;
1716
- var releaseInjectionSpan;
1717
- var absolueEntrypointPaths = new Set();
1718
- return {
1719
- name: "sentry-plugin",
1720
- enforce: "pre",
1721
- // needed for Vite to call resolveId hook
1722
1540
 
1723
- /**
1724
- * Responsible for starting the plugin execution transaction and the release injection span
1725
- */
1726
- buildStart: function buildStart() {
1727
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1728
- var isAllowedToSendToSendTelemetry, releaseName;
1729
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1730
- while (1) {
1731
- switch (_context.prev = _context.next) {
1732
- case 0:
1733
- logger.debug("Called 'buildStart'");
1734
- _context.next = 3;
1735
- return allowedToSendTelemetryPromise;
1541
+ var shouldSendTelemetry = allowedToSendTelemetry(options);
1736
1542
 
1737
- case 3:
1738
- isAllowedToSendToSendTelemetry = _context.sent;
1739
-
1740
- if (isAllowedToSendToSendTelemetry) {
1741
- logger.info("Sending error and performance telemetry data to Sentry.");
1742
- logger.info("To disable telemetry, set `options.telemetry` to `false`.");
1743
- sentryHub.addBreadcrumb({
1744
- level: "info",
1745
- message: "Telemetry enabled."
1746
- });
1747
- } else {
1748
- sentryHub.addBreadcrumb({
1749
- level: "info",
1750
- message: "Telemetry disabled. This should never show up in a Sentry event."
1751
- });
1752
- }
1543
+ var _createSentryInstance = createSentryInstance(options, shouldSendTelemetry, unpluginMetaContext.framework),
1544
+ sentryHub = _createSentryInstance.sentryHub,
1545
+ sentryClient = _createSentryInstance.sentryClient;
1753
1546
 
1754
- _context.next = 7;
1755
- return releaseNamePromise;
1547
+ var pluginExecutionTransaction = sentryHub.startTransaction({
1548
+ name: "Sentry Bundler Plugin execution"
1549
+ });
1550
+ sentryHub.getScope().setSpan(pluginExecutionTransaction);
1551
+ var logger = createLogger({
1552
+ prefix: "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
1553
+ silent: options.silent,
1554
+ debug: options.debug
1555
+ });
1756
1556
 
1757
- case 7:
1758
- releaseName = _context.sent;
1557
+ function handleRecoverableError(unknownError) {
1558
+ pluginExecutionTransaction.setStatus("internal_error");
1759
1559
 
1760
- // At this point, we either have determined a release or we have to bail
1761
- if (!releaseName) {
1762
- handleError(new Error("Unable to determine a release name. Make sure to set the `release` option or use an environment that supports auto-detection https://docs.sentry.io/cli/releases/#creating-releases`"), logger, internalOptions.errorHandler);
1763
- }
1560
+ if (options.errorHandler) {
1561
+ if (unknownError instanceof Error) {
1562
+ options.errorHandler(unknownError);
1563
+ } else {
1564
+ options.errorHandler(new Error("An unknown error occured"));
1565
+ }
1566
+ } else {
1567
+ throw unknownError;
1568
+ }
1569
+ }
1764
1570
 
1765
- transaction = sentryHub.startTransaction({
1766
- op: "function.plugin",
1767
- name: "Sentry Bundler Plugin execution"
1768
- });
1769
- releaseInjectionSpan = addSpanToTransaction({
1770
- hub: sentryHub,
1771
- parentSpan: transaction,
1772
- logger: logger,
1773
- cli: cli
1774
- }, "function.plugin.inject_release", "Release injection");
1571
+ if (!validateOptions(options, logger)) {
1572
+ handleRecoverableError(new Error("Options were not set correctly. See output above for more details."));
1573
+ }
1775
1574
 
1776
- case 11:
1777
- case "end":
1778
- return _context.stop();
1779
- }
1780
- }
1781
- }, _callee);
1782
- }))();
1783
- },
1575
+ if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) {
1576
+ logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
1577
+ }
1784
1578
 
1785
- /**
1786
- * Responsible for returning the "sentry-release-injector" ID when we encounter it. We return the ID so load is
1787
- * called and we can "virtually" load the module. See `load` hook for more info on why it's virtual.
1788
- *
1789
- * We also record the id (i.e. absolute path) of any non-entrypoint.
1790
- *
1791
- * @param id For imports: The absolute path of the module to be imported. For entrypoints: The path the user defined as entrypoint - may also be relative.
1792
- * @param importer For imports: The absolute path of the module that imported this module. For entrypoints: `undefined`.
1793
- * @param options Additional information to use for making a resolving decision.
1794
- * @returns `"sentry-release-injector"` when the imported file is called `"sentry-release-injector"`. Otherwise returns `undefined`.
1795
- */
1796
- resolveId: function resolveId(id, importer, _ref) {
1797
- var isEntry = _ref.isEntry;
1798
- logger.debug('Called "resolveId":', {
1799
- id: id,
1800
- importer: importer,
1801
- isEntry: isEntry
1579
+ var plugins = [];
1580
+ plugins.push(telemetryPlugin({
1581
+ pluginExecutionTransaction: pluginExecutionTransaction,
1582
+ logger: logger,
1583
+ shouldSendTelemetry: shouldSendTelemetry,
1584
+ sentryClient: sentryClient
1585
+ }));
1586
+
1587
+ if (!options.release.inject) {
1588
+ logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
1589
+ } else if (!options.release.name) {
1590
+ logger.warn("No release name provided. Will not inject release. Please set the `release.name` option to identifiy your release.");
1591
+ } else {
1592
+ var _injectionCode = generateGlobalInjectorCode({
1593
+ release: options.release.name,
1594
+ injectBuildInformation: options._experiments.injectBuildInformation || false
1802
1595
  });
1803
1596
 
1804
- if (isEntry) {
1805
- absolueEntrypointPaths.add(path__default["default"].resolve(path__default["default"].normalize(id)));
1806
- }
1807
-
1808
- return undefined;
1809
- },
1597
+ plugins.push(releaseInjectionPlugin(_injectionCode));
1598
+ }
1810
1599
 
1811
- /**
1812
- * This hook determines whether we want to transform a module. In the sentry bundler plugin we want to transform every entrypoint
1813
- * unless configured otherwise with the `releaseInjectionTargets` option.
1814
- *
1815
- * @param id Always the absolute (fully resolved) path to the module.
1816
- * @returns `true` or `false` depending on whether we want to transform the module. For the sentry bundler plugin we only
1817
- * want to transform the release injector file.
1818
- */
1819
- transformInclude: function transformInclude(id) {
1820
- logger.debug('Called "transformInclude":', {
1821
- id: id
1822
- }); // We normalize the id because vite always passes `id` as a unix style path which causes problems when a user passes
1823
- // a windows style path to `releaseInjectionTargets`
1824
-
1825
- var normalizedId = path__default["default"].normalize(id);
1826
-
1827
- if (internalOptions.releaseInjectionTargets) {
1828
- // If there's an `releaseInjectionTargets` option transform (ie. inject the release varible) when the file path matches the option.
1829
- if (typeof internalOptions.releaseInjectionTargets === "function") {
1830
- return internalOptions.releaseInjectionTargets(normalizedId);
1600
+ if (!options.release.name) {
1601
+ logger.warn("No release name provided. Will not create release. Please set the `release.name` option to identifiy your release.");
1602
+ } else if (!options.authToken) {
1603
+ 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/");
1604
+ } else if (!options.org) {
1605
+ logger.warn("No organization slug provided. Will not create release. Please set the `org` option to your Sentry organization slug.");
1606
+ } else if (!options.project) {
1607
+ logger.warn("No project provided. Will not create release. Please set the `project` option to your Sentry project slug.");
1608
+ } else {
1609
+ plugins.push(releaseManagementPlugin({
1610
+ logger: logger,
1611
+ releaseName: options.release.name,
1612
+ shouldCreateRelease: options.release.create,
1613
+ shouldCleanArtifacts: options.release.cleanArtifacts,
1614
+ shouldFinalizeRelease: options.release.finalize,
1615
+ include: options.release.uploadLegacySourcemaps,
1616
+ setCommitsOption: options.release.setCommits,
1617
+ deployOptions: options.release.deploy,
1618
+ dist: options.release.dist,
1619
+ handleRecoverableError: handleRecoverableError,
1620
+ sentryHub: sentryHub,
1621
+ sentryClient: sentryClient,
1622
+ sentryCliOptions: {
1623
+ authToken: options.authToken,
1624
+ org: options.org,
1625
+ project: options.project,
1626
+ silent: options.silent,
1627
+ url: options.url,
1628
+ vcsRemote: options.release.vcsRemote,
1629
+ headers: options.headers
1831
1630
  }
1631
+ }));
1632
+ }
1832
1633
 
1833
- return internalOptions.releaseInjectionTargets.some(function (entry) {
1834
- if (entry instanceof RegExp) {
1835
- return entry.test(normalizedId);
1836
- } else {
1837
- var normalizedEntry = path__default["default"].normalize(entry);
1838
- return normalizedId === normalizedEntry;
1839
- }
1840
- });
1841
- } else if (absolueEntrypointPaths.has(normalizedId)) {
1842
- var pathIsOrdinary = !normalizedId.includes("?") && !normalizedId.includes("#");
1843
- var pathHasAllowedFileEnding = ALLOWED_TRANSFORMATION_FILE_ENDINGS.some(function (allowedFileEnding) {
1844
- return normalizedId.endsWith(allowedFileEnding);
1845
- });
1846
- return pathIsOrdinary && pathHasAllowedFileEnding;
1634
+ if (options.sourcemaps) {
1635
+ if (!options.authToken) {
1636
+ 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/");
1637
+ } else if (!options.org) {
1638
+ logger.warn("No org provided. Will not upload source maps. Please set the `org` option to your Sentry organization slug.");
1639
+ } else if (!options.project) {
1640
+ logger.warn("No project provided. Will not upload source maps. Please set the `project` option to your Sentry project slug.");
1641
+ } else if (!options.sourcemaps.assets) {
1642
+ logger.warn("No assets defined. Will not upload source maps. Please provide set the `assets` option to your build-output folder.");
1847
1643
  } else {
1848
- return false;
1644
+ plugins.push(debugIdInjectionPlugin());
1645
+ plugins.push(debugIdUploadPlugin({
1646
+ assets: options.sourcemaps.assets,
1647
+ ignore: options.sourcemaps.ignore,
1648
+ dist: options.release.dist,
1649
+ releaseName: options.release.name,
1650
+ logger: logger,
1651
+ handleRecoverableError: handleRecoverableError,
1652
+ sentryHub: sentryHub,
1653
+ sentryClient: sentryClient,
1654
+ sentryCliOptions: {
1655
+ authToken: options.authToken,
1656
+ org: options.org,
1657
+ project: options.project,
1658
+ silent: options.silent,
1659
+ url: options.url,
1660
+ vcsRemote: options.release.vcsRemote,
1661
+ headers: options.headers
1662
+ }
1663
+ }));
1849
1664
  }
1850
- },
1665
+ }
1851
1666
 
1852
- /**
1853
- * This hook is responsible for injecting the "sentry release injector" imoprt statement into each entrypoint unless
1854
- * configured otherwise with the `releaseInjectionTargets` option (logic for that is in the `transformInclude` hook).
1855
- *
1856
- * @param code Code of the file to transform.
1857
- * @param id Always the absolute (fully resolved) path to the module.
1858
- * @returns transformed code + source map
1859
- */
1860
- transform: function transform(code, id) {
1861
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1862
- var ms;
1863
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1864
- while (1) {
1865
- switch (_context2.prev = _context2.next) {
1866
- case 0:
1867
- logger.debug('Called "transform":', {
1868
- id: id
1869
- }); // The MagicString library allows us to generate sourcemaps for the changes we make to the user code.
1870
-
1871
- ms = new MagicString__default["default"](code);
1872
- _context2.t0 = ms;
1873
- _context2.t1 = generateGlobalInjectorCode;
1874
- _context2.next = 6;
1875
- return releaseNamePromise;
1876
-
1877
- case 6:
1878
- _context2.t2 = _context2.sent;
1879
- _context2.t3 = internalOptions.injectReleasesMap;
1880
- _context2.t4 = internalOptions.org;
1881
- _context2.t5 = internalOptions.project;
1882
- _context2.t6 = {
1883
- release: _context2.t2,
1884
- injectReleasesMap: _context2.t3,
1885
- org: _context2.t4,
1886
- project: _context2.t5
1887
- };
1888
- _context2.t7 = (0, _context2.t1)(_context2.t6);
1889
-
1890
- _context2.t0.prepend.call(_context2.t0, _context2.t7);
1891
-
1892
- if (!(unpluginMetaContext.framework === "esbuild")) {
1893
- _context2.next = 17;
1894
- break;
1895
- }
1667
+ return plugins;
1668
+ });
1669
+ }
1670
+ function getBuildInformation() {
1671
+ var packageJson = getPackageJson();
1896
1672
 
1897
- return _context2.abrupt("return", ms.toString());
1673
+ var _ref2 = packageJson ? getDependencies(packageJson) : {
1674
+ deps: [],
1675
+ depsVersions: {}
1676
+ },
1677
+ deps = _ref2.deps,
1678
+ depsVersions = _ref2.depsVersions;
1898
1679
 
1899
- case 17:
1900
- return _context2.abrupt("return", {
1901
- code: ms.toString(),
1902
- map: ms.generateMap()
1903
- });
1680
+ return {
1681
+ deps: deps,
1682
+ depsVersions: depsVersions,
1683
+ nodeVersion: parseMajorVersion(process.version)
1684
+ };
1685
+ }
1686
+ /**
1687
+ * Determines whether the Sentry CLI binary is in its expected location.
1688
+ * This function is useful since `@sentry/cli` installs the binary via a post-install
1689
+ * script and post-install scripts may not always run. E.g. with `npm i --ignore-scripts`.
1690
+ */
1904
1691
 
1905
- case 18:
1906
- case "end":
1907
- return _context2.stop();
1908
- }
1909
- }
1910
- }, _callee2);
1911
- }))();
1692
+ function sentryCliBinaryExists() {
1693
+ return fs__default["default"].existsSync(SentryCli__default["default"].getPath());
1694
+ }
1695
+ function createRollupReleaseInjectionHooks(injectionCode) {
1696
+ var virtualReleaseInjectionFileId = "\0sentry-release-injection-file";
1697
+ return {
1698
+ resolveId: function resolveId(id) {
1699
+ if (id === virtualReleaseInjectionFileId) {
1700
+ return {
1701
+ id: virtualReleaseInjectionFileId,
1702
+ external: false,
1703
+ moduleSideEffects: true
1704
+ };
1705
+ } else {
1706
+ return null;
1707
+ }
1912
1708
  },
1709
+ load: function load(id) {
1710
+ if (id === virtualReleaseInjectionFileId) {
1711
+ return injectionCode;
1712
+ } else {
1713
+ return null;
1714
+ }
1715
+ },
1716
+ transform: function transform(code, id) {
1717
+ if (id === virtualReleaseInjectionFileId) {
1718
+ return null;
1719
+ }
1913
1720
 
1914
- /**
1915
- * Responsible for executing the sentry release creation pipeline (i.e. creating a release on
1916
- * Sentry.io, uploading sourcemaps, associating commits and deploys and finalizing the release)
1917
- */
1918
- writeBundle: function writeBundle() {
1919
- return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1920
- var _releaseInjectionSpan;
1921
-
1922
- var releasePipelineSpan, ctx, releaseName, _transaction, _transaction2, _transaction3;
1923
-
1924
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1925
- while (1) {
1926
- switch (_context3.prev = _context3.next) {
1927
- case 0:
1928
- logger.debug('Called "writeBundle"');
1929
- (_releaseInjectionSpan = releaseInjectionSpan) === null || _releaseInjectionSpan === void 0 ? void 0 : _releaseInjectionSpan.finish();
1930
- releasePipelineSpan = transaction && addSpanToTransaction({
1931
- hub: sentryHub,
1932
- parentSpan: transaction,
1933
- logger: logger,
1934
- cli: cli
1935
- }, "function.plugin.release", "Release pipeline");
1936
- sentryHub.addBreadcrumb({
1937
- category: "writeBundle:start",
1938
- level: "info"
1939
- });
1940
- ctx = {
1941
- hub: sentryHub,
1942
- parentSpan: releasePipelineSpan,
1943
- logger: logger,
1944
- cli: cli
1945
- };
1946
- _context3.next = 7;
1947
- return releaseNamePromise;
1948
-
1949
- case 7:
1950
- releaseName = _context3.sent;
1951
- _context3.prev = 8;
1952
- _context3.next = 11;
1953
- return createNewRelease(internalOptions, ctx, releaseName);
1954
-
1955
- case 11:
1956
- _context3.next = 13;
1957
- return cleanArtifacts(internalOptions, ctx, releaseName);
1958
-
1959
- case 13:
1960
- _context3.next = 15;
1961
- return uploadSourceMaps(internalOptions, ctx, releaseName);
1962
-
1963
- case 15:
1964
- _context3.next = 17;
1965
- return setCommits(internalOptions, ctx, releaseName);
1966
-
1967
- case 17:
1968
- _context3.next = 19;
1969
- return finalizeRelease(internalOptions, ctx, releaseName);
1970
-
1971
- case 19:
1972
- _context3.next = 21;
1973
- return addDeploy(internalOptions, ctx, releaseName);
1974
-
1975
- case 21:
1976
- (_transaction = transaction) === null || _transaction === void 0 ? void 0 : _transaction.setStatus("ok");
1977
- _context3.next = 29;
1978
- break;
1979
-
1980
- case 24:
1981
- _context3.prev = 24;
1982
- _context3.t0 = _context3["catch"](8);
1983
- (_transaction2 = transaction) === null || _transaction2 === void 0 ? void 0 : _transaction2.setStatus("cancelled");
1984
- sentryHub.addBreadcrumb({
1985
- level: "error",
1986
- message: "Error during writeBundle"
1987
- });
1988
- handleError(_context3.t0, logger, internalOptions.errorHandler);
1989
-
1990
- case 29:
1991
- _context3.prev = 29;
1992
- releasePipelineSpan === null || releasePipelineSpan === void 0 ? void 0 : releasePipelineSpan.finish();
1993
- (_transaction3 = transaction) === null || _transaction3 === void 0 ? void 0 : _transaction3.finish();
1994
- _context3.next = 34;
1995
- return sentryClient.flush().then(null, function () {
1996
- logger.warn("Sending of telemetry failed");
1997
- });
1721
+ if (id.match(/\\node_modules\\|\/node_modules\//)) {
1722
+ return null;
1723
+ }
1998
1724
 
1999
- case 34:
2000
- return _context3.finish(29);
1725
+ if (![".js", ".ts", ".jsx", ".tsx", ".mjs"].some(function (ending) {
1726
+ return id.endsWith(ending);
1727
+ })) {
1728
+ return null;
1729
+ }
2001
1730
 
2002
- case 35:
2003
- sentryHub.addBreadcrumb({
2004
- category: "writeBundle:finish",
2005
- level: "info"
2006
- });
1731
+ var ms = new MagicString__default["default"](code); // Appending instead of prepending has less probability of mucking with user's source maps.
1732
+ // Luckily import statements get hoisted to the top anyways.
2007
1733
 
2008
- case 36:
2009
- case "end":
2010
- return _context3.stop();
2011
- }
2012
- }
2013
- }, _callee3, null, [[8, 24, 29, 35]]);
2014
- }))();
1734
+ ms.append("\n\n;import \"".concat(virtualReleaseInjectionFileId, "\";"));
1735
+ return {
1736
+ code: ms.toString(),
1737
+ map: ms.generateMap()
1738
+ };
2015
1739
  }
2016
1740
  };
2017
- });
2018
-
2019
- function handleError(unknownError, logger, errorHandler) {
2020
- if (unknownError instanceof Error) {
2021
- logger.error(unknownError.message);
2022
- } else {
2023
- logger.error(String(unknownError));
2024
- }
1741
+ }
1742
+ function createRollupDebugIdInjectionHooks() {
1743
+ return {
1744
+ renderChunk: function renderChunk(code, chunk) {
1745
+ if ([".js", ".mjs", ".cjs"].some(function (ending) {
1746
+ return chunk.fileName.endsWith(ending);
1747
+ }) // chunks could be any file (html, md, ...)
1748
+ ) {
1749
+ var _code$match;
1750
+
1751
+ var debugId = stringToUUID(code); // generate a deterministic debug ID
1752
+
1753
+ var codeToInject = getDebugIdSnippet(debugId);
1754
+ var ms = new MagicString__default["default"](code, {
1755
+ filename: chunk.fileName
1756
+ }); // We need to be careful not to inject the snippet before any `"use strict";`s.
1757
+ // As an additional complication `"use strict";`s may come after any number of comments.
1758
+
1759
+ var commentUseStrictRegex = // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.
1760
+ /^(?:\s*|\/\*(?:.|\r|\n)*\*\/|\/\/.*[\n\r])*(?:"[^"]*";|'[^']*';)?/;
1761
+
1762
+ if ((_code$match = code.match(commentUseStrictRegex)) !== null && _code$match !== void 0 && _code$match[0]) {
1763
+ // Add injected code after any comments or "use strict" at the beginning of the bundle.
1764
+ ms.replace(commentUseStrictRegex, function (match) {
1765
+ return "".concat(match).concat(codeToInject);
1766
+ });
1767
+ } else {
1768
+ // ms.replace() doesn't work when there is an empty string match (which happens if
1769
+ // there is neither, a comment, nor a "use strict" at the top of the chunk) so we
1770
+ // need this special case here.
1771
+ ms.prepend(codeToInject);
1772
+ }
2025
1773
 
2026
- if (errorHandler) {
2027
- if (unknownError instanceof Error) {
2028
- errorHandler(unknownError);
2029
- } else {
2030
- errorHandler(new Error("An unknown error occured"));
1774
+ return {
1775
+ code: ms.toString(),
1776
+ map: ms.generateMap({
1777
+ file: chunk.fileName
1778
+ })
1779
+ };
1780
+ } else {
1781
+ return null; // returning null means not modifying the chunk at all
1782
+ }
2031
1783
  }
2032
- } else {
2033
- throw unknownError;
2034
- }
1784
+ };
1785
+ }
1786
+ function getDebugIdSnippet(debugId) {
1787
+ return ";!function(){try{var e=\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"".concat(debugId, "\",e._sentryDebugIdIdentifier=\"sentry-dbid-").concat(debugId, "\")}catch(e){}}();");
2035
1788
  }
2036
- /**
2037
- * Generates code for the "sentry-release-injector" which is responsible for setting the global `SENTRY_RELEASE`
2038
- * variable.
2039
- */
2040
-
2041
-
2042
- function generateGlobalInjectorCode(_ref2) {
2043
- var release = _ref2.release,
2044
- injectReleasesMap = _ref2.injectReleasesMap,
2045
- org = _ref2.org,
2046
- project = _ref2.project;
2047
- // The code below is mostly ternary operators because it saves bundle size.
2048
- // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
2049
- var code = "\n var _global =\n typeof window !== 'undefined' ?\n window :\n typeof global !== 'undefined' ?\n global :\n typeof self !== 'undefined' ?\n self :\n {};\n\n _global.SENTRY_RELEASE={id:\"".concat(release, "\"};");
2050
-
2051
- if (injectReleasesMap && project) {
2052
- var key = org ? "".concat(project, "@").concat(org) : project;
2053
- code += "\n _global.SENTRY_RELEASES=_global.SENTRY_RELEASES || {};\n _global.SENTRY_RELEASES[\"".concat(key, "\"]={id:\"").concat(release, "\"};");
2054
- }
2055
-
2056
- return code;
2057
- } // eslint-disable-next-line @typescript-eslint/no-explicit-any
2058
-
2059
-
2060
- var sentryVitePlugin = unplugin.vite; // eslint-disable-next-line @typescript-eslint/no-explicit-any
2061
-
2062
- var sentryRollupPlugin = unplugin.rollup; // eslint-disable-next-line @typescript-eslint/no-explicit-any
2063
-
2064
- var sentryWebpackPlugin = unplugin.webpack; // eslint-disable-next-line @typescript-eslint/no-explicit-any
2065
-
2066
- var sentryEsbuildPlugin = unplugin.esbuild;
2067
1789
 
2068
- exports.sentryEsbuildPlugin = sentryEsbuildPlugin;
2069
- exports.sentryRollupPlugin = sentryRollupPlugin;
2070
- exports.sentryVitePlugin = sentryVitePlugin;
2071
- exports.sentryWebpackPlugin = sentryWebpackPlugin;
1790
+ exports.createRollupDebugIdInjectionHooks = createRollupDebugIdInjectionHooks;
1791
+ exports.createRollupReleaseInjectionHooks = createRollupReleaseInjectionHooks;
1792
+ exports.getBuildInformation = getBuildInformation;
1793
+ exports.getDebugIdSnippet = getDebugIdSnippet;
1794
+ exports.sentryCliBinaryExists = sentryCliBinaryExists;
1795
+ exports.sentryUnpluginFactory = sentryUnpluginFactory;
2072
1796
  //# sourceMappingURL=index.js.map