@sentry/bundler-plugin-core 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1550 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var unplugin$1 = require('unplugin');
6
+ var MagicString = require('magic-string');
7
+ var child_process = require('child_process');
8
+ var axios = require('axios');
9
+ var FormData = require('form-data');
10
+ var node = require('@sentry/node');
11
+ var path = require('path');
12
+ var fs = require('fs');
13
+ require('@sentry/tracing');
14
+
15
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
+
17
+ function _interopNamespace(e) {
18
+ if (e && e.__esModule) return e;
19
+ var n = Object.create(null);
20
+ if (e) {
21
+ Object.keys(e).forEach(function (k) {
22
+ if (k !== 'default') {
23
+ var d = Object.getOwnPropertyDescriptor(e, k);
24
+ Object.defineProperty(n, k, d.get ? d : {
25
+ enumerable: true,
26
+ get: function () { return e[k]; }
27
+ });
28
+ }
29
+ });
30
+ }
31
+ n["default"] = e;
32
+ return Object.freeze(n);
33
+ }
34
+
35
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
36
+ var child_process__namespace = /*#__PURE__*/_interopNamespace(child_process);
37
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
38
+ var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData);
39
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
40
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
41
+
42
+ function ownKeys(object, enumerableOnly) {
43
+ var keys = Object.keys(object);
44
+
45
+ if (Object.getOwnPropertySymbols) {
46
+ var symbols = Object.getOwnPropertySymbols(object);
47
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
48
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
49
+ })), keys.push.apply(keys, symbols);
50
+ }
51
+
52
+ return keys;
53
+ }
54
+
55
+ function _objectSpread2(target) {
56
+ for (var i = 1; i < arguments.length; i++) {
57
+ var source = null != arguments[i] ? arguments[i] : {};
58
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
59
+ _defineProperty(target, key, source[key]);
60
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
61
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
62
+ });
63
+ }
64
+
65
+ return target;
66
+ }
67
+
68
+ function _regeneratorRuntime() {
69
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
70
+
71
+ _regeneratorRuntime = function () {
72
+ return exports;
73
+ };
74
+
75
+ var exports = {},
76
+ Op = Object.prototype,
77
+ hasOwn = Op.hasOwnProperty,
78
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
79
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
80
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
81
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
82
+
83
+ function define(obj, key, value) {
84
+ return Object.defineProperty(obj, key, {
85
+ value: value,
86
+ enumerable: !0,
87
+ configurable: !0,
88
+ writable: !0
89
+ }), obj[key];
90
+ }
91
+
92
+ try {
93
+ define({}, "");
94
+ } catch (err) {
95
+ define = function (obj, key, value) {
96
+ return obj[key] = value;
97
+ };
98
+ }
99
+
100
+ function wrap(innerFn, outerFn, self, tryLocsList) {
101
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
102
+ generator = Object.create(protoGenerator.prototype),
103
+ context = new Context(tryLocsList || []);
104
+ return generator._invoke = function (innerFn, self, context) {
105
+ var state = "suspendedStart";
106
+ return function (method, arg) {
107
+ if ("executing" === state) throw new Error("Generator is already running");
108
+
109
+ if ("completed" === state) {
110
+ if ("throw" === method) throw arg;
111
+ return doneResult();
112
+ }
113
+
114
+ for (context.method = method, context.arg = arg;;) {
115
+ var delegate = context.delegate;
116
+
117
+ if (delegate) {
118
+ var delegateResult = maybeInvokeDelegate(delegate, context);
119
+
120
+ if (delegateResult) {
121
+ if (delegateResult === ContinueSentinel) continue;
122
+ return delegateResult;
123
+ }
124
+ }
125
+
126
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
127
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
128
+ context.dispatchException(context.arg);
129
+ } else "return" === context.method && context.abrupt("return", context.arg);
130
+ state = "executing";
131
+ var record = tryCatch(innerFn, self, context);
132
+
133
+ if ("normal" === record.type) {
134
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
135
+ return {
136
+ value: record.arg,
137
+ done: context.done
138
+ };
139
+ }
140
+
141
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
142
+ }
143
+ };
144
+ }(innerFn, self, context), generator;
145
+ }
146
+
147
+ function tryCatch(fn, obj, arg) {
148
+ try {
149
+ return {
150
+ type: "normal",
151
+ arg: fn.call(obj, arg)
152
+ };
153
+ } catch (err) {
154
+ return {
155
+ type: "throw",
156
+ arg: err
157
+ };
158
+ }
159
+ }
160
+
161
+ exports.wrap = wrap;
162
+ var ContinueSentinel = {};
163
+
164
+ function Generator() {}
165
+
166
+ function GeneratorFunction() {}
167
+
168
+ function GeneratorFunctionPrototype() {}
169
+
170
+ var IteratorPrototype = {};
171
+ define(IteratorPrototype, iteratorSymbol, function () {
172
+ return this;
173
+ });
174
+ var getProto = Object.getPrototypeOf,
175
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
176
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
177
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
178
+
179
+ function defineIteratorMethods(prototype) {
180
+ ["next", "throw", "return"].forEach(function (method) {
181
+ define(prototype, method, function (arg) {
182
+ return this._invoke(method, arg);
183
+ });
184
+ });
185
+ }
186
+
187
+ function AsyncIterator(generator, PromiseImpl) {
188
+ function invoke(method, arg, resolve, reject) {
189
+ var record = tryCatch(generator[method], generator, arg);
190
+
191
+ if ("throw" !== record.type) {
192
+ var result = record.arg,
193
+ value = result.value;
194
+ return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
195
+ invoke("next", value, resolve, reject);
196
+ }, function (err) {
197
+ invoke("throw", err, resolve, reject);
198
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
199
+ result.value = unwrapped, resolve(result);
200
+ }, function (error) {
201
+ return invoke("throw", error, resolve, reject);
202
+ });
203
+ }
204
+
205
+ reject(record.arg);
206
+ }
207
+
208
+ var previousPromise;
209
+
210
+ this._invoke = function (method, arg) {
211
+ function callInvokeWithMethodAndArg() {
212
+ return new PromiseImpl(function (resolve, reject) {
213
+ invoke(method, arg, resolve, reject);
214
+ });
215
+ }
216
+
217
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
218
+ };
219
+ }
220
+
221
+ function maybeInvokeDelegate(delegate, context) {
222
+ var method = delegate.iterator[context.method];
223
+
224
+ if (undefined === method) {
225
+ if (context.delegate = null, "throw" === context.method) {
226
+ if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
227
+ context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
228
+ }
229
+
230
+ return ContinueSentinel;
231
+ }
232
+
233
+ var record = tryCatch(method, delegate.iterator, context.arg);
234
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
235
+ var info = record.arg;
236
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
237
+ }
238
+
239
+ function pushTryEntry(locs) {
240
+ var entry = {
241
+ tryLoc: locs[0]
242
+ };
243
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
244
+ }
245
+
246
+ function resetTryEntry(entry) {
247
+ var record = entry.completion || {};
248
+ record.type = "normal", delete record.arg, entry.completion = record;
249
+ }
250
+
251
+ function Context(tryLocsList) {
252
+ this.tryEntries = [{
253
+ tryLoc: "root"
254
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
255
+ }
256
+
257
+ function values(iterable) {
258
+ if (iterable) {
259
+ var iteratorMethod = iterable[iteratorSymbol];
260
+ if (iteratorMethod) return iteratorMethod.call(iterable);
261
+ if ("function" == typeof iterable.next) return iterable;
262
+
263
+ if (!isNaN(iterable.length)) {
264
+ var i = -1,
265
+ next = function next() {
266
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
267
+
268
+ return next.value = undefined, next.done = !0, next;
269
+ };
270
+
271
+ return next.next = next;
272
+ }
273
+ }
274
+
275
+ return {
276
+ next: doneResult
277
+ };
278
+ }
279
+
280
+ function doneResult() {
281
+ return {
282
+ value: undefined,
283
+ done: !0
284
+ };
285
+ }
286
+
287
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
288
+ var ctor = "function" == typeof genFun && genFun.constructor;
289
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
290
+ }, exports.mark = function (genFun) {
291
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
292
+ }, exports.awrap = function (arg) {
293
+ return {
294
+ __await: arg
295
+ };
296
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
297
+ return this;
298
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
299
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
300
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
301
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
302
+ return result.done ? result.value : iter.next();
303
+ });
304
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
305
+ return this;
306
+ }), define(Gp, "toString", function () {
307
+ return "[object Generator]";
308
+ }), exports.keys = function (object) {
309
+ var keys = [];
310
+
311
+ for (var key in object) keys.push(key);
312
+
313
+ return keys.reverse(), function next() {
314
+ for (; keys.length;) {
315
+ var key = keys.pop();
316
+ if (key in object) return next.value = key, next.done = !1, next;
317
+ }
318
+
319
+ return next.done = !0, next;
320
+ };
321
+ }, exports.values = values, Context.prototype = {
322
+ constructor: Context,
323
+ reset: function (skipTempReset) {
324
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
325
+ },
326
+ stop: function () {
327
+ this.done = !0;
328
+ var rootRecord = this.tryEntries[0].completion;
329
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
330
+ return this.rval;
331
+ },
332
+ dispatchException: function (exception) {
333
+ if (this.done) throw exception;
334
+ var context = this;
335
+
336
+ function handle(loc, caught) {
337
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
338
+ }
339
+
340
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
341
+ var entry = this.tryEntries[i],
342
+ record = entry.completion;
343
+ if ("root" === entry.tryLoc) return handle("end");
344
+
345
+ if (entry.tryLoc <= this.prev) {
346
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
347
+ hasFinally = hasOwn.call(entry, "finallyLoc");
348
+
349
+ if (hasCatch && hasFinally) {
350
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
351
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
352
+ } else if (hasCatch) {
353
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
354
+ } else {
355
+ if (!hasFinally) throw new Error("try statement without catch or finally");
356
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
357
+ }
358
+ }
359
+ }
360
+ },
361
+ abrupt: function (type, arg) {
362
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
363
+ var entry = this.tryEntries[i];
364
+
365
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
366
+ var finallyEntry = entry;
367
+ break;
368
+ }
369
+ }
370
+
371
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
372
+ var record = finallyEntry ? finallyEntry.completion : {};
373
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
374
+ },
375
+ complete: function (record, afterLoc) {
376
+ if ("throw" === record.type) throw record.arg;
377
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
378
+ },
379
+ finish: function (finallyLoc) {
380
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
381
+ var entry = this.tryEntries[i];
382
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
383
+ }
384
+ },
385
+ catch: function (tryLoc) {
386
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
387
+ var entry = this.tryEntries[i];
388
+
389
+ if (entry.tryLoc === tryLoc) {
390
+ var record = entry.completion;
391
+
392
+ if ("throw" === record.type) {
393
+ var thrown = record.arg;
394
+ resetTryEntry(entry);
395
+ }
396
+
397
+ return thrown;
398
+ }
399
+ }
400
+
401
+ throw new Error("illegal catch attempt");
402
+ },
403
+ delegateYield: function (iterable, resultName, nextLoc) {
404
+ return this.delegate = {
405
+ iterator: values(iterable),
406
+ resultName: resultName,
407
+ nextLoc: nextLoc
408
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
409
+ }
410
+ }, exports;
411
+ }
412
+
413
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
414
+ try {
415
+ var info = gen[key](arg);
416
+ var value = info.value;
417
+ } catch (error) {
418
+ reject(error);
419
+ return;
420
+ }
421
+
422
+ if (info.done) {
423
+ resolve(value);
424
+ } else {
425
+ Promise.resolve(value).then(_next, _throw);
426
+ }
427
+ }
428
+
429
+ function _asyncToGenerator(fn) {
430
+ return function () {
431
+ var self = this,
432
+ args = arguments;
433
+ return new Promise(function (resolve, reject) {
434
+ var gen = fn.apply(self, args);
435
+
436
+ function _next(value) {
437
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
438
+ }
439
+
440
+ function _throw(err) {
441
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
442
+ }
443
+
444
+ _next(undefined);
445
+ });
446
+ };
447
+ }
448
+
449
+ function _defineProperty(obj, key, value) {
450
+ if (key in obj) {
451
+ Object.defineProperty(obj, key, {
452
+ value: value,
453
+ enumerable: true,
454
+ configurable: true,
455
+ writable: true
456
+ });
457
+ } else {
458
+ obj[key] = value;
459
+ }
460
+
461
+ return obj;
462
+ }
463
+
464
+ function getGitBranchHead() {
465
+ try {
466
+ return child_process__namespace.execSync("git rev-parse HEAD").toString().trim();
467
+ } catch (e) {
468
+ // no git installed
469
+ return undefined;
470
+ }
471
+ }
472
+
473
+ function getReleaseName(releaseName) {
474
+ if (releaseName) {
475
+ return releaseName;
476
+ } // Env var SENTRY_RELEASE takes presendace over other env vars listed below
477
+ // this is why we are looking for it before proceeding with others
478
+
479
+
480
+ if (process.env["SENTRY_RELEASE"]) {
481
+ return process.env["SENTRY_RELEASE"];
482
+ }
483
+
484
+ var ENV_VARS = ["SOURCE_VERSION", // Heroku #1 https://devcenter.heroku.com/changelog-items/630
485
+ "HEROKU_SLUG_COMMIT", // Heroku #2: https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases
486
+ "CODEBUILD_RESOLVED_SOURCE_VERSION", // AWS CodeBuild: https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
487
+ "CIRCLE_SHA1", // CircleCI: https://circleci.com/docs/2.0/env-vars/
488
+ "VERCEL_GIT_COMMIT_SHA" // Vercel docs: https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables
489
+ ];
490
+ var releaseFromEnvironmentVar = ENV_VARS.find(function (key) {
491
+ return Object.keys(process.env).includes(key);
492
+ });
493
+
494
+ if (releaseFromEnvironmentVar) {
495
+ return process.env[releaseFromEnvironmentVar];
496
+ }
497
+
498
+ var gitBranchHead = getGitBranchHead();
499
+
500
+ if (gitBranchHead) {
501
+ return gitBranchHead;
502
+ } else {
503
+ throw new Error("Could not return a release name");
504
+ }
505
+ }
506
+
507
+ function makeSentryClient(dsn, telemetryEnabled, org) {
508
+ var client = new node.NodeClient({
509
+ dsn: dsn,
510
+ enabled: telemetryEnabled,
511
+ tracesSampleRate: telemetryEnabled ? 1.0 : 0.0,
512
+ sampleRate: telemetryEnabled ? 1.0 : 0.0,
513
+ release: "0.0.1-alpha.0",
514
+ integrations: [new node.Integrations.Http({
515
+ tracing: true
516
+ })],
517
+ tracePropagationTargets: ["sentry.io/api"],
518
+ stackParser: node.defaultStackParser,
519
+ transport: node.makeNodeTransport,
520
+ debug: true
521
+ });
522
+ var hub = new node.Hub(client);
523
+ hub.configureScope(function (scope) {
524
+ if (org) {
525
+ scope.setTag("org", org);
526
+ }
527
+ }); //TODO: This call is problematic because as soon as we set our hub as the current hub
528
+ // we might interfere with other plugins that use Sentry. However, for now, we'll
529
+ // leave it in because without it, we can't get distributed traces (which are pretty nice)
530
+ // Let's keep it until someone complains about interference.
531
+ // The ideal solution would be a code change in the JS SDK but it's not a straight-forward fix.
532
+
533
+ node.makeMain(hub);
534
+ return {
535
+ client: client,
536
+ hub: hub
537
+ };
538
+ }
539
+ /**
540
+ * Adds a span to the passed parentSpan or to the current transaction that's on the passed hub's scope.
541
+ */
542
+
543
+ function addSpanToTransaction(ctx, op, description) {
544
+ var _hub$getScope;
545
+
546
+ var hub = ctx.hub,
547
+ parentSpan = ctx.parentSpan;
548
+ var actualSpan = parentSpan || ((_hub$getScope = hub.getScope()) === null || _hub$getScope === void 0 ? void 0 : _hub$getScope.getTransaction());
549
+ var span = actualSpan === null || actualSpan === void 0 ? void 0 : actualSpan.startChild({
550
+ op: op,
551
+ description: description
552
+ });
553
+ hub.configureScope(function (scope) {
554
+ return scope.setSpan(span);
555
+ });
556
+ return span;
557
+ }
558
+ function captureMinimalError(error, hub) {
559
+ var isAxiosError = error instanceof axios.AxiosError;
560
+ var sentryError = error instanceof Error ? {
561
+ name: "".concat(isAxiosError && error.status ? error.status : "", ": ").concat(error.name),
562
+ message: error.message,
563
+ stack: error.stack
564
+ } : {};
565
+ hub.captureException(sentryError);
566
+ }
567
+
568
+ var API_PATH = "/api/0";
569
+ var USER_AGENT = "sentry-bundler-plugin/".concat("0.0.1-alpha.0");
570
+
571
+ var sentryApiAxiosInstance = function sentryApiAxiosInstance(_ref) {
572
+ var authToken = _ref.authToken,
573
+ customHeaders = _ref.customHeaders;
574
+ return axios__default["default"].create({
575
+ headers: _objectSpread2(_objectSpread2({}, customHeaders), {}, {
576
+ "User-Agent": USER_AGENT,
577
+ Authorization: "Bearer ".concat(authToken)
578
+ })
579
+ });
580
+ };
581
+
582
+ function createRelease(_x) {
583
+ return _createRelease.apply(this, arguments);
584
+ }
585
+
586
+ function _createRelease() {
587
+ _createRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
588
+ var org, project, release, authToken, sentryUrl, sentryHub, customHeaders, requestUrl, releasePayload;
589
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
590
+ while (1) {
591
+ switch (_context.prev = _context.next) {
592
+ case 0:
593
+ org = _ref2.org, project = _ref2.project, release = _ref2.release, authToken = _ref2.authToken, sentryUrl = _ref2.sentryUrl, sentryHub = _ref2.sentryHub, customHeaders = _ref2.customHeaders;
594
+ requestUrl = "".concat(sentryUrl).concat(API_PATH, "/organizations/").concat(org, "/releases/");
595
+ releasePayload = {
596
+ version: release,
597
+ projects: [project],
598
+ // we currently only support creating releases for a single project
599
+ dateStarted: new Date(),
600
+ dateReleased: new Date() //TODO: figure out if these dates are set correctly
601
+
602
+ };
603
+ _context.prev = 3;
604
+ _context.next = 6;
605
+ return sentryApiAxiosInstance({
606
+ authToken: authToken,
607
+ customHeaders: customHeaders
608
+ }).post(requestUrl, releasePayload, {
609
+ headers: {
610
+ Authorization: "Bearer ".concat(authToken)
611
+ }
612
+ });
613
+
614
+ case 6:
615
+ _context.next = 12;
616
+ break;
617
+
618
+ case 8:
619
+ _context.prev = 8;
620
+ _context.t0 = _context["catch"](3);
621
+ captureMinimalError(_context.t0, sentryHub);
622
+ throw _context.t0;
623
+
624
+ case 12:
625
+ case "end":
626
+ return _context.stop();
627
+ }
628
+ }
629
+ }, _callee, null, [[3, 8]]);
630
+ }));
631
+ return _createRelease.apply(this, arguments);
632
+ }
633
+
634
+ function deleteAllReleaseArtifacts(_x2) {
635
+ return _deleteAllReleaseArtifacts.apply(this, arguments);
636
+ }
637
+
638
+ function _deleteAllReleaseArtifacts() {
639
+ _deleteAllReleaseArtifacts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref3) {
640
+ var org, project, release, authToken, sentryUrl, sentryHub, customHeaders, requestUrl;
641
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
642
+ while (1) {
643
+ switch (_context2.prev = _context2.next) {
644
+ case 0:
645
+ org = _ref3.org, project = _ref3.project, release = _ref3.release, authToken = _ref3.authToken, sentryUrl = _ref3.sentryUrl, sentryHub = _ref3.sentryHub, customHeaders = _ref3.customHeaders;
646
+ requestUrl = "".concat(sentryUrl).concat(API_PATH, "/projects/").concat(org, "/").concat(project, "/files/source-maps/?name=").concat(release);
647
+ _context2.prev = 2;
648
+ _context2.next = 5;
649
+ return sentryApiAxiosInstance({
650
+ authToken: authToken,
651
+ customHeaders: customHeaders
652
+ })["delete"](requestUrl, {
653
+ headers: {
654
+ Authorization: "Bearer ".concat(authToken)
655
+ }
656
+ });
657
+
658
+ case 5:
659
+ _context2.next = 11;
660
+ break;
661
+
662
+ case 7:
663
+ _context2.prev = 7;
664
+ _context2.t0 = _context2["catch"](2);
665
+ captureMinimalError(_context2.t0, sentryHub);
666
+ throw _context2.t0;
667
+
668
+ case 11:
669
+ case "end":
670
+ return _context2.stop();
671
+ }
672
+ }
673
+ }, _callee2, null, [[2, 7]]);
674
+ }));
675
+ return _deleteAllReleaseArtifacts.apply(this, arguments);
676
+ }
677
+
678
+ function updateRelease(_x3) {
679
+ return _updateRelease.apply(this, arguments);
680
+ }
681
+
682
+ function _updateRelease() {
683
+ _updateRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
684
+ var release, org, authToken, sentryUrl, project, sentryHub, customHeaders, requestUrl, releasePayload;
685
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
686
+ while (1) {
687
+ switch (_context3.prev = _context3.next) {
688
+ case 0:
689
+ release = _ref4.release, org = _ref4.org, authToken = _ref4.authToken, sentryUrl = _ref4.sentryUrl, project = _ref4.project, sentryHub = _ref4.sentryHub, customHeaders = _ref4.customHeaders;
690
+ requestUrl = "".concat(sentryUrl).concat(API_PATH, "/projects/").concat(org, "/").concat(project, "/releases/").concat(release, "/");
691
+ releasePayload = {
692
+ dateReleased: new Date().toISOString()
693
+ };
694
+ _context3.prev = 3;
695
+ _context3.next = 6;
696
+ return sentryApiAxiosInstance({
697
+ authToken: authToken,
698
+ customHeaders: customHeaders
699
+ }).put(requestUrl, releasePayload, {
700
+ headers: {
701
+ Authorization: "Bearer ".concat(authToken)
702
+ }
703
+ });
704
+
705
+ case 6:
706
+ _context3.next = 12;
707
+ break;
708
+
709
+ case 8:
710
+ _context3.prev = 8;
711
+ _context3.t0 = _context3["catch"](3);
712
+ captureMinimalError(_context3.t0, sentryHub);
713
+ throw _context3.t0;
714
+
715
+ case 12:
716
+ case "end":
717
+ return _context3.stop();
718
+ }
719
+ }
720
+ }, _callee3, null, [[3, 8]]);
721
+ }));
722
+ return _updateRelease.apply(this, arguments);
723
+ }
724
+
725
+ function uploadReleaseFile(_x4) {
726
+ return _uploadReleaseFile.apply(this, arguments);
727
+ }
728
+
729
+ function _uploadReleaseFile() {
730
+ _uploadReleaseFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref5) {
731
+ var org, project, release, authToken, sentryUrl, filename, fileContent, sentryHub, customHeaders, requestUrl, form;
732
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
733
+ while (1) {
734
+ switch (_context4.prev = _context4.next) {
735
+ case 0:
736
+ org = _ref5.org, project = _ref5.project, release = _ref5.release, authToken = _ref5.authToken, sentryUrl = _ref5.sentryUrl, filename = _ref5.filename, fileContent = _ref5.fileContent, sentryHub = _ref5.sentryHub, customHeaders = _ref5.customHeaders;
737
+ requestUrl = "".concat(sentryUrl).concat(API_PATH, "/projects/").concat(org, "/").concat(project, "/releases/").concat(release, "/files/");
738
+ form = new FormData__default["default"]();
739
+ form.append("name", filename);
740
+ form.append("file", Buffer.from(fileContent, "utf-8"), {
741
+ filename: filename
742
+ });
743
+ _context4.prev = 5;
744
+ _context4.next = 8;
745
+ return sentryApiAxiosInstance({
746
+ authToken: authToken,
747
+ customHeaders: customHeaders
748
+ }).post(requestUrl, form, {
749
+ headers: {
750
+ Authorization: "Bearer ".concat(authToken),
751
+ "Content-Type": "multipart/form-data"
752
+ }
753
+ });
754
+
755
+ case 8:
756
+ _context4.next = 14;
757
+ break;
758
+
759
+ case 10:
760
+ _context4.prev = 10;
761
+ _context4.t0 = _context4["catch"](5);
762
+ captureMinimalError(_context4.t0, sentryHub);
763
+ throw _context4.t0;
764
+
765
+ case 14:
766
+ case "end":
767
+ return _context4.stop();
768
+ }
769
+ }
770
+ }, _callee4, null, [[5, 10]]);
771
+ }));
772
+ return _uploadReleaseFile.apply(this, arguments);
773
+ }
774
+
775
+ function getFiles(path, allowedExtensions) {
776
+ var includedFiles = getAllIncludedFileNames(path, allowedExtensions, []);
777
+ return includedFiles.map(function (filename) {
778
+ var content = fs__default["default"].readFileSync(filename, {
779
+ encoding: "utf-8"
780
+ });
781
+ return {
782
+ name: "~" + filename.replace(new RegExp("^".concat(path)), ""),
783
+ content: content
784
+ };
785
+ });
786
+ }
787
+
788
+ function getAllIncludedFileNames(dirPath, allowedExtensions, accFiles) {
789
+ var files = fs__default["default"].readdirSync(dirPath);
790
+ files.map(function (file) {
791
+ return path__default["default"].join(dirPath, "/", file);
792
+ }).forEach(function (file) {
793
+ if (fs__default["default"].statSync(file).isDirectory()) {
794
+ accFiles = accFiles.concat(getAllIncludedFileNames(file, allowedExtensions, accFiles));
795
+ } else {
796
+ if (allowedExtensions.some(function (e) {
797
+ return file.endsWith(e);
798
+ })) {
799
+ accFiles.push(file);
800
+ }
801
+ }
802
+ });
803
+ return accFiles;
804
+ }
805
+
806
+ function createNewRelease(_x, _x2, _x3) {
807
+ return _createNewRelease.apply(this, arguments);
808
+ }
809
+
810
+ function _createNewRelease() {
811
+ _createNewRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(release, options, ctx) {
812
+ var span;
813
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
814
+ while (1) {
815
+ switch (_context.prev = _context.next) {
816
+ case 0:
817
+ span = addSpanToTransaction(ctx, "function.plugin.create_release"); // TODO: pull these checks out of here and simplify them
818
+
819
+ if (!(options.authToken === undefined)) {
820
+ _context.next = 6;
821
+ break;
822
+ }
823
+
824
+ ctx.logger.warn('Missing "authToken" option. Will not create release.');
825
+ return _context.abrupt("return", Promise.resolve("nothing to do here"));
826
+
827
+ case 6:
828
+ if (!(options.org === undefined)) {
829
+ _context.next = 11;
830
+ break;
831
+ }
832
+
833
+ ctx.logger.warn('Missing "org" option. Will not create release.');
834
+ return _context.abrupt("return", Promise.resolve("nothing to do here"));
835
+
836
+ case 11:
837
+ if (!(options.url === undefined)) {
838
+ _context.next = 16;
839
+ break;
840
+ }
841
+
842
+ ctx.logger.warn('Missing "url" option. Will not create release.');
843
+ return _context.abrupt("return", Promise.resolve("nothing to do here"));
844
+
845
+ case 16:
846
+ if (!(options.project === undefined)) {
847
+ _context.next = 19;
848
+ break;
849
+ }
850
+
851
+ ctx.logger.warn('Missing "project" option. Will not create release.');
852
+ return _context.abrupt("return", Promise.resolve("nothing to do here"));
853
+
854
+ case 19:
855
+ _context.next = 21;
856
+ return createRelease({
857
+ release: release,
858
+ authToken: options.authToken,
859
+ org: options.org,
860
+ project: options.project,
861
+ sentryUrl: options.url,
862
+ sentryHub: ctx.hub,
863
+ customHeaders: options.customHeaders
864
+ });
865
+
866
+ case 21:
867
+ ctx.logger.info("Successfully created release.");
868
+ span === null || span === void 0 ? void 0 : span.finish();
869
+ return _context.abrupt("return", Promise.resolve("nothing to do here"));
870
+
871
+ case 24:
872
+ case "end":
873
+ return _context.stop();
874
+ }
875
+ }
876
+ }, _callee);
877
+ }));
878
+ return _createNewRelease.apply(this, arguments);
879
+ }
880
+
881
+ function uploadSourceMaps(_x4, _x5, _x6) {
882
+ return _uploadSourceMaps.apply(this, arguments);
883
+ }
884
+
885
+ function _uploadSourceMaps() {
886
+ _uploadSourceMaps = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(release, options, ctx) {
887
+ var span, include, ext, org, project, authToken, url, fileExtensions, files;
888
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
889
+ while (1) {
890
+ switch (_context2.prev = _context2.next) {
891
+ case 0:
892
+ span = addSpanToTransaction(ctx, "function.plugin.upload_sourcemaps"); // This is what Sentry CLI does:
893
+ // TODO: 0. Preprocess source maps
894
+ // - (Out of scope for now)
895
+ // - For rewriting source maps see https://github.com/getsentry/rust-sourcemap/blob/master/src/types.rs#L763
896
+ // TODO: 1. Creates a new release to make sure it exists
897
+ // - can we assume that the release will exist b/c we don't give unplugin users the
898
+ // option to skip this step?
899
+ // TODO: 2. download already uploaded files and get their checksums
900
+ // TODO: 3. identify new or changed files (by comparing checksums)
901
+ // TODO: 4. upload new and changed files
902
+ // - CLI asks API for chunk options https://github.com/getsentry/sentry-cli/blob/7b8466885d9cfd51aee6fdc041eca9f645026303/src/utils/file_upload.rs#L106-L112
903
+ // - WTF?
904
+ // - don't upload more than 20k files
905
+ // - upload files concurrently
906
+ // - 2 options: chunked upload (multiple files per chunk) or single file upload
907
+
908
+ include = options.include, ext = options.ext, org = options.org, project = options.project, authToken = options.authToken, url = options.url; // TODO: pull these checks out of here and simplify them
909
+
910
+ if (!(authToken === undefined)) {
911
+ _context2.next = 7;
912
+ break;
913
+ }
914
+
915
+ ctx.logger.warn('Missing "authToken" option. Will not create release.');
916
+ return _context2.abrupt("return", Promise.resolve("nothing to do here"));
917
+
918
+ case 7:
919
+ if (!(org === undefined)) {
920
+ _context2.next = 12;
921
+ break;
922
+ }
923
+
924
+ ctx.logger.warn('Missing "org" option. Will not create release.');
925
+ return _context2.abrupt("return", Promise.resolve("nothing to do here"));
926
+
927
+ case 12:
928
+ if (!(url === undefined)) {
929
+ _context2.next = 17;
930
+ break;
931
+ }
932
+
933
+ ctx.logger.warn('Missing "url" option. Will not create release.');
934
+ return _context2.abrupt("return", Promise.resolve("nothing to do here"));
935
+
936
+ case 17:
937
+ if (!(project === undefined)) {
938
+ _context2.next = 20;
939
+ break;
940
+ }
941
+
942
+ ctx.logger.warn('Missing "project" option. Will not create release.');
943
+ return _context2.abrupt("return", Promise.resolve("nothing to do here"));
944
+
945
+ case 20:
946
+ ctx.logger.info("Uploading Sourcemaps."); //TODO: Remove this once we have internal options. this property must always be present
947
+
948
+ fileExtensions = ext || [];
949
+ files = getFiles(include, fileExtensions);
950
+ ctx.logger.info("Found ".concat(files.length, " files to upload."));
951
+ return _context2.abrupt("return", Promise.all(files.map(function (file) {
952
+ return uploadReleaseFile({
953
+ org: org,
954
+ project: project,
955
+ release: release,
956
+ authToken: authToken,
957
+ sentryUrl: url,
958
+ filename: file.name,
959
+ fileContent: file.content,
960
+ sentryHub: ctx.hub,
961
+ customHeaders: options.customHeaders
962
+ });
963
+ })).then(function () {
964
+ ctx.logger.info("Successfully uploaded sourcemaps.");
965
+ span === null || span === void 0 ? void 0 : span.finish();
966
+ return "done";
967
+ }));
968
+
969
+ case 25:
970
+ case "end":
971
+ return _context2.stop();
972
+ }
973
+ }
974
+ }, _callee2);
975
+ }));
976
+ return _uploadSourceMaps.apply(this, arguments);
977
+ }
978
+
979
+ function finalizeRelease(_x7, _x8, _x9) {
980
+ return _finalizeRelease.apply(this, arguments);
981
+ }
982
+
983
+ function _finalizeRelease() {
984
+ _finalizeRelease = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(release, options, ctx) {
985
+ var span, authToken, org, url, project;
986
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
987
+ while (1) {
988
+ switch (_context3.prev = _context3.next) {
989
+ case 0:
990
+ span = addSpanToTransaction(ctx, "function.plugin.finalize_release");
991
+
992
+ if (!options.finalize) {
993
+ _context3.next = 9;
994
+ break;
995
+ }
996
+
997
+ authToken = options.authToken, org = options.org, url = options.url, project = options.project;
998
+
999
+ if (!(!authToken || !org || !url || !project)) {
1000
+ _context3.next = 6;
1001
+ break;
1002
+ }
1003
+
1004
+ ctx.logger.warn("Missing required option. Will not clean existing artifacts.");
1005
+ return _context3.abrupt("return", Promise.resolve("nothing to do here"));
1006
+
1007
+ case 6:
1008
+ _context3.next = 8;
1009
+ return updateRelease({
1010
+ authToken: authToken,
1011
+ org: org,
1012
+ release: release,
1013
+ sentryUrl: url,
1014
+ project: project,
1015
+ sentryHub: ctx.hub,
1016
+ customHeaders: options.customHeaders
1017
+ });
1018
+
1019
+ case 8:
1020
+ ctx.logger.info("Successfully finalized release.");
1021
+
1022
+ case 9:
1023
+ span === null || span === void 0 ? void 0 : span.finish();
1024
+ return _context3.abrupt("return", Promise.resolve("nothing to do here"));
1025
+
1026
+ case 11:
1027
+ case "end":
1028
+ return _context3.stop();
1029
+ }
1030
+ }
1031
+ }, _callee3);
1032
+ }));
1033
+ return _finalizeRelease.apply(this, arguments);
1034
+ }
1035
+
1036
+ function cleanArtifacts(_x10, _x11, _x12) {
1037
+ return _cleanArtifacts.apply(this, arguments);
1038
+ } // TODO: Stuff we worry about later:
1039
+
1040
+ function _cleanArtifacts() {
1041
+ _cleanArtifacts = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(release, options, ctx) {
1042
+ var span;
1043
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1044
+ while (1) {
1045
+ switch (_context4.prev = _context4.next) {
1046
+ case 0:
1047
+ span = addSpanToTransaction(ctx, "function.plugin.clean_artifacts");
1048
+
1049
+ if (!options.cleanArtifacts) {
1050
+ _context4.next = 23;
1051
+ break;
1052
+ }
1053
+
1054
+ if (!(options.authToken === undefined)) {
1055
+ _context4.next = 7;
1056
+ break;
1057
+ }
1058
+
1059
+ ctx.logger.warn('Missing "authToken" option. Will not clean existing artifacts.');
1060
+ return _context4.abrupt("return", Promise.resolve("nothing to do here"));
1061
+
1062
+ case 7:
1063
+ if (!(options.org === undefined)) {
1064
+ _context4.next = 12;
1065
+ break;
1066
+ }
1067
+
1068
+ ctx.logger.warn('Missing "org" option. Will not clean existing artifacts.');
1069
+ return _context4.abrupt("return", Promise.resolve("nothing to do here"));
1070
+
1071
+ case 12:
1072
+ if (!(options.url === undefined)) {
1073
+ _context4.next = 17;
1074
+ break;
1075
+ }
1076
+
1077
+ ctx.logger.warn('Missing "url" option. Will not clean existing artifacts.');
1078
+ return _context4.abrupt("return", Promise.resolve("nothing to do here"));
1079
+
1080
+ case 17:
1081
+ if (!(options.project === undefined)) {
1082
+ _context4.next = 20;
1083
+ break;
1084
+ }
1085
+
1086
+ ctx.logger.warn('Missing "project" option. Will not clean existing artifacts.');
1087
+ return _context4.abrupt("return", Promise.resolve("nothing to do here"));
1088
+
1089
+ case 20:
1090
+ _context4.next = 22;
1091
+ return deleteAllReleaseArtifacts({
1092
+ authToken: options.authToken,
1093
+ org: options.org,
1094
+ release: release,
1095
+ sentryUrl: options.url,
1096
+ project: options.project,
1097
+ sentryHub: ctx.hub,
1098
+ customHeaders: options.customHeaders
1099
+ });
1100
+
1101
+ case 22:
1102
+ ctx.logger.info("Successfully cleaned previous artifacts.");
1103
+
1104
+ case 23:
1105
+ span === null || span === void 0 ? void 0 : span.finish();
1106
+ return _context4.abrupt("return", Promise.resolve("nothing to do here"));
1107
+
1108
+ case 25:
1109
+ case "end":
1110
+ return _context4.stop();
1111
+ }
1112
+ }
1113
+ }, _callee4);
1114
+ }));
1115
+ return _cleanArtifacts.apply(this, arguments);
1116
+ }
1117
+
1118
+ function setCommits(_x13) {
1119
+ return _setCommits.apply(this, arguments);
1120
+ }
1121
+
1122
+ function _setCommits() {
1123
+ _setCommits = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(
1124
+ /* version: string, */
1125
+ ctx) {
1126
+ var span;
1127
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1128
+ while (1) {
1129
+ switch (_context5.prev = _context5.next) {
1130
+ case 0:
1131
+ span = addSpanToTransaction(ctx, "function.plugin.set_commits");
1132
+ span === null || span === void 0 ? void 0 : span.finish();
1133
+ return _context5.abrupt("return", Promise.resolve("Noop"));
1134
+
1135
+ case 3:
1136
+ case "end":
1137
+ return _context5.stop();
1138
+ }
1139
+ }
1140
+ }, _callee5);
1141
+ }));
1142
+ return _setCommits.apply(this, arguments);
1143
+ }
1144
+
1145
+ function addDeploy(_x14) {
1146
+ return _addDeploy.apply(this, arguments);
1147
+ }
1148
+
1149
+ function _addDeploy() {
1150
+ _addDeploy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(
1151
+ /* version: string, */
1152
+ ctx) {
1153
+ var span;
1154
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1155
+ while (1) {
1156
+ switch (_context6.prev = _context6.next) {
1157
+ case 0:
1158
+ span = addSpanToTransaction(ctx, "function.plugin.add_deploy");
1159
+ span === null || span === void 0 ? void 0 : span.finish();
1160
+ return _context6.abrupt("return", Promise.resolve("Noop"));
1161
+
1162
+ case 3:
1163
+ case "end":
1164
+ return _context6.stop();
1165
+ }
1166
+ }
1167
+ }, _callee6);
1168
+ }));
1169
+ return _addDeploy.apply(this, arguments);
1170
+ }
1171
+
1172
+ function createLogger(options) {
1173
+ function addBreadcrumb(level, message) {
1174
+ options.hub.addBreadcrumb({
1175
+ category: "logger",
1176
+ level: level,
1177
+ message: message
1178
+ });
1179
+ }
1180
+
1181
+ return {
1182
+ info: function info(message) {
1183
+ if (!(options !== null && options !== void 0 && options.silent)) {
1184
+ // eslint-disable-next-line no-console
1185
+ console.log("".concat(options.prefix, " ").concat(message));
1186
+ }
1187
+
1188
+ addBreadcrumb("info", message);
1189
+ },
1190
+ warn: function warn(message) {
1191
+ if (!(options !== null && options !== void 0 && options.silent)) {
1192
+ // eslint-disable-next-line no-console
1193
+ console.log("".concat(options.prefix, " Warning! ").concat(message));
1194
+ }
1195
+
1196
+ addBreadcrumb("warning", message);
1197
+ },
1198
+ error: function error(message) {
1199
+ if (!(options !== null && options !== void 0 && options.silent)) {
1200
+ // eslint-disable-next-line no-console
1201
+ console.log("".concat(options.prefix, " Error: ").concat(message));
1202
+ }
1203
+
1204
+ addBreadcrumb("error", message);
1205
+ }
1206
+ };
1207
+ }
1208
+
1209
+ var defaultOptions = {
1210
+ //TODO: add default options here as we port over options from the webpack plugin
1211
+ // validate: false
1212
+ debug: false,
1213
+ cleanArtifacts: false,
1214
+ finalize: true,
1215
+ url: "https://sentry.io",
1216
+ ext: ["js", "map", "jsbundle", "bundle"],
1217
+ telemetry: true
1218
+ }; // We prefix the polyfill id with \0 to tell other plugins not to try to load or transform it.
1219
+ // This hack is taken straight from https://rollupjs.org/guide/en/#resolveid.
1220
+ // This probably doesn't work for all bundlers but for rollup it does.
1221
+
1222
+ var RELEASE_INJECTOR_ID = "\0sentry-release-injector";
1223
+ /**
1224
+ * The sentry-unplugin concerns itself with two things:
1225
+ * - Release injection
1226
+ * - Sourcemaps upload
1227
+ *
1228
+ * Release injection:
1229
+ *
1230
+ * Per default the sentry-unpugin will inject a global `SENTRY_RELEASE` variable into the entrypoint of all bundles. On
1231
+ * a technical level this is done by appending an import (`import "sentry-release-injector;"`) to all entrypoint files
1232
+ * of the user code (see `transformInclude` and `transform` hooks). This import is then resolved by the sentry-unplugin
1233
+ * to a virtual module that sets the global variable (see `resolveId` and `load` hooks).
1234
+ *
1235
+ * The resulting output approximately looks like this:
1236
+ *
1237
+ * ```text
1238
+ * entrypoint1.js (user file)
1239
+ * ┌───────────────────┐ ┌─────────────────────────────────────────────────┐
1240
+ * │ │ │ import { myFunction } from "./my-library.js"; │
1241
+ * │ sentry-unplugin │ │ │
1242
+ * │ │ │ const myResult = myFunction(); │
1243
+ * └---------│---------┘ │ export { myResult }; │
1244
+ * │ │ │
1245
+ * │ injects │ // injected by sentry-unplugin │
1246
+ * ├───────────────────► import "sentry-release-injector"; ─────────────────────┐
1247
+ * │ └─────────────────────────────────────────────────┘ │
1248
+ * │ │
1249
+ * │ │
1250
+ * │ entrypoint2.js (user file) │
1251
+ * │ ┌─────────────────────────────────────────────────┐ │
1252
+ * │ │ export function myFunction() { │ │
1253
+ * │ │ return "Hello world!"; │ │
1254
+ * │ │ } │ │
1255
+ * │ │ │ │
1256
+ * │ injects │ // injected by sentry-unplugin │ │
1257
+ * └───────────────────► import "sentry-release-injector"; ─────────────────────┤
1258
+ * └─────────────────────────────────────────────────┘ │
1259
+ * │
1260
+ * │
1261
+ * sentry-release-injector │
1262
+ * ┌──────────────────────────────────┐ │
1263
+ * │ │ is resolved │
1264
+ * │ global.SENTRY_RELEASE = { ... } │ by unplugin │
1265
+ * │ // + a little more logic │<─────────────────────┘
1266
+ * │ │ (only once)
1267
+ * └──────────────────────────────────┘
1268
+ * ```
1269
+ *
1270
+ * Source maps upload:
1271
+ *
1272
+ * The sentry-unplugin will also take care of uploading source maps to Sentry. This is all done in the `buildEnd` hook.
1273
+ * TODO: elaborate a bit on how sourcemaps upload works
1274
+ */
1275
+
1276
+ var unplugin = unplugin$1.createUnplugin(function (originalOptions, unpluginMetaContext) {
1277
+ var options = _objectSpread2(_objectSpread2({}, defaultOptions), originalOptions); //TODO: We can get rid of this variable once we have internal plugin options
1278
+
1279
+
1280
+ var telemetryEnabled = options.telemetry === true;
1281
+
1282
+ var _makeSentryClient = makeSentryClient("https://4c2bae7d9fbc413e8f7385f55c515d51@o1.ingest.sentry.io/6690737", telemetryEnabled, options.org),
1283
+ sentryHub = _makeSentryClient.hub;
1284
+
1285
+ var logger = createLogger({
1286
+ hub: sentryHub,
1287
+ prefix: "[sentry-".concat(unpluginMetaContext.framework, "-plugin]"),
1288
+ silent: options.silent
1289
+ });
1290
+
1291
+ if (telemetryEnabled) {
1292
+ logger.info("Sending error and performance telemetry data to Sentry.");
1293
+ logger.info("To disable telemetry, set `options.telemetry` to `false`.");
1294
+ }
1295
+
1296
+ sentryHub.setTags({
1297
+ organization: options.org,
1298
+ project: options.project,
1299
+ bundler: unpluginMetaContext.framework
1300
+ });
1301
+ sentryHub.setUser({
1302
+ id: options.org
1303
+ }); // This is `nonEntrypointSet` instead of `entrypointSet` because this set is filled in the `resolveId` hook and there
1304
+ // we don't have guaranteed access to *absolute* paths of files if they're entrypoints. For non-entrypoints we're
1305
+ // guaranteed to have absolute paths - we're then using the paths in later hooks to make decisions about whether a
1306
+ // file is an entrypoint or a non-entrypoint.
1307
+
1308
+ var nonEntrypointSet = new Set();
1309
+ var transaction;
1310
+ var releaseInjectionSpan;
1311
+ return {
1312
+ name: "sentry-plugin",
1313
+ enforce: "pre",
1314
+ // needed for Vite to call resolveId hook
1315
+
1316
+ /**
1317
+ * Responsible for starting the plugin execution transaction and the release injection span
1318
+ */
1319
+ buildStart: function buildStart() {
1320
+ transaction = sentryHub.startTransaction({
1321
+ op: "function.plugin",
1322
+ name: "Sentry Bundler Plugin execution"
1323
+ });
1324
+ releaseInjectionSpan = addSpanToTransaction({
1325
+ hub: sentryHub,
1326
+ parentSpan: transaction,
1327
+ logger: logger
1328
+ }, "function.plugin.inject_release", "Release injection");
1329
+ },
1330
+
1331
+ /**
1332
+ * Responsible for returning the "sentry-release-injector" ID when we encounter it. We return the ID so load is
1333
+ * called and we can "virtually" load the module. See `load` hook for more info on why it's virtual.
1334
+ *
1335
+ * We also record the id (i.e. absolute path) of any non-entrypoint.
1336
+ *
1337
+ * @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.
1338
+ * @param importer For imports: The absolute path of the module that imported this module. For entrypoints: `undefined`.
1339
+ * @param options Additional information to use for making a resolving decision.
1340
+ * @returns `"sentry-release-injector"` when the imported file is called `"sentry-release-injector"`. Otherwise returns `undefined`.
1341
+ */
1342
+ resolveId: function resolveId(id, importer, _ref) {
1343
+ var isEntry = _ref.isEntry;
1344
+ sentryHub.addBreadcrumb({
1345
+ category: "resolveId",
1346
+ message: "isEntry: ".concat(String(isEntry)),
1347
+ level: "info"
1348
+ });
1349
+
1350
+ if (!isEntry) {
1351
+ nonEntrypointSet.add(id);
1352
+ }
1353
+
1354
+ if (id === RELEASE_INJECTOR_ID) {
1355
+ return RELEASE_INJECTOR_ID;
1356
+ } else {
1357
+ return undefined;
1358
+ }
1359
+ },
1360
+ loadInclude: function loadInclude(id) {
1361
+ logger.info("Called \"loadInclude\": ".concat(JSON.stringify({
1362
+ id: id
1363
+ })));
1364
+ return id === RELEASE_INJECTOR_ID;
1365
+ },
1366
+
1367
+ /**
1368
+ * Responsible for "virtually" loading the "sentry-release-injector" module. "Virtual" means that the module is not
1369
+ * read from somewhere on disk but rather just returned via a string.
1370
+ *
1371
+ * @param id Always the absolute (fully resolved) path to the module.
1372
+ * @returns The global injector code when we load the "sentry-release-injector" module. Otherwise returns `undefined`.
1373
+ */
1374
+ load: function load(id) {
1375
+ sentryHub.addBreadcrumb({
1376
+ category: "load",
1377
+ level: "info"
1378
+ });
1379
+
1380
+ if (id === RELEASE_INJECTOR_ID) {
1381
+ return generateGlobalInjectorCode({
1382
+ release: getReleaseName(options.release)
1383
+ });
1384
+ } else {
1385
+ return undefined;
1386
+ }
1387
+ },
1388
+
1389
+ /**
1390
+ * This hook determines whether we want to transform a module. In the unplugin we want to transform every entrypoint
1391
+ * unless configured otherwise with the `entries` option.
1392
+ *
1393
+ * @param id Always the absolute (fully resolved) path to the module.
1394
+ * @returns `true` or `false` depending on whether we want to transform the module. For the sentry-unplugin we only
1395
+ * want to transform the release injector file.
1396
+ */
1397
+ transformInclude: function transformInclude(id) {
1398
+ sentryHub.addBreadcrumb({
1399
+ category: "transformInclude",
1400
+ level: "info"
1401
+ });
1402
+
1403
+ if (options.entries) {
1404
+ // If there's an `entries` option transform (ie. inject the release varible) when the file path matches the option.
1405
+ if (typeof options.entries === "function") {
1406
+ return options.entries(id);
1407
+ }
1408
+
1409
+ var arrayifiedEntriesOption = Array.isArray(options.entries) ? options.entries : [options.entries];
1410
+ return arrayifiedEntriesOption.some(function (entry) {
1411
+ if (entry instanceof RegExp) {
1412
+ return entry.test(id);
1413
+ } else {
1414
+ return id === entry;
1415
+ }
1416
+ });
1417
+ } // We want to transform (release injection) every module except for "sentry-release-injector".
1418
+
1419
+
1420
+ return id !== RELEASE_INJECTOR_ID && !nonEntrypointSet.has(id);
1421
+ },
1422
+
1423
+ /**
1424
+ * This hook is responsible for injecting the "sentry release injector" imoprt statement into each entrypoint unless
1425
+ * configured otherwise with the `entries` option (logic for that is in the `transformInclude` hook).
1426
+ *
1427
+ * @param code Code of the file to transform.
1428
+ * @param id Always the absolute (fully resolved) path to the module.
1429
+ * @returns transformed code + source map
1430
+ */
1431
+ transform: function transform(code) {
1432
+ sentryHub.addBreadcrumb({
1433
+ category: "transform",
1434
+ level: "info"
1435
+ }); // The MagicString library allows us to generate sourcemaps for the changes we make to the user code.
1436
+
1437
+ var ms = new MagicString__default["default"](code); // Very stupid author's note: For some absurd reason, when we add a JSDoc to this hook, the TS language server starts complaining about `ms` and adding a type annotation helped so that's why it's here. (┛ಠ_ಠ)┛彡┻━┻
1438
+ // appending instead of prepending has less probability of mucking with user'sadly
1439
+ // source maps and import statements get to the top anyways
1440
+
1441
+ ms.append("import \"".concat(RELEASE_INJECTOR_ID, "\";"));
1442
+
1443
+ if (unpluginMetaContext.framework === "esbuild") {
1444
+ // esbuild + unplugin is buggy at the moment when we return an object with a `map` (sourcemap) property.
1445
+ // Currently just returning a string here seems to work and even correctly sourcemaps the code we generate.
1446
+ // However, other bundlers need the `map` property
1447
+ return ms.toString();
1448
+ } else {
1449
+ return {
1450
+ code: ms.toString(),
1451
+ map: ms.generateMap()
1452
+ };
1453
+ }
1454
+ },
1455
+
1456
+ /**
1457
+ * Responsible for executing the sentry release creation pipeline (i.e. creating a release on
1458
+ * Sentry.io, uploading sourcemaps, associating commits and deploys and finalizing the release)
1459
+ */
1460
+ buildEnd: function buildEnd() {
1461
+ var _releaseInjectionSpan;
1462
+
1463
+ (_releaseInjectionSpan = releaseInjectionSpan) === null || _releaseInjectionSpan === void 0 ? void 0 : _releaseInjectionSpan.finish();
1464
+ var releasePipelineSpan = transaction && addSpanToTransaction({
1465
+ hub: sentryHub,
1466
+ parentSpan: transaction,
1467
+ logger: logger
1468
+ }, "function.plugin.release", "Release pipeline");
1469
+ var release = getReleaseName(options.release);
1470
+ sentryHub.addBreadcrumb({
1471
+ category: "buildEnd:start",
1472
+ level: "info"
1473
+ }); //TODO:
1474
+ // 1. validate options to see if we get a valid include property, release name, etc.
1475
+ // 2. normalize the include property: Users can pass string | string [] | IncludeEntry[].
1476
+ // That's good for them but a hassle for us. Let's try to normalize this into one data type
1477
+ // (I vote IncludeEntry[]) and continue with that down the line
1478
+
1479
+ var ctx = {
1480
+ hub: sentryHub,
1481
+ parentSpan: releasePipelineSpan,
1482
+ logger: logger
1483
+ };
1484
+ createNewRelease(release, options, ctx).then(function () {
1485
+ return cleanArtifacts(release, options, ctx);
1486
+ }).then(function () {
1487
+ return uploadSourceMaps(release, options, ctx);
1488
+ }).then(function () {
1489
+ return setCommits(ctx);
1490
+ }) // this is a noop for now
1491
+ .then(function () {
1492
+ return finalizeRelease(release, options, ctx);
1493
+ }).then(function () {
1494
+ return addDeploy(ctx);
1495
+ }) // this is a noop for now
1496
+ .then(function () {
1497
+ var _transaction;
1498
+
1499
+ (_transaction = transaction) === null || _transaction === void 0 ? void 0 : _transaction.setStatus("ok");
1500
+ })["catch"](function (e) {
1501
+ var _transaction2;
1502
+
1503
+ captureMinimalError(e, sentryHub);
1504
+ (_transaction2 = transaction) === null || _transaction2 === void 0 ? void 0 : _transaction2.setStatus("cancelled");
1505
+ logger.error(e.message);
1506
+
1507
+ if (options.errorHandler) {
1508
+ options.errorHandler(e);
1509
+ } else {
1510
+ throw e;
1511
+ }
1512
+ })["finally"](function () {
1513
+ var _transaction3;
1514
+
1515
+ sentryHub.addBreadcrumb({
1516
+ category: "buildEnd:finish",
1517
+ level: "info"
1518
+ });
1519
+ releasePipelineSpan === null || releasePipelineSpan === void 0 ? void 0 : releasePipelineSpan.finish();
1520
+ (_transaction3 = transaction) === null || _transaction3 === void 0 ? void 0 : _transaction3.finish();
1521
+ });
1522
+ }
1523
+ };
1524
+ });
1525
+ /**
1526
+ * Generates code for the "sentry-release-injector" which is responsible for setting the global `SENTRY_RELEASE`
1527
+ * variable.
1528
+ */
1529
+
1530
+ function generateGlobalInjectorCode(_ref2) {
1531
+ var release = _ref2.release;
1532
+ // The code below is mostly ternary operators because it saves bundle size.
1533
+ // The checks are to support as many environments as possible. (Node.js, Browser, webworkers, etc.)
1534
+ return "\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, "\"};");
1535
+ } // eslint-disable-next-line @typescript-eslint/no-explicit-any
1536
+
1537
+
1538
+ var sentryVitePlugin = unplugin.vite; // eslint-disable-next-line @typescript-eslint/no-explicit-any
1539
+
1540
+ var sentryRollupPlugin = unplugin.rollup; // eslint-disable-next-line @typescript-eslint/no-explicit-any
1541
+
1542
+ var sentryWebpackPlugin = unplugin.webpack; // eslint-disable-next-line @typescript-eslint/no-explicit-any
1543
+
1544
+ var sentryEsbuildPlugin = unplugin.esbuild;
1545
+
1546
+ exports.sentryEsbuildPlugin = sentryEsbuildPlugin;
1547
+ exports.sentryRollupPlugin = sentryRollupPlugin;
1548
+ exports.sentryVitePlugin = sentryVitePlugin;
1549
+ exports.sentryWebpackPlugin = sentryWebpackPlugin;
1550
+ //# sourceMappingURL=index.js.map