@sentry/esbuild-plugin 4.9.1 → 5.1.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.
@@ -1,763 +1,143 @@
1
- import { sentryUnpluginFactory, getDebugIdSnippet } from '@sentry/bundler-plugin-core';
2
- export { sentryCliBinaryExists } from '@sentry/bundler-plugin-core';
3
- import * as path from 'path';
4
- import { v4 } from 'uuid';
5
-
6
- function _iterableToArrayLimit(arr, i) {
7
- var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
8
- if (null != _i) {
9
- var _s,
10
- _e,
11
- _x,
12
- _r,
13
- _arr = [],
14
- _n = !0,
15
- _d = !1;
16
- try {
17
- if (_x = (_i = _i.call(arr)).next, 0 === i) {
18
- if (Object(_i) !== _i) return;
19
- _n = !1;
20
- } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
21
- } catch (err) {
22
- _d = !0, _e = err;
23
- } finally {
24
- try {
25
- if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
26
- } finally {
27
- if (_d) throw _e;
28
- }
29
- }
30
- return _arr;
31
- }
32
- }
33
- function ownKeys(object, enumerableOnly) {
34
- var keys = Object.keys(object);
35
- if (Object.getOwnPropertySymbols) {
36
- var symbols = Object.getOwnPropertySymbols(object);
37
- enumerableOnly && (symbols = symbols.filter(function (sym) {
38
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
39
- })), keys.push.apply(keys, symbols);
40
- }
41
- return keys;
42
- }
43
- function _objectSpread2(target) {
44
- for (var i = 1; i < arguments.length; i++) {
45
- var source = null != arguments[i] ? arguments[i] : {};
46
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
47
- _defineProperty(target, key, source[key]);
48
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
49
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
50
- });
51
- }
52
- return target;
53
- }
54
- function _regeneratorRuntime() {
55
- _regeneratorRuntime = function () {
56
- return exports;
57
- };
58
- var exports = {},
59
- Op = Object.prototype,
60
- hasOwn = Op.hasOwnProperty,
61
- defineProperty = Object.defineProperty || function (obj, key, desc) {
62
- obj[key] = desc.value;
63
- },
64
- $Symbol = "function" == typeof Symbol ? Symbol : {},
65
- iteratorSymbol = $Symbol.iterator || "@@iterator",
66
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
67
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
68
- function define(obj, key, value) {
69
- return Object.defineProperty(obj, key, {
70
- value: value,
71
- enumerable: !0,
72
- configurable: !0,
73
- writable: !0
74
- }), obj[key];
75
- }
76
- try {
77
- define({}, "");
78
- } catch (err) {
79
- define = function (obj, key, value) {
80
- return obj[key] = value;
81
- };
82
- }
83
- function wrap(innerFn, outerFn, self, tryLocsList) {
84
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
85
- generator = Object.create(protoGenerator.prototype),
86
- context = new Context(tryLocsList || []);
87
- return defineProperty(generator, "_invoke", {
88
- value: makeInvokeMethod(innerFn, self, context)
89
- }), generator;
90
- }
91
- function tryCatch(fn, obj, arg) {
92
- try {
93
- return {
94
- type: "normal",
95
- arg: fn.call(obj, arg)
96
- };
97
- } catch (err) {
98
- return {
99
- type: "throw",
100
- arg: err
101
- };
102
- }
103
- }
104
- exports.wrap = wrap;
105
- var ContinueSentinel = {};
106
- function Generator() {}
107
- function GeneratorFunction() {}
108
- function GeneratorFunctionPrototype() {}
109
- var IteratorPrototype = {};
110
- define(IteratorPrototype, iteratorSymbol, function () {
111
- return this;
112
- });
113
- var getProto = Object.getPrototypeOf,
114
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
115
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
116
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
117
- function defineIteratorMethods(prototype) {
118
- ["next", "throw", "return"].forEach(function (method) {
119
- define(prototype, method, function (arg) {
120
- return this._invoke(method, arg);
121
- });
122
- });
123
- }
124
- function AsyncIterator(generator, PromiseImpl) {
125
- function invoke(method, arg, resolve, reject) {
126
- var record = tryCatch(generator[method], generator, arg);
127
- if ("throw" !== record.type) {
128
- var result = record.arg,
129
- value = result.value;
130
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
131
- invoke("next", value, resolve, reject);
132
- }, function (err) {
133
- invoke("throw", err, resolve, reject);
134
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
135
- result.value = unwrapped, resolve(result);
136
- }, function (error) {
137
- return invoke("throw", error, resolve, reject);
138
- });
139
- }
140
- reject(record.arg);
141
- }
142
- var previousPromise;
143
- defineProperty(this, "_invoke", {
144
- value: function (method, arg) {
145
- function callInvokeWithMethodAndArg() {
146
- return new PromiseImpl(function (resolve, reject) {
147
- invoke(method, arg, resolve, reject);
148
- });
149
- }
150
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
151
- }
152
- });
153
- }
154
- function makeInvokeMethod(innerFn, self, context) {
155
- var state = "suspendedStart";
156
- return function (method, arg) {
157
- if ("executing" === state) throw new Error("Generator is already running");
158
- if ("completed" === state) {
159
- if ("throw" === method) throw arg;
160
- return doneResult();
161
- }
162
- for (context.method = method, context.arg = arg;;) {
163
- var delegate = context.delegate;
164
- if (delegate) {
165
- var delegateResult = maybeInvokeDelegate(delegate, context);
166
- if (delegateResult) {
167
- if (delegateResult === ContinueSentinel) continue;
168
- return delegateResult;
169
- }
170
- }
171
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
172
- if ("suspendedStart" === state) throw state = "completed", context.arg;
173
- context.dispatchException(context.arg);
174
- } else "return" === context.method && context.abrupt("return", context.arg);
175
- state = "executing";
176
- var record = tryCatch(innerFn, self, context);
177
- if ("normal" === record.type) {
178
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
179
- return {
180
- value: record.arg,
181
- done: context.done
182
- };
183
- }
184
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
185
- }
186
- };
187
- }
188
- function maybeInvokeDelegate(delegate, context) {
189
- var methodName = context.method,
190
- method = delegate.iterator[methodName];
191
- if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
192
- var record = tryCatch(method, delegate.iterator, context.arg);
193
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
194
- var info = record.arg;
195
- 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);
196
- }
197
- function pushTryEntry(locs) {
198
- var entry = {
199
- tryLoc: locs[0]
200
- };
201
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
202
- }
203
- function resetTryEntry(entry) {
204
- var record = entry.completion || {};
205
- record.type = "normal", delete record.arg, entry.completion = record;
206
- }
207
- function Context(tryLocsList) {
208
- this.tryEntries = [{
209
- tryLoc: "root"
210
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
211
- }
212
- function values(iterable) {
213
- if (iterable) {
214
- var iteratorMethod = iterable[iteratorSymbol];
215
- if (iteratorMethod) return iteratorMethod.call(iterable);
216
- if ("function" == typeof iterable.next) return iterable;
217
- if (!isNaN(iterable.length)) {
218
- var i = -1,
219
- next = function next() {
220
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
221
- return next.value = undefined, next.done = !0, next;
222
- };
223
- return next.next = next;
224
- }
225
- }
226
- return {
227
- next: doneResult
228
- };
229
- }
230
- function doneResult() {
231
- return {
232
- value: undefined,
233
- done: !0
234
- };
235
- }
236
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
237
- value: GeneratorFunctionPrototype,
238
- configurable: !0
239
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
240
- value: GeneratorFunction,
241
- configurable: !0
242
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
243
- var ctor = "function" == typeof genFun && genFun.constructor;
244
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
245
- }, exports.mark = function (genFun) {
246
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
247
- }, exports.awrap = function (arg) {
248
- return {
249
- __await: arg
250
- };
251
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
252
- return this;
253
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
254
- void 0 === PromiseImpl && (PromiseImpl = Promise);
255
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
256
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
257
- return result.done ? result.value : iter.next();
258
- });
259
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
260
- return this;
261
- }), define(Gp, "toString", function () {
262
- return "[object Generator]";
263
- }), exports.keys = function (val) {
264
- var object = Object(val),
265
- keys = [];
266
- for (var key in object) keys.push(key);
267
- return keys.reverse(), function next() {
268
- for (; keys.length;) {
269
- var key = keys.pop();
270
- if (key in object) return next.value = key, next.done = !1, next;
271
- }
272
- return next.done = !0, next;
273
- };
274
- }, exports.values = values, Context.prototype = {
275
- constructor: Context,
276
- reset: function (skipTempReset) {
277
- 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);
278
- },
279
- stop: function () {
280
- this.done = !0;
281
- var rootRecord = this.tryEntries[0].completion;
282
- if ("throw" === rootRecord.type) throw rootRecord.arg;
283
- return this.rval;
284
- },
285
- dispatchException: function (exception) {
286
- if (this.done) throw exception;
287
- var context = this;
288
- function handle(loc, caught) {
289
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
290
- }
291
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
292
- var entry = this.tryEntries[i],
293
- record = entry.completion;
294
- if ("root" === entry.tryLoc) return handle("end");
295
- if (entry.tryLoc <= this.prev) {
296
- var hasCatch = hasOwn.call(entry, "catchLoc"),
297
- hasFinally = hasOwn.call(entry, "finallyLoc");
298
- if (hasCatch && hasFinally) {
299
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
300
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
301
- } else if (hasCatch) {
302
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
303
- } else {
304
- if (!hasFinally) throw new Error("try statement without catch or finally");
305
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
306
- }
307
- }
308
- }
309
- },
310
- abrupt: function (type, arg) {
311
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
312
- var entry = this.tryEntries[i];
313
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
314
- var finallyEntry = entry;
315
- break;
316
- }
317
- }
318
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
319
- var record = finallyEntry ? finallyEntry.completion : {};
320
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
321
- },
322
- complete: function (record, afterLoc) {
323
- if ("throw" === record.type) throw record.arg;
324
- 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;
325
- },
326
- finish: function (finallyLoc) {
327
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
328
- var entry = this.tryEntries[i];
329
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
330
- }
331
- },
332
- catch: function (tryLoc) {
333
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
334
- var entry = this.tryEntries[i];
335
- if (entry.tryLoc === tryLoc) {
336
- var record = entry.completion;
337
- if ("throw" === record.type) {
338
- var thrown = record.arg;
339
- resetTryEntry(entry);
340
- }
341
- return thrown;
342
- }
343
- }
344
- throw new Error("illegal catch attempt");
345
- },
346
- delegateYield: function (iterable, resultName, nextLoc) {
347
- return this.delegate = {
348
- iterator: values(iterable),
349
- resultName: resultName,
350
- nextLoc: nextLoc
351
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
352
- }
353
- }, exports;
354
- }
355
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
356
- try {
357
- var info = gen[key](arg);
358
- var value = info.value;
359
- } catch (error) {
360
- reject(error);
361
- return;
362
- }
363
- if (info.done) {
364
- resolve(value);
365
- } else {
366
- Promise.resolve(value).then(_next, _throw);
367
- }
368
- }
369
- function _asyncToGenerator(fn) {
370
- return function () {
371
- var self = this,
372
- args = arguments;
373
- return new Promise(function (resolve, reject) {
374
- var gen = fn.apply(self, args);
375
- function _next(value) {
376
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
377
- }
378
- function _throw(err) {
379
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
380
- }
381
- _next(undefined);
382
- });
383
- };
384
- }
385
- function _defineProperty(obj, key, value) {
386
- key = _toPropertyKey(key);
387
- if (key in obj) {
388
- Object.defineProperty(obj, key, {
389
- value: value,
390
- enumerable: true,
391
- configurable: true,
392
- writable: true
393
- });
394
- } else {
395
- obj[key] = value;
396
- }
397
- return obj;
398
- }
399
- function _slicedToArray(arr, i) {
400
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
401
- }
402
- function _arrayWithHoles(arr) {
403
- if (Array.isArray(arr)) return arr;
404
- }
405
- function _unsupportedIterableToArray(o, minLen) {
406
- if (!o) return;
407
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
408
- var n = Object.prototype.toString.call(o).slice(8, -1);
409
- if (n === "Object" && o.constructor) n = o.constructor.name;
410
- if (n === "Map" || n === "Set") return Array.from(o);
411
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
412
- }
413
- function _arrayLikeToArray(arr, len) {
414
- if (len == null || len > arr.length) len = arr.length;
415
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
416
- return arr2;
417
- }
418
- function _nonIterableRest() {
419
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
420
- }
421
- function _toPrimitive(input, hint) {
422
- if (typeof input !== "object" || input === null) return input;
423
- var prim = input[Symbol.toPrimitive];
424
- if (prim !== undefined) {
425
- var res = prim.call(input, hint || "default");
426
- if (typeof res !== "object") return res;
427
- throw new TypeError("@@toPrimitive must return a primitive value.");
428
- }
429
- return (hint === "string" ? String : Number)(input);
430
- }
431
- function _toPropertyKey(arg) {
432
- var key = _toPrimitive(arg, "string");
433
- return typeof key === "symbol" ? key : String(key);
434
- }
435
-
436
- function esbuildReleaseInjectionPlugin(injectionCode) {
437
- var pluginName = "sentry-esbuild-release-injection-plugin";
438
- var virtualReleaseInjectionFilePath = path.resolve("_sentry-release-injection-stub"); // needs to be an absolute path for older eslint versions
439
-
440
- return {
441
- name: pluginName,
442
- esbuild: {
443
- setup: function setup(_ref) {
444
- var initialOptions = _ref.initialOptions,
445
- onLoad = _ref.onLoad,
446
- onResolve = _ref.onResolve;
447
- initialOptions.inject = initialOptions.inject || [];
448
- initialOptions.inject.push(virtualReleaseInjectionFilePath);
449
- onResolve({
450
- filter: /_sentry-release-injection-stub/
451
- }, function (args) {
452
- return {
453
- path: args.path,
454
- sideEffects: true,
455
- pluginName: pluginName
456
- };
457
- });
458
- onLoad({
459
- filter: /_sentry-release-injection-stub/
460
- }, function () {
461
- return {
462
- loader: "js",
463
- pluginName: pluginName,
464
- contents: injectionCode
465
- };
466
- });
467
- }
468
- }
469
- };
470
- }
471
-
472
- /**
473
- * Shared set to track entry points that have been wrapped by the metadata plugin
474
- * This allows the debug ID plugin to know when an import is coming from a metadata proxy
475
- */
476
- var metadataProxyEntryPoints = new Set();
477
-
478
- /**
479
- * Set to track which paths have already been wrapped with debug ID injection
480
- * This prevents the debug ID plugin from wrapping the same module multiple times
481
- */
482
- var debugIdWrappedPaths = new Set();
483
- function esbuildDebugIdInjectionPlugin(logger) {
484
- var pluginName = "sentry-esbuild-debug-id-injection-plugin";
485
- var stubNamespace = "sentry-debug-id-stub";
486
- return {
487
- name: pluginName,
488
- esbuild: {
489
- setup: function setup(_ref2) {
490
- var initialOptions = _ref2.initialOptions,
491
- onLoad = _ref2.onLoad,
492
- onResolve = _ref2.onResolve;
493
- // Clear state from previous builds (important for watch mode and test suites)
494
- debugIdWrappedPaths.clear();
495
- // Also clear metadataProxyEntryPoints here because if moduleMetadataInjectionPlugin
496
- // is not instantiated in this build (e.g., moduleMetadata was disabled), we don't
497
- // want stale entries from a previous build to affect the current one.
498
- metadataProxyEntryPoints.clear();
499
- if (!initialOptions.bundle) {
500
- logger.warn("The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/");
501
- }
502
- onResolve({
503
- filter: /.*/
504
- }, function (args) {
505
- var _args$importer, _initialOptions$injec;
506
- // Inject debug IDs into entry points and into imports from metadata proxy modules
507
- var isEntryPoint = args.kind === "entry-point";
508
-
509
- // Check if this import is coming from a metadata proxy module
510
- // The metadata plugin registers entry points it wraps in the shared Set
511
- // We need to strip the query string suffix because esbuild includes the suffix
512
- // (e.g., ?sentryMetadataProxyModule=true) in args.importer
513
- var importerPath = (_args$importer = args.importer) === null || _args$importer === void 0 ? void 0 : _args$importer.split("?")[0];
514
- var isImportFromMetadataProxy = args.kind === "import-statement" && importerPath !== undefined && metadataProxyEntryPoints.has(importerPath);
515
- if (!isEntryPoint && !isImportFromMetadataProxy) {
516
- return;
517
- }
518
-
519
- // Skip injecting debug IDs into modules specified in the esbuild `inject` option
520
- // since they're already part of the entry points
521
- if ((_initialOptions$injec = initialOptions.inject) !== null && _initialOptions$injec !== void 0 && _initialOptions$injec.includes(args.path)) {
522
- return;
523
- }
524
- var resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);
525
-
526
- // Skip injecting debug IDs into paths that have already been wrapped
527
- if (debugIdWrappedPaths.has(resolvedPath)) {
528
- return;
529
- }
530
- debugIdWrappedPaths.add(resolvedPath);
531
- return {
532
- pluginName: pluginName,
533
- // needs to be an abs path, otherwise esbuild will complain
534
- path: resolvedPath,
535
- pluginData: {
536
- isProxyResolver: true,
537
- originalPath: args.path,
538
- originalResolveDir: args.resolveDir
539
- },
540
- // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse
541
- // the module tree any further down past the proxy module because we're essentially creating a dependency
542
- // loop back to the proxy module.
543
- // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,
544
- // making it re-resolve the entrypoint when it is imported from the proxy module.
545
- // Super confusing? Yes. Works? Apparently... Let's see.
546
- suffix: "?sentryProxyModule=true"
547
- };
548
- });
549
- onLoad({
550
- filter: /.*/
551
- }, function (args) {
552
- var _args$pluginData;
553
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
554
- if (!((_args$pluginData = args.pluginData) !== null && _args$pluginData !== void 0 && _args$pluginData.isProxyResolver)) {
555
- return null;
556
- }
557
-
558
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
559
- var originalPath = args.pluginData.originalPath;
560
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
561
- var originalResolveDir = args.pluginData.originalResolveDir;
562
- return {
563
- loader: "js",
564
- pluginName: pluginName,
565
- // We need to use JSON.stringify below so that any escape backslashes stay escape backslashes, in order not to break paths on windows
566
- contents: "\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ".concat(JSON.stringify(originalPath), ";\n export default OriginalModule.default;\n export * from ").concat(JSON.stringify(originalPath), ";"),
567
- resolveDir: originalResolveDir
568
- };
569
- });
570
- onResolve({
571
- filter: /_sentry-debug-id-injection-stub/
572
- }, function (args) {
573
- return {
574
- path: args.path,
575
- sideEffects: true,
576
- pluginName: pluginName,
577
- namespace: stubNamespace,
578
- suffix: "?sentry-module-id=" + v4() // create different module, each time this is resolved
579
- };
580
- });
581
-
582
- onLoad({
583
- filter: /_sentry-debug-id-injection-stub/,
584
- namespace: stubNamespace
585
- }, function () {
586
- return {
587
- loader: "js",
588
- pluginName: pluginName,
589
- contents: getDebugIdSnippet(v4()).code()
590
- };
591
- });
592
- }
593
- }
594
- };
595
- }
596
- function esbuildModuleMetadataInjectionPlugin(injectionCode) {
597
- var pluginName = "sentry-esbuild-module-metadata-injection-plugin";
598
- var stubNamespace = "sentry-module-metadata-stub";
599
- return {
600
- name: pluginName,
601
- esbuild: {
602
- setup: function setup(_ref3) {
603
- var initialOptions = _ref3.initialOptions,
604
- onLoad = _ref3.onLoad,
605
- onResolve = _ref3.onResolve;
606
- // Clear state from previous builds (important for watch mode and test suites)
607
- metadataProxyEntryPoints.clear();
608
- onResolve({
609
- filter: /.*/
610
- }, function (args) {
611
- if (args.kind !== "entry-point") {
612
- return;
613
- } else {
614
- var _initialOptions$injec2;
615
- // Injected modules via the esbuild `inject` option do also have `kind == "entry-point"`.
616
- // We do not want to inject debug IDs into those files because they are already bundled into the entrypoints
617
- if ((_initialOptions$injec2 = initialOptions.inject) !== null && _initialOptions$injec2 !== void 0 && _initialOptions$injec2.includes(args.path)) {
618
- return;
619
- }
620
- var resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);
621
-
622
- // Register this entry point so the debug ID plugin knows to wrap imports from
623
- // this proxy module, this because the debug ID may run after the metadata plugin
624
- metadataProxyEntryPoints.add(resolvedPath);
625
- return {
626
- pluginName: pluginName,
627
- // needs to be an abs path, otherwise esbuild will complain
628
- path: resolvedPath,
629
- pluginData: {
630
- isMetadataProxyResolver: true,
631
- originalPath: args.path,
632
- originalResolveDir: args.resolveDir
633
- },
634
- // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse
635
- // the module tree any further down past the proxy module because we're essentially creating a dependency
636
- // loop back to the proxy module.
637
- // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,
638
- // making it re-resolve the entrypoint when it is imported from the proxy module.
639
- // Super confusing? Yes. Works? Apparently... Let's see.
640
- suffix: "?sentryMetadataProxyModule=true"
641
- };
642
- }
643
- });
644
- onLoad({
645
- filter: /.*/
646
- }, function (args) {
647
- var _args$pluginData2;
648
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
649
- if (!((_args$pluginData2 = args.pluginData) !== null && _args$pluginData2 !== void 0 && _args$pluginData2.isMetadataProxyResolver)) {
650
- return null;
651
- }
652
-
653
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
654
- var originalPath = args.pluginData.originalPath;
655
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
656
- var originalResolveDir = args.pluginData.originalResolveDir;
657
- return {
658
- loader: "js",
659
- pluginName: pluginName,
660
- // We need to use JSON.stringify below so that any escape backslashes stay escape backslashes, in order not to break paths on windows
661
- contents: "\n import \"_sentry-module-metadata-injection-stub\";\n import * as OriginalModule from ".concat(JSON.stringify(originalPath), ";\n export default OriginalModule.default;\n export * from ").concat(JSON.stringify(originalPath), ";"),
662
- resolveDir: originalResolveDir
663
- };
664
- });
665
- onResolve({
666
- filter: /_sentry-module-metadata-injection-stub/
667
- }, function (args) {
668
- return {
669
- path: args.path,
670
- sideEffects: true,
671
- pluginName: pluginName,
672
- namespace: stubNamespace,
673
- suffix: "?sentry-module-id=" + v4() // create different module, each time this is resolved
674
- };
675
- });
676
-
677
- onLoad({
678
- filter: /_sentry-module-metadata-injection-stub/,
679
- namespace: stubNamespace
680
- }, function () {
681
- return {
682
- loader: "js",
683
- pluginName: pluginName,
684
- contents: injectionCode
685
- };
686
- });
687
- }
688
- }
689
- };
690
- }
691
- function esbuildDebugIdUploadPlugin(upload, _logger, createDependencyOnBuildArtifacts) {
692
- var freeGlobalDependencyOnDebugIdSourcemapArtifacts = createDependencyOnBuildArtifacts();
693
- return {
694
- name: "sentry-esbuild-debug-id-upload-plugin",
695
- esbuild: {
696
- setup: function setup(_ref4) {
697
- var initialOptions = _ref4.initialOptions,
698
- onEnd = _ref4.onEnd;
699
- initialOptions.metafile = true;
700
- onEnd( /*#__PURE__*/function () {
701
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(result) {
702
- var _buildArtifacts;
703
- return _regeneratorRuntime().wrap(function _callee$(_context) {
704
- while (1) switch (_context.prev = _context.next) {
705
- case 0:
706
- _context.prev = 0;
707
- _buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];
708
- _context.next = 4;
709
- return upload(_buildArtifacts);
710
- case 4:
711
- _context.prev = 4;
712
- freeGlobalDependencyOnDebugIdSourcemapArtifacts();
713
- return _context.finish(4);
714
- case 7:
715
- case "end":
716
- return _context.stop();
717
- }
718
- }, _callee, null, [[0,, 4, 7]]);
719
- }));
720
- return function (_x) {
721
- return _ref5.apply(this, arguments);
722
- };
723
- }());
724
- }
725
- }
726
- };
727
- }
728
- function esbuildBundleSizeOptimizationsPlugin(replacementValues) {
729
- return {
730
- name: "sentry-esbuild-bundle-size-optimizations-plugin",
731
- esbuild: {
732
- setup: function setup(_ref6) {
733
- var initialOptions = _ref6.initialOptions;
734
- var replacementStringValues = {};
735
- Object.entries(replacementValues).forEach(function (_ref7) {
736
- var _ref8 = _slicedToArray(_ref7, 2),
737
- key = _ref8[0],
738
- value = _ref8[1];
739
- replacementStringValues[key] = JSON.stringify(value);
740
- });
741
- initialOptions.define = _objectSpread2(_objectSpread2({}, initialOptions.define), replacementStringValues);
742
- }
743
- }
744
- };
745
- }
746
- var sentryUnplugin = sentryUnpluginFactory({
747
- injectionPlugin: {
748
- releaseInjectionPlugin: esbuildReleaseInjectionPlugin,
749
- debugIdInjectionPlugin: esbuildDebugIdInjectionPlugin,
750
- moduleMetadataInjectionPlugin: esbuildModuleMetadataInjectionPlugin
751
- },
752
- debugIdUploadPlugin: esbuildDebugIdUploadPlugin,
753
- bundleSizeOptimizationsPlugin: esbuildBundleSizeOptimizationsPlugin
754
- });
755
-
756
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
757
- var sentryEsbuildPlugin = sentryUnplugin.esbuild;
758
-
759
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
760
- var index = sentryUnplugin.esbuild;
761
-
762
- export { index as default, sentryEsbuildPlugin };
763
- //# sourceMappingURL=index.mjs.map
1
+ import { createRequire } from "node:module";
2
+ import { CodeInjection, createDebugIdUploadFunction, createSentryBuildPluginManager, generateModuleMetadataInjectorCode, generateReleaseInjectorCode, getDebugIdSnippet, sentryCliBinaryExists } from "@sentry/bundler-plugin-core";
3
+ import * as path from "node:path";
4
+ import { v4 } from "uuid";
5
+
6
+ //#region src/index.ts
7
+ function getEsbuildMajorVersion() {
8
+ try {
9
+ return createRequire(import.meta.url)("esbuild").version?.split(".")[1];
10
+ } catch (err) {}
11
+ }
12
+ const pluginName = "sentry-esbuild-plugin";
13
+ function sentryEsbuildPlugin(userOptions = {}) {
14
+ const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {
15
+ loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,
16
+ buildTool: "esbuild",
17
+ buildToolMajorVersion: getEsbuildMajorVersion()
18
+ });
19
+ const { logger, normalizedOptions: options, bundleSizeOptimizationReplacementValues: replacementValues, bundleMetadata, createDependencyOnBuildArtifacts } = sentryBuildPluginManager;
20
+ if (options.disable) return {
21
+ name: "sentry-esbuild-noop-plugin",
22
+ setup() {}
23
+ };
24
+ if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
25
+ const sourcemapsEnabled = options.sourcemaps?.disable !== true;
26
+ const staticInjectionCode = new CodeInjection();
27
+ if (!options.release.inject) logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
28
+ else if (!options.release.name) logger.debug("No release name provided. Will not inject release. Please set the `release.name` option to identify your release.");
29
+ else staticInjectionCode.append(generateReleaseInjectorCode({
30
+ release: options.release.name,
31
+ injectBuildInformation: options._experiments.injectBuildInformation || false
32
+ }));
33
+ if (Object.keys(bundleMetadata).length > 0) staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));
34
+ if (options.reactComponentAnnotation?.enabled) logger.warn("Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.");
35
+ const transformReplace = Object.keys(replacementValues).length > 0;
36
+ const debugIdWrappedPaths = /* @__PURE__ */ new Set();
37
+ sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {});
38
+ return {
39
+ name: pluginName,
40
+ setup({ initialOptions, onLoad, onResolve, onEnd }) {
41
+ if (!staticInjectionCode.isEmpty()) {
42
+ const virtualInjectionFilePath = path.resolve("_sentry-injection-stub");
43
+ initialOptions.inject = initialOptions.inject || [];
44
+ initialOptions.inject.push(virtualInjectionFilePath);
45
+ onResolve({ filter: /_sentry-injection-stub/ }, (args) => {
46
+ return {
47
+ path: args.path,
48
+ sideEffects: true,
49
+ pluginName
50
+ };
51
+ });
52
+ onLoad({ filter: /_sentry-injection-stub/ }, () => {
53
+ return {
54
+ loader: "js",
55
+ pluginName,
56
+ contents: staticInjectionCode.code()
57
+ };
58
+ });
59
+ }
60
+ if (transformReplace) {
61
+ const replacementStringValues = {};
62
+ Object.entries(replacementValues).forEach(([key, value]) => {
63
+ replacementStringValues[key] = JSON.stringify(value);
64
+ });
65
+ initialOptions.define = {
66
+ ...initialOptions.define,
67
+ ...replacementStringValues
68
+ };
69
+ }
70
+ if (sourcemapsEnabled) {
71
+ debugIdWrappedPaths.clear();
72
+ if (!initialOptions.bundle) logger.warn("The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/");
73
+ onResolve({ filter: /.*/ }, (args) => {
74
+ if (args.kind !== "entry-point") return;
75
+ if (initialOptions.inject?.includes(args.path)) return;
76
+ const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);
77
+ if (debugIdWrappedPaths.has(resolvedPath)) return;
78
+ debugIdWrappedPaths.add(resolvedPath);
79
+ return {
80
+ pluginName,
81
+ path: resolvedPath,
82
+ pluginData: {
83
+ isDebugIdProxy: true,
84
+ originalPath: args.path,
85
+ originalResolveDir: args.resolveDir
86
+ },
87
+ suffix: "?sentryDebugIdProxy=true"
88
+ };
89
+ });
90
+ onLoad({ filter: /.*/ }, (args) => {
91
+ if (!args.pluginData?.isDebugIdProxy) return null;
92
+ const originalPath = args.pluginData.originalPath;
93
+ const originalResolveDir = args.pluginData.originalResolveDir;
94
+ return {
95
+ loader: "js",
96
+ pluginName,
97
+ contents: `
98
+ import "_sentry-debug-id-injection-stub";
99
+ import * as OriginalModule from ${JSON.stringify(originalPath)};
100
+ export default OriginalModule.default;
101
+ export * from ${JSON.stringify(originalPath)};`,
102
+ resolveDir: originalResolveDir
103
+ };
104
+ });
105
+ onResolve({ filter: /_sentry-debug-id-injection-stub/ }, (args) => {
106
+ return {
107
+ path: args.path,
108
+ sideEffects: true,
109
+ pluginName,
110
+ namespace: "sentry-debug-id-stub",
111
+ suffix: "?sentry-module-id=" + v4()
112
+ };
113
+ });
114
+ onLoad({
115
+ filter: /_sentry-debug-id-injection-stub/,
116
+ namespace: "sentry-debug-id-stub"
117
+ }, () => {
118
+ return {
119
+ loader: "js",
120
+ pluginName,
121
+ contents: getDebugIdSnippet(v4()).code()
122
+ };
123
+ });
124
+ }
125
+ const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
126
+ const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });
127
+ initialOptions.metafile = true;
128
+ onEnd(async (result) => {
129
+ try {
130
+ await sentryBuildPluginManager.createRelease();
131
+ if (sourcemapsEnabled && options.sourcemaps?.disable !== "disable-upload") await upload(result.metafile ? Object.keys(result.metafile.outputs) : []);
132
+ } finally {
133
+ freeGlobalDependencyOnBuildArtifacts();
134
+ await sentryBuildPluginManager.deleteArtifacts();
135
+ }
136
+ });
137
+ }
138
+ };
139
+ }
140
+
141
+ //#endregion
142
+ export { sentryEsbuildPlugin as default, sentryEsbuildPlugin, sentryCliBinaryExists };
143
+ //# sourceMappingURL=index.mjs.map